Refuse a module to anyone who has no row for it

Until now an account was a key to every module. Being unassigned meant
seeing an empty screen -- nothing had refused you, and "you can see
nothing" is not an access decision.

`dredd.module_permission` is now the one table that says what a person
may do here: no row is no access, `user` may use it, `moderator` may
administer it, and a platform administrator needs no row. It is written
only in the hub; this app holds SELECT on it and nothing else, because a
module that could write it would admit anyone and promote itself.

The check sits in `deps.get_current_user`, right after the token-scope
check and for the same reason the scope check is there: every
authenticated route depends on that function, so one call covers all of
them and no route added later can forget it. Standalone it emits no SQL
and refuses nobody -- core answers `user` for everybody when there is no
platform -- so there is one guard rather than a second code path.

A new revision renames the local `module_moderator` where one exists,
adds the `role` column and backfills every existing row to `moderator`,
because every row that existed was a moderator grant. Editing the cutover
alone would not have reached it: `0001` is stamped and never runs again,
which is the same shape as the `node_kind` failure this family already
learned from. It builds nothing where identity belongs to the hub --
there a local copy would be the shadow table the lifespan assertion
exists to catch.

Requires dredd-core v0.11.0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 11:52:05 +02:00
co-authored by Claude Opus 5
parent 0db2c9214b
commit afca6d13cb
14 changed files with 653 additions and 75 deletions
+4 -4
View File
@@ -97,13 +97,13 @@ IDENTITY_SCHEMA=
# signs nobody out mid-change.
#SESSION_COOKIE_NAME=dredd_session
# This module's name ON THE PLATFORM — the one string the hub and this module have to agree on by
# hand. It is what a moderator grant names (`module_moderator.module_slug`), what the hub's module
# hand. It is what a grant of access names (`module_permission.module_slug`), what the hub's module
# catalogue calls this app, and what the hub stamps a token it mints for this app with
# (`<slug>_pat_`). Written out rather than left to the default, unlike the two lines above, because
# a mismatch here is SILENT in both directions: this module only ever SELECTs `module_moderator`
# a mismatch here is SILENT in both directions: this module only ever SELECTs `module_permission`
# WHERE module_slug = its own name, so a grant written against a different spelling simply never
# matches — the administrator sees a successful delegation, the person stays unprivileged, and no
# error is raised anywhere. An absent key that "obviously defaults right" is exactly the kind of
# matches — the administrator sees a successful delegation and the person is refused at the door,
# with nothing anywhere raising an error to say why. An absent key that "obviously defaults right" is exactly the kind of
# thing nobody checks against the catalogue; a present one can be read off both sides in a second.
# It is `counsel` — the same word as the schema, both role names, the URL path and the cookie, and
# never `scorecard` or `counsel-scorecard`. Change it only if the module is renamed in every one of
+10 -5
View File
@@ -423,10 +423,11 @@ jobs:
END $$;
SQL
- name: Run the platform-live tests (as counsel_app, with the hub able to write sessions)
# The claims themselves: a hub-issued session signs you in here; nobody signs in here; no
# account can be written from here; the runtime role cannot read a password hash, mint a
# credential or grant itself the moderator tier; and no local copy of the identity tables
# survived.
# The claims themselves: a hub-issued session signs you in here; a signed-in account with no
# `module_permission` row for `counsel` is refused at the door and admitted the moment the
# hub writes one; nobody signs in here; no account can be written from here; the runtime
# role cannot read a password hash, mint a credential or admit anyone (itself included);
# and no local copy of the identity tables survived.
env:
IDENTITY_SCHEMA: dredd
PLATFORM_HUB_DATABASE_URL: ${{ env.HUB_MIGRATION_URL }}
@@ -452,8 +453,12 @@ jobs:
psql "$SUPERUSER_PSQL" -v ON_ERROR_STOP=1 <<'SQL'
DO $$
BEGIN
-- Both spellings of the module tier. 0005 runs right after the cutover on this very
-- upgrade, and its "neither table, so build it" branch would put a local copy back
-- here if it were not skipped on the platform. That is the shadow table.
IF EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'counsel'
AND tablename IN ('app_user', 'session', 'module_moderator')) THEN
AND tablename IN ('app_user', 'session', 'module_permission',
'module_moderator')) THEN
RAISE EXCEPTION 'a local copy of an identity table came back';
END IF;
IF EXISTS (SELECT 1 FROM pg_constraint c JOIN pg_class t ON t.oid = c.confrelid
+35 -8
View File
@@ -34,8 +34,10 @@ hostname ever said `scorecard`; don't reintroduce it.
**Where the platform is today:** one origin, four paths, and **one account**. With
`IDENTITY_SCHEMA=dredd` this app has no accounts of its own: `app_user`, `session` and
`module_moderator` live in a neutral schema the hub owns and every module reads, so signing in once
at `/atrium` signs you in here — same origin, same cookie, same `session` row, no handoff. Standalone
`module_permission` live in a neutral schema the hub owns and every module reads, so signing in once
at `/atrium` signs you in here — same origin, same cookie, same `session` row, no handoff. Being
signed in is not being let in: **no `module_permission` row naming `counsel` means no entry**, and
that is decided once, in `deps.get_current_user`. Standalone
at the origin root stays supported and is the **default** (`ROOT_PATH` and `IDENTITY_SCHEMA` empty,
this repo's own `docker-compose.yml` and `Caddyfile`), and platform mode must never become a code
fork of it: every default reproduces the standalone behaviour, and `settings.shares_identity` is the
@@ -57,6 +59,9 @@ backend/alembic/ env + 0001 (create_enum_types + create_all: dredd-core core +
+ 0002_runtime_grants (dredd-core runtime_grants_sql for DB_APP_ROLE)
+ 0003_user_role_admin_removed (native enum swap: `admin` leaves `user_role`)
+ 0004_shared_identity (the cutover; a no-op unless IDENTITY_SCHEMA is set)
+ 0005_module_permission (module_moderator -> module_permission + role, for a
database whose 0001 ran under a v0.10.x core; the MIRROR of 0004 — a no-op
when IDENTITY_SCHEMA *is* set, since the table is then the hub's)
backend/tests/ unit (DB-free) + integration (Postgres)
backend/scripts/license_gate.py
frontend/index.html the entire admin console (one static file, no build)
@@ -170,10 +175,10 @@ Backend:
- **PG 16 + 17:** CI runs the suite on both, plus the `managed-db` job (emulate → provision → migrate →
tests as `counsel_app` → `managed check` with isolation) on 17.
- **One platform, one account — and this module is a READER of identity, never a writer.** With
`IDENTITY_SCHEMA` set, `app_user` / `session` / `module_moderator` live in the shared schema the
`IDENTITY_SCHEMA` set, `app_user` / `session` / `module_permission` live in the shared schema the
hub owns. `counsel_app` holds `SELECT` on seven columns of `app_user` (never `password_hash`,
`failed_login_count` or `locked_until`), `SELECT` plus `UPDATE (last_seen_at, expires_at,
revoked_at)` on `session`, `SELECT` on `module_moderator`, and nothing else in that schema. Three
revoked_at)` on `session`, `SELECT` on `module_permission`, and nothing else in that schema. Three
things follow, and each is refused **at the edge** so a missing grant never surfaces as a 500 on
an ordinary screen (`services/auth.POLICY`, from `AuthPolicy.identity_writes_enabled` /
`local_login_enabled` / `app_tokens_enabled`):
@@ -186,20 +191,35 @@ Backend:
legitimate `is_admin` write in the repo, and it is standalone-only).
- **app tokens: list and revoke here, mint in the hub** (`POST /api/v1/me/modules/counsel/tokens`,
still `counsel_pat_`).
- **No row means no entry, and that is the point of `module_permission`.** One row per person per
module in the shared schema, with a `role` — so there are **four** answers and the first is the
absence of a row: *no row* = no access to Counsel at all; `user` = may use it; `moderator` = may
use **and** administer it; `app_user.is_admin` = ADMINISTRATOR, platform-wide, everything
everywhere, no row needed. Enforced **once**, in `deps.get_current_user`
(`moderation.assert_may_use`, right after the token-scope check) — every authenticated route
depends on it, so no route can forget it and the three `require_*` helpers need no change:
`require_role` is a pure domain-role check and takes no `db` precisely because admission was
settled at the edge. Before this, a stranger with a platform account could open every screen here
and merely see nothing, which is not an access decision. **Standalone it refuses nobody** — core
answers `user` for everybody where there is no platform, and emits no SQL — which is what lets one
guard serve both shapes. Granting is Atrium's, always: this app holds `SELECT` on that table and
no `INSERT`, so it can neither admit anyone nor promote anyone, itself least of all.
- **Two tiers, two words, used verbatim: ADMINISTRATOR is platform-wide (`app_user.is_admin`),
MODERATOR is one module (a `module_moderator` row naming `counsel`).** Both are granted in Atrium;
MODERATOR is one module (a `role = 'moderator'` row in `module_permission` naming `counsel`).**
Both are granted in Atrium;
this app reads them through `services/moderation.py` and `deps.require_moderator` /
`require_moderator_or_role`. **This module defines no `require_administrator` and must not** — a
module route guarded by the platform-wide tier would be a module deciding who runs the platform.
Counsel has no node tree, so the projection is flat: *a moderator of `counsel` holds every power
`UserRole.admin` used to hold*. It does NOT lift separation of duties — submitting an evaluation
still needs `matter_owner`.
still needs `matter_owner`. Counsel also has no `authz.bind_moderation` call, and must not grow
one: there is no role ladder and no tree here for the tier to project onto.
- **`MODULE_SLUG` is `counsel`, and it is the one name the hub has to spell the same way.** The
catalogue entry, `POST /admin/modules/<slug>/moderators`, `POST /me/modules/<slug>/tokens` and the
`<slug>_pat_` stamp are all keyed by it, in Atrium's repository, by hand. A mismatch is **silent**:
this module only ever `SELECT`s `module_moderator` WHERE `module_slug` = its own name, so a grant
this module only ever `SELECT`s `module_permission` WHERE `module_slug` = its own name, so a grant
written against another spelling does not error, it simply never matches — the administrator sees
the delegation succeed and the person stays unprivileged for ever. (It happened: the catalogue
the delegation succeed and the person is now refused at the door. (It happened: the catalogue
said `counsel-scorecard` while this app answered to `counsel`, so moderator grants and hub-minted
tokens both went nowhere.) It is the same word as the schema, both role names, the URL path and
the cookie — never `scorecard`, never the hyphenated display name, which belongs to the Python
@@ -231,6 +251,13 @@ Backend:
ordinary route but not a downgrade run with `IDENTITY_SCHEMA` merely unset, which is why the
guard is on the database rather than on a setting. Any future revision naming a bare identity
table inherits the same hazard.
- **Never change what `0001` creates without a follow-up revision for databases migrated before.**
`0001` builds from `Base.metadata`, so a core bump silently changes what a *fresh* database gets
and reaches no existing one — `0001` is stamped and never runs again. Renaming
`module_moderator` to `module_permission` in dredd-core v0.11.0 is exactly that, and `0005` is the
follow-up: a catalog check in the app's own schema, then rename-or-create, idempotent. The
symptoms of skipping it all arrive far from the cause (a query for a relation that does not
exist, on an ordinary screen), which is why this is a rule and not a judgement call.
- Argon2id hashing + app-level login lockout (`LOGIN_MAX_ATTEMPTS`/`LOGIN_LOCKOUT_MINUTES`).
- Server-side sessions (`session` table) so logout/deactivate is an instant kill-switch.
- **The session cookie is `Path=/`, `HttpOnly`, `SameSite=Lax`, `Secure` auto-detected from the
+29 -10
View File
@@ -81,7 +81,7 @@ It's the real [`frontend/index.html`](frontend/index.html) with a lightweight mo
|---|---|
| **PostgreSQL + Full-Text Search** | PostgreSQL 16 with generated `tsvector` columns + **GIN** indexes on `firm`, `matter`, `question`, `response`; `pg_trgm` trigram fuzzy fallback; one `GET /api/v1/search` endpoint. |
| **Generic questionnaire engine** | `question` → `answer_option` (possible answers) → `questionnaire` + `questionnaire_question` (grouped, weighted set) → `response` → `response_item` → `response_revision` (**append-only history**). Questions/answers/weights are data, not code. |
| **Role controls (RBAC)** | Two questions, kept apart. What you DO here is `user_role` (`legal_ops` / `matter_owner` / `viewer`) on Counsel's own side table. Whether you ADMINISTER this module is a platform tier — an administrator, or a moderator of `counsel` — granted in the hub and only read here. Server-side sessions give an instant kill-switch. |
| **Role controls (RBAC)** | Three questions, kept apart. Whether you may OPEN this module at all is a `module_permission` row naming `counsel` — no row, no entry — granted in the hub. Whether you ADMINISTER it is that row's `role` (`moderator`), or the platform-wide administrator. What you DO here is `user_role` (`legal_ops` / `matter_owner` / `viewer`) on Counsel's own side table. Server-side sessions give an instant kill-switch. |
| **Observability** | OpenTelemetry SDK → **OTel Collector** → **ClickHouse** → **HyperDX** unified UI (metrics + logs + traces on one screen). Opt-in. |
| **Audit & least-privilege** | Append-only `audit_log` (runtime role has no `UPDATE`/`DELETE`); separate `migrator` (DDL) and `app` (DML-only) DB roles; Postgres never published to the host. |
| **Scoring & fairness** | `present_i` weighted mean with per-evaluation **materiality weighting** (complexity/value bands); constrained-choice evaluations excluded; firms below `min_evaluations` stay `provisional`. |
@@ -370,9 +370,9 @@ All via `.env` (copy from `.env.example`; it's git-ignored). Keys you'll set:
| `FORWARDED_ALLOW_IPS` | upstream IPs uvicorn trusts for `X-Forwarded-For`, so the real client IP reaches the audit log |
| `BASE_CURRENCY` | instance base currency (stored in `app_setting`) |
| `BOOTSTRAP_ADMIN_EMAIL` / `_PASSWORD` | first administrator, created idempotently by the seed. Standalone only: on the platform the account comes from the hub and the seed skips it |
| `IDENTITY_SCHEMA` | empty (default) = Counsel owns its accounts. Set (`dredd`) = a module of the platform: one account, one cookie, no sign-in here |
| `IDENTITY_SCHEMA` | empty (default) = Counsel owns its accounts. Set (`dredd`) = a module of the platform: one account, one cookie, no sign-in here, and access to this module decided by a `module_permission` row |
| `SESSION_COOKIE_NAME` | the cookie's name (`counsel_session`; `dredd_session` on the platform, where all four modules read one cookie) |
| `MODULE_SLUG` | this module's name on the platform (`counsel`) — what a moderator grant names, what the hub's catalogue must call this app, and what a token the hub mints for it is stamped with (`counsel_pat_`). Set explicitly in `.env.example` rather than left to the default, because a mismatch with the catalogue is silent: this app only ever reads `module_moderator` by its own name, so a grant spelled differently never matches and nothing anywhere reports it |
| `MODULE_SLUG` | this module's name on the platform (`counsel`) — what a grant of access names, what the hub's catalogue must call this app, and what a token the hub mints for it is stamped with (`counsel_pat_`). Set explicitly in `.env.example` rather than left to the default, because a mismatch with the catalogue is silent: this app only ever reads `module_permission` by its own name, so a grant spelled differently never matches, nothing anywhere reports it, and the person stays locked out |
| `LOGIN_MAX_ATTEMPTS` / `LOGIN_LOCKOUT_MINUTES` | brute-force lockout (defaults `5` / `15`) |
| `CORS_ALLOW_ORIGINS` | comma-separated origins for a separately-served admin console (empty = same-origin only) |
| `OTEL_ENABLED` | turn OTLP export on/off (off → backend runs standalone) |
@@ -383,19 +383,30 @@ All via `.env` (copy from `.env.example`; it's git-ignored). Keys you'll set:
## RBAC
Two separate questions, and keeping them separate is the point.
Three separate questions, and keeping them separate is the point.
**Whether you may open Counsel at all** is the first, and on the platform it is not implied by being
signed in: one account spans four modules, so a session says who you are and nothing about where you
may go. Access is a row in the shared `module_permission` table naming `counsel` — `user` (may use
it) or `moderator` (may use *and* administer it) — and **no row means no entry**, refused once at the
edge (`deps.get_current_user`) rather than shown as an empty screen. Standalone there is one app and
nothing to be admitted to, so everybody with an account may use it, exactly as before.
**Who administers Counsel** is a platform tier, not a role in this app: an **administrator**
(platform-wide) or a **moderator of `counsel`** (this module only). Both are granted in the hub, and
this app can only read them — `counsel_app` holds `SELECT` on the tier table and nothing else, so a
compromised Counsel cannot promote anybody, itself included. Standalone, with no platform, the tier
is simply the account's `is_admin`, which the seed gives the bootstrap administrator.
(platform-wide `app_user.is_admin`, who needs no row anywhere) or a **moderator of `counsel`** (this
module only). Both are granted in the hub, and this app can only read them — `counsel_app` holds
`SELECT` on that table and nothing else, so a compromised Counsel can neither admit anybody nor
promote anybody, itself included. Standalone, with no platform, the tier is simply the account's
`is_admin`, which the seed gives the bootstrap administrator.
**What you do here** is `user_role` on `counsel_user_profile`, Counsel's own side table. There used
to be an `admin` value in it; it was deleted (revision `0003`) because the app kept the shared
`app_user.is_admin` in step with it — the one place in the family where a module minted a
platform-wide administrator.
Everything in the table below assumes the first question was answered yes; without a
`module_permission` row (or the administrator flag) none of these rows is reachable at all.
| Action | administrator / moderator | legal_ops | matter_owner | viewer |
|---|:--:|:--:|:--:|:--:|
| Manage Counsel roles | ✅ | — | — | — |
@@ -508,7 +519,7 @@ session cookie is already `Path=/`, so it travels with every path under the orig
### One account, one sign-in
Set `IDENTITY_SCHEMA=dredd` and this app stops having accounts of its own. `app_user`, `session` and
the moderator table live in a neutral schema the hub owns and every module reads, so signing in once
`module_permission` live in a neutral schema the hub owns and every module reads, so signing in once
at `/atrium` signs you in here — the browser sends the same cookie to the same origin, and this app
resolves the same `session` row. There is no handoff to configure: no signed assertion, no audience
binding, no second password. Set `SESSION_COOKIE_NAME=dredd_session` at the same time so all four
@@ -527,9 +538,17 @@ What changes for this app, all of it enforced by the database rather than by a h
`counsel_user_profile`;
* **app tokens are listed and revoked here, minted in the hub**
(`POST /api/v1/me/modules/counsel/tokens`, still stamped `counsel_pat_`), for the same reason;
* **being signed in is not being let in.** Access to this module is a `module_permission` row naming
`counsel`, granted in Atrium, and **no row means no entry** — checked once, in
`deps.get_current_user`, for every authenticated route. Before it, a stranger with a platform
account could open every screen here and merely find them empty, which is not an access decision.
A module holds `SELECT` on that table and no `INSERT`, so it can neither admit anyone nor promote
anyone, least of all itself;
* **revision `0004` merges this schema's people into the shared store**, matching on lower-cased
e-mail and re-pointing every row that named the local id. See it for exactly what happens to the
live `admin@example.com`.
live `admin@example.com`. **Revision `0005`** is its mirror for the standalone shape: it renames
this schema's own `module_moderator` to `module_permission` and adds the `role` column, for a
database whose `0001` ran while a v0.10.x core was pinned.
Standalone is unchanged and stays the default: leave `IDENTITY_SCHEMA` empty and Counsel owns its
accounts, serves its own sign-in and behaves as it always has. It is the same code either way.
@@ -16,8 +16,10 @@ so minting a "Counsel admin" here minted an administrator of Atrium, Galena and
the only place in the family where a module made a platform-wide administrator, and it is gone.
What replaces it is a tier the module reads and cannot write: an ADMINISTRATOR (platform-wide
``is_admin``) or a MODERATOR of ``counsel`` (a row in the shared ``module_moderator``, granted in
Atrium). ``services/moderation.py`` explains what that means in a flat model with no node tree.
``is_admin``) or a MODERATOR of ``counsel`` (a ``role = 'moderator'`` row in the shared table,
granted in Atrium). ``services/moderation.py`` explains what that means in a flat model with no node
tree. (That table was called ``module_moderator`` when this revision was written and is
``module_permission`` since dredd-core v0.11.0 — see ``0005``.)
This revision is **not** part of the shared-identity cutover and does not depend on it. It runs the
same way on a standalone Counsel, where the tier is simply ``is_admin`` and the administrator is
@@ -113,10 +113,13 @@ depends_on: str | Sequence[str] | None = None
log = logging.getLogger("alembic.runtime.migration")
#: Local tables to drop once their rows have been merged, children before parents.
#: ``module_moderator`` arrives on ``Base.metadata`` with dredd-core v0.10.0, so a database whose
#: ``0001`` ran after that bump has a local one and a database migrated before it has none — which
#: is why every drop is IF EXISTS rather than a list somebody has to keep in step with a version.
_LOCAL_TABLES = ("module_moderator", "session", "app_user")
#: The module tier arrives on ``Base.metadata`` with dredd-core v0.10.0 and is RENAMED by v0.11.0
#: (``module_moderator`` → ``module_permission``), so which of the two a database has — or neither —
#: depends entirely on which core was pinned the day its ``0001`` ran. Both names are listed, and
#: every drop is IF EXISTS, rather than keeping a list in step with a version: ``0005`` does the
#: rename but runs AFTER this, so on the platform the cutover still meets the old name on a database
#: migrated before the bump, and the new one on anything migrated since.
_LOCAL_TABLES = ("module_permission", "module_moderator", "session", "app_user")
def _ident(value: str, what: str) -> str:
@@ -510,7 +513,7 @@ def upgrade() -> None:
# There is deliberately no grant block here, of either kind.
#
# The reader tier this app runs on - SELECT on seven columns of app_user, SELECT plus UPDATE of
# three session columns, SELECT on module_moderator, and nothing else anywhere in that schema -
# three session columns, SELECT on module_permission, and nothing else anywhere in that schema -
# is granted by the schema's OWNER, in the hub's own revision. A GRANT by anyone else is a
# warning rather than an error, so attempting it here would produce a migration that looks
# successful and changes nothing.
@@ -0,0 +1,250 @@
"""The module tier becomes a module PERMISSION: ``module_moderator`` is renamed and gains a role.
Revision ID: 0005_module_permission
Revises: 0004_shared_identity
Create Date: 2026-09-29
dredd-core v0.11.0 replaces ``module_moderator`` with ``module_permission``: the same one row per
person per module, plus a ``role`` column — and with it the answer this family did not have::
no row no access to this module at all
role = 'user' may use it
role = 'moderator' may use it AND administer it
Before it, anyone with an account could type ``/counsel`` and be let in. They saw an empty screen
and every write was refused, but nothing had *refused them*, and "you can see nothing" is not an
access decision. ``deps.get_current_user`` makes it one (``moderation.assert_may_use``, immediately
after the token-scope check); this revision is the table that guard reads.
Why a revision at all, when the model already says so
-----------------------------------------------------
Because ``0001`` has already run — on the live box and on every developer database. It builds from
``Base.metadata``, so a database migrated while a v0.10.x core was pinned has a table called
``module_moderator`` in this schema, and renaming the class does not reach it: ``0001`` is stamped
and will never run again. Nothing reports the mismatch, either. The symptoms arrive later and
nowhere near the cause — a query for ``module_permission`` failing with *relation does not exist* on
an ordinary screen, and a cutover trying to drop a table that is not there.
That is precisely the ``node_kind`` failure the family already paid for once, and the rule it left
behind: **never change what ``0001`` creates without a follow-up revision for databases migrated
before.**
Standalone and platform
-----------------------
This is the STANDALONE half, and the mirror of ``0004``: that revision runs only when
``IDENTITY_SCHEMA`` is set, this one only when it is not. On the platform the three identity tables
belong to the hub, ``0004`` has just dropped this schema's local copies, and creating one here would
be exactly the shadow table ``assert_identity_schema`` exists to catch — a second, invisible roster
that the ``search_path`` reaches first. So on a module there is nothing here to do, and nothing is
done.
Three states, one catalog check
-------------------------------
Whether this database has the old table, the new one, or neither cannot be known from outside it: it
depends on which core was pinned the day ``0001`` ran. So the decision is made in the database, by
``to_regclass``, inside one statement — which also keeps ``alembic upgrade --sql`` honest, since an
offline render has no connection to ask and must emit SQL that decides for itself.
"""
from __future__ import annotations
from collections.abc import Sequence
from dredd_core.identity import MODULE_ROLES
from dredd_core.moderation import MODERATOR, USER
from sqlalchemy.dialects import postgresql
from sqlalchemy.schema import CreateIndex, CreateTable
from alembic import op
from app.config import get_settings
from app.models import Base
revision: str = "0005_module_permission"
down_revision: str | None = "0004_shared_identity"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
#: Old name → new name for everything PostgreSQL does *not* carry along with the table.
#: ``ALTER TABLE ... RENAME TO`` renames the table and nothing else, so its constraints and its one
#: index keep names built from the old one. That is cosmetic — a constraint enforces the same rule
#: under either name — which is why each rename below is skipped rather than demanded when it is
#: missing. It is done at all because the day a later revision says
#: ``DROP CONSTRAINT ck_module_permission_role`` against a database whose copy is still called
#: ``ck_module_moderator_role``, it fails for a reason nobody will guess from the message.
_RENAMES: tuple[tuple[str, str], ...] = (
("pk_module_moderator", "pk_module_permission"),
("uq_module_moderator_user_module", "uq_module_permission_user_module"),
("ck_module_moderator_slug", "ck_module_permission_slug"),
("fk_module_moderator_user_id_app_user", "fk_module_permission_user_id_app_user"),
("fk_module_moderator_created_by_app_user", "fk_module_permission_created_by_app_user"),
)
def _pairs(*, reverse: bool = False) -> str:
"""``_RENAMES`` as the body of a two-dimensional SQL array literal, either way round."""
return ",\n".join(
" ARRAY['" + (new if reverse else old) + "', '" + (old if reverse else new) + "']"
for old, new in _RENAMES
)
def _ddl() -> str:
"""The statements ``0001`` emits for this table today, rendered from ``Base.metadata``.
Written out by hand they would be a second description of the same table, free to drift from
the model the day core adds a column. Rendered, the "create it" branch below *is* by
construction the table ``create_all`` would have built — server defaults, both CHECKs and both
foreign keys included.
Each statement is flattened onto one line and dollar-quoted with a tag of its own, because it is
about to be a string literal inside another dollar-quoted body.
"""
dialect = postgresql.dialect()
table = Base.metadata.tables["module_permission"]
elements = [CreateTable(table), *(CreateIndex(index) for index in table.indexes)]
return ",\n".join(
" $counsel_ddl$" + " ".join(str(element.compile(dialect=dialect)).split())
+ "$counsel_ddl$"
for element in elements
)
#: The two role names as they appear INSIDE a quoted SQL string — doubled, because every statement
#: below is assembled as a literal and handed to ``EXECUTE``. Rendered from core's own constants so
#: the column default, the backfill and the CHECK cannot drift from what ``create_all`` writes.
_USER = "''" + USER + "''"
_MODERATOR = "''" + MODERATOR + "''"
_ROLE_VALUES = ", ".join("''" + role + "''" for role in MODULE_ROLES)
# No percent sign and no colon-name sequence anywhere below, comments included: `op.execute` wraps
# the string in `text()`, which scans all of it, and a comment quoting that very rule has already
# killed a migration on its first live run elsewhere in this family. `tests/test_identity_unit.py`
# asserts it. (The table's own slug CHECK carries braces, which is why the DDL arrives through
# `.format()` as an argument rather than sitting in the template: format reads the template only.)
_UPGRADE = """
DO $counsel_module_permission$
DECLARE
own text := current_schema();
pair text[];
stmt text;
renames text[] := ARRAY[
{renames}
];
creates text[] := ARRAY[
{creates}
];
BEGIN
-- Already what the model describes: a database created since the bump, or this revision run
-- twice. Nothing to do, and answering that first is what makes the whole block idempotent.
IF to_regclass(quote_ident(own) || '.module_permission') IS NOT NULL THEN
RETURN;
END IF;
-- Neither table: a database whose 0001 ran before core had one at all. Build it.
IF to_regclass(quote_ident(own) || '.module_moderator') IS NULL THEN
FOREACH stmt IN ARRAY creates LOOP
EXECUTE stmt;
END LOOP;
RETURN;
END IF;
-- The case this revision exists for: the live shape, carrying the v0.10.x table.
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_moderator RENAME TO module_permission';
FOREACH pair SLICE 1 IN ARRAY renames LOOP
IF EXISTS (SELECT 1 FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE n.nspname = own AND t.relname = 'module_permission'
AND c.conname = pair[1]) THEN
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission RENAME CONSTRAINT '
|| quote_ident(pair[1]) || ' TO ' || quote_ident(pair[2]);
END IF;
END LOOP;
IF to_regclass(quote_ident(own) || '.ix_module_moderator_module_slug') IS NOT NULL THEN
EXECUTE 'ALTER INDEX ' || quote_ident(own) || '.ix_module_moderator_module_slug'
|| ' RENAME TO ix_module_permission_module_slug';
END IF;
-- The lesser role is the default, here as in the model: an INSERT that forgets to name one
-- admits a user, never a moderator.
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|| 'ADD COLUMN role varchar(20) NOT NULL DEFAULT {user}';
-- And then the statement that carries the old table's meaning across: EVERY row that existed was
-- a moderator grant, because there was no other kind. Leaving them at the column default would
-- silently demote every moderator the platform has ever appointed - and nothing would report it;
-- they would simply stop being able to administer their own module. The branch above guarantees
-- this runs on a table whose role column was added one statement ago, so there is no genuine
-- 'user' row for it to overwrite.
EXECUTE 'UPDATE ' || quote_ident(own) || '.module_permission SET role = {moderator}';
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission ADD CONSTRAINT '
|| 'ck_module_permission_role CHECK (role IN ({roles}))';
END
$counsel_module_permission$
"""
_DOWNGRADE = """
DO $counsel_module_permission_undo$
DECLARE
own text := current_schema();
pair text[];
renames text[] := ARRAY[
{renames}
];
BEGIN
IF to_regclass(quote_ident(own) || '.module_permission') IS NULL THEN
RETURN;
END IF;
-- The one thing a downgrade here must not do quietly. Under the old table a row meant MODERATOR,
-- full stop - there was no column to say otherwise. So a 'user' row carried back would promote
-- everyone merely admitted to this module into someone who administers it: a widening, on a
-- rollback, with nothing anywhere recording that it happened. They lose their access instead,
-- which an administrator can grant again in the hub.
EXECUTE 'DELETE FROM ' || quote_ident(own) || '.module_permission '
|| 'WHERE role <> {moderator}';
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|| 'DROP CONSTRAINT IF EXISTS ck_module_permission_role';
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission DROP COLUMN IF EXISTS role';
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission RENAME TO module_moderator';
FOREACH pair SLICE 1 IN ARRAY renames LOOP
IF EXISTS (SELECT 1 FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE n.nspname = own AND t.relname = 'module_moderator'
AND c.conname = pair[1]) THEN
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_moderator RENAME CONSTRAINT '
|| quote_ident(pair[1]) || ' TO ' || quote_ident(pair[2]);
END IF;
END LOOP;
IF to_regclass(quote_ident(own) || '.ix_module_permission_module_slug') IS NOT NULL THEN
EXECUTE 'ALTER INDEX ' || quote_ident(own) || '.ix_module_permission_module_slug'
|| ' RENAME TO ix_module_moderator_module_slug';
END IF;
END
$counsel_module_permission_undo$
"""
_MODULE_PERMISSION = _UPGRADE.format(renames=_pairs(), creates=_ddl(), user=_USER,
moderator=_MODERATOR, roles=_ROLE_VALUES)
_UNDO = _DOWNGRADE.format(renames=_pairs(reverse=True), moderator=_MODERATOR)
def upgrade() -> None:
if get_settings().shares_identity:
# A module of the platform: these tables are the hub's, 0004 has just dropped this schema's
# copies of them, and a local one built here would be the shadow that gives this app a
# second roster nobody can see. Not a skipped step - there is nothing here to rename.
return
op.execute(_MODULE_PERMISSION)
def downgrade() -> None:
"""Back to the v0.10.x shape, minus the rows that shape cannot express (see ``_DOWNGRADE``)."""
if get_settings().shares_identity:
return
op.execute(_UNDO)
+20
View File
@@ -209,6 +209,22 @@ def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser
# read-scoped app token may read but never write.
if credential.scope == TokenScope.read.value and request.method.upper() not in SAFE_METHODS:
raise AuthorizationError("This app token is read-only; it cannot make changes.")
# And, for exactly that reason, the other question every authenticated route has to ask: may
# this person open Counsel at all? A signed-in account is a PLATFORM account — one identity
# across the four modules — so holding a session says nothing about being admitted to this one.
# Admission is a `module_permission` row naming `counsel`, granted in the hub, and NO ROW MEANS
# NO ENTRY. Until this line a stranger with an account could reach every screen here: they saw
# nothing and could write nothing, but nothing had refused them, and "you can see nothing" is
# not an access decision.
#
# It belongs at the edge rather than in the three guards below, because all three depend on
# this function — so it covers them and no future route can forget it. `require_role` stays a
# pure DOMAIN-role check and needs no `db` precisely because admission is settled here;
# `require_moderator` asks a strictly narrower question (the moderator role, or the
# administrator); and `require_moderator_or_role`'s domain-role branch is now reachable only by
# someone already admitted. Standalone it refuses nobody and costs nothing: with no platform to
# be admitted to, core answers "user" for everybody and emits no SQL at all.
moderation.assert_may_use(db, user)
return user
@@ -220,6 +236,10 @@ def require_role(*roles: UserRole):
whoever administers Counsel must not be able to score the firms they oversee — separation of
duties, and it predates the tier (``UserRole.admin`` could not submit either). Use
``require_moderator_or_role`` wherever administering the module *should* be enough.
It takes no ``db``, and that is not an omission: whether this person may open Counsel at all is
settled once in ``get_current_user``, which this guard depends on. What is left here is the
domain role, which lives on ``counsel_user_profile`` and is already loaded with the user.
"""
allowed: set[UserRole] = set(roles)
+4 -1
View File
@@ -203,7 +203,10 @@ def seed(db: Session) -> None:
else:
admin = AppUser(
email=settings.bootstrap_admin_email,
full_name="Bootstrap Admin",
# "Administrator", as Atrium, Galena and Sygna all seed it. Standalone it makes no
# difference; on the platform a fresh install would otherwise be the one account
# whose name differs from its siblings' for no reason anyone can explain later.
full_name="Administrator",
password_hash=hash_password(settings.bootstrap_admin_password),
is_admin=True,
)
+41 -18
View File
@@ -1,20 +1,27 @@
"""The two administration tiers, bound to this app's policy — and what they mean in a FLAT model.
"""Who may open Counsel, and who may administer it — the tiers, in a FLAT model.
dredd-core owns both tiers (``dredd_core.moderation``); like ``services/auth.py`` this module only
maps Counsel's settings onto the core policy and re-exposes the two questions this app actually
asks. The tiers, in the family's words, used verbatim everywhere:
dredd-core owns all of this (``dredd_core.moderation``); like ``services/auth.py`` this module only
maps Counsel's settings onto the core policy and re-exposes the questions this app actually asks.
One row per person per module, in the shared ``module_permission`` table, and **four** answers —
the first of which is the absence of a row:
* **ADMINISTRATOR** — platform-wide, every module plus the hub. It is ``app_user.is_admin``.
* **MODERATOR** — exactly one module. It is a ``module_moderator`` row naming ``counsel``.
* **no row** — no access to Counsel at all. The default for everybody, and the whole reason that
table exists. Enforced once, in ``deps.get_current_user``, via :func:`assert_may_use`.
* **USER** (``role = 'user'``) — may use Counsel.
* **MODERATOR** (``role = 'moderator'``) — may use it AND administer it.
* **ADMINISTRATOR** — platform-wide, every module plus the hub. It is ``app_user.is_admin``, a flag
on the person rather than a row about a module, and it needs no row anywhere.
An administrator is a moderator of everything by definition; a moderator is nothing outside their
own module. **Neither can be granted or revoked from inside Counsel**: the shared
``module_moderator`` table is granted to this app ``SELECT`` and nothing else, so the enforcement is
a missing INSERT, not a hidden menu item. Both are granted in Atrium, where each grant is audited.
own module. **None of it can be granted or revoked from inside Counsel**: the shared
``module_permission`` table is granted to this app ``SELECT`` and nothing else, so the enforcement
is a missing INSERT, not a hidden menu item. Access is granted in Atrium, where each one is audited.
Standalone (``IDENTITY_SCHEMA`` empty) there is no platform for a per-module moderator to exist in,
so ``is_moderator`` is exactly ``user.is_admin`` and emits no SQL at all — the same behaviour this
app has always had, reached by the same code path.
Standalone (``IDENTITY_SCHEMA`` empty) there is no platform to be admitted to — there is one app —
so core answers ``"user"`` for everyone and ``"moderator"`` for an administrator, emitting no SQL at
all. ``assert_may_use`` is therefore a no-op there, and ``is_moderator`` is exactly
``user.is_admin``: the same behaviour this app has always had, reached by the same code path. That
is what lets one guard sit at the edge of both deployments.
What moderator means here, and why that is not quite what it means in Galena or Sygna
-------------------------------------------------------------------------------------
@@ -55,15 +62,31 @@ _settings = get_settings()
service = ModerationService(ModerationPolicy(
module_slug=_settings.module_slug,
# Off until this deployment is part of a platform. Core then returns `user.is_admin` and never
# touches `module_moderator` — which is also the only correct answer, since a standalone
# database has no such table to read.
shared_moderators=_settings.shares_identity,
# Never true in a module. A module that could write this table could make itself a moderator.
moderator_writes_enabled=False,
# Off until this deployment is part of a platform. Core then answers "user" for everybody (and
# "moderator" for an administrator) and never touches `module_permission` — which is also the
# only correct answer, since a standalone database has no shared table to read.
shared_permissions=_settings.shares_identity,
# Never true in a module. A module that could write this table could admit itself, or promote
# itself to moderator of itself.
permission_writes_enabled=False,
))
def may_use(db: Session, user: AppUser) -> bool:
"""May `user` open Counsel at all — either role, or the platform administrator?"""
return service.may_use(db, user)
def assert_may_use(db: Session, user: AppUser) -> AppUser:
"""Return `user`, or raise ``AuthorizationError``. Behind ``deps.get_current_user``.
The guard that makes the table mean anything, and it belongs at the edge, where a signed-in
person first reaches this module. Without it Counsel still shows a stranger nothing and still
refuses every write — but by accident, one empty result at a time, rather than by decision.
"""
return service.assert_may_use(db, user)
def is_moderator(db: Session, user: AppUser) -> bool:
"""May `user` administer Counsel — as a platform administrator, or as a moderator of it?"""
return service.is_moderator(db, user)
+11 -1
View File
@@ -20,7 +20,17 @@
# grants already made the same two checks, but 0002 is only reached once 0001 has succeeded, so as the
# wrong role Counsel built every table first and nothing but Alembic's transaction undid it.
# Required, not optional: 0001 imports it.
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.10.2
#
# v0.11.0 is the second half of "one account": `module_moderator` becomes `module_permission`, one
# row per person per module carrying a `role` of 'user' or 'moderator' — and NO ROW MEANS NO ACCESS
# to that module. That fourth answer is the whole change: until it, anyone with a platform account
# could open any module and merely see nothing, which is not an access decision.
# `deps.get_current_user` now calls `moderation.assert_may_use`, `services/moderation.py` renames
# the two policy flags (`shared_permissions` / `permission_writes_enabled`), and
# `alembic/versions/0005_module_permission.py` carries the rename to databases whose 0001 ran under
# v0.10.x. A STANDALONE Counsel is unchanged: with no platform to be admitted to, core answers
# "user" for everybody and emits no SQL at all.
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.11.0
# Web framework
fastapi==0.136.3
+158 -11
View File
@@ -166,43 +166,108 @@ def test_a_module_of_the_platform_neither_writes_accounts_nor_signs_anyone_in():
def test_the_moderator_tier_is_inert_without_a_platform():
"""Standalone, `is_moderator` is exactly `is_admin` and emits no SQL.
A `db` that raises if it is touched proves the second half: there is no `module_moderator`
A `db` that raises if it is touched proves the second half: there is no `module_permission`
table in a standalone database, so a query for one would be a 500 on every guarded screen. The
slug is still set, because it is what this module is CALLED on the platform, not a mode.
"""
service = _bound_under("app.services.moderation", "service")
assert service.policy.shared_moderators is False
assert service.policy.shared_permissions is False
assert service.policy.module_slug == "counsel"
assert service.policy.moderator_writes_enabled is False # never, in a module
assert service.policy.permission_writes_enabled is False # never, in a module
class _NoDB:
info: dict = {}
def scalar(self, *a, **k): # pragma: no cover - the point is that it is never called
raise AssertionError("standalone must not query for moderators")
raise AssertionError("standalone must not query for permissions")
assert service.is_moderator(_NoDB(), SimpleNamespace(id=1, is_admin=True)) is True
assert service.is_moderator(_NoDB(), SimpleNamespace(id=2, is_admin=False)) is False
def test_admission_refuses_nobody_on_a_standalone_install():
""""No row means no entry" must not lock a standalone Counsel out of itself.
`deps.get_current_user` calls `assert_may_use` for every authenticated request in BOTH shapes —
that is the point of putting it at the edge rather than behind a branch. What makes that safe
here is core's answer where there is no platform: everybody is a `user` of the one app there is,
decided without a query. A `db` that raises if it is touched proves the second half.
"""
service = _bound_under("app.services.moderation", "service")
class _NoDB:
info: dict = {}
def scalar(self, *a, **k): # pragma: no cover - the point is that it is never called
raise AssertionError("standalone must not query for permissions")
ordinary = SimpleNamespace(id=2, is_admin=False)
assert service.may_use(_NoDB(), ordinary) is True
assert service.assert_may_use(_NoDB(), ordinary) is ordinary
def test_the_moderator_tier_turns_itself_on_with_the_shared_identity_schema():
"""A per-module moderator is meaningless without a platform, so one setting decides both."""
"""A per-module permission is meaningless without a platform, so one setting decides both."""
service = _bound_under("app.services.moderation", "service", identity_schema="dredd")
assert service.policy.shared_moderators is True
assert service.policy.shared_permissions is True
assert service.policy.module_slug == "counsel"
def test_a_platform_account_with_no_row_for_counsel_is_refused_at_the_edge():
"""THE behaviour this whole change exists for, and the one that did not exist before it.
On the platform an account is one identity across four modules, so holding a session says
nothing about being admitted to this one. With no `module_permission` row naming `counsel` the
lookup returns None, and `assert_may_use` turns that into a refusal instead of an empty screen.
The administrator still needs no row — the tier is a flag on the person, not a row about a
module.
"""
from dredd_core.errors import AuthorizationError
service = _bound_under("app.services.moderation", "service", identity_schema="dredd")
class _EmptyDB:
"""The shared table, with nothing in it for this person."""
info: dict = {}
def scalar(self, *a, **k):
return None
stranger = SimpleNamespace(id=2, is_admin=False)
assert service.may_use(_EmptyDB(), stranger) is False
with pytest.raises(AuthorizationError):
service.assert_may_use(_EmptyDB(), stranger)
assert service.may_use(_EmptyDB(), SimpleNamespace(id=1, is_admin=True)) is True
def test_every_authenticated_route_asks_whether_this_person_may_open_counsel():
"""The guard is in `get_current_user`, which every authenticated route depends on.
Asserted on the source rather than through a request, because what matters is WHERE it sits:
moved into one of the three `require_*` helpers it would cover only the routes that happen to
use that one, and `require_role` — which takes no `db` — could not call it at all.
"""
source = (BACKEND / "app" / "deps.py").read_text(encoding="utf-8")
body = source.split("def get_current_user(", 1)[1].split("\ndef ", 1)[0]
assert "moderation.assert_may_use(db, user)" in body
# After the scope check, not before it: a read-only token making a write is refused as a token
# problem, which is what it is.
assert body.index("token is read-only") < body.index("moderation.assert_may_use")
# ── the one name two repositories have to agree on ───────────────────────────
#
# The slug is the only thing about this module the HUB also has to know, by hand, in its own
# repository: its catalogue keys a module by slug, `POST /admin/modules/<slug>/moderators` writes a
# `module_moderator` row naming it, and `POST /me/modules/<slug>/tokens` mints a credential stamped
# `module_permission` row naming it, and `POST /me/modules/<slug>/tokens` mints a credential stamped
# `<slug>_pat_`. Nothing downstream can catch a mismatch, because this module only ever SELECTs
# `module_moderator` WHERE module_slug = its OWN name: a grant written against another spelling does
# `module_permission` WHERE module_slug = its OWN name: a grant against another spelling does
# not error, it simply never matches — the administrator sees a delegation succeed and the person
# stays unprivileged for ever. (That is not hypothetical. The catalogue said `counsel-scorecard`
# while this module answered to `counsel`; moderator grants and hub-minted tokens both went nowhere,
# in silence, until someone drove both halves by hand.)
# in silence, until someone drove both halves by hand.) Since v0.11.0 the same mismatch is louder
# and earlier: a grant against the wrong spelling leaves the person with NO row for `counsel`, and
# they are refused at the door rather than admitted to an empty screen.
#
# A test in THIS repository cannot see the hub's catalogue. What it can do is make the slug a pinned
# fact rather than an incidental default, so that a rename has to be deliberate here and is then
@@ -449,7 +514,8 @@ def test_no_statement_in_the_cutover_carries_a_sequence_a_driver_would_eat():
placeholder — and it scans the whole statement, COMMENTS INCLUDED, which is exactly how a
comment quoting this rule once broke the migration that quoted it."""
for filename, name in (("0003_user_role_admin_removed.py", "counsel_rev_0003"),
("0004_shared_identity.py", "counsel_rev_0004")):
("0004_shared_identity.py", "counsel_rev_0004"),
("0005_module_permission.py", "counsel_rev_0005")):
module = _revision(filename, name)
for attr in dir(module):
value = getattr(module, attr)
@@ -503,7 +569,7 @@ def test_0004_moves_every_person_shaped_column_in_this_schema():
}
# The shared tables are not in it: their rows belong to the hub, and this revision drops the
# local copies rather than re-pointing them.
assert not {t for t, _ in columns} & {"app_user", "session", "module_moderator"}
assert not {t for t, _ in columns} & {"app_user", "session", "module_permission"}
def test_0004_drops_the_foreign_keys_before_it_moves_the_rows_and_re_adds_them_after(monkeypatch):
@@ -627,3 +693,84 @@ def test_0004_grants_nothing_and_matches_people_by_email(monkeypatch):
# It refuses rather than orphaning anyone, and the drop happens only after that proof.
assert "no account in dredd for" in joined
assert joined.index("no account in dredd for") < joined.index("DROP TABLE IF EXISTS")
# ── the rename `0001` cannot reach ───────────────────────────────────────────
def test_0005_follows_the_cutover_and_is_the_head_of_the_chain():
"""It has to come after 0004, not before: on the platform the cutover drops this schema's local
identity tables, and a rename that ran first would leave 0004 dropping a name that is no longer
there — which is why `_LOCAL_TABLES` lists BOTH spellings."""
module = _revision("0005_module_permission.py", "counsel_rev_0005")
assert (module.revision, module.down_revision) == ("0005_module_permission",
"0004_shared_identity")
cutover = _revision("0004_shared_identity.py", "counsel_rev_0004")
assert {"module_permission", "module_moderator"} <= set(cutover._LOCAL_TABLES)
def test_0005_does_nothing_at_all_on_a_module_of_the_platform(monkeypatch):
"""The mirror of 0004's rule, and the trap it avoids.
On the platform these tables are the hub's and 0004 has just dropped this schema's copies. The
"create it" branch would put one straight back — the shadow table `assert_identity_schema`
exists to catch, silently giving this module a second roster the `search_path` reaches first.
"""
module = _revision("0005_module_permission.py", "counsel_rev_0005")
executed: list[str] = []
monkeypatch.setattr(module, "op", _offline_op(executed))
monkeypatch.setattr(module, "get_settings",
lambda: SimpleNamespace(shares_identity=True, identity_schema="dredd"))
module.upgrade()
module.downgrade()
assert executed == []
def test_0005_decides_in_the_database_and_treats_every_old_row_as_a_moderator():
"""Three states in one statement, and the backfill that carries the old table's meaning.
Which state a database is in depends on which core was pinned the day its 0001 ran, so the
decision cannot be made here — it is `to_regclass` in the rendered SQL, which also keeps
`alembic upgrade --sql` honest. And every row the old table held WAS a moderator grant: left at
the column default they would all be silently demoted, with no symptom but people who can no
longer administer their own module.
"""
sql = _revision("0005_module_permission.py", "counsel_rev_0005")._MODULE_PERMISSION
assert sql.count("to_regclass") >= 2
assert "RENAME TO module_permission" in sql
assert "SET role = ''moderator''" in sql
assert sql.index("ADD COLUMN role") < sql.index("SET role = ''moderator''")
# The already-renamed case answers first, which is what makes a second run a no-op.
assert sql.index("'.module_permission') IS NOT NULL") < sql.index("RENAME TO module_permission")
def test_0005_builds_the_table_from_the_model_rather_than_a_second_description():
"""The "neither table" branch is `create_all`'s own DDL, rendered — not a hand-written copy
free to drift the day core adds a column. The role CHECK comes from `MODULE_ROLES` for the same
reason: one list, in core, that the database and Python both read."""
from dredd_core.identity import MODULE_ROLES
module = _revision("0005_module_permission.py", "counsel_rev_0005")
sql = module._MODULE_PERMISSION
assert "CREATE TABLE module_permission" in sql
assert "CREATE INDEX ix_module_permission_module_slug" in sql
for name in ("pk_module_permission", "uq_module_permission_user_module",
"ck_module_permission_slug", "ck_module_permission_role",
"fk_module_permission_user_id_app_user"):
assert name in sql, name
for role in MODULE_ROLES:
assert f"''{role}''" in sql, role
# Renaming the table leaves its constraints named after the old one, so each is renamed too.
assert all(old.startswith(("pk_", "uq_", "ck_", "fk_")) and "module_moderator" in old
and new == old.replace("module_moderator", "module_permission")
for old, new in module._RENAMES)
def test_0005_refuses_to_carry_a_plain_user_back_to_a_table_that_cannot_say_so():
"""The downgrade's one real hazard. Under the v0.10.x table a row meant MODERATOR and nothing
else, so a `user` row carried back would promote everyone merely admitted to this module into
someone who administers it — a widening, on a rollback, that nothing would record."""
sql = _revision("0005_module_permission.py", "counsel_rev_0005")._UNDO
assert "WHERE role <> ''moderator''" in sql
assert sql.index("DELETE FROM") < sql.index("DROP COLUMN IF EXISTS role")
assert "RENAME TO module_moderator" in sql
+70 -4
View File
@@ -10,6 +10,9 @@ What it proves, in the order it matters:
* **the cookie set at the hub is the cookie this app accepts** — a `session` row written by the hub
authenticates here, with no handoff of any kind. That is the whole of single sign-on at one
origin, and it is the one thing the owner actually asked for;
* **and being signed in is not being admitted**: with no `module_permission` row naming `counsel`
that same session is refused at the door, and granted one it is not. One account across four
modules means a session says who you are and nothing about where you may go;
* **nobody signs in here** and no account can be written from here, refused at the edge with a
sentence rather than as a 500 from a missing grant;
* **the grants really are what the design says**: this app cannot read a password hash, cannot
@@ -110,6 +113,65 @@ def test_a_session_the_hub_issued_signs_you_in_here(client, hub):
assert client.get("/api/v1/auth/me", cookies={SESSION_COOKIE: raw}).status_code == 401
def test_a_platform_account_with_no_row_for_counsel_is_refused_at_the_door(client, hub):
"""No row means no entry — the behaviour that did not exist before `module_permission`.
One account across four modules means a session proves who you are and nothing about *where*
you are allowed. Until this table, a signed-in stranger could open every screen in Counsel; they
saw nothing and could write nothing, but nothing had refused them, and an empty screen is not an
access decision. Both halves are asserted here, in order, because only the pair is the claim:
refused with no row, admitted the moment the hub writes one — and admitted as a USER, which is
not the same as administering the module.
"""
from dredd_core.security import hash_token
from sqlalchemy import text
from app.config import get_settings
from app.deps import SESSION_COOKIE
slug = get_settings().module_slug
raw = f"platform-test-{uuid.uuid4().hex}"
email = f"stranger-{uuid.uuid4().hex}@example.com"
account = hub.execute(text(
f"INSERT INTO {_q(IDENTITY_SCHEMA)}.app_user "
"(email, password_hash, full_name, is_admin, is_active) "
"VALUES (:email, 'hub-side-hash', 'A Stranger', false, true) RETURNING id"
), {"email": email}).scalar_one()
hub.execute(
text(f"INSERT INTO {_q(IDENTITY_SCHEMA)}.session "
"(id, user_id, token_hash, expires_at, kind, scope) "
"VALUES (:id, :user_id, :token_hash, :expires_at, 'session', 'read_write')"),
{"id": uuid.uuid4(), "user_id": account, "token_hash": hash_token(raw),
"expires_at": dt.datetime.now(dt.UTC) + dt.timedelta(hours=12)},
)
hub.commit()
try:
refused = client.get("/api/v1/auth/me", cookies={SESSION_COOKIE: raw})
# 403 and not 401: the session is perfectly valid and this app knows exactly who they are.
assert refused.status_code == 403, refused.text
hub.execute(
text(f"INSERT INTO {_q(IDENTITY_SCHEMA)}.module_permission "
"(user_id, module_slug, role) VALUES (:user_id, :slug, 'user')"),
{"user_id": account, "slug": slug},
)
hub.commit()
admitted = client.get("/api/v1/auth/me", cookies={SESSION_COOKIE: raw})
assert admitted.status_code == 200, admitted.text
assert admitted.json()["email"] == email
assert admitted.json()["is_moderator"] is False
finally:
# The account is deactivated rather than deleted: `account_delete_guard_sql` makes a DELETE
# from the shared `app_user` raise, because its cascades reach into every module's schema.
hub.execute(text(f"DELETE FROM {_q(IDENTITY_SCHEMA)}.module_permission "
"WHERE user_id = :id"), {"id": account})
hub.execute(text(f"DELETE FROM {_q(IDENTITY_SCHEMA)}.session WHERE user_id = :id"),
{"id": account})
hub.execute(text(f"UPDATE {_q(IDENTITY_SCHEMA)}.app_user SET is_active = false "
"WHERE id = :id"), {"id": account})
hub.commit()
def test_nobody_signs_in_here_and_the_refusal_says_where_to_go(client):
"""A 409 naming the hub, not a 401. The distinction is the whole user experience: 401 sends a
person looking for the right password, and there is no right password to find."""
@@ -159,12 +221,14 @@ def test_this_app_can_end_a_session_but_never_mint_one(runtime):
" has_table_privilege(current_user, :m, 'INSERT') AS grant_tier, "
" has_table_privilege(current_user, :m, 'DELETE') AS revoke_tier"
), {"s": f"{IDENTITY_SCHEMA}.session",
"m": f"{IDENTITY_SCHEMA}.module_moderator"}).mappings().one()
"m": f"{IDENTITY_SCHEMA}.module_permission"}).mappings().one()
assert row["read_it"] and row["revoke_it"]
assert not row["mint"], "the runtime role can mint a credential"
assert not row["rebind"], "the runtime role can point a session at another account"
# The tier is read here and granted in the hub. A module that could write it could promote
# itself, which is the one thing the two-tier model exists to prevent.
# Access is read here and granted in the hub. A module that could write this table could admit
# itself or promote itself — the one thing the whole arrangement exists to prevent — and with
# `module_permission` that is now true of admission as well as of the moderator role: a module
# holding INSERT could let a stranger in through the guard that is supposed to stop them.
assert row["read_tier"]
assert not (row["grant_tier"] or row["revoke_tier"])
@@ -238,7 +302,9 @@ def test_this_schema_keeps_no_copy_of_the_identity_tables(runtime):
assert own != IDENTITY_SCHEMA
local = runtime.execute(text(
"SELECT count(*) FROM pg_tables WHERE schemaname = :own "
"AND tablename IN ('app_user', 'session', 'module_moderator')"
# Both spellings of the module tier: which one a database has depends on which core was
# pinned the day its 0001 ran, and neither may survive here.
"AND tablename IN ('app_user', 'session', 'module_permission', 'module_moderator')"
), {"own": own}).scalar_one()
assert local == 0
resolves = runtime.execute(text(
+9 -6
View File
@@ -51,7 +51,7 @@ Don't start Counsel until each of these holds:
| schema `counsel` | Counsel's tables, enum types and `alembic_version`, never `public`. Owned by `counsel_migrator`; `PUBLIC` holds nothing on it |
| role `counsel_migrator` | Owns every object; used only by the one-shot `migrate` service (`alembic upgrade head`, then the seed). Its `search_path` is `counsel, extensions` and its `statement_timeout` is `30min`, because a provider may cap statements at a couple of minutes, too short for a migration |
| role `counsel_app` | The runtime role, the backend's only login: DML on Counsel's tables, but `audit_log` is append-only (no `UPDATE`, `DELETE` or `TRUNCATE`). Its `search_path` is `counsel, extensions` |
| schema `dredd` (platform only) | The shared identity schema — `app_user`, `session`, `module_moderator`, one account for the whole family. Owned by the HUB's migrator, not by Counsel. Provisioning gives Counsel's two roles `USAGE` and appends it to their `search_path`, **after** `counsel`; the tables and the per-role grants come from the hub's own migration |
| schema `dredd` (platform only) | The shared identity schema — `app_user`, `session`, `module_permission`: one account for the whole family, plus one row per person per module saying which modules they may open and which they may administer. Owned by the HUB's migrator, not by Counsel. Provisioning gives Counsel's two roles `USAGE` and appends it to their `search_path`, **after** `counsel`; the tables and the per-role grants come from the hub's own migration |
| extension `pg_trgm` | In schema `extensions`, created by provisioning: fuzzy search (the `%` operator, `similarity()`, the `gin_trgm_ops` indexes). Both roles get `USAGE` on that schema. `btree_gin`, which the local stack also installs, is not used by any index |
Role names are cluster-wide, so they carry the app's name. With a generic `app` / `migrator`, one app's
@@ -64,12 +64,15 @@ in `counsel`; Counsel's roles get none in any other app's schema, and no other a
The one deliberate exception to "no privilege outside my schema" is the shared identity schema, and
it is narrow enough to state in full: `counsel_app` may read seven columns of `app_user` (never
`password_hash`, `failed_login_count` or `locked_until`), read `session` and update three of its
columns (`last_seen_at`, `expires_at`, `revoked_at`), read `module_moderator`, and nothing else
columns (`last_seen_at`, `expires_at`, `revoked_at`), read `module_permission`, and nothing else
anywhere in `dredd`. `counsel_migrator` holds `SELECT` and `REFERENCES` on `app_user` — enough to
point this schema's foreign keys at it — and nothing else. Neither may INSERT: a role that can write
an `app_user` row can create an account, and one that can write a `session` row can mint a
credential for the administrator. `managed check --identity-schema dredd --identity-tier reader`
prints that matrix back and fails on anything wider.
an `app_user` row can create an account, one that can write a `session` row can mint a credential
for the administrator, and one that can write a `module_permission` row can let itself in — or
promote itself to moderator of itself. That last one is why "no row means no entry" is worth
anything: the refusal is a grant this app does not hold, not a check it could be talked out of.
`managed check --identity-schema dredd --identity-tier reader` prints that matrix back and fails on
anything wider.
## 1. Provision Counsel (once, as the platform admin)
@@ -256,7 +259,7 @@ pass, 1 = a check failed, 2 = could not run. It proves:
- The current schema is `counsel` and the `search_path` starts with it (and, on the platform,
names `dredd` after it — add `--identity-schema dredd --identity-tier reader` and `check` also
prints the full identity matrix, fails on a privilege wider than the reader tier, and fails if a
local copy of `app_user`, `session` or `module_moderator` has appeared in `counsel`).
local copy of `app_user`, `session` or `module_permission` has appeared in `counsel`).
- `counsel_migrator` owns the schema and every table and view in it (any other owner fails), and has a
30-minute `statement_timeout`.
- `counsel_app` has `USAGE`, and `audit_log` is append-only for it.