party.counterparty_id; create/update sync an organisation through core's link_or_create when Sygna may write the register (natural persons never). Revision 0006 links existing organisations, through the hub's import door on the platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
26 KiB
Sygna in the family's shared managed database
The 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, so Sygna's backend (with its two schedulers and its
DATA_DIR) 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.
Database-wide steps come first. 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. Sections 1 to 6
cover only Sygna's part.
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, with the members limited to the people who operate it (section 1, "That last revoke is not
a wall"). Keep the platform admin's password (the provider's
postgresrole, usually not a superuser there) in your secret store; Sygna uses it only for provisioning. - Download the provider's root CA from its dashboard, save it as
certs/db-ca.crt(or whereverMANAGED_DB_CA_FILEpoints) on every container host, check it withopenssl x509 -in certs/db-ca.crt -noout -subject -enddate -fingerprint -sha256, and put its expiry date in the ops calendar: after it, everyverify-fullconnection fails. Skip the file only if the server's certificate chains to a public CA;verify-fullthen uses the system trust store and the URLs carry nosslrootcert. - 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, so nothing needs it. - Enforce TLS on incoming connections if the provider offers the setting (changing it may restart the database), and restrict the network to the backend hosts, plus the machine you provision from while you do.
- Size the connection budget for four apps with section 2, including any pooler's per-role pool size.
- A backup decision. A provider backup or point-in-time restore rewinds all four apps together; Sygna's own backup (section 5) rewinds Sygna alone. A provider restore means: stop every app's backend, restore, reset every app's role passwords (a restore may drop custom role passwords; for Sygna, section 5), lift any IP ban, start, check.
The rest of this page covers only Sygna's part.
| Sygna | |
|---|---|
| Schema | sygna (never public), owned by the migrator |
| Migrator role | sygna_migrator: owns every object; used by alembic upgrade head in the one-shot migrate service and by the one-shot restore. Its statement_timeout is 30min, because a provider may cap statements at a couple of minutes, which is too short for a migration or a restore |
| Runtime role | sygna_app: DML only; no UPDATE / DELETE / TRUNCATE on audit_log, no DELETE / TRUNCATE on conflict_check and aml_assessment; the backend's only login |
| Extensions | none. gen_random_uuid() is built into PostgreSQL, and 0001's CREATE EXTENSION IF NOT EXISTS pgcrypto is a no-op next to the provider's copy in extensions |
Role names are cluster-wide, so they carry the app's name. With a shared app role, another app's
migration could grant back the DELETE that Sygna revokes on its evidence tables, and one password
would open every app. Sygna's migrations never name a role or a schema: they grant to DB_APP_ROLE
in the migrator's current schema. The API roles (anon, authenticated, service_role) get no
privilege in sygna, and Sygna's roles get none in any other app's schema.
1. Provision Sygna (once, as the platform admin)
dredd-core owns the provisioning routine; nothing here is hand-written SQL.
From a shell (preferred). Passwords come from environment variables, are sent as SCRAM
verifiers and are never printed. Run it in Sygna's own image, on the backend host: the image has
dredd-core (a private package you would otherwise have to install), the override mounts the CA at
/run/certs/db-ca.crt, and the host is already inside the network restrictions. It needs the image
built and a .env in place (section 2; the roles need not exist yet).
read -rs SYGNA_MIGRATOR_PASSWORD && export SYGNA_MIGRATOR_PASSWORD
read -rs SYGNA_APP_PASSWORD && export SYGNA_APP_PASSWORD
read -rs ADMIN_DATABASE_URL && export ADMIN_DATABASE_URL
# postgresql+pg8000://postgres.<tenant>:<url-encoded password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
DREDD_CORE_TOKEN=github_pat_... \
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml build migrate
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps \
-e ADMIN_DATABASE_URL -e SYGNA_MIGRATOR_PASSWORD -e SYGNA_APP_PASSWORD \
migrate python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
--schema sygna --app-role sygna_app --migrator-role sygna_migrator \
--migrator-password-env SYGNA_MIGRATOR_PASSWORD --app-password-env SYGNA_APP_PASSWORD
The .<tenant> suffix is only for poolers that want the tenant in the user name; otherwise the user
is plain postgres. 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.
Outside the container, install dredd-core at the version backend/requirements.txt pins and give
sslrootcert a path that holds from where you run it: sslrootcert=../certs/db-ca.crt from
backend/, or an absolute path. A relative path is read from the current directory, and a missing
file stops the command before it connects.
Provisioning runs in one transaction and reports each step (exit 0 = done, 1 = refused or failed
and rolled back, 2 = could not run): plain LOGIN roles, schema sygna owned by sygna_migrator,
nothing for PUBLIC on it, USAGE for sygna_app, USAGE on extensions for both,
search_path = sygna, extensions for both, statement_timeout = 30min for the migrator, and
finally the admin's temporary membership in sygna_migrator revoked. Re-running is safe; an
existing role keeps its password unless you add --reset-passwords.
That last revoke is not a wall. It removes the standing membership, nothing more. The platform
admin created both roles and keeps ADMIN OPTION on them (PostgreSQL 16+), so anyone with the
provider's SQL editor can run GRANT sygna_migrator TO postgres again, reset either role's
password, and then read or change every Sygna table, deleting conflict checks and rewriting the
audit log included. The provisioning itself does exactly that grant on every re-run. Treat SQL-editor
access at the provider as full control over Sygna's data: keep the database's members to the few who
operate it, and rely on the provider's own records of their access, not on this revoke.
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 history then holds the plaintext passwords, which the shell path
avoids.
provision.sql is dredd-core's rendering; do not edit it. After a dredd-core upgrade:
cd backend
python -m dredd_core.managed provision --sql-only --schema sygna --app-role sygna_app \
--migrator-role sygna_migrator --output ../db/managed/provision.sql
CI runs the same command with --check-file ../db/managed/provision.sql and fails when the file is
stale.
2. Configure .env
Take the commented Managed PostgreSQL block from .env.example in place of
the Database settings, and put the provider's CA at ./certs/db-ca.crt (or point
MANAGED_DB_CA_FILE at it):
DATABASE_URL=postgresql+pg8000://sygna_app.<tenant>:<url-encoded password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
MIGRATION_DATABASE_URL=postgresql+pg8000://sygna_migrator.<tenant>:<url-encoded password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
DB_APP_ROLE=sygna_app
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=10
MANAGED_DB_CA_FILE=./certs/db-ca.crt
- Connection. Host and port from the provider's connection details. Through a pooler, its
session mode, never transaction mode (it breaks prepared statements; port 6543 on some
providers). Some poolers want the tenant in the user name: then it is
<role>.<tenant>, otherwise the plain role name. - TLS.
sslmode=verify-fullagainst the provider's CA, which the override mounts at/run/certs/db-ca.crt(leavesslrootcertout to verify against the system trust store). Every engine Sygna builds (runtime, Alembic, the seed, restore) goes throughdredd_core.db.make_engine, which turns the two parameters into a verifying TLS context.make_engineon its own refuses onlyprefer/allow/disable: it still takesrequireandverify-ca, which do not check the host name, and a URL with nosslmode, where pg8000 does not verify the server and falls back to plaintext if the server allows it. So Sygna'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, and migrations, the seed, the restore and the backend stop before connecting.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. - Passwords. Percent-encode each one with
python -c 'import urllib.parse, getpass; print(urllib.parse.quote(getpass.getpass(), safe=""))', not by hand.% @ : / ? #break the URL, and Compose substitutes a$in.env(an unencoded$HOMEsilently becomes a directory name, the login fails, and some providers ban the host's IP after a few failures).quoteturns$into%24. Alembic uses the URL directly, so an encoded%is fine. DB_APP_ROLEis the role inDATABASE_URLwithout.<tenant>. Migration0002grants it its privileges; a role that does not exist stops the migration withruntime grants: role … does not existand rolls it back.- Pool. Each backend process holds up to
DB_POOL_SIZE + DB_MAX_OVERFLOWconnections. The seed, migrations, restores andmanaged checkuse one unpooled connection each. Two limits apply:- A pooler's pool size, where the provider has one: poolers keep a separate pool per role,
database and mode, and in session mode a pool admits at most that many clients; one more waits and
is then refused.
sygna_app's backend plus amanaged checkor one-shot beside it needs a pool size of at leastDB_POOL_SIZE + DB_MAX_OVERFLOW + 1(16 with the defaults). Where the setting is database-wide, the largest app's pool decides it. - The database's connection limit (the server's
max_connections), shared by all four apps' pools, the migrator sessions and the provider's own services. Keep the sum of every app'sDB_POOL_SIZE + DB_MAX_OVERFLOW + 1well under it: with the defaults that is 4 × 16 = 64, which fits a limit of 90. For a limit of 60 setDB_POOL_SIZE=3andDB_MAX_OVERFLOW=2in every app (4 × 6 = 24). How much the provider's services take, and whether these numbers hold under load, has not been measured yet (see the end of this page).
- A pooler's pool size, where the provider has one: poolers keep a separate pool per role,
database and mode, and in session mode a pool admits at most that many clients; one more waits and
is then refused.
POSTGRES_PASSWORDandDB_*_PASSWORDare unused here (no local postgres); remove them.
Then the pre-flight, which reads the files and never connects or prints a password:
python backend/scripts/deploy_check.py --env .env
For the environment file it fails on: a URL without sslmode=verify-full, or with an sslrootcert
other than the mount target /run/certs/db-ca.crt, port 6543, a user that is the platform admin, a
role that does not start with sygna_, the same role in both URLs, DB_APP_ROLE not matching the
runtime user before .<tenant>, an unencoded @, #, $ or bare %, a leftover <placeholder>
or change_me, and a missing CA file. It warns about a pooler user without .<tenant> and about
verify-full with no sslrootcert (the system trust store).
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, mounts the CA into migrate and backend, and passes the pool
knobs to backend. It sets nothing for TLS: the rule is in Sygna's settings and cannot be switched
off. It does not set DB_APP_ROLE either: that comes from .env alone, the file
deploy_check.py checked. An environment: entry would let a DB_APP_ROLE exported in your shell
win over .env, and 0002 would then grant Sygna's tables to whichever existing role it names,
another app's included.
migraterunsalembic upgrade headassygna_migrator. Through the role'ssearch_pathevery table, enum type andalembic_versionlands insygna; nothing is schema-qualified in code, and another app's same-namedaudit_log,app_useror enum type in its own schema neither hides a table fromcreate_allnor makes Alembic think Sygna is already migrated.0002then grantssygna_appits privileges, keeps the evidence tables protected, strips the API roles and verifies all of it.- The seed runs as
sygna_app. backendgets an emptyMIGRATION_DATABASE_URL, so the long-running process can only log in assygna_app(see Restore for the opt-in).- 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: objects it created would be owned bypostgresand sit inpublic, where an auto-generated API looks.0002's grants make the same check a second time. That used to be the only time, and it was reached only when0001happened to succeed first; as a module it did not, and the refusal arrived asrelation "app_user" does not existinstead. - Nothing retries a failed migration: some providers ban the host's IP after a few wrong
passwords in a row. Fix
.env, then runmigrateonce more.
Pass both -f files on every compose command (ps, logs, run, down).
To review the DDL without a database: alembic upgrade head --sql with MIGRATION_DATABASE_URL and
DB_APP_ROLE set (the TLS parameters are dropped offline, so the CA file need not exist).
4. Verify
for url in DATABASE_URL MIGRATION_DATABASE_URL; do
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \
python -m dredd_core.managed check --url "$url" --expect-schema sygna --require-tls \
--app-role sygna_app --migrator-role sygna_migrator \
--append-only audit_log --no-delete conflict_check aml_assessment
done
On the platform, add --identity-schema dredd --identity-tier reader --counterparties writer (Sygna
writes the shared counterparty register since dredd-core 0.21.0) — reader is a module's
tier; the hub's own roles are checked as owner. Without the flag the check would sweep dredd
as "another app's schema" and fail Sygna for holding privileges there, which is exactly the
privilege it is supposed to hold.
Read-only, never prints a password; exit 0 = pass, 1 = a check failed, 2 = could not run. Exit 0
is not enough for TLS: read the TLS (client) line. --require-tls fails a URL with no
sslmode, but reports sslmode=require and verify-ca only as a WARN and still exits 0. Anything
there but OK with verify-full means .env is wrong (Sygna's settings and deploy_check.py refuse
such a URL anyway). Through a pooler, the TLS (server view) line describes the pooler's own link to
the database, not yours. Beyond that, it checks that the current schema and search_path start with
sygna, that sygna_migrator owns the schema and every table (with a 30-minute
statement_timeout), that sygna_app has USAGE and cannot rewrite audit_log or delete from
conflict_check and aml_assessment, isolation (neither Sygna role holds anything 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), and that anon, authenticated and
service_role hold nothing in sygna.
4a. Joining the platform's one account (the cutover)
Everything above describes Sygna owning its own accounts. This section is the one-time change that
makes it a module: it reads the platform's accounts and never writes them, and the cookie
somebody was given when they signed in at the hub is the cookie Sygna resolves. Because the family
runs at one origin, that is the entire mechanism — one cookie, one session row, no protocol.
Three parties, in this order, and none can do another's half. Getting the order wrong is the one mistake worth spelling out, because it fails at the hub's migration rather than at Sygna's:
- The platform admin provisions every app with the identity flags. Sygna's committed
provision.sqlis already rendered with them; re-run section 1 with--identity-schema dredd --identity-owner atrium_migratoradded. That is what grantssygna_appandsygna_migratorUSAGEondreddand sets theirsearch_pathtosygna, dredd, extensions— Sygna's own schema first, which is not negotiable (otherwisealembic_version, the enum types and every new table land in a schemasygna_migratordoes not own). It is idempotent. - The hub's migrator creates the three tables in
dreddand grants each role its tier. It can only do this after step 1 for every app: the grant block refuses to grant on a table to a role holding noUSAGEon the schema, andUSAGEcomes from provisioning. If the hub's migration reports<role> has no USAGE on schema dredd, step 1 has not been run for that app. - This app's
alembic upgrade head, which runs0003_shared_identity.
Before step 3, the census. Revision 0003 matches this schema's accounts to the shared ones by
lower(email) and refuses by name if one has no match, rather than orphaning it — because
neither side can fix it alone (sygna_migrator holds no INSERT on the shared app_user, and the
hub's migrator holds nothing in sygna). So run, as the platform admin:
SELECT 'sygna' AS schema, email, is_admin, is_active FROM sygna.app_user
UNION ALL SELECT 'dredd', email, is_admin, is_active FROM dredd.app_user ORDER BY email;
Anything in sygna and not in dredd is a decision for a person: import it (as the platform
admin, forcing is_admin to false — a module could previously mint its own administrator, and
carrying that flag across would silently make them an administrator of everything), or delete that
account and its rows here deliberately. On a seeded install the likely candidate is the demo
adwokat@example.com from seed.py.
What 0003 does, in one transaction. Refuses unless dredd exists, holds all three tables,
and this role can SELECT and REFERENCES dredd.app_user; matches the accounts and raises on an
unmatched e-mail, on two local accounts matching one shared one, and on a shared id that is also a
local account id; drops this schema's foreign keys to the local app_user; rewrites all 35
person-columns plus permission_grant.principal_id (which has no foreign key at all — it is
polymorphic, so nothing else would ever mention a row it missed); counts orphans and raises; re-adds
every foreign key against dredd.app_user, which validates each one; and drops the local
app_user, session and the permission table under either of its names — module_permission
since dredd-core v0.11.0, module_moderator on a database migrated before it, and this revision
runs before the rename in 0004, so it has to know both. Not CASCADE, deliberately, because
a foreign key the revision failed to move would then refuse the drop, and that refusal is the
completeness proof.
What happens to the admin@example.com row in sygna: it is matched to the surviving account
in dredd, every id that named it is rewritten to the survivor's, and the local row is dropped. No
data is renumbered — matters, time entries, audit rows, grants and ethical walls keep their own ids
and only the reference changes. What the person loses is a password: theirs is now the one they use
at the hub.
What is genuinely lost: sessions and app tokens. No module holds INSERT on dredd.session,
deliberately — a role that can write a session row can mint a working credential for the
administrator — so the local session table is dropped with its rows. Everybody signs in again, at
the hub. Any sygna_pat_… app token stops working and is re-minted in Atrium
(POST /me/modules/sygna/tokens), which stamps the same prefix.
Then set, in .env: IDENTITY_SCHEMA=dredd and SESSION_COOKIE_NAME=dredd_session (the same
value in every app in the family — that is what makes one cookie work everywhere). Recreate the
backend and look for the boot assertion in its log:
Shared identity schema dredd: every identity table resolves there
It runs on every start and the backend refuses to boot without it. It is the only guard against
the failure mode with no other symptom: a local app_user that the search_path reaches first, so
everything keeps working and you are silently back to two rows per person.
Verify with section 4's command plus --identity-schema dredd --identity-tier reader. A
passing report prints the tier in full, including nothing at all on password_hash/failed_login_count/locked_until, and an identity shadow line confirming sygna
holds no copy of the three tables.
There is no downgrade. 0003 refuses one while IDENTITY_SCHEMA is set: the accounts were
merged across schemas and the mapping back does not exist. Take a full dump before step 3 — that is
the rollback.
5. Restore: Sygna specifics
Sygna has its own app-level backup (Ustawienia Sygny → Poczta, integracje i kopie: one archive of every table
plus DATA_DIR, in DATA_DIR/backups). It restores Sygna alone, which a provider backup or
point-in-time restore cannot: those rewind all four apps together. Copy the archives off the host;
they are not at the provider.
A restore rewrites every table, including audit_log and conflict_check, so it needs the migrator.
By default the long-running backend has no migrator credentials and the console's restore
answers with an error naming the one-shot path:
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 migrate \
python -m app.restore # list the archives
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm migrate \
python -m app.restore <backup name> --yes # restore one
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml start backend
migrate has both URLs, the CA and the sygna-data volume. The restore is atomic, records its
intent in the audit log first, and assumes the same schema version.
Opt-in: set BACKEND_MIGRATION_DATABASE_URL in .env to the migrator URL and the console's
restore works again. The running, network-facing backend then holds a credential that can rewrite
the audit log and delete conflict checks and AML assessments; prefer the one-shot.
After a provider restore (item 6 at the top of this page), for Sygna: stop the backend; re-run
the provision command from section 1 with --reset-passwords (a restore may drop custom role
passwords); up -d (migrate is a no-op at head); run the check in section 4.
6. Removing Sygna from the database
As the platform admin, in one transaction (after taking a backup):
BEGIN;
GRANT sygna_migrator, sygna_app TO CURRENT_USER;
DROP SCHEMA sygna CASCADE;
REVOKE USAGE ON SCHEMA extensions FROM sygna_migrator, sygna_app;
DROP OWNED BY sygna_migrator, sygna_app;
DROP ROLE sygna_app, sygna_migrator;
COMMIT;
How this is tested
- CI, job
managed-db, onpostgres:17:dredd_core.managed emulate(TEST-ONLY: a non-superuser platform admin, the API roles, anextensionsschema), provisioning twice, a refused migration as the platform admin that leaves nothing inpublic, migrate + seed assygna_migratorwith a password holding% @ : / ? #, the whole integration suite assygna_app, the managed check as both roles,sygna_apprefused onaudit_log,conflict_checkandaml_assessment, and a downgrade to base and back. Thebackendjob runs on PostgreSQL 16 and 17 and checks thatprovision.sqlis current. - A local TLS emulation on PostgreSQL 16: the same path over
verify-full, next to a second app schema holding a complete copy of Sygna's tables, enum types andalembic_version, with isolation proven both ways, plus the negative cases (migrating as the admin,DB_APP_ROLEnaming a missing role,sslmode=prefer).
Not yet confirmed on a real managed database: the provider's postgres running
GRANT sygna_migrator TO postgres, CREATE SCHEMA … AUTHORIZATION and
GRANT USAGE ON SCHEMA extensions (provisioning stops with a clear error if the last does not take);
the roles' search_path / statement_timeout settings surviving the provider's own configuration;
sygna_app.<tenant> logins through a pooler's session mode and after a restore; certificate
host-name checks against a pooler host; pg8000 through a pooler with a 15-connection pool; the
connection budget in section 2: a pooler's default pool size, how session mode behaves at that cap,
how many connections the provider's own services hold, and whether four apps at their defaults
really fit a 90-connection limit; what --require-tls reports through a pooler; real latency.