Files
adminandClaude Opus 5 afca6d13cb Refuse a module to anyone who has no row for it
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>
2026-10-01 11:52:05 +02:00

24 KiB
Raw Permalink Blame History

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 postgres role, 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_role and exposes public by 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 in counsel.
  • 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-full then uses the system trust store and the URLs carry no sslrootcert). One file serves the whole database. Save it as certs/db-ca.crt next to docker-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 every verify-full connection 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 most DB_POOL_SIZE + DB_MAX_OVERFLOW connections; count one more per app for a seed, migrate 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, set DB_POOL_SIZE=3 and DB_MAX_OVERFLOW=2 in 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 least DB_POOL_SIZE + DB_MAX_OVERFLOW + 1 per 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 it provision only 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 LOGIN roles and schema counsel owned by counsel_migrator. PUBLIC gets nothing on the schema; counsel_app gets USAGE.
  • Both roles get USAGE on extensions (pg_trgm's operators and operator classes resolve through it) and search_path = counsel, extensions — counsel, dredd, extensions with the identity arguments. Counsel's own schema stays FIRST either way, or alembic_version, the enum types and every new table would land in a schema its migrator does not own. The migrator also gets statement_timeout = 30min.
  • With --identity-schema, both roles also get USAGE on it and the run verifies the grant took — a GRANT by 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_trgm WITH 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 can SET ROLE counsel_migrator and rewrite audit_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).

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

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

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

python -m dredd_core.managed provision --sql-only --schema 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

  1. Start from the commented "managed provider" block in .env.example.
  2. Replace the URL, role and pool settings with it.
  3. Delete DB_SUPERUSER_PASSWORD, DB_APP_PASSWORD and DB_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 plain counsel_app / counsel_migrator.
    • A provider's direct connection may be IPv6-only, and migrate and backend run on Compose bridge networks without IPv6 (edge and internal in docker-compose.yml). From this stack it then needs the provider's IPv4 option, or IPv6 in Docker: ip6tables enabled in the daemon, plus enable_ipv6: true and an IPv6 subnet on both internal and edge in a further override. Without either, migrate can't reach the database and fails on every start: use the pooler.
  • TLS. sslmode=verify-full against the provider's CA, which the override mounts at /run/certs/db-ca.crt from MANAGED_DB_CA_FILE (leave sslrootcert out 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 and scripts/create_extensions.py — is built by dredd_core.db.make_engine, which turns these parameters into a verifying TLS context. sslmode=prefer / allow / disable are refused with an error before anything connects.
    • Leaving sslmode out 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 compose postgres service, or an entry of DB_LOCAL_HOSTS) unless it has sslmode=verify-full. migrate then stops before it connects, with DATABASE_URL points at a remote database without sslmode=verify-full … (or the same for MIGRATION_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=true is the one escape hatch that lifts the rule for both URLs. Never set either for a managed provider.
  • 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_ROLE names the runtime role for the runtime-grants migration (0002_runtime_grants). It must be the user in DATABASE_URL without the .<tenant> suffix, and MIGRATION_DATABASE_URL must log in as a different user. Settings refuse anything else at start-up, before anything connects: the migrator's URL pasted as DATABASE_URL stops migrate with DATABASE_URL logs in as 'counsel_migrator' but DB_APP_ROLE is 'counsel_app', instead of running the backend as the owner of audit_log. If DB_APP_ROLE names a role that doesn't exist, the migration stops with runtime grants: role … does not exist and rolls back.
  • Pool. The backend (one uvicorn process) holds up to DB_POOL_SIZE + DB_MAX_OVERFLOW connections. Count one more for a seed or managed check running 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 / 2 fit 60. Through a pooler in session mode, where a client keeps its connection, the pooler's per-role pool size must be at least DB_POOL_SIZE + DB_MAX_OVERFLOW + 1 (16 with the defaults); below that, under load, the backend's overflow connections fail, and so do a managed check or 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).

  • migrate runs alembic upgrade head as counsel_migrator. Through the role's search_path, every table, enum type and alembic_version lands in counsel, and nothing is schema-qualified in code. Another app's same-named audit_log, app_user, firm, alembic_version or user_role type in its own schema doesn't make a table or type get skipped. 0002 then grants DB_APP_ROLE its privileges, strips the API roles and verifies the result.
  • The seed then runs, also as counsel_migrator (MIGRATION_DATABASE_URL); it is idempotent.
  • backend gets a blank MIGRATION_DATABASE_URL and blank DB_*_PASSWORDs, so the long-running process can only log in as counsel_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 in public could be exposed through an auto-generated API. 0002 checks the same thing again; that used to be the only check, and it was reached only when 0001 happened 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, then docker compose -f … -f … run --rm migrate once.

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-user names. Without it, the migrator's credentials in DATABASE_URL would pass every other line.
  • The current schema is counsel and the search_path starts with it (and, on the platform, names dredd after it — add --identity-schema dredd --identity-tier reader and check also prints the full identity matrix, fails on a privilege wider than the reader tier, and fails if a local copy of app_user, session or module_permission has appeared in counsel).
  • counsel_migrator owns the schema and every table and view in it (any other owner fails), and has a 30-minute statement_timeout.
  • counsel_app has USAGE, and audit_log is 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 NAME for a provider schema the check should not count as another app's.
  • anon, authenticated and service_role hold nothing in counsel.

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:
    1. Stop Counsel's backend: docker compose -f … -f … stop backend.
    2. 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).
    3. Start: up -d. migrate is a no-op at head, and the seed changes nothing.
    4. Run the check in section 4.
  • 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-db job, on postgres:17. It checks that provision.sql is current, runs dredd_core.managed emulate (TEST-ONLY: a CREATEROLE admin standing in for the provider's postgres, the API roles and an extensions schema), provisions a decoy app whose schema holds a same-named audit_log, app_user, alembic_version and user_role type, then provisions Counsel, migrates and seeds as counsel_migrator and runs the integration suite as counsel_app with DB_APP_ROLE=counsel_app. It runs the managed check as both roles, asserts that everything is in counsel, nothing in public, 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, a DB_APP_ROLE naming 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 as DATABASE_URL and a remote URL without sslmode (both refused at start-up, before connecting), the check's --expect-user against 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 with DB_LOCAL_HOSTS and DB_ALLOW_UNVERIFIED_TLS, the role checks, every engine built by make_engine, the offline DDL with a percent-encoded password, and provision.sql being current.

Not yet confirmed on a real managed database:

  • The provider's postgres running GRANT counsel_migrator TO postgres, CREATE SCHEMA … AUTHORIZATION, GRANT USAGE ON SCHEMA extensions and CREATE EXTENSION pg_trgm WITH SCHEMA extensions. Provisioning stops with a clear error if the extensions grant doesn't take.
  • The custom roles' search_path and statement_timeout settings 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.