Scribe joins Atrium as a module, so db/managed/provision.sql is now the rendering with --identity-schema dredd --identity-owner atrium_migrator (the one Atrium's push.sh compares), and CI's --check-file step passes the same two flags, as Lexicon and Agora do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 KiB
Scribe in the family's shared managed database
The Dredd family can run in one managed PostgreSQL database — one Postgres 16/17 database at a managed provider, one schema and two roles per app — with Atrium as the hub and every other app (Galena, Sygna, Counsel Scorecard, and now Scribe) as its modules. The provider hosts only the database; Scribe's backend still runs on your own server with Docker Compose. The same steps work against any PostgreSQL 16/17 whose admin may create roles and schemas.
Step 0 applies to the whole database, so do it once, whichever app you deploy first. The family runbook
in the Atrium repository (deploy/README.md) covers it in more depth; the checklist below is the
minimum and works on its own. Steps 1 to 5 cover only Scribe's part.
0. The database itself (once, for every app)
- Create the database at the provider: Postgres 16 or 17, in a region close to your container hosts.
Keep the platform admin's password (the provider's
postgresrole, usually not a superuser there) in your secret store. Scribe uses it only for provisioning (step 1). - Keep the schemas out of any auto-generated API. Some providers 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 backends connect to Postgres directly;0002and step 4's check also make sure those roles hold nothing inscribe. - Enforce TLS on the server side if the provider offers a setting for it, so no client can connect in plaintext. Changing it may briefly restart the database.
- Download the provider's root CA from its dashboard (skip this if the server's certificate chains to
a public CA;
verify-fullthen uses the system trust store and the URLs carry nosslrootcert). One file serves the whole database. Save it ascerts/db-ca.crtnext todocker-compose.ymlon every container host, and compare its fingerprint and expiry on each host with what you recorded:openssl x509 -in certs/db-ca.crt -noout -fingerprint -sha256 -enddate. - Restrict the network. If the provider offers IP restrictions, allow only your container hosts' egress addresses, for direct and pooled connections alike.
- Size the connection budget for every app (section 2 below has the arithmetic). The provider's own services may draw on the same total.
- Provider backups and point-in-time restores rewind the whole database, so they rewind every app
together. After any provider restore, reset every app's role passwords (step 1 with
--reset-passwords, and each other app's equivalent), because a restore may drop custom role passwords, and run every app's check (step 4) before you start the backends.
What Scribe gets
| Scribe | |
|---|---|
| Schema | scribe (never public), owned by the migrator; PUBLIC holds nothing on it |
| Migrator role | scribe_migrator: owns every object; used only by alembic upgrade head in the one-shot migrate service. Its statement_timeout is 30min, because a provider may cap statements at a couple of minutes, which is too short for a migration |
| Runtime role | scribe_app: DML only, no UPDATE / DELETE / TRUNCATE on audit_log; the backend's only login |
| Extensions | none. gen_random_uuid() is core PostgreSQL, and 0001's CREATE EXTENSION IF NOT EXISTS pgcrypto is a no-op where the provider keeps a copy in extensions |
| Shared identity | only if this app joins a platform (section 6): USAGE on a neutral schema the hub owns, plus a column-restricted read of the accounts in it. Never ownership, never CREATE, never an INSERT |
Role names are cluster-wide, so they carry the app's name: with a generic app / migrator, one app's
migration could grant back what another app revoked, and one password would open every app. Never
create plain app or migrator roles in the shared database — those names are for the local stack
and CI only.
1. Provision Scribe (once, as the platform admin)
dredd-core owns the provisioning routine; nothing here is hand-written SQL.
From a shell (preferred), on any machine with the backend's requirements installed. Passwords come from environment variables, go to the server as SCRAM verifiers, and are never printed:
python -c "import secrets; print(secrets.token_urlsafe(32))" # once per role: URL-safe, no encoding later
read -rs SCRIBE_MIGRATOR_PASSWORD && export SCRIBE_MIGRATOR_PASSWORD
read -rs SCRIBE_APP_PASSWORD && export SCRIBE_APP_PASSWORD
read -rs ADMIN_DATABASE_URL && export ADMIN_DATABASE_URL
# postgresql+pg8000://postgres.<tenant>:<admin-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=./certs/db-ca.crt
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
--schema scribe --app-role scribe_app --migrator-role scribe_migrator \
--migrator-password-env SCRIBE_MIGRATOR_PASSWORD --app-password-env SCRIBE_APP_PASSWORD
In one transaction it creates both roles as plain LOGIN roles and schema scribe owned by the
migrator; gives PUBLIC nothing on the schema and the runtime role USAGE; grants both roles USAGE
on extensions and sets search_path = scribe, extensions (the migrator also gets
statement_timeout = 30min); then revokes the admin's temporary membership in the migrator, which
removes its standing SET ROLE path to the migrator, and verifies the result. That revoke is not a
wall: the admin keeps ADMIN OPTION on the roles it created and can grant itself membership again, so
anyone with the provider's SQL console can still rewrite audit_log. Treat that access as full trust and
keep the database's members minimal. Exit 0 = done, 1 = refused or failed (rolled back, nothing
changed), 2 = could not run. Re-running is safe: an existing role keeps its password unless you add
--reset-passwords. Weak or placeholder passwords are refused (16 printable ASCII characters minimum).
From the provider's SQL editor (no shell): paste the whole of provision.sql, replace
the two change_me passwords in step 2 there (never in the committed file), and 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
(CI's managed-db job runs the same command with --check-file and fails when the file is stale):
python -m dredd_core.managed provision --sql-only --schema scribe --app-role scribe_app \
--migrator-role scribe_migrator --identity-schema dredd --identity-owner atrium_migrator \
--output db/managed/provision.sql
The committed file is the platform rendering (Scribe is a module of Atrium, as Lexicon and Agora
are), and CI's --check-file step passes the same two identity flags. A standalone deployment of
its own renders without them (see section 6).
Joining Atrium (the platform) means re-rendering with the identity flags — the committed file already is that rendering:
python -m dredd_core.managed provision --sql-only --schema scribe --app-role scribe_app --migrator-role scribe_migrator --identity-schema dredd --identity-owner atrium_migrator --output db/managed/provision.sql
(plus every --extension this app's 0001 needs). The platform's deploy/push.sh checks it: before
it provisions anything, it re-renders each module's provision.sql from that module's checkout with
the canonical role names and the identity flags, and refuses the push when the committed file differs.
A module still shipping the standalone rendering therefore cannot be deployed onto the platform.
2. Configure .env
Replace the Database settings with the commented "managed PostgreSQL" block in
.env.example, and delete POSTGRES_PASSWORD / DB_*_PASSWORD (unused there):
MANAGED_DB_CA_FILE=./certs/db-ca.crt
DATABASE_URL=postgresql+pg8000://scribe_app.<tenant>:<password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
MIGRATION_DATABASE_URL=postgresql+pg8000://scribe_migrator.<tenant>:<password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
DB_APP_ROLE=scribe_app
# the connection budget below
DB_POOL_SIZE=4
DB_MAX_OVERFLOW=8
- Connection. The host and port from the provider's connection details. Through a pooler, use its
session mode (transaction mode breaks prepared statements; on the poolers the family knows that is
port 5432 against 6543) —
deploy_checkrefuses 6543. Some poolers require the tenant in the user name: then the user is<role>.<tenant>, andDB_APP_ROLEis the part before the dot. A direct connection may be IPv6-only, which Docker containers usually lack; the pooler is IPv4. - TLS — the family's one rule. A database host that is not local (
"",localhost,127.0.0.1,::1,postgres— the compose service — or an entry ofDB_LOCAL_HOSTS) must carrysslmode=verify-full, or the backend, migrate and the seed refuse to start when their settings load: pg8000 would otherwise skip verification and fall back to plaintext. Withsslrootcertthe server is verified against the provider's CA, which the override mounts at/run/certs/db-ca.crt; without it, against the system trust store. Every engine — the backend's, Alembic's, the seed's — is built bydredd_core.db.make_engine, which turns these parameters into a verifying TLS context;sslmode=prefer/allow/disableare refused before anything connects.DB_LOCAL_HOSTS(comma-separated) is for a private database on a trusted network that truly needs no TLS — the only exception, and one to write down. - Passwords. Percent-encode everything outside
A-Z a-z 0-9 - . _ ~(@→%40,%→%25). Alembic reads the URL directly, never through its configparser, so an encoded%is fine. DB_APP_ROLEis the role inDATABASE_URL(without a pooler's.<tenant>); the runtime-grants migration (0002) grants to it.migraterefuses to start when the two differ (refusing to migrate: DB_APP_ROLE is …), before anything is granted: aDB_APP_ROLEcopied from a sibling's.envwould otherwise hand that app's runtime role this schema. Naming a role that does not exist stops the migration withruntime grants: role … does not exist, and everything 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.DB_POOL_SIZEmust be at least 1 andDB_MAX_OVERFLOWat least 0 (SQLAlchemy reads 0 / -1 as no limit, so the settings refuse them).- The database's connection limit (the server's
max_connections, or the pooler's per-tenant pool) is shared by every app and by the provider's own services. CountDB_POOL_SIZE + DB_MAX_OVERFLOW + 1per app (the busy backend plus a seed,migrateor check beside it), and keep the apps' total at or below about 80% of the limit: 72 of 90, 48 of 60. - Five apps do not fit a 90-connection limit at the defaults: Atrium, Galena, Sygna, Counsel
Scorecard and Scribe at
5/10take 5 × (15 + 1) = 80. SetDB_POOL_SIZE=4andDB_MAX_OVERFLOW=8in every app, 5 × (12 + 1) = 65, or size the instance for more. - With a 60-connection limit, set
DB_POOL_SIZE=3andDB_MAX_OVERFLOW=2in every app: 5 × (5 + 1) = 30. - Through a pooler in session mode, each client keeps its connection, so the pooler's own pool size
(per user + database) must be at least
DB_POOL_SIZE + DB_MAX_OVERFLOW + 1. With less, the extra client queues and then fails. - The family runbook's connection table counts four apps: add Scribe's row there, and change the
other apps'
.envfiles to match.
- The database's connection limit (the server's
Then run the pre-flight (--env checks another file): python backend/scripts/deploy_check.py. For an
external DATABASE_URL it also checks both URLs — sslmode=verify-full, and sslrootcert at the
mounted CA when given; the roles are exactly scribe_app (DATABASE_URL) and
scribe_migrator (MIGRATION_DATABASE_URL), never postgres or another platform role, a sibling
app's roles or a generic app / migrator; not port 6543; a percent-encoded password and no
<placeholder>; different migrator and runtime roles; DB_APP_ROLE matching the runtime role; a bounded
pool; and that the CA file exists when the URLs name one. Compose does not run it, so run it yourself.
3. 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 off,
stops migrate waiting for it, and mounts the CA into migrate and backend.
migraterunsalembic upgrade headasscribe_migrator. Through the role'ssearch_path, every table, enum type andalembic_versionlands inscribewith nothing schema-qualified in code; a sibling's same-namedaudit_log,app_userornode_rolein its own schema does not make a table or type here get skipped.0002then grantsDB_APP_ROLEits privileges, strips the API roles, and verifies the result. The seed then runs asscribe_app.backendgets a blankMIGRATION_DATABASE_URL(and blank local-postgres passwords), so the long-running process can only log in asscribe_app. This skeleton never needs the migrator at runtime. If you add an in-app restore (as Galena and Sygna have), keeping the migrator's URL in the backend is an explicit opt-in; prefer a one-shot restore container (docker compose -f … -f … run --rm -e MIGRATION_DATABASE_URL=… backend python -m <restore>).- Never migrate as the platform admin (
postgresat a provider;postgres_managedin the local emulation) or a superuser.0002refuses (runtime grants: refusing to migrate as postgres …) and the whole migration rolls back: anything created as the admin would be owned by it, and anything inpublicexposed to 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, then rundocker compose -f … -f … run --rm migrateonce.
Pass both -f files on every compose command (ps, logs, run, down).
4. Verify
As the runtime role and as the migrator, inside the migrate container: it has both URLs from .env
and the CA at the path they name, which a shell on the host has neither of.
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 scribe --require-tls \
--app-role scribe_app --migrator-role scribe_migrator --append-only audit_log
done
It only reads, and fails (exit 1) unless: TLS is on from both ends; the connected role is neither a
superuser nor the platform admin; the current schema is scribe and search_path starts with it;
the migrator owns the schema and no table belongs to a superuser or the platform admin;
scribe_app cannot modify audit_log; isolation
— neither role holds USAGE, CREATE, ownership or an object privilege in any other app's schema;
and anon, authenticated and service_role hold nothing in scribe. Keep --append-only /
--no-delete in step with APPEND_ONLY_TABLES / NO_DELETE_TABLES in backend/app/models/__init__.py.
A provider whose platform keeps further schemas of its own in the database: 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) shows 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. Restore
A point-in-time or backup restore at the provider rewinds every app in the database together — there is no per-app database restore (an app's own backup/export is the only per-app path). Follow the family runbook's restore procedure (stop every backend, restore, reset custom-role passwords, start). For Scribe that means:
- Reset both passwords — a provider's restore may drop custom role passwords — by re-running step 1
with the passwords from your secret store and
--reset-passwords. It changes nothing else. docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm migrate— a no-op when the restored schema is already at head; otherwise it brings it forward.- Start the stack, then run step 4's
checkas both roles.
Not yet confirmed on a real managed database (the local verification used a TLS-only PostgreSQL
emulation, python -m dredd_core.managed emulate): that a provider's postgres may grant the migrator to
itself, create a schema for it and grant USAGE on extensions (provisioning stops with a clear error
if the last does not take); that custom roles' search_path / statement_timeout survive the
provider's own configuration; logins through a pooler and after a restore; certificate host-name checks
against the direct and the pooler host; the pooler's default pool size; and whether the pooler's own
connection to Postgres uses TLS (section 4's --require-tls).
6. Joining the platform (one account)
Everything above is true whether or not this app shares a roster. This section is the one change
that makes it a module of a platform rather than an app that merely lives next door: app_user,
session and module_permission move out of scribe into a neutral schema the hub owns, and
this app reads them. One person, one account, one password, one sign-in — and because the family
runs at ONE origin, the cookie they got at the hub already arrives here. There is nothing to hand
over and nothing to sign.
It also changes who may be here. module_permission holds one row per person per module, carrying a
role of user or moderator, and no row is no access: an account the hub knows nothing about
admitting to this app is refused at the door instead of shown an empty screen. Admitting somebody,
and promoting them to moderator of this app, happens in the hub — this app holds SELECT on that
table and nothing else, which is the whole reason it is safe for the modules to be separate
deployments reading one table.
Only the last of the four steps happens in this repository, and that split is forced by privileges, not by taste. Read the whole section before starting; step 3 is the one nobody can automate.
6.1 Provision, as the platform admin
Two extra flags on step 1's command, and on the --sql-only re-render:
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
--schema scribe --app-role scribe_app --migrator-role scribe_migrator \
--identity-schema dredd --identity-owner atrium_migrator \
--migrator-password-env SCRIBE_MIGRATOR_PASSWORD --app-password-env SCRIBE_APP_PASSWORD
It grants this app's two roles USAGE on dredd — only its own two, so the
grants accumulate one provisioning run per app and no script ever has to enumerate every role on the
platform — and changes the search_path to scribe, dredd, extensions. It does
not create the schema: that happens on the owning app's own run, and a module provisioned before
its owner is refused by name rather than left half-configured.
The app's own schema stays FIRST on that path, and it has to: alembic_version, the enum types and
every new table land in the first schema, which must be one this app's migrator owns. The entire
price of that correct choice is that an unqualified app_user resolves to a local copy if one
exists — which is why the backend asserts at startup that it does not, and why that assertion is not
optional. Never "fix" anything by putting the identity schema first.
Re-render provision.sql with the same two flags (section 1 has the command), add them to CI's
--check-file step, and commit both — or CI fails, correctly, because the committed file would no
longer describe this deployment, and the platform's push.sh refuses the module for the same reason.
6.2 The hub migrates
The schema's owner creates the three tables in it and grants this app's roles their tier. Nothing
here can do that: only the owner may create a table in its schema or grant a privilege on it. Make
sure the hub knows this app's two role names — it reads them from its own configuration — and that
its migration runs before this one. Compose should say so
(depends_on: <hub>-migrate: {condition: service_completed_successfully}); the migration below also
refuses by name if it finds the tables missing, which is the loud version of the same thing.
What this app ends up holding, and nothing more:
| on | scribe_app (runtime) |
scribe_migrator |
|---|---|---|
app_user |
SELECT on the ordinary columns only — nothing at all on password_hash, failed_login_count, locked_until |
SELECT, REFERENCES (it re-points foreign keys) |
session |
SELECT, and UPDATE on last_seen_at / expires_at / revoked_at |
nothing |
module_permission |
SELECT |
nothing |
| anything else there | nothing | nothing |
No INSERT anywhere, and that is the load-bearing line: a role that could insert a session row
could mint a working credential for the administrator, one that could insert an app_user row could
create or elevate anyone, and one that could write module_permission could admit anyone, promote
anyone and promote itself. The console's 409s are politeness; this table is the enforcement.
6.3 Import the accounts this app has and the hub does not
Run a census first — one SELECT id, email, is_admin, is_active per schema's app_user — and
compare by lower-cased e-mail. Anybody present here and absent there must be created in the hub
before step 6.4, because neither side can do it: this app's migrator holds no INSERT on the
shared app_user, and the hub's migrator holds nothing in scribe to read from. It is a
platform-admin step, run by eye, and on a freshly seeded pair of apps it is usually zero rows.
Anybody who administered this app and is not a platform administrator will come out an ordinary user. That is deliberate — a module must never be able to mint a platform administrator — so name them a moderator of this module in the hub afterwards. The migration warns about each such person by name as it runs.
6.4 Migrate this app
Set IDENTITY_SCHEMA=dredd (and, if the platform has settled on one cookie name,
SESSION_COOKIE_NAME; the old name keeps being accepted, so nobody is signed out by the rename),
then alembic upgrade head. That runs 0003_shared_identity, in one transaction: match every local
account to a shared one by e-mail, rewrite every id in this schema that names a person, re-point
every foreign key at the shared table, prove no row was missed, and drop the local copies. It
refuses rather than guessing if an account is unmatched, and it cannot be downgraded — restore
the dump you took first.
Then run section 4's check again with --identity-schema dredd: it stops treating
that schema as a leak and starts asserting the table above, column by column, with a closed
allowlist. A passing report prints exactly what these two roles may touch there, which is the
sentence to keep in the change record.