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>
24 KiB
Counsel Scorecard in the family's shared managed database
All four apps of the Dredd family (Atrium, Galena, Sygna and 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; Counsel'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 7 cover only Counsel's part of the database.
0. The database itself (once, for all four apps)
Don't start Counsel until each of these holds:
- Create the database at the provider: Postgres 16 or 17, in a region close to your server. Keep
the platform admin's password (the provider's
postgresrole, usually not a superuser there) in your secret store. Counsel uses it only for provisioning (step 1); it never goes into.env. - 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. No app of the family uses it; section 4's check proves those roles hold nothing incounsel. - Enforce TLS on the server side if the provider offers a setting for it, so no client can connect in plaintext. Changing it may restart the database, so do it before go-live.
- 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.yml, and compare its fingerprint and expiry with what the dashboard shows:openssl x509 -in certs/db-ca.crt -noout -subject -enddate -fingerprint -sha256. Put the expiry date in the ops calendar: after it everyverify-fullconnection fails. - Restrict the network. If the provider offers IP restrictions, allow only the backend host's outbound addresses, for direct and pooled connections alike. Until then the database accepts connections from any IP.
- 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), and the provider's own services may draw on the same total: 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,migrateor 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 per-role 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 (section 6). After any restore, set every app's role passwords again (a restore may drop custom role passwords) and, if the provider bans a client IP after a few failed logins, lift the ban on the backend host, which would lock out all four apps there.
What Counsel gets
| Object | What it is |
|---|---|
schema counsel |
Counsel's tables, enum types and alembic_version, never public. Owned by counsel_migrator; PUBLIC holds nothing on it |
role counsel_migrator |
Owns every object; used only by the one-shot migrate service (alembic upgrade head, then the seed). Its search_path is counsel, extensions and its statement_timeout is 30min, because a provider may cap statements at a couple of minutes, too short for a migration |
role counsel_app |
The runtime role, the backend's only login: DML on Counsel's tables, but audit_log is append-only (no UPDATE, DELETE or TRUNCATE). Its search_path is counsel, extensions |
schema dredd (platform only) |
The shared identity schema — app_user, session, module_permission: one account for the whole family, plus one row per person per module saying which modules they may open and which they may administer. Owned by the HUB's migrator, not by Counsel. Provisioning gives Counsel's two roles USAGE and appends it to their search_path, after counsel; the tables and the per-role grants come from the hub's own migration |
extension pg_trgm |
In schema extensions, created by provisioning: fuzzy search (the % operator, similarity(), the gin_trgm_ops indexes). Both roles get USAGE on that schema. btree_gin, which the local stack also installs, is not used by any index |
Role names are cluster-wide, so they carry the app's name. With a generic app / migrator, one app's
migration could undo another app's protections. So never create plain app or migrator roles in the
shared database: Counsel's 0001 still revokes from a role literally named app when one exists,
which is the local-stack shape. The API roles (anon, authenticated, service_role) get no privilege
in counsel; Counsel's roles get none in any other app's schema, and no other app's roles get any in
counsel.
The one deliberate exception to "no privilege outside my schema" is the shared identity schema, and
it is narrow enough to state in full: counsel_app may read seven columns of app_user (never
password_hash, failed_login_count or locked_until), read session and update three of its
columns (last_seen_at, expires_at, revoked_at), read module_permission, and nothing else
anywhere in dredd. counsel_migrator holds SELECT and REFERENCES on app_user — enough to
point this schema's foreign keys at it — and nothing else. Neither may INSERT: a role that can write
an app_user row can create an account, one that can write a session row can mint a credential
for the administrator, and one that can write a module_permission row can let itself in — or
promote itself to moderator of itself. That last one is why "no row means no entry" is worth
anything: the refusal is a grant this app does not hold, not a check it could be talked out of.
managed check --identity-schema dredd --identity-tier reader prints that matrix back and fails on
anything wider.
1. Provision Counsel (once, as the platform admin)
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 COUNSEL_MIGRATOR_PASSWORD && export COUNSEL_MIGRATOR_PASSWORD
read -rs COUNSEL_APP_PASSWORD && export COUNSEL_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
# (<role>.<tenant> only where the pooler wants the tenant in the user name; plain postgres otherwise)
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
--schema counsel --app-role counsel_app --migrator-role counsel_migrator --extension pg_trgm \
--identity-schema dredd --identity-owner atrium_migrator \
--migrator-password-env COUNSEL_MIGRATOR_PASSWORD --app-password-env COUNSEL_APP_PASSWORD
The two --identity-* arguments are the platform's; drop both for a Counsel that owns its own
accounts. They never create that schema here — the hub's provisioning does, as its owner — so run
the hub's first, or this refuses by name rather than racing it.
- Keep
?sslmode=verify-full&sslrootcert=...on the admin URL: without itprovisiononly warns, and by then it has connected and sent the admin password. - 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 schemacounselowned bycounsel_migrator.PUBLICgets nothing on the schema;counsel_appgetsUSAGE. - Both roles get
USAGEonextensions(pg_trgm's operators and operator classes resolve through it) andsearch_path = counsel, extensions—counsel, dredd, extensionswith the identity arguments. Counsel's own schema stays FIRST either way, oralembic_version, the enum types and every new table would land in a schema its migrator does not own. The migrator also getsstatement_timeout = 30min. - With
--identity-schema, both roles also getUSAGEon it and the run verifies the grant took — aGRANTby a role that does not own the schema is only a warning in PostgreSQL, which is exactly the kind of silent half-success this family refuses to ship. - It creates
pg_trgmWITH SCHEMA extensions, and refuses to run if pg_trgm is already installed somewhere else. - It ends by revoking the admin's temporary membership in
counsel_migrator(so nobody with dashboard SQL access canSET ROLE counsel_migratorand rewriteaudit_log), 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, different per role).
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 counsel --app-role counsel_app \
--migrator-role counsel_migrator --extension pg_trgm \
--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, and
the DB-free test tests/test_managed_db.py::test_managed_provision_sql_is_current does the same in a
plain pytest.
2. Configure .env
- Start from the commented "managed provider" block in
.env.example. - Replace the URL, role and pool settings with it.
- Delete
DB_SUPERUSER_PASSWORD,DB_APP_PASSWORDandDB_MIGRATOR_PASSWORD: nothing uses them here. The platform admin's password never goes into.env.
MANAGED_DB_CA_FILE=./certs/db-ca.crt
DATABASE_URL=postgresql+pg8000://counsel_app.<tenant>:<password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
MIGRATION_DATABASE_URL=postgresql+pg8000://counsel_migrator.<tenant>:<password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
DB_APP_ROLE=counsel_app
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=10
- Connection.
- Take the host and port from the provider's connection details. Through a pooler, use its
session mode, never transaction mode (no prepared statements, and clients keep no session
state). Some poolers want the tenant in the user name: then it is
<role>.<tenant>, otherwise plaincounsel_app/counsel_migrator. - A provider's direct connection may be IPv6-only, and
migrateandbackendrun on Compose bridge networks without IPv6 (edgeandinternalindocker-compose.yml). From this stack it then needs the provider's IPv4 option, or IPv6 in Docker:ip6tablesenabled in the daemon, plusenable_ipv6: trueand an IPv6 subnet on bothinternalandedgein a further override. Without either,migratecan't reach the database and fails on every start: use the pooler.
- Take the host and port from the provider's connection details. Through a pooler, use its
session mode, never transaction mode (no prepared statements, and clients keep no session
state). Some poolers want the tenant in the user name: then it is
- TLS.
sslmode=verify-fullagainst the provider's CA, which the override mounts at/run/certs/db-ca.crtfromMANAGED_DB_CA_FILE(leavesslrootcertout to verify against the system trust store, when the server's certificate chains to a public CA). Every engine — the backend's, Alembic's, the seed's, the test fixture's andscripts/create_extensions.py— is built bydredd_core.db.make_engine, which turns these parameters into a verifying TLS context.sslmode=prefer/allow/disableare refused with an error before anything connects.- Leaving
sslmodeout is refused too: the family's one TLS rule (dredd_core.db.require_verified_tls). Without it pg8000 would encrypt without checking the server, or fall back to plaintext. Settings refuse a URL whose host is not local ("",localhost,127.0.0.1,::1, the composepostgresservice, or an entry ofDB_LOCAL_HOSTS) unless it hassslmode=verify-full.migratethen stops before it connects, withDATABASE_URL points at a remote database without sslmode=verify-full …(or the same forMIGRATION_DATABASE_URL); the message names neither the host nor the password. DB_LOCAL_HOSTS(comma-separated) is for a private database on a trusted network that truly needs no TLS.DB_ALLOW_UNVERIFIED_TLS=trueis the one escape hatch that lifts the rule for both URLs. Never set either for a managed provider.
- Leaving
- Passwords. In the URL, percent-encode everything outside
A-Z a-z 0-9 - . _ ~(@→%40,%→%25). Alembic reads the URL directly (never through configparser), so an encoded%is fine. DB_APP_ROLEnames the runtime role for the runtime-grants migration (0002_runtime_grants). It must be the user inDATABASE_URLwithout the.<tenant>suffix, andMIGRATION_DATABASE_URLmust log in as a different user. Settings refuse anything else at start-up, before anything connects: the migrator's URL pasted asDATABASE_URLstopsmigratewithDATABASE_URL logs in as 'counsel_migrator' but DB_APP_ROLE is 'counsel_app', instead of running the backend as the owner ofaudit_log. IfDB_APP_ROLEnames a role that doesn't exist, the migration stops withruntime grants: role … does not existand rolls back.- Pool. The backend (one uvicorn process) holds up to
DB_POOL_SIZE + DB_MAX_OVERFLOWconnections. Count one more for a seed ormanaged checkrunning beside it; migrate and seed use no pool. Step 0 has the budget for four apps: the defaults fit a limit of 90 connections,3/2fit 60. Through a pooler in session mode, where a client keeps its connection, the pooler's per-role pool size must be at leastDB_POOL_SIZE + DB_MAX_OVERFLOW + 1(16 with the defaults); below that, under load, the backend's overflow connections fail, and so do amanaged checkor a second backend during a redeploy.
Settings check .env whenever migrate or the backend starts, before anything connects. They refuse a
remote URL without verify-full, a DATABASE_URL user other than DB_APP_ROLE, and the same user in both
URLs. migrate then exits non-zero and the backend never starts. Check the rest by hand:
sslrootcert=/run/certs/db-ca.crt (the path inside the containers) on both URLs, users that are not the
platform admin, the pooler's session-mode port.
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, stops migrate and backend waiting for it, mounts the CA into both, and passes
DB_APP_ROLE and the pool knobs through (Compose refuses to start when DB_APP_ROLE is unset).
migraterunsalembic upgrade headascounsel_migrator. Through the role'ssearch_path, every table, enum type andalembic_versionlands incounsel, and nothing is schema-qualified in code. Another app's same-namedaudit_log,app_user,firm,alembic_versionoruser_roletype in its own schema doesn't make a table or type get skipped.0002then grantsDB_APP_ROLEits privileges, strips the API roles and verifies the result.- The seed then runs, also as
counsel_migrator(MIGRATION_DATABASE_URL); it is idempotent. backendgets a blankMIGRATION_DATABASE_URLand blankDB_*_PASSWORDs, so the long-running process can only log in ascounsel_app. Counsel has no in-app restore, so it never needs the migrator.- Never migrate as the platform admin (
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. Anything created as the admin would be owned by it, and anything created inpubliccould be exposed through an auto-generated API.0002checks the same thing again; that used to be the only check, and it was reached only when0001happened to succeed. - Nothing retries a failed migration. Some providers ban the client IP for a while after a few wrong
passwords in a row. Fix
.env, thendocker compose -f … -f … run --rm migrateonce.
Pass both -f files on every compose command (ps, logs, run, down).
4. Verify
check() { # check URL-variable expected-login-role
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \
python -m dredd_core.managed check --url "$1" --expect-user "$2" --expect-schema counsel \
--require-tls --app-role counsel_app --migrator-role counsel_migrator --append-only audit_log \
${IDENTITY_SCHEMA:+--identity-schema "$IDENTITY_SCHEMA" --identity-tier reader}
}
check DATABASE_URL counsel_app
check MIGRATION_DATABASE_URL counsel_migrator
Run it inside the container, as above: the URLs' sslrootcert=/run/certs/db-ca.crt exists only there,
and on the host the check exits 2 with sslrootcert file not found.
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).
- Each URL logs in as the role
--expect-usernames. Without it, the migrator's credentials inDATABASE_URLwould pass every other line. - The current schema is
counseland thesearch_pathstarts with it (and, on the platform, namesdreddafter it — add--identity-schema dredd --identity-tier readerandcheckalso prints the full identity matrix, fails on a privilege wider than the reader tier, and fails if a local copy ofapp_user,sessionormodule_permissionhas appeared incounsel). counsel_migratorowns the schema and every table and view in it (any other owner fails), and has a 30-minutestatement_timeout.counsel_apphasUSAGE, andaudit_logis append-only for it.- Isolation: neither Counsel role holds any privilege in another app's schema (the other apps' checks
prove the reverse). Pass
--system-schema NAMEfor a provider schema the check should not count as another app's. anon,authenticatedandservice_rolehold nothing incounsel.
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 .env's DATABASE_URL,
MIGRATION_DATABASE_URL and DB_APP_ROLE set (settings check them offline too). The TLS parameters are
stripped offline, so the CA file doesn't have to exist.
A new revision that adds a table must end with op.execute(runtime_grants_sql(...)) again, with the same
arguments as 0002: the shared database sets no default privileges.
6. Restore: Counsel specifics
- Counsel has no app-level backup. Its data comes back only with a provider backup or a point-in-time restore, and that rewinds all four apps together (step 0). Galena and Sygna have per-app backups; Counsel does not.
- After a provider restore, follow the family runbook, and for Counsel:
- Stop Counsel's backend:
docker compose -f … -f … stop backend. - Once the database is back, set the passwords again, because a restore may drop 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, and the seed changes nothing. - Run the check in section 4.
- Stop Counsel's backend:
- The backend never needs migrator credentials for any of this.
7. Removing Counsel from the database
As the platform admin, in one transaction (pg_trgm stays: it lives in extensions and another app may
use it):
BEGIN;
GRANT counsel_migrator, counsel_app TO CURRENT_USER;
DROP SCHEMA counsel CASCADE;
REVOKE USAGE ON SCHEMA extensions FROM counsel_migrator, counsel_app;
DROP OWNED BY counsel_migrator, counsel_app;
DROP ROLE counsel_app, counsel_migrator;
COMMIT;
How this is tested
- CI's
managed-dbjob, onpostgres:17. It checks thatprovision.sqlis current, runsdredd_core.managed emulate(TEST-ONLY: a CREATEROLE admin standing in for the provider'spostgres, the API roles and anextensionsschema), provisions a decoy app whose schema holds a same-namedaudit_log,app_user,alembic_versionanduser_roletype, then provisions Counsel, migrates and seeds ascounsel_migratorand runs the integration suite ascounsel_appwithDB_APP_ROLE=counsel_app. It runs the managed check as both roles, asserts that everything is incounsel, nothing inpublic, the decoy untouched and neither app able to reach the other, and runs a downgrade/upgrade cycle. - A local TLS emulation, on PostgreSQL 16. The same path ran over
verify-full, with passwords containing% @ : / ? #, next to a decoy app's schema. Negative cases: migrating as the admin, aDB_APP_ROLEnaming no role,sslmode=prefer, a CA that did not sign the server certificate, and a leaked cross-schema grant (the check fails, then passes after the revoke). Also: the migrator's URL asDATABASE_URLand a remote URL withoutsslmode(both refused at start-up, before connecting), the check's--expect-useragainst the wrong login, and a table owned by a role other than the migrator. - DB-free, in a plain
pytest(tests/test_managed_db.py): the TLS rule withDB_LOCAL_HOSTSandDB_ALLOW_UNVERIFIED_TLS, the role checks, every engine built bymake_engine, the offline DDL with a percent-encoded password, andprovision.sqlbeing current.
Not yet confirmed on a real managed database:
- The provider's
postgresrunningGRANT counsel_migrator TO postgres,CREATE SCHEMA … AUTHORIZATION,GRANT USAGE ON SCHEMA extensionsandCREATE EXTENSION pg_trgm WITH SCHEMA extensions. Provisioning stops with a clear error if theextensionsgrant doesn't take. - The custom roles'
search_pathandstatement_timeoutsettings surviving the provider's own configuration. counsel_app.<tenant>logins through a pooler's session mode, and after a restore.- The pooler's default session-mode pool size on the chosen instance, compared with the backend's
DB_POOL_SIZE + DB_MAX_OVERFLOW(15, plus 1 for a check or seed beside it). - Certificate host-name checks against the pooler host.
- PostgreSQL 17 end to end (CI covers it; locally only 16 was run) and real latency.