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>
25 KiB
Galena in the family's shared managed database
All four apps of the family (Atrium, Galena, Sygna, Counsel Scorecard) can share one managed
PostgreSQL database: one Postgres 16/17 database at a managed provider, one schema and two roles per
app. The provider hosts only the database. Galena's backend still runs on your container host, because
it needs the git binary, a disk volume for the project repositories and a background scheduler. 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) is meant to cover it in more depth. The checklist
below is the minimum and works on its own. Steps 1 to 5 cover only Galena's part of the database.
0. The database itself (once, for all four apps)
- 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. Galena 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; with the API off, no auto-generated endpoint answers, whatever the grants are. - 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 four apps. All four apps share the database's connection limit
(the server's
max_connections, or the pooler's per-tenant pool). The provider's own services may draw on the same total, so keep the apps at or below about 80% of it. Each backend process holds at mostDB_POOL_SIZE + DB_MAX_OVERFLOWconnections. Count one more per app for a seed,migrate, a restore or a check running beside it. With the defaults, four apps need 4 × (5 + 10 + 1) = 64 connections, which fits a limit of 90; for a limit of 60, setDB_POOL_SIZE=3andDB_MAX_OVERFLOW=2in every app (4 × (3 + 2 + 1) = 24 of 48). Through a pooler in session mode, the pooler's own pool size must be at leastDB_POOL_SIZE + DB_MAX_OVERFLOW + 1per app. - Provider backups and point-in-time restores rewind the whole database, so they rewind all four
apps together. The per-app restore paths are Galena's and Sygna's own backups (step 5). 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 Galena gets
| Object | What it is |
|---|---|
schema galena |
Galena's tables, enum types and alembic_version. Owned by galena_migrator; PUBLIC holds nothing on it. |
role galena_migrator |
Runs migrations and restores; owns every object. Its search_path is galena, dredd, extensions and its statement_timeout is 30min, because a provider may cap statements at a couple of minutes, which is too short for migrations and restores. Only the migrate container and the one-shot restore use it. |
role galena_app |
The runtime role. It has DML on Galena's tables, but audit_log is append-only (no UPDATE, DELETE or TRUNCATE). Its search_path is galena, dredd, extensions. |
extension pgcrypto |
Kept in schema extensions. Both roles get USAGE on that schema. |
schema dredd |
Not Galena's. The family's shared identity schema, created and owned by the hub's migrator. Galena's two roles get USAGE on it and nothing more; the tables in it, and the privileges each role holds on them, come from the hub's own migration. |
Galena creates nothing in public and nothing in dredd. The API roles (anon, authenticated,
service_role) get no privilege in either. Galena's roles get no privilege in any other app's schema,
and no other app's roles get any in galena. Role names are cluster-wide, which is why they carry the
app's name: with generic app / migrator roles, one app's migration could undo another app's
protections.
One account for the whole platform
Galena runs in two shapes, and the flags below decide which. Standalone — drop --identity-schema
and --identity-owner everywhere in this file, leave IDENTITY_SCHEMA empty, and Galena owns its own
app_user / session / module_permission exactly as it always has. As a module of the platform,
those three tables live in dredd, the hub owns them, a person has one account for every module, and
this app READS identity and never writes it:
dredd.app_user |
dredd.session |
dredd.module_permission |
|
|---|---|---|---|
galena_app |
SELECT on seven columns — nothing at all on password_hash, failed_login_count, locked_until |
SELECT, UPDATE (last_seen_at, expires_at, revoked_at) |
SELECT |
galena_migrator |
SELECT, REFERENCES (its foreign keys point here) |
— | — |
module_permission is one row per person per module — role of user (may use it) or moderator
(may use and administer it), and no row at all, which is no access to that module. This app reads
it to decide whether to let somebody in, and holds SELECT and nothing else: a module that could
write it could admit anyone, promote anyone and promote itself.
No INSERT anywhere, for either role: a role that can insert a session row can mint a working
credential for the administrator, and a role that can insert an app_user row can create one. That
is the enforcement — the refusals in the application are only the matching sentence at the edge. The
UPDATE on three session columns is not optional: resolve_session_full writes last_seen_at when
it is stale, so a read-only grant would break the first request older than five minutes.
Order matters and nothing in it can be skipped:
- the hub is provisioned first — its run is the one that creates
dredd. Galena's provisioning refuses by name if the schema is not there yet; - Galena is provisioned with the two flags (step 1 below), which grants its roles
USAGEand sets theirsearch_pathtogalena, dredd, extensions; - the hub's migration creates the three tables and grants each role the tier above. Galena's migration refuses by name if this has not happened;
alembic upgrade headhere runs0007_shared_identity, the cutover.
Set IDENTITY_SCHEMA before that last step, not after. 0007 is a no-op when the setting is
empty, and Alembic records it as run either way — so a deployment that upgraded first and switched on
afterwards is at 0007 with its local identity tables still in place, and the next
alembic upgrade head will say there is nothing to do. Nothing is lost and nothing is broken; the
backend simply refuses to start, and its error message names the remedy:
alembic stamp 0006 && alembic upgrade head, with the setting in place. That is safe on a database
that has already been converted, because the revision is idempotent.
Read 0007_shared_identity.py before
running it on anything you care about. In one transaction it matches every local account to the shared
store by lower(email), refuses outright on an account the platform has never heard of (that one
is a platform-admin import step, run between the hub's migration and this one — neither side can do it
alone), rewrites every id in this schema that names a person, re-points thirteen foreign keys at
dredd.app_user, and drops the local identity tables.
Everyone signs in again afterwards, and every app token is re-minted at the hub. Galena's local
sessions are dropped with the table: no module holds INSERT on the shared session, so there is no
privilege to carry them across — and promoting a credential that was issued for one module into one
that opens the whole platform is a widening this app declines to make silently.
1. Provision Galena (once, as the platform admin)
Generate two passwords, one per role, and keep them in your secret store. Each needs at least 16
printable ASCII characters, and the two must differ. URL-safe passwords avoid percent-encoding later:
python -c "import secrets; print(secrets.token_urlsafe(32))".
From a shell (preferred). Passwords are read from environment variables and sent as SCRAM
verifiers, so they never appear in output or in the server's logs. The command runs in the migrate
container, which has the CA mounted. Compose needs a .env file for every command, because the
migrate and backend services load it (step 2 fills it in). run also needs the CA at certs/db-ca.crt
(step 0). Building the image needs the dredd-core token in the shell, never in .env:
cp .env.example .env
DREDD_CORE_TOKEN=github_pat_... docker compose -f docker-compose.yml -f docker-compose.managed-db.yml build
export ADMIN_DATABASE_URL='postgresql+pg8000://postgres.<tenant>:<percent-encoded-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt'
export GALENA_MIGRATOR_PASSWORD=... GALENA_APP_PASSWORD=... # from your secret store
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps \
-e ADMIN_DATABASE_URL -e GALENA_MIGRATOR_PASSWORD -e GALENA_APP_PASSWORD migrate \
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
--schema galena --app-role galena_app --migrator-role galena_migrator --extension pgcrypto \
--identity-schema dredd --identity-owner atrium_migrator \
--migrator-password-env GALENA_MIGRATOR_PASSWORD --app-password-env GALENA_APP_PASSWORD
Drop the --identity-schema / --identity-owner line for a standalone Galena that owns its own
accounts. With it, this run asks for USAGE on the shared identity schema and puts it on both roles'
search_path; it never creates that schema — the hub's own provisioning does, and this one refuses by
name if it has not.
The <tenant> suffix is only for poolers that want it in the user name; otherwise the user is plain
postgres. Keep ?sslmode=verify-full&sslrootcert=... on the admin URL exactly as shown. Without it,
provision only prints a warning, and by then it has already connected and sent the admin password.
It prints each step and ends with result: DONE, committed. If a step fails, nothing is committed.
Running it again is safe, and an existing role keeps its password. Add --reset-passwords to set the
passwords again, for example after a provider restore.
From the SQL editor (no shell). provision.sql contains the same steps as plain
SQL:
- Paste the whole file into the provider's SQL editor.
- Replace both
change_mepasswords in step 2. Do this only in the editor, never in the committed file. - Run it once as the platform admin.
The script refuses placeholder passwords. An editor's query history may keep the plaintext passwords, so prefer the command above. dredd-core renders this file, so don't edit it by hand. CI fails when the file is out of date. To re-render it:
cd backend && python -m dredd_core.managed provision --sql-only --schema galena --app-role galena_app \
--migrator-role galena_migrator --extension pgcrypto \
--identity-schema dredd --identity-owner atrium_migrator --output ../db/managed/provision.sql
The committed file is rendered with the identity flags, because that is the shape the family runs.
Re-render without them for a standalone install — but do not commit that version, or CI's
--check-file fails for everybody else.
2. Configure .env
Start from the commented Managed PostgreSQL block in .env.example.
-
Connection: take the host and port from the provider's connection details. Through a pooler, use its session mode, never transaction mode: transaction pooling breaks prepared statements. Some poolers want the tenant in the user name: then it is
<role>.<tenant>, otherwise plaingalena_app/galena_migrator. -
Passwords must be percent-encoded in the URL.
-
TLS: add
?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crtto both URLs. Put the provider's CA at./certs/db-ca.crt, or pointMANAGED_DB_CA_FILEat it (leavesslrootcertout to verify against the system trust store).dredd_core.db.make_enginebuilds every engine and turns these parameters into a verifying TLS context. It refusesdisable,allowandprefer, because those modes permit plaintext. Galena's settings apply the family's one TLS rule: a URL whose host is not local ("",localhost,127.0.0.1,::1,postgres, or an entry ofDB_LOCAL_HOSTS) is refused withoutsslmode=verify-full, somigrate, the seed, the restore and the backend stop before connecting. Without that check, pg8000 would use TLS without verifying the server, and plaintext if the server declined TLS.DB_LOCAL_HOSTS(comma-separated) is for a private database on a trusted network that truly needs no TLS; there is no other opt-out. -
DB_APP_ROLE=galena_appmust be the role inDATABASE_URL, meaning the user name before.<tenant>where a pooler adds one. The grants migration grants DML to that role. Galena's settings refuse a mismatch, for example another app's role or the migrator's user name inDATABASE_URL, somigratestops before it grants anything. SetDB_APP_ROLE=galena_appin.envor leave it out, sincedocker-compose.managed-db.ymldefaults it togalena_app. Never keep aDB_APP_ROLE=appline. -
DB_POOL_SIZE/DB_MAX_OVERFLOWsize the backend's pool. A backend process uses at most their sum (15 by default).migrate, the seed and the one-shot restore each hold one unpooled connection while they run. All four apps share the database's connection limit: keep the defaults for a limit of 90 connections, or use 3 / 2 for a limit of 60. Step 0 has the calculation. -
IDENTITY_SCHEMA=dredd,MODULE_SLUG=galenaandSESSION_COOKIE_NAME=dredd_sessionmake this a module of the platform. All three are absent by default, and a Galena with them absent owns its own accounts and is not deprecated. SetIDENTITY_SCHEMAonly once the hub has been provisioned and has run its own migration: the backend refuses to start if the shared tables do not resolve where it expects, andalembic upgrade headrefuses by name rather than half-migrating.MODULE_SLUGis required alongside it — moderator rows are keyed by slug, so an empty one would make every moderator of this app resolve to nobody.IDENTITY_HUB_URLis deliberately not in that list: the hub is a sibling path at this same origin, so the sign-in card works its address out from its own (../atrium/) and one less environment variable can be forgotten.
.env holds MIGRATION_DATABASE_URL for the migrate container. docker-compose.managed-db.yml blanks
it for the long-running backend (see step 5).
3. Preflight, then migrate, seed and start
Before anything migrates, test the migrator's connection (read-only):
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate sh -c '
python -c "from app.config import get_settings; get_settings()" &&
python -m dredd_core.managed check --url MIGRATION_DATABASE_URL --app-role galena_app \
--migrator-role galena_migrator --require-tls'
The first command only loads Galena's settings, which refuse a URL for a non-local host without
sslmode=verify-full and a DATABASE_URL whose user is not DB_APP_ROLE. It fails before anything
connects. The check then connects as galena_migrator and must end in result: PASS. Because the
schema is still empty, tables and append-only audit_log warn "not migrated?". Every other line must
be OK, especially TLS (client) and connected role (galena_migrator).
DREDD_CORE_TOKEN=github_pat_... \
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
The local postgres service stays off. migrate runs alembic upgrade head as galena_migrator, then
the seed as galena_app. The backend starts once migrate has succeeded. Pass both -f files on every
later command (ps, logs, run, down).
Never migrate as the platform admin (postgres). Objects it creates may pick up the provider's
default grants for its auto-generated API, and the migrator could not manage them. The migration fails
loudly and rolls back completely when:
- it runs as
postgresor another superuser —0001's very first statement, before it creates anything ("migration preflight: refusing to migrate as postgres"). 0006's grants check it again, and used to be the only check, reached only when 0001 through 0005 happened to succeed first; DB_APP_ROLEnames a role that does not exist;- a grant did not take effect.
A URL with sslmode=prefer is refused before any connection is made.
4. Check
Both checks are read-only.
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps backend \
python -m dredd_core.managed check --url DATABASE_URL --app-role galena_app \
--migrator-role galena_migrator --expect-schema galena --require-tls \
--identity-schema dredd --identity-tier reader
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \
python -m dredd_core.managed check --url MIGRATION_DATABASE_URL --app-role galena_app \
--migrator-role galena_migrator --expect-schema galena --require-tls \
--identity-schema dredd --identity-tier reader
Drop the two identity flags for a standalone Galena. With them, reader is the tier a module is held
to — never writer (the hub) or owner (whoever owns the schema), which would report an escalation
on a perfectly correct deployment.
Both must end in result: PASS. The check covers:
-
verified TLS;
-
a connected role that is neither a superuser nor
postgres; -
the
galenaschema at the start of thesearch_path; -
the schema owned by
galena_migrator, and no table owned by a superuser orpostgres(it does not prove thatgalena_migratorowns every table); -
galena_apphaving no UPDATE, DELETE or TRUNCATE onaudit_log; -
no API role privilege on Galena's tables;
-
isolation: neither role holds any privilege in another app's schema (pass
--system-schema NAMEfor a provider schema the check should not count as another app's); -
with
--identity-schema, a positive allowlist in place of that negative sweep for the one schema that is a deliberate exception. The passing line is worth reading rather than skipping, because it is the whole security argument of one account in two sentences:[OK] identity shadow: galena holds no copy of app_user, module_permission, session [OK] identity galena_app: app_user: SELECT (id, created_at, updated_at, email, full_name, is_admin, is_active), nothing at all on password_hash/failed_login_count/locked_until; module_permission: SELECT; session: SELECT, UPDATE (last_seen_at, expires_at, revoked_at); nothing else in dreddThe allowlist is closed — any privilege on any other relation in that schema fails — and a module holding INSERT or UPDATE where it should not gets its own failure title,
identity escalation <role>for the accounts and the credentials,permission escalation <role>for who may use which module, rather than being folded into a generic leak. The shadow line is the one to read twice: a leftovergalena.app_userhas no other symptom, because thesearch_pathreaches it first and everything keeps working, silently back to two accounts per person.
After migrating, treat these warnings as failures too, because the check reports them only as WARN
and still ends in PASS:
tables: schemagalenahas no tables;append-only audit_log: the table is missing;API role ...: an API role hasUSAGEon schemagalena, or default privileges would grant it new tables.
The check does not test PUBLIC's privileges on galena directly. The API-role warnings above are the
only indirect sign. If PUBLIC held USAGE, every other app's roles could reach the schema. Run this in
the SQL editor. It must return false:
SELECT has_schema_privilege('public', 'galena', 'USAGE') OR has_schema_privilege('public', 'galena', 'CREATE');
Behind a pooler, the "TLS (server view)" line describes the pooler's own link to the database.
5. Backups and restore
-
A provider restore rewinds every app. The provider's backups and point-in-time restores rewind the whole shared database, but not
DATA_DIRon your host, which holds Galena's git repositories. After a provider restore:- Reset the role passwords (step 0): re-run step 1 with
--reset-passwords, because a restore may drop custom role passwords. Every other app in the database needs the same. - Restore the Galena backup closest to the restore point, which contains both the database and
DATA_DIR, so the rows and the repositories match again (see the one-shot restore below). - Run step 4, then start the backend.
- Reset the role passwords (step 0): re-run step 1 with
-
Galena's own backup is its per-app restore path (Administration → Backups): a
.tar.gzofDATA_DIRplus a database dump. Store the archives off the host, for example with the S3 target. A restore needs the same schema version and the sameENCRYPTION_MASTER_KEY. -
A PRE-cutover archive is not a way back to four accounts. It still has an
app_usersection, which a post-cutover restore ignores rather than writing into a schema it may not touch — so it restores this module's own data under the ids it had before the merge, which no longer name anybody. Restoring across the cutover is a database-wide operation (the dump taken before it), not a per-module one. Take that dump; the hub's runbook refuses to start without it. -
A backup carries this module, not the platform. With
IDENTITY_SCHEMAset,app_user,sessionandmodule_permissionare excluded from the archive and from the restore's delete sweep. Both halves matter: an archive containing them would put every account on the platform, and who may use or administer every other module, inside one module's backup; a restore attempting to delete them would fail outright, becausegalena_migratorholds onlySELECTandREFERENCESthere — and you would discover that mid-incident. The rows that name people come back with the ids they had, and those ids still name the same accounts, because the accounts never moved. -
By default the long-running backend holds no migrator credentials. The override sets its
MIGRATION_DATABASE_URLto empty, so nobody with a shell in the backend can rewrite the audit log. The in-app restore then answers with a clear refusal. Restore with the one-shot container instead:docker compose -f docker-compose.yml -f docker-compose.managed-db.yml stop backend docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \ python -m app.restore # list the backups docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \ python -m app.restore galena-backup-YYYYMMDD-HHMMSS.tar.gz --yes docker compose -f docker-compose.yml -f docker-compose.managed-db.yml start backend -
Opt-in in-app restore: set
BACKEND_MIGRATION_DATABASE_URLin.envto the migrator URL. The running backend then holds credentials that can rewrite every table, including the audit log.
Not yet confirmed on a real managed database
Steps 1 to 4 were run on a local emulation (dredd-core's emulate over Postgres 16, with TLS
verify-full and SCRAM), without Docker. CI's managed-db job exercises them on Postgres 17 with the
dredd-core tag it pins. Step 0 and the Compose commands have not been run against a managed provider.
Test these on a throwaway database before production:
- as the provider's
postgresrole:GRANT galena_migrator TO postgres,CREATE SCHEMA ... AUTHORIZATION galena_migratorandGRANT USAGE ON SCHEMA extensions(provisioning stops with a clear error if the last one does not take); - logins as
galena_app(orgalena_app.<tenant>) through the pooler's session mode, andverify-fullagainst the pooler's certificate; - whether the pooler's session-mode pool size fits
DB_POOL_SIZE + DB_MAX_OVERFLOW; - custom-role logins after a provider restore;
- real request latency from your host.