Files
adminandClaude Opus 5 d923c075af Grant a module to a person, and let a unit stay a shortcut
Atrium becomes the writer of `dredd.module_permission` -- the one table
that decides who may use which module, and with what role. No row is no
access; `user` may use; `moderator` may administer; a platform
administrator needs no row anywhere.

The administration pane grants and revokes per module, with a role, and
`module_assignment` survives only as the record of WHY somebody holds a
row: naming a unit is still how you grant a whole department at once, but
it now writes the per-user rows, so the three modules read exactly one
table and never have to reach into this schema to find out who may enter.

The shortcut re-materialises on every change that can alter who is in a
unit -- an assignment added or removed, availability changed, a module
created, an access request approved, a unit grant given or taken away, a
unit deleted, an account created, and every deploy through the seed. That
is possible without a background job for one reason: the hub is the only
writer of membership AND of permissions, so every input is a request this
app served. Freezing it instead would have been a regression -- unit
membership already resolved live -- and re-resolving on read would mean a
GET that writes, in three deployments that hold SELECT and nothing else.

Two rules keep the set-difference safe. Naming somebody on a roster pins
a direct assignment for them, so an unrelated change to that module
cannot sweep them away later -- a silent, delayed revocation. And a
deactivated account takes no part in either direction, so switching
somebody off and on again does not strip every module they moderated.

Two gaps found by running it rather than reading it:

- Existing modules have no permission rows, and nothing in the trigger
  list creates them -- so the first deploy of this would have let nobody
  into anything, including modules marked available to everyone. The seed
  now sweeps every module, which makes it a backstop as well as a
  backfill since it writes only differences.
- A table created by the new revision carries no runtime grants: 0003
  granted ON ALL TABLES at the time it ran. Invisible until the day the
  deployment joins a platform and every roster read is a permission
  error. The new revision re-runs the grants, as 0003's own docstring
  says every later revision adding a table must.

The HTTP route keeps its name. `/admin/modules/<slug>/moderators` is
quoted in three other repositories and scanned by a test in one of them;
renaming it to match the table would be tidiness bought with four repos
and a broken suite.

Requires dredd-core v0.11.0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-01 11:53:04 +02:00

20 KiB
Raw Permalink Blame History

Atrium on a managed PostgreSQL provider

The Dredd family can run in one managed PostgreSQL database — one database (PostgreSQL 17) on a managed provider — with Atrium as the hub and Galena, Sygna and Counsel Scorecard as its modules. The provider hosts only the database; Atrium's backend still runs on your own server with Docker Compose and the docker-compose.managed-db.yml override — or the whole family runs on one server through the deploy kit in deploy/, which supports both its own Postgres and a managed one.

Nothing here names a provider. What providers do differently is written as it applies to any of them: the root CA they hand out, the form their pooler wants the user name in, the auto-generated API some of them put in front of a database, what their restores keep.

Section 0 is project-wide — once per database, before any app is provisioned. The rest is Atrium's part; the other apps' runbooks assume section 0 too.

Atrium
Schema atrium (never public), owned by the migrator
Migrator role atrium_migrator: owns every object, used only by alembic upgrade head in the one-shot migrate service
Runtime role atrium_app: DML only, holds no UPDATE / DELETE / TRUNCATE on audit_log; the backend's only login
Extensions none. gen_random_uuid() is built into PostgreSQL, and 0001's CREATE EXTENSION IF NOT EXISTS pgcrypto is a no-op next to a pre-installed copy in extensions

Role names are cluster-wide, so they carry the app's name. With a generic app / migrator, one app's migration could undo another app's protections. So never create plain app or migrator roles in the shared database. Atrium's 0001 still grants a role literally named app on schema public when one exists (the local-stack shape); 0002 does so only while the current schema is public, so nothing of atrium's goes to such a role. deploy_check refuses any role in Atrium's URLs other than atrium_app / atrium_migrator.

0. Project-wide steps (once per database, any provider)

  1. Create the database — the provider's "project" or "instance": PostgreSQL 16 or 17, in the region your servers run in. Its platform admin (postgres on most providers, and not a superuser there) is what provisioning runs as. Its password belongs in no app's .env.
  2. Download the provider's root CA certificate from its dashboard (a PEM file). Every app mounts the same file read-only at /run/certs/db-ca.crt and names it in its URLs' sslrootcert; without it sslmode=verify-full cannot verify the server. Keep it out of git (certs/ is ignored).
  3. Keep the schemas out of any auto-generated API. Providers may expose tables through an auto-generated HTTP API that connects as anon / authenticated / service_role and exposes public by default. Switch such an API off, or never add an app schema to it. The apps never use public; 0003 revokes everything from those roles in atrium, and managed check proves it.
  4. Enforce SSL and restrict the network where the provider offers it: refuse plaintext at the server, and allow only your servers' addresses. The apps refuse to start without verify-full on any host that is not local, so a plaintext-only setup fails on both sides.
  5. Connections and compute. The four apps and the provider's own services share one connection limit. Connect through session-mode pooling on port 5432 — never a transaction-mode pooler (commonly port 6543: prepared statements and SET ROLE break there). Some poolers need the tenant in the user name (<role>.<tenant>); the provider's dashboard shows the exact form. Size DB_POOL_SIZE / DB_MAX_OVERFLOW so the apps stay within about 80% of the limit (section 2, Pool).
  6. Backups and restore. The provider's backups (daily snapshots, point-in-time recovery) cover the whole database, so a restore rewinds all four apps together. A restore may also drop custom role passwords: after one, run each app's provisioning again with --reset-passwords (section 6). Galena and Sygna have per-app backups on top; Atrium and Counsel Scorecard do not.
  7. Rehearse on a throwaway database first — the same steps, then drop it. Some providers ban a client IP for a while after a few failed password logins in a row, so a wrong password is worth catching there.

1. Provision Atrium (once, as the platform admin)

dredd-core owns the provisioning routine; nothing here is hand-written SQL. Choose one of two paths.

From a shell (preferred). Use any machine with the backend's requirements installed. Passwords come from environment variables. They are sent as SCRAM verifiers and never printed.

# URL-safe passwords need no percent-encoding later:
python -c "import secrets; print(secrets.token_urlsafe(32))"     # once for each role
read -rs ATRIUM_MIGRATOR_PASSWORD && export ATRIUM_MIGRATOR_PASSWORD
read -rs ATRIUM_APP_PASSWORD && export ATRIUM_APP_PASSWORD
read -rs ADMIN_DATABASE_URL && export ADMIN_DATABASE_URL
#   postgresql+pg8000://postgres.<tenant>:<admin-password>@<pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=./certs/db-ca.crt
#   (plain `postgres` as the user where the host needs no tenant suffix)

python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
    --schema atrium --app-role atrium_app --migrator-role atrium_migrator \
    --identity-schema dredd --identity-owner atrium_migrator \
    --migrator-password-env ATRIUM_MIGRATOR_PASSWORD --app-password-env ATRIUM_APP_PASSWORD
  • --identity-schema / --identity-owner are the shared identity schema: the neutral schema where app_user, session and module_permission live so that a person has ONE account across the whole family. Atrium's migrator owns it, so Atrium's run is the one that creates it; each module's run then grants only its own two roles USAGE and never creates a schema for someone else, which is what keeps provisioning per-app and stops any script having to enumerate all eight role names. It also makes each role's search_path <slug>, dredd, extensions — the app's own schema first, always, or alembic_version, the enum types and every new table would land somewhere its migrator does not own. Omit both flags for a standalone install, which shares nothing and behaves exactly as it did before.

  • The tables inside that schema are not provisioning: they are Atrium's revision 0004, and nothing else can do either half. A migrator holds no CREATE on the database, so the schema cannot come from Alembic; a GRANT by a non-owner only warns rather than failing, so the tiers cannot come from anywhere but the owner. deploy/RUNBOOK-one-account.md is the operator sequence.

  • It runs in one transaction and reports each step. Exit codes: 0 = done, 1 = refused or failed (rolled back, nothing changed), 2 = could not run.

  • It creates both roles as plain LOGIN roles and creates schema atrium owned by atrium_migrator. PUBLIC gets nothing on the schema, and atrium_app gets USAGE.

  • Both roles get USAGE on extensions and search_path = atrium, extensions. The migrator also gets statement_timeout = 30min (some providers cap statements at a couple of minutes).

  • It ends by revoking the admin's temporary membership in atrium_migrator, then verifies the result.

  • Re-running is safe: an existing role keeps its password unless you add --reset-passwords.

  • It refuses weak or placeholder passwords (16 printable ASCII characters minimum).

  • Copy the command as it stands. --schema atrium goes with atrium_app / atrium_migrator and nothing else. Provisioning sets the given roles' search_path to the given schema, so another app's role names here (say galena_app from Galena's runbook) would repoint that app's roles at atrium and take it down. Check the three names before you run it.

From the provider's SQL editor (no shell).

  1. Paste the whole of provision.sql into the editor.
  2. Replace the two change_me passwords in step 2 there, never in the committed file.
  3. Run it once, as the platform admin.

The editor's query history then holds the plaintext passwords, which the shell path avoids.

provision.sql is rendered by dredd-core; don't edit it. After a dredd-core upgrade, re-render it:

python -m dredd_core.managed provision --sql-only --schema atrium --app-role atrium_app \
    --migrator-role atrium_migrator --identity-schema dredd --identity-owner atrium_migrator \
    --output db/managed/provision.sql

CI's managed-db job runs the same command with --check-file and fails when the file is stale.

2. Configure .env

  1. Start from the commented "managed PostgreSQL provider" block in .env.example.
  2. Replace the Database settings with it.
  3. Delete POSTGRES_PASSWORD and DB_*_PASSWORD: nothing uses them here, and deploy_check fails on a leftover change_me.
MANAGED_DB_CA_FILE=./certs/db-ca.crt
DATABASE_URL=postgresql+pg8000://atrium_app.<tenant>:<password>@<pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
MIGRATION_DATABASE_URL=postgresql+pg8000://atrium_migrator.<tenant>:<password>@<pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
DB_APP_ROLE=atrium_app
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=10
  • Connection.
    • Use the provider's pooler in session mode on port 5432, with the user in the form the pooler needs — <role>.<tenant> on some, the plain <role> on others.
    • Or the direct connection on port 5432 with the plain <role> (some providers make it IPv6-only unless an IPv4 option is enabled).
    • Never a transaction-mode pooler (commonly port 6543).
  • TLS. sslmode=verify-full against the provider's root CA, which the override mounts at /run/certs/db-ca.crt. Every engine is built by dredd_core.db.make_engine, which turns these parameters into a verifying TLS context, and Settings apply the family's rule before anything connects: a host that is not local ("", localhost, 127.0.0.1, ::1, postgres, or a DB_LOCAL_HOSTS entry) without sslmode=verify-full stops the process. sslmode=prefer / allow / disable are refused everywhere.
  • Passwords. Percent-encode everything outside A-Z a-z 0-9 - . _ ~ (@ → %40, % → %25). Alembic reads the URL directly, so an encoded % is fine.
  • DB_APP_ROLE names the runtime role for the runtime-grants migration (0003). It must be the role in DATABASE_URL without any .<tenant> suffix. If it names a role that doesn't exist, the migration stops with runtime grants: role … does not exist and rolls back.
  • Pool. The backend holds up to DB_POOL_SIZE + DB_MAX_OVERFLOW connections. Migrate, the seed and the section 4 check use no pool, one connection each.
    • A pooler's own pool size (per user + database + mode, where the provider lets you set it) caps the connections it opens to Postgres. In session mode each client keeps its connection, so set it to at least DB_POOL_SIZE + DB_MAX_OVERFLOW + 1: the busy backend plus a seed or check as atrium_app. With less, the extra client queues and then fails.
    • The database's connection limit is shared by all four apps and by the provider's own services. Keep the four apps' total at or below about 80% of it.
    • With the defaults, the family takes 4 × (15 + 1) = 64 — fine on a limit of 90 or more.
    • On a small plan (a limit around 60), set DB_POOL_SIZE=3 and DB_MAX_OVERFLOW=2 in every app: 4 × (5 + 1) = 24.

Then run the pre-flight check:

python backend/scripts/deploy_check.py        # or: --env path/to/other.env

Because DATABASE_URL points at an external host, deploy_check also checks both URLs:

  • sslmode=verify-full, with sslrootcert pointing at the mounted CA;
  • the roles are exactly atrium_app (DATABASE_URL) and atrium_migrator (MIGRATION_DATABASE_URL): never postgres or another platform role, another app's roles, or a generic app / migrator;
  • the port is not 6543;
  • a pooler host whose user carries no .<tenant> suffix gets a warning (only the provider knows whether it needs one; a wrong form is a failed login);
  • the password is percent-encoded, and no <placeholder> is left;
  • the migrator and runtime roles differ;
  • DB_APP_ROLE matches the runtime role;
  • the CA file exists.

3. Start: migrate, seed, run

DREDD_CORE_TOKEN=github_pat_... \
  docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build

docker-compose.managed-db.yml switches the local postgres service off and stops migrate waiting for it. It mounts the CA into migrate and backend.

  • migrate runs alembic upgrade head as atrium_migrator. Through the role's search_path, every table, enum type and alembic_version lands in atrium, and nothing is schema-qualified in code. Another app's same-named audit_log, app_user or node_role in its own schema doesn't make a table or type get skipped. 0003 then grants DB_APP_ROLE its privileges and strips the provider's API roles, then verifies the result.
  • The seed then runs as atrium_app.
  • backend gets blank MIGRATION_DATABASE_URL / DB_*_PASSWORD / POSTGRES_PASSWORD, so the long-running process can only log in as atrium_app. Atrium has no in-app restore, so it never needs the migrator.
  • Never migrate as postgres. 0001's very first statement refuses a superuser or the platform admin — migration preflight: refusing to migrate as postgres — before it creates anything, and the whole migration rolls back. 0003 checks the same thing again; that used to be the only check, and it was reached only when 0001 and 0002 happened to succeed first.
    • Anything created as postgres would be owned by it.
    • Anything created in public may be exposed by an auto-generated API.
  • Nothing retries a failed migration. Some providers ban the client IP for a while after a few wrong passwords in a row. Fix .env, wait out or lift the ban in the provider's dashboard, then docker compose -f … -f … run --rm migrate once.

Pass both -f files on every compose command (ps, logs, run, down).

4. Verify

for url in DATABASE_URL MIGRATION_DATABASE_URL; do
  docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \
    python -m dredd_core.managed check --url "$url" --expect-schema atrium --require-tls \
      --app-role atrium_app --migrator-role atrium_migrator \
      --identity-schema dredd --identity-tier owner
done

--identity-tier owner, not writer: Atrium's migrator owns the shared schema, so measuring it against the writer tier reports an "escalation" on a perfectly correct deployment — the loudest possible message about the role the design trusts most. A module is checked with --identity-tier reader, and that report is the whole security argument in one line: it names the seven columns of an account its runtime role may read, the three columns of a session row it may write, and the fact that it holds nothing at all on password_hash, failed_login_count, locked_until, or on any other relation in the schema.

It only reads, inside a read-only transaction that it rolls back, and never prints passwords. Exit 0 = pass, 1 = a check failed, 2 = could not run. It proves:

  • TLS: verify-full in the URL, and an encrypted session. Behind a pooler, the server view describes the pooler's own link to Postgres, not yours (see below).
  • The current schema and search_path start with atrium.
  • atrium_migrator owns the schema and every table, and has a 30-minute statement_timeout.
  • atrium_app has USAGE, and audit_log is append-only for it.
  • Isolation: neither Atrium role holds any privilege in another app's schema, and the other apps' roles hold none in atrium (their own checks prove that).
  • anon, authenticated and service_role hold nothing in atrium.

If the provider keeps further service schemas of its own, name them with --system-schema NAME so the isolation check skips them.

Through a pooler, --require-tls can fail a correct setup. There, pg_stat_ssl describes the pooler's own connection to Postgres, which is encrypted only if the provider configures it that way. If the only failure is TLS (server view) while TLS (client) is OK with verify-full, your own link is verified. Run the check again without --require-tls, where that row is a warning, and note it. Over the direct connection, keep --require-tls.

5. Upgrades

Pull, then run the same up -d --build: migrate runs first and the backend starts only after it succeeds.

To review the DDL without a database, run alembic upgrade head --sql with MIGRATION_DATABASE_URL and DB_APP_ROLE set. The TLS parameters are stripped offline, so the CA file doesn't have to exist.

A new revision that adds a table must call runtime_grants_sql again (see 0003).

6. Restore: Atrium specifics

  • Atrium has no app-level backup. Its data comes back only with a database restore or a point-in-time recovery, and that rewinds all four apps together (section 0). Galena and Sygna have per-app backups; Atrium does not.
  • After a database restore, follow section 0, and for Atrium:
    1. Stop Atrium's backend: docker compose -f … -f … stop backend.
    2. Once the database is back, set the passwords again, because a restore may not keep custom-role passwords. Re-run the provision command from section 1 with --reset-passwords, with the passwords in .env (or new ones, and update .env).
    3. Start: up -d. migrate is a no-op at head.
    4. Run the check in section 4.
  • The backend never needs migrator credentials for any of this.

7. Removing Atrium from the database

As the platform admin, in one transaction:

BEGIN;
GRANT atrium_migrator, atrium_app TO CURRENT_USER;
DROP SCHEMA atrium CASCADE;
REVOKE USAGE ON SCHEMA extensions FROM atrium_migrator, atrium_app;
DROP OWNED BY atrium_migrator, atrium_app;
DROP ROLE atrium_app, atrium_migrator;
COMMIT;

How this is tested

  • CI's managed-db job, on postgres:17. It runs dredd_core.managed emulate (TEST-ONLY: a managed-Postgres lookalike — a CREATEROLE admin postgres_managed standing in for the provider's postgres, the API roles anon / authenticated / service_role, and an extensions schema). Then it provisions Atrium, migrates as atrium_migrator, seeds, and runs the integration suite as atrium_app. It runs the managed check as both roles, asserts that nothing is in public, and runs a downgrade/upgrade cycle.
  • CI's backend and compose-smoke jobs. deploy_check runs on a managed-database-shaped .env, which must pass, and on broken copies of it, which must fail (sslmode=prefer, no sslmode, port 6543, another app's role, generic roles, the platform admin as the migrator) or warn (a pooler host without the tenant suffix). compose-smoke renders the two compose files merged and checks the override's promises: no local postgres, the CA mounted into migrate and backend, and no migrator URL in backend.
  • tests/test_settings_db_urls.py pins the TLS rule: a remote host without verify-full is refused for either URL, the local names and a DB_LOCAL_HOSTS entry are accepted, and the error never carries the password.
  • A local TLS emulation, on PostgreSQL 16. The same path ran over verify-full, with passwords containing % @ : / ? #. A second app's schema held same-named tables and an enum type with other labels. Negative cases covered migrating as the admin, a wrong DB_APP_ROLE and sslmode=prefer.

Not yet confirmed on a real managed database:

  • The provider's postgres running GRANT atrium_migrator TO postgres, CREATE SCHEMA … AUTHORIZATION and GRANT USAGE ON SCHEMA extensions. Provisioning stops with a clear error if the last one doesn't take.
  • The custom roles' search_path and statement_timeout settings surviving the provider's own configuration.
  • atrium_app.<tenant> logins through a session-mode pooler, and after a restore.
  • Whether the pooler's own connection to Postgres uses TLS, which decides whether managed check --require-tls passes through the pooler (section 4).
  • The pooler's default per-user pool size on the chosen plan (section 2, Pool).
  • Certificate host-name checks against the pooler host.
  • The migrator's CREATE EXTENSION IF NOT EXISTS pgcrypto being a no-op there.
  • Real latency.