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>
20 KiB
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)
- Create the database — the provider's "project" or "instance": PostgreSQL 16 or 17, in the region
your servers run in. Its platform admin (
postgreson most providers, and not a superuser there) is what provisioning runs as. Its password belongs in no app's.env. - 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.crtand names it in its URLs'sslrootcert; without itsslmode=verify-fullcannot verify the server. Keep it out of git (certs/is ignored). - 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_roleand exposespublicby default. Switch such an API off, or never add an app schema to it. The apps never usepublic;0003revokes everything from those roles inatrium, andmanaged checkproves it. - 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-fullon any host that is not local, so a plaintext-only setup fails on both sides. - 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 ROLEbreak there). Some poolers need the tenant in the user name (<role>.<tenant>); the provider's dashboard shows the exact form. SizeDB_POOL_SIZE/DB_MAX_OVERFLOWso the apps stay within about 80% of the limit (section 2, Pool). - 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. - 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-ownerare the shared identity schema: the neutral schema whereapp_user,sessionandmodule_permissionlive 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 rolesUSAGEand 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'ssearch_path<slug>, dredd, extensions— the app's own schema first, always, oralembic_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 noCREATEon the database, so the schema cannot come from Alembic; aGRANTby a non-owner only warns rather than failing, so the tiers cannot come from anywhere but the owner.deploy/RUNBOOK-one-account.mdis 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
LOGINroles and creates schemaatriumowned byatrium_migrator.PUBLICgets nothing on the schema, andatrium_appgetsUSAGE. -
Both roles get
USAGEonextensionsandsearch_path = atrium, extensions. The migrator also getsstatement_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 atriumgoes withatrium_app/atrium_migratorand nothing else. Provisioning sets the given roles'search_pathto the given schema, so another app's role names here (saygalena_appfrom Galena's runbook) would repoint that app's roles atatriumand take it down. Check the three names before you run it.
From the provider's SQL editor (no shell).
- Paste the whole of
provision.sqlinto the editor. - Replace the two
change_mepasswords in step 2 there, never in the committed file. - 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
- Start from the commented "managed PostgreSQL provider" block in
.env.example. - Replace the Database settings with it.
- Delete
POSTGRES_PASSWORDandDB_*_PASSWORD: nothing uses them here, anddeploy_checkfails on a leftoverchange_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).
- Use the provider's pooler in session mode on port 5432, with the user in the form the pooler
needs —
- TLS.
sslmode=verify-fullagainst the provider's root CA, which the override mounts at/run/certs/db-ca.crt. Every engine is built bydredd_core.db.make_engine, which turns these parameters into a verifying TLS context, andSettingsapply the family's rule before anything connects: a host that is not local ("",localhost,127.0.0.1,::1,postgres, or aDB_LOCAL_HOSTSentry) withoutsslmode=verify-fullstops the process.sslmode=prefer/allow/disableare 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_ROLEnames the runtime role for the runtime-grants migration (0003). It must be the role inDATABASE_URLwithout any.<tenant>suffix. If it names a role that doesn't exist, the migration stops withruntime grants: role … does not existand rolls back.- Pool. The backend holds up to
DB_POOL_SIZE + DB_MAX_OVERFLOWconnections. 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 asatrium_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=3andDB_MAX_OVERFLOW=2in every app: 4 × (5 + 1) = 24.
- 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
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, withsslrootcertpointing at the mounted CA;- the roles are exactly
atrium_app(DATABASE_URL) andatrium_migrator(MIGRATION_DATABASE_URL): neverpostgresor another platform role, another app's roles, or a genericapp/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_ROLEmatches 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.
migraterunsalembic upgrade headasatrium_migrator. Through the role'ssearch_path, every table, enum type andalembic_versionlands inatrium, and nothing is schema-qualified in code. Another app's same-namedaudit_log,app_userornode_rolein its own schema doesn't make a table or type get skipped.0003then grantsDB_APP_ROLEits privileges and strips the provider's API roles, then verifies the result.- The seed then runs as
atrium_app. backendgets blankMIGRATION_DATABASE_URL/DB_*_PASSWORD/POSTGRES_PASSWORD, so the long-running process can only log in asatrium_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.0003checks the same thing again; that used to be the only check, and it was reached only when0001and0002happened to succeed first.- Anything created as
postgreswould be owned by it. - Anything created in
publicmay be exposed by an auto-generated API.
- Anything created as
- 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, thendocker compose -f … -f … run --rm migrateonce.
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_pathstart withatrium. atrium_migratorowns the schema and every table, and has a 30-minutestatement_timeout.atrium_apphasUSAGE, andaudit_logis 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,authenticatedandservice_rolehold nothing inatrium.
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:
- Stop Atrium's backend:
docker compose -f … -f … stop backend. - 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). - Start:
up -d.migrateis a no-op at head. - Run the check in section 4.
- Stop Atrium's backend:
- 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-dbjob, onpostgres:17. It runsdredd_core.managed emulate(TEST-ONLY: a managed-Postgres lookalike — a CREATEROLE adminpostgres_managedstanding in for the provider'spostgres, the API rolesanon/authenticated/service_role, and anextensionsschema). Then it provisions Atrium, migrates asatrium_migrator, seeds, and runs the integration suite asatrium_app. It runs the managed check as both roles, asserts that nothing is inpublic, and runs a downgrade/upgrade cycle. - CI's
backendandcompose-smokejobs.deploy_checkruns 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-smokerenders the two compose files merged and checks the override's promises: no local postgres, the CA mounted intomigrateandbackend, and no migrator URL inbackend. tests/test_settings_db_urls.pypins the TLS rule: a remote host withoutverify-fullis refused for either URL, the local names and aDB_LOCAL_HOSTSentry 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 wrongDB_APP_ROLEandsslmode=prefer.
Not yet confirmed on a real managed database:
- The provider's
postgresrunningGRANT atrium_migrator TO postgres,CREATE SCHEMA … AUTHORIZATIONandGRANT USAGE ON SCHEMA extensions. Provisioning stops with a clear error if the last one doesn't take. - The custom roles'
search_pathandstatement_timeoutsettings 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-tlspasses 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 pgcryptobeing a no-op there. - Real latency.