Managed PostgreSQL without a provider name; dredd-core v0.9.0

- Names: docker-compose.managed-db.yml, db/managed/ (provision.sql
  re-rendered by dredd-core, a generic runbook), MANAGED_DB_* settings,
  /run/certs/db-ca.crt. No provider is named anywhere; provider know-how
  is written generically.
- One TLS rule from dredd_core.db.require_verified_tls replaces Sygna's
  DB_REQUIRE_VERIFY_FULL: a database host that is not local (localhost,
  127.0.0.1, ::1, postgres, or DB_LOCAL_HOSTS) must carry
  sslmode=verify-full or the app refuses to start.
- CI: the managed-db job emulates a generic managed Postgres.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
2026-09-23 17:05:29 +02:00
co-authored by Claude Fable 5.1
parent 40bcbf5b6e
commit 712985ef35
23 changed files with 739 additions and 629 deletions
+27 -26
View File
@@ -26,37 +26,38 @@ DB_APP_ROLE=app
# The runtime connection pool, per backend process: up to DB_POOL_SIZE + DB_MAX_OVERFLOW.
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=10
# true = refuse to start unless DATABASE_URL (and MIGRATION_DATABASE_URL, when set) has
# sslmode=verify-full and sslrootcert. Off for this local database without TLS;
# docker-compose.supabase.yml turns it on for migrate and backend whatever this file says.
DB_REQUIRE_VERIFY_FULL=false
# TLS rule: a database host that is not local ("", localhost, 127.0.0.1, ::1 or `postgres`) must
# say sslmode=verify-full in its URL, or migrate and the backend refuse to start before anything
# connects. A private database on a trusted network that truly needs no TLS is listed here instead
# (comma-separated). There is no other opt-out.
DB_LOCAL_HOSTS=
# ── Database on the family's shared Supabase project ─────────────────────────
# With docker-compose.supabase.yml (runbook: db/supabase/README.md) the settings above are
# ── Managed PostgreSQL (optional; replaces the local postgres service) ────────
# With docker-compose.managed-db.yml (runbook: db/managed/README.md) the settings above are
# replaced by these, uncommented. POSTGRES_* and DB_*_PASSWORD are then unused (no local postgres).
# - Host: the project's shared pooler in SESSION mode, port 5432 — never 6543, the transaction
# mode. (Or the direct db.<project-ref>.supabase.co:5432, which is IPv6-only without the
# IPv4 add-on; there the user names have no .<project-ref> suffix.)
# - User names on the pooler are <role>.<project-ref>: sygna_app.<project-ref> for the runtime,
# sygna_migrator.<project-ref> for migrations. Never postgres, and the two always differ.
# - 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>, i.e.
# sygna_app.<tenant> for the runtime and sygna_migrator.<tenant> for migrations; otherwise the
# plain role names. Never the platform admin, and the two always differ.
# - URL-encode each password with urllib.parse.quote(password, safe=""), never by hand: a
# % @ : / ? # breaks the URL, and Compose substitutes a $ ($HOME becomes a directory).
# - sslmode=verify-full against the project's root CA, which the override mounts at
# /run/certs/supabase-ca.crt from SUPABASE_CA_FILE. The override also sets
# DB_REQUIRE_VERIFY_FULL=true, so migrate and backend refuse any other sslmode, or none, before
# connecting; deploy_check.py --env refuses it too. Outside that override the engine alone
# still accepts sslmode=require and verify-ca (neither checks the host name) and a URL with
# no sslmode.
# DATABASE_URL=postgresql+pg8000://sygna_app.<project-ref>:<url-encoded password>@aws-0-eu-central-1.pooler.supabase.com:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/supabase-ca.crt
# MIGRATION_DATABASE_URL=postgresql+pg8000://sygna_migrator.<project-ref>:<url-encoded password>@aws-0-eu-central-1.pooler.supabase.com:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/supabase-ca.crt
# - sslmode=verify-full against the provider's root CA (downloaded from its dashboard), 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 instead. A URL for a host that is not local is
# refused without sslmode=verify-full, before anything connects (config.py); deploy_check.py
# --env refuses it too. The engine alone would still take sslmode=require and verify-ca
# (neither checks the host name) and a URL with no sslmode.
# 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
# SUPABASE_CA_FILE=./certs/supabase-ca.crt
# The four apps share the project's connection limit (Micro 60, Small 90), with Supabase's own
# services. Count DB_POOL_SIZE + DB_MAX_OVERFLOW + 1 per app (the +1 is a check or one-shot
# beside the backend): 16 each, 64 for four, with the defaults; on Micro set 3 + 2 in EVERY app.
# The pooler also caps session-mode clients per role and database at the project's Pool Size
# (Database Settings): set it to at least DB_POOL_SIZE + DB_MAX_OVERFLOW + 1, or a client past
# it waits and is then refused. Not yet measured on a real project: db/supabase/README.md.
# MANAGED_DB_CA_FILE=./certs/db-ca.crt
# The four apps share the database's connection limit, with the provider's own services. Count
# DB_POOL_SIZE + DB_MAX_OVERFLOW + 1 per app (the +1 is a check or one-shot beside the backend):
# 16 each, 64 for four, with the defaults, which fits a limit of 90; for a limit of 60 set 3 + 2
# in EVERY app. Through a pooler in session mode, its pool size per role must be at least
# DB_POOL_SIZE + DB_MAX_OVERFLOW + 1, or a client past it waits and is then refused. Not yet
# measured on a real managed database: db/managed/README.md.
# DB_POOL_SIZE=5
# DB_MAX_OVERFLOW=10
# Opt-in only: gives the long-running backend the migrator URL, so the console's restore works.
+19 -17
View File
@@ -4,7 +4,7 @@ on: [push, pull_request]
jobs:
backend:
runs-on: ubuntu-latest
# 16 is what the local stack runs; 17 is what Supabase runs (new projects default to it).
# 16 is what the local stack runs; 17 is what managed providers commonly run today.
strategy:
fail-fast: false
matrix:
@@ -74,15 +74,16 @@ jobs:
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
- name: Supabase provisioning SQL is current
- name: db/managed/provision.sql is what dredd-core renders
working-directory: backend
# db/supabase/provision.sql is dredd-core's rendering for Sygna (schema sygna, roles
# sygna_migrator / sygna_app), committed for operators who only have the SQL editor. It
# cannot drift from the routine it renders: exit 1 = stale, re-render with --output.
# db/managed/provision.sql is dredd-core's rendering for Sygna (schema sygna, roles
# sygna_migrator / sygna_app), committed for operators who only have a provider's SQL
# editor. It cannot drift from the routine it renders: exit 1 = stale, re-render with
# --output.
run: >-
python -m dredd_core.managed provision --sql-only
--schema sygna --app-role sygna_app --migrator-role sygna_migrator
--check-file ../db/supabase/provision.sql
--check-file ../db/managed/provision.sql
- name: Migrate + seed
working-directory: backend
run: alembic upgrade head && python -m app.seed
@@ -108,15 +109,16 @@ jobs:
GALENA_REPO: ${{ github.workspace }}/.galena
run: python scripts/shared_check.py
# ── the family's shared Supabase project, emulated ─────────────────────────────
# In production every application of the family lives in ONE Supabase database (PostgreSQL 17),
# one schema each, with per-application roles. Supabase cannot run here, so
# `dredd_core.managed emulate` (TEST-ONLY) turns the service container into a lookalike: a
# NOSUPERUSER CREATEROLE admin standing in for Supabase's `postgres`, the Data API roles and an
# `extensions` schema. Everything after that runs the way db/supabase/README.md tells an operator
# to: provision as the admin, migrate + seed as sygna_migrator, the whole integration suite as
# sygna_app, then the managed check. It needs dredd-core v0.8.0 (the provisioning CLI), so it
# cannot pass until that tag is pushed.
# ── the family's shared managed database, emulated ─────────────────────────────
# In production every application of the family lives in ONE managed PostgreSQL database
# (Postgres 17), one schema each, with per-application roles. A managed provider cannot run
# here, so `dredd_core.managed emulate` (TEST-ONLY) turns the service container into a
# managed-Postgres lookalike: a NOSUPERUSER CREATEROLE admin standing in for the provider's
# `postgres`, the API roles anon / authenticated / service_role (what an auto-generated table
# API connects as) and an `extensions` schema. Everything after that runs the way
# db/managed/README.md tells an operator to: provision as the admin, migrate + seed as
# sygna_migrator, the whole integration suite as sygna_app, then the managed check. It needs
# dredd-core v0.9.0 (the pin in requirements.txt).
managed-db:
runs-on: ubuntu-latest
services:
@@ -159,7 +161,7 @@ jobs:
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
- name: Emulate Supabase (TEST-ONLY)
- name: Emulate a managed Postgres (TEST-ONLY)
working-directory: backend
run: python -m dredd_core.managed emulate --superuser-url SUPERUSER_URL --database shared --password-env PM_PASSWORD
- name: Provision Sygna as the platform admin (twice, because it must be idempotent)
@@ -186,7 +188,7 @@ jobs:
- name: Integration suite as sygna_app
working-directory: backend
run: pytest -q
- name: Managed check as both roles (isolation, evidence tables, Data API roles)
- name: Managed check as both roles (isolation, evidence tables, API roles)
working-directory: backend
run: |
for url in DATABASE_URL MIGRATION_DATABASE_URL; do
+45 -28
View File
@@ -6,7 +6,7 @@ Guidance for Claude Code when working in this repository.
**Sygna** — practice management (CRM + matters + time) for **Polish law firms**. A sibling of
**[Galena](../Galena)**: separate applications and deployments, separate data — its own database
on a local stack, its own schema `sygna` in the family's shared Supabase project — built on
on a local stack, its own schema `sygna` in the family's shared managed database — built on
one shared package (**`dredd-core`**). They are not merging into one system — that plan was
superseded (PLAN.md §3.4); what they share is imported, not copied. Stack: **FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17**, Argon2id
auth + server-side cookie sessions, a **no-build static console** (vanilla JS), Docker Compose +
@@ -66,9 +66,9 @@ backend/app/
frontend/ index.html · app.css · app.js (no build step, PL-first)
Tabler icons vendored into app.js's ICN map (CREDITS.md)
db/init/ 01-roles.sh (creates the app + migrator roles)
db/supabase/ provision.sql (dredd-core's rendering, CI-checked) · README.md (Sygna's runbook
in the family's shared Supabase project)
docker-compose.yml · docker-compose.supabase.yml · Caddyfile · .env.example · .github/workflows/ci.yml
db/managed/ provision.sql (dredd-core's rendering, CI-checked) · README.md (Sygna's runbook
in the family's shared managed database, plus the database-wide checklist)
docker-compose.yml · docker-compose.managed-db.yml · Caddyfile · .env.example · .github/workflows/ci.yml
docs/CRMecenas-Discovery-Report.md (research; §4 superseded by PLAN.md)
```
@@ -161,15 +161,19 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
- **Append-only audit.** The `app` role holds no UPDATE/DELETE on `audit_log` (enforced in the
migration). `migrator` owns DDL; `app` is DML-only. In a law firm the audit log is a
confidentiality control, not an ops convenience.
- **Managed Postgres = the family's shared Supabase project** (db/supabase/README.md). Every
application of the family lives in one PostgreSQL 17 database, one schema each:
- **Managed Postgres = the family's shared managed database** (db/managed/README.md): one database
at a managed PostgreSQL provider for Atrium, Galena, Sygna and Counsel Scorecard, one schema each.
Never name a provider — write "a managed PostgreSQL provider" / "managed Postgres" and keep
provider know-how generic ("some poolers want `<role>.<tenant>` user names", "download the
provider's root CA from its dashboard", "keep the schema out of any auto-generated API", "a
restore may drop custom role passwords"). Preserve:
- **Sygna's schema is `sygna`, never `public`**, owned by `sygna_migrator`. Nothing in the code
names a schema — the roles' `search_path` (`sygna, extensions`, set by dredd-core's
provisioning) puts tables, enum types and `alembic_version` there, and `create_all`'s existence
check never sees another app's same-named `audit_log` or `app_user`. Keep it that way: never
schema-qualify, never hard-code `public`.
- **Role names are configuration, per application.** Locally and in CI the roles are `app` /
`migrator`; in the shared project `sygna_app` / `sygna_migrator`, because role names are
`migrator`; in the shared database `sygna_app` / `sygna_migrator`, because role names are
cluster-wide and a shared `app` would let another app's migration grant back the DELETE that
protects `conflict_check`. The runtime role's name is `DB_APP_ROLE` (config.py); the grant
migrations read it and nothing else needs a role name. A new revision that creates a table
@@ -184,20 +188,30 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
`dredd_core.db.make_engine`, never `create_engine` (a test greps for it): only it turns
`?sslmode=verify-full&sslrootcert=…` into a verifying context for pg8000, and it refuses
`prefer`/`allow`/`disable`. `alembic/env.py` uses the URL directly, never
`config.set_main_option` (configparser breaks a URL-encoded `%`). `make_engine` still accepts
`require`, `verify-ca` and no `sslmode`, so verify-full is enforced by Sygna's settings:
`DB_REQUIRE_VERIFY_FULL`, a literal `"true"` for `migrate` and `backend` in
`docker-compose.supabase.yml`. Keep it a literal there, and never give `DB_APP_ROLE` an
`environment:` entry (a shell export would beat the `.env` that `deploy_check.py` checked).
- **The provisioning's final revoke is not a wall.** `postgres` keeps ADMIN OPTION on the roles
it created and can make itself `sygna_migrator` again, so dashboard SQL access is full control
of Sygna's data. Never document it as protection against dashboard users.
- **Connections:** the session pooler on port 5432 (never 6543, the transaction mode), users
`<role>.<project-ref>`. The pool is `DB_POOL_SIZE` + `DB_MAX_OVERFLOW` per process, sized to
the connection limit four apps share; one-shot processes (seed, restore, migrations) use
`NullPool`. `deploy_check.py --env` checks the URLs.
- **PostgreSQL 16 and 17:** the local stack runs 16, Supabase 17; CI runs the suite on both plus
a `managed-db` job on 17 that provisions, migrates and tests exactly as the runbook says.
`config.set_main_option` (configparser breaks a URL-encoded `%`).
- **The family's one TLS rule** (`dredd_core.db.require_verified_tls`, applied by `Settings` to
both URLs, unconditionally): a database host counts as local when it is `""`, `localhost`,
`127.0.0.1`, `::1`, `postgres` or listed in `DB_LOCAL_HOSTS` (comma-separated, optional);
every other host must say `sslmode=verify-full` (with `sslrootcert` or the system store) or
Sygna refuses to start — `make_engine` alone would still take `require`, `verify-ca` and no
`sslmode` (unverified TLS with a plaintext fallback). No provider host lists, no compose
literal, no other opt-out (`DB_REQUIRE_VERIFY_FULL` is gone; `deploy_check.py` fails if it
returns). And never give `DB_APP_ROLE` an `environment:` entry in
`docker-compose.managed-db.yml` (a shell export would beat the `.env` that `deploy_check.py`
checked).
- **The provisioning's final revoke is not a wall.** The platform admin (`postgres`) keeps ADMIN
OPTION on the roles it created and can make itself `sygna_migrator` again, so SQL-editor
access at the provider is full control of Sygna's data. Never document it as protection
against dashboard users.
- **Connections:** through a pooler, its session mode, never transaction mode (port 6543 on
some providers); users `<role>.<tenant>` where the pooler wants the tenant in the user name.
The pool is `DB_POOL_SIZE` + `DB_MAX_OVERFLOW` per process, sized to the connection limit
four apps share; one-shot processes (seed, restore, migrations) use `NullPool`.
`deploy_check.py --env` checks the URLs.
- **PostgreSQL 16 and 17:** the local stack runs 16, managed providers commonly 17; CI runs the
suite on both plus a `managed-db` job on 17 that provisions, migrates and tests exactly as the
runbook says. `db/managed/provision.sql` is rendered by `python -m dredd_core.managed provision
--sql-only` — re-render it, never hand-edit (CI fails when it is stale).
- **`legal_service_date` is set once, from the source system, never inferred.** It lives on
`correspondence` and is the only thing a procedural deadline may count from — `received_at` is
the separate, operational fact of when the row appeared here, and nothing counts from it.
@@ -343,7 +357,7 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
or `conflict_check`, which is precisely why it cannot be the role that rewrites them. Archives
never contain `.env`, so a leaked archive is not also a credential leak. **A process without
migrator credentials refuses to restore** (`MIGRATION_DATABASE_URL` empty): that is the
long-running backend under `docker-compose.supabase.yml` by default, and the restore there is
long-running backend under `docker-compose.managed-db.yml` by default, and the restore there is
the one-shot `python -m app.restore` in the `migrate` container. Giving the backend the migrator
URL (`BACKEND_MIGRATION_DATABASE_URL`) is an opt-in, never the default — a network-facing
process holding a credential that can rewrite the audit log is what the role split exists to
@@ -399,7 +413,7 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
- **App tokens mean the same thing in both applications.** `SessionKind` / `TokenScope`, the
sliding idle renewal and the whole `AuthService` are `dredd_core`'s, so the two cannot drift by
construction. They no longer share a `session` table — separate databases, or separate schemas
in the shared project — but they do share
in the shared managed database — but they do share
the code, and a token minted by one is not resolvable by the other. Scope is enforced in
**`deps.get_current_user` and nowhere else**: every authenticated route depends on it, so one
check covers all of them and no future route can forget it. The prefix (`sygna_pat_`, set in
@@ -535,15 +549,18 @@ token minted **in Galena**) are all set. The endpoints live in one `ENDPOINTS` m
`0001_initial` was extended in place with the `correspondence` table and its enums rather than
adding a revision, because nothing was deployed — the `create_all`-from-metadata style means a
table added to the model would otherwise be created twice. That stopped with **`0002_runtime_grants`**
(September 2026, the shared Supabase project): the grants are now dredd-core's, loud and
(September 2026, the shared managed database): the grants are now dredd-core's, loud and
schema-aware, for `DB_APP_ROLE`, and new tables need their own revision, ending with the same
`runtime_grants_sql` call. `0001`'s own grant block follows `DB_APP_ROLE` in the current schema
too, and its downgrade drops pgcrypto only when the migrator owns it (it never does locally or on
Supabase, so the old unconditional drop made every downgrade fail).
too, and its downgrade drops pgcrypto only when the migrator owns it (it never does locally or at
a managed provider, so the old unconditional drop made every downgrade fail).
**The shared Supabase project is emulated, not yet real** (2026-09-15): dredd-core's TEST-ONLY
**The shared managed database is emulated, not yet real** (2026-09-15): dredd-core's TEST-ONLY
`emulate` on PostgreSQL 16 with TLS required, Sygna provisioned beside a second app schema holding
a complete copy of Sygna's tables, migrated over `verify-full` as its migrator role with a
password full of `% @ : / ? #`, the whole suite as the runtime role, the managed check with
isolation both ways, and the negative cases (migrating as the admin, a missing `DB_APP_ROLE`,
`sslmode=prefer`). CI's `managed-db` job repeats it on 17 and needs dredd-core v0.8.0 tagged.
`sslmode=prefer`). CI's `managed-db` job repeats it on 17 with dredd-core v0.9.0 (the pin). The
provider is never named anywhere in the repository (2026-09-23): `db/managed/`,
`docker-compose.managed-db.yml`, `MANAGED_DB_CA_FILE`, and the family's one TLS rule
(`require_verified_tls` + `DB_LOCAL_HOSTS`) replaced Sygna's own `DB_REQUIRE_VERIFY_FULL`.
+2 -2
View File
@@ -8,7 +8,7 @@ Sibling application to **Galena**; designed from day one to merge into one share
server-side cookie sessions, a no-build static console (vanilla JS), Docker Compose + Caddy.
- **Supersedes:** §4 of [`docs/CRMecenas-Discovery-Report.md`](docs/CRMecenas-Discovery-Report.md).
The discovery report's requirements analysis (§3) still stands; its *technology* recommendation
(Atomic CRM / react-admin / Supabase) is withdrawn — see §1.2.
(Atomic CRM / react-admin / a hosted Postgres BaaS) is withdrawn — see §1.2.
---
@@ -26,7 +26,7 @@ Sibling application to **Galena**; designed from day one to merge into one share
### 1.2 What this changes versus the discovery report
The report recommended forking Atomic CRM (MIT, React + Supabase). Requirement 2 overrides that — and
The report recommended forking Atomic CRM (MIT, React + a hosted Postgres BaaS). Requirement 2 overrides that — and
on inspection the override is an improvement, not a compromise:
- **Galena already is the better starting point.** It is Apache-2.0, already ours, and already
+19 -17
View File
@@ -58,29 +58,31 @@ docker compose up -d --build
Postgres → migrate (+seed) → backend → Caddy on `:80`. Only Caddy is published; the backend and
database are expose-only. Sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
### Deploying on Supabase (the family's shared project)
### Deploying on a managed PostgreSQL provider
The family — Atrium as the hub, Galena, Sygna and Counsel Scorecard as its modules — can share
**one Supabase project** (one PostgreSQL 17 database, EU region). Supabase hosts only the database;
the backend still runs with Docker Compose on your own server. Sygna lives in its own schema
`sygna`, with its own roles `sygna_migrator` / `sygna_app`, and holds nothing in any other app's
schema.
**one managed PostgreSQL database** (Postgres 16/17 at a managed provider). The provider hosts only
the database; the backend still runs with Docker Compose on your own server. Sygna lives in its own
schema `sygna`, with its own roles `sygna_migrator` / `sygna_app`, and holds nothing in any other
app's schema; a provider's auto-generated API roles get nothing in it.
```bash
python -m dredd_core.managed provision ... # once, as postgres: schema + roles (db/supabase/README.md)
DREDD_CORE_TOKEN=... docker compose -f docker-compose.yml -f docker-compose.supabase.yml up -d --build
python -m dredd_core.managed provision ... # once, as the platform admin: schema + roles (db/managed/README.md)
DREDD_CORE_TOKEN=... docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
```
- **Project-wide steps** (creating the project, the CA, Data API off, SSL enforcement, network
restrictions, compute, backups/PITR, project restore): the checklist at the top of
[`db/supabase/README.md`](db/supabase/README.md); the full procedure is
[Atrium's family runbook](https://github.com/Alpaq92/Atrium/blob/main/deploy/README.md) once
Atrium publishes it.
- **Database-wide steps** (creating the database, the provider's root CA, any auto-generated API
off, TLS enforcement, network restrictions, the connection budget, backups and provider
restores): the checklist at the top of [`db/managed/README.md`](db/managed/README.md), once for
all four apps; the family runbook in Atrium's repository (`deploy/README.md`) covers it in more
depth.
- **Sygna's steps** (provisioning, `.env`, migrate and seed, the managed check, restore):
[`db/supabase/README.md`](db/supabase/README.md).
- Connect through the session pooler (port 5432, never 6543) with `sslmode=verify-full`; set
`DB_APP_ROLE=sygna_app` and size `DB_POOL_SIZE` / `DB_MAX_OVERFLOW` to the shared connection
limit. `python backend/scripts/deploy_check.py --env .env` checks all of that before you start.
[`db/managed/README.md`](db/managed/README.md).
- Connect with `sslmode=verify-full` (through a pooler, its session mode, never transaction mode;
`<role>.<tenant>` user names where the pooler wants them); set `DB_APP_ROLE=sygna_app` and size
`DB_POOL_SIZE` / `DB_MAX_OVERFLOW` to the shared connection limit. Sygna's settings refuse a URL
for a host that is not local without `verify-full` before anything connects, and
`python backend/scripts/deploy_check.py --env .env` checks all of the above before you start.
- The long-running backend gets no migrator credentials there, so a restore runs as the one-shot
`python -m app.restore` (or opt in to the console's restore — the runbook says what that costs).
@@ -104,7 +106,7 @@ is privileged material, and a proxy in front of it is one more place that sees i
### Local development
You need PostgreSQL 16 (17 works too — it is what Supabase runs) and Python 3.12.
You need PostgreSQL 16 (17 works too — it is what managed providers commonly run) and Python 3.12.
```bash
cd backend && python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
+2 -2
View File
@@ -9,7 +9,7 @@ That is over. The substrate is **[`dredd-core`](https://github.com/Alpaq92/dredd
private package, Apache-2.0, pinned in `backend/requirements.txt`:
```
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.8.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.9.0
```
Both applications import it. There is nothing left to keep diff-clean, because there is only one
@@ -33,7 +33,7 @@ byte-identical contract becomes a package pin"); this is that.
| `audit.record` | the append-only writer |
| `schema.create_enum_types` | enum types derived from the metadata, so labels cannot drift from models |
Those seven tables live alongside Sygna's own, in whatever schema the migrator's `search_path` names: `public` on a local stack, `sygna` in the family's shared Supabase project (db/supabase/README.md), where every application has its own schema and its own roles and none can reach another's. Nothing in the code names the schema. There was briefly a `core.*` / `sygna.*` split, built when the plan was one database shared with Galena; separate applications mean there is nothing to tell apart and nothing to merge, so it was removed (PLAN.md §3.6).
Those seven tables live alongside Sygna's own, in whatever schema the migrator's `search_path` names: `public` on a local stack, `sygna` in the family's shared managed database (db/managed/README.md), where every application has its own schema and its own roles and none can reach another's. Nothing in the code names the schema. There was briefly a `core.*` / `sygna.*` split, built when the plan was one database shared with Galena; separate applications mean there is nothing to tell apart and nothing to merge, so it was removed (PLAN.md §3.6).
## What Sygna keeps, and why
+1 -1
View File
@@ -9,7 +9,7 @@ The URL is used directly rather than through `config.set_main_option`: that goes
configparser interpolation, which rejects a URL-encoded password (any `%`).
Nothing here names a schema. In the family's shared managed database the migrator's search_path
is `<the app's schema>, extensions` (set by the provisioning, db/supabase/), so `alembic_version`,
is `<the app's schema>, extensions` (set by the provisioning, db/managed/), so `alembic_version`,
the enum types and every table land in the application's own schema; locally it is `public`.
"""
from __future__ import annotations
+2 -2
View File
@@ -11,7 +11,7 @@ a model needs no edit to this file.
**One schema, and nothing here names it.** Everything lands in the migrator's current schema:
`public` on a local stack, `sygna` in the family's shared managed database, where provisioning
(db/supabase/) sets the migrator's `search_path` to `sygna, extensions` — so the core tables, the
(db/managed/) sets the migrator's `search_path` to `sygna, extensions` — so the core tables, the
enum types and `alembic_version` sit beside Sygna's own, and another application's `audit_log` in
its own schema is invisible to `create_all`'s existence check. There was briefly a `core.*` /
`sygna.*` split inside one database; it cost a superuser-only `CREATE SCHEMA` mirrored in CI and
@@ -80,7 +80,7 @@ def downgrade() -> None:
for name in sorted(enum_types()):
op.execute(f"DROP TYPE IF EXISTS {name}")
# Only if this role owns it. CI, db/init and a managed Postgres (Supabase keeps pgcrypto in its
# Only if this role owns it. CI, db/init and a managed Postgres (which keeps pgcrypto in its
# `extensions` schema) create pgcrypto as another role, so the least-privilege migrator never
# needs extension rights — and DROP EXTENSION by a non-owner fails the whole downgrade, rolling
# back every table drop above with it.
@@ -1,10 +1,10 @@
"""Runtime grants for the runtime role: explicit, schema-aware and loud (`runtime_grants_sql`).
0001 carried its own grant block, written for a local cluster and silently skipped when the role
was missing. In the family's shared managed Postgres (Supabase) Sygna lives in its own schema
`sygna`, its runtime role is `sygna_app` (role names are cluster-wide there, so every application's
carry its name — with a shared `app` role, another application's migration could grant back the
DELETE this one revokes), and the Data API roles must never reach it. This revision runs
was missing. In the family's shared managed database Sygna lives in its own schema `sygna`, its
runtime role is `sygna_app` (role names are cluster-wide there, so every application's carry its
name — with a shared `app` role, another application's migration could grant back the DELETE this
one revokes), and the provider's API roles must never reach it. This revision runs
dredd-core's one idempotent `DO` block in `current_schema()` — the migrator's search_path puts
`sygna` first there, `public` locally — for the role named by `DB_APP_ROLE` (default `app`):
@@ -15,8 +15,9 @@ dredd-core's one idempotent `DO` block in `current_schema()` — the migrator's
* `audit_log` stays append-only (UPDATE, DELETE and TRUNCATE revoked), and the two evidence tables
stay undeletable — `conflict_check` and `aml_assessment` keep UPDATE, because recording the one
human decision writes to the row, and lose DELETE and TRUNCATE;
* Supabase's `anon` / `authenticated` / `service_role` lose every privilege in the schema, including
default privileges (skipped where those roles do not exist, e.g. a plain local cluster);
* the API roles `anon` / `authenticated` / `service_role` (what a provider's auto-generated table
API connects as) lose every privilege in the schema, including default privileges (skipped where
those roles do not exist, e.g. a plain local cluster);
* it **fails loudly** — a missing runtime role (DB_APP_ROLE pointing nowhere), migrating as a
superuser / `postgres` / the runtime role itself, or a grant that did not take (a table the
migrator does not own, an evidence table still writable some other way) raises and rolls the
@@ -40,7 +41,7 @@ depends_on = None
# Evidence the runtime role may insert and read but never rewrite, and evidence it may update once
# but never delete. Keep in step with every `python -m dredd_core.managed check --append-only /
# --no-delete` invocation (CI, db/supabase/README.md) and with scripts/deploy_check.py.
# --no-delete` invocation (CI, db/managed/README.md) and with scripts/deploy_check.py.
APPEND_ONLY = ("audit_log",)
NO_DELETE = ("conflict_check", "aml_assessment")
+39 -34
View File
@@ -8,9 +8,11 @@ import re
from functools import lru_cache
from pathlib import Path
from dredd_core.db import require_verified_tls
from pydantic import Field, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy.engine import make_url
from sqlalchemy.exc import ArgumentError
class Settings(BaseSettings):
@@ -27,34 +29,34 @@ class Settings(BaseSettings):
# Database (runtime = least-privilege "app" role; migrator = DDL)
database_url: str = "postgresql+pg8000://app:app@localhost:5432/sygna"
# Empty = this process holds no migrator credentials and refuses to restore
# (docker-compose.supabase.yml does that to the long-running backend; the one-shot
# (docker-compose.managed-db.yml does that to the long-running backend; the one-shot
# `python -m app.restore` is the path there). A managed Postgres URL adds
# ?sslmode=verify-full&sslrootcert=<CA file>: every engine is built by
# dredd_core.db.make_engine, which turns those into a verifying TLS context.
# dredd_core.db.make_engine, which turns those into a verifying TLS context (db/managed/).
migration_database_url: str = "postgresql+pg8000://migrator:migrator@localhost:5432/sygna"
# The family's one TLS rule (dredd_core.db.require_verified_tls, applied below to both URLs):
# a database host that is not local must carry sslmode=verify-full, or Sygna refuses to start.
# Local = "", localhost, 127.0.0.1, ::1, `postgres` (the compose service) or an entry of this
# comma-separated list — a private database on a trusted network that truly needs no TLS.
# There is no other opt-out.
db_local_hosts: str = ""
# The runtime role's name. The runtime-grants migration grants it DML (audit_log append-only,
# conflict_check and aml_assessment never deleted), so it must be the role DATABASE_URL logs
# in as — on Supabase's pooler, the user name before `.<project-ref>`. `app` locally and in CI;
# `sygna_app` in the family's shared Supabase project, where role names are cluster-wide.
# Nothing else needs a role name: the migrator is whoever MIGRATION_DATABASE_URL logs in as.
# in as — where a pooler wants the tenant in the user name (`<role>.<tenant>`), the part before
# the dot. `app` locally and in CI; `sygna_app` in the family's shared managed database, where
# role names are cluster-wide. Nothing else needs a role name: the migrator is whoever
# MIGRATION_DATABASE_URL logs in as.
db_app_role: str = "app"
# The runtime engine's pool, per backend process: at most pool_size + max_overflow
# connections. The family's apps share one managed project's connection limit, so size these
# to it (db/supabase/README.md). The seed, migrations and restores hold one unpooled
# connections. The family's apps share one managed database's connection limit, so size these
# to it (db/managed/README.md). The seed, migrations and restores hold one unpooled
# connection each.
db_pool_size: int = Field(default=5, ge=1)
db_max_overflow: int = Field(default=10, ge=0)
# Refuse to start unless DATABASE_URL (and MIGRATION_DATABASE_URL, when set) carries
# sslmode=verify-full and an sslrootcert CA file. make_engine also accepts require, verify-ca
# and a URL with no sslmode at all; pg8000 then encrypts without checking the server, or falls
# back to plaintext. docker-compose.supabase.yml turns this on for migrate and backend, so the
# runtime, Alembic, the seed and the restore all refuse a weaker URL before connecting. Off
# locally, where the database runs beside the app without TLS.
db_require_verify_full: bool = False
# Working directory for anything written to disk (exports, generated documents).
data_dir: str = "data"
@@ -84,16 +86,12 @@ class Settings(BaseSettings):
return v
@model_validator(mode="after")
def _verify_full_when_required(self) -> Settings:
if not self.db_require_verify_full:
return self
def _urls_verify_tls(self) -> Settings:
for key, url in (("DATABASE_URL", self.database_url),
("MIGRATION_DATABASE_URL", self.migration_database_url)):
if key == "MIGRATION_DATABASE_URL" and not url.strip():
continue # this process holds no migrator credentials
problem = _verify_full_problem(url)
if problem:
raise ValueError(f"DB_REQUIRE_VERIFY_FULL is on, but {key} {problem}")
_require_verified_tls(key, url, self.db_local_hosts)
return self
@field_validator("session_cookie_secure", mode="before")
@@ -196,20 +194,27 @@ class Settings(BaseSettings):
return "//".join([parts[0], parts[2]]) if len(parts) > 2 else console
def _verify_full_problem(url: str) -> str | None:
"""Why `url` is not verify-full TLS against a CA file, or None. Never includes the password."""
def _require_verified_tls(key: str, url: str, local_hosts: str) -> None:
"""Refuse `url` unless its host is local or it carries sslmode=verify-full (the family's one TLS
rule, dredd_core.db.require_verified_tls).
Left without sslmode, pg8000 negotiates TLS without verifying the server and falls back to
plaintext when the server declines, so the migrator's or the app's password would cross the
network open to a man-in-the-middle. make_engine already refuses the modes that permit
plaintext; this closes the missing-sslmode gap (and require / verify-ca, which do not check the
host name) for every host that is not local — "", localhost, 127.0.0.1, ::1, `postgres` or an
entry of DB_LOCAL_HOSTS (`local_hosts`). verify-full with no sslrootcert verifies against the
system trust store. Neither message ever includes the password.
"""
try:
query = make_url(url).query
except Exception: # noqa: BLE001 — any parse failure is a refusal; its message may hold the URL
return "is not a parseable database URL (is the password URL-encoded?)"
mode, root = query.get("sslmode"), query.get("sslrootcert")
if isinstance(mode, tuple) or isinstance(root, tuple):
return "gives sslmode or sslrootcert more than once"
if (mode or "").strip().lower() != "verify-full":
return f"must carry sslmode=verify-full (it has {mode.strip() if mode else 'no sslmode'})"
if not (root or "").strip() or root.strip() == "system":
return "must carry sslrootcert=<the project's CA file>"
return None
parsed = make_url(url)
except (ArgumentError, ValueError): # its message may hold the URL, password included
raise ValueError(
f"{key} is not a parseable database URL (is the password URL-encoded?)") from None
try:
require_verified_tls(parsed, local_hosts=local_hosts)
except ValueError as exc: # names the host, never the password
raise ValueError(f"{key}: {exc} (db/managed/README.md)") from exc
@lru_cache
+1 -1
View File
@@ -20,7 +20,7 @@ from .config import get_settings
settings = get_settings()
# Pooled, sized from DB_POOL_SIZE / DB_MAX_OVERFLOW: on a managed Postgres the family's apps share
# one connection limit (db/supabase/README.md).
# one connection limit (db/managed/README.md).
engine = make_engine(settings.database_url, pool_size=settings.db_pool_size,
max_overflow=settings.db_max_overflow)
SessionLocal = make_session_factory(engine)
+2 -2
View File
@@ -4,9 +4,9 @@
python -m app.restore NAME --yes # restore NAME: every table, then the files in DATA_DIR
For a deployment whose long-running backend holds no migrator credentials
(docker-compose.supabase.yml leaves MIGRATION_DATABASE_URL empty there, so the in-app restore is
(docker-compose.managed-db.yml leaves MIGRATION_DATABASE_URL empty there, so the in-app restore is
refused): stop the backend, run this in a one-shot container that has both database URLs and the
backend's DATA_DIR volume, then start the backend again. db/supabase/README.md has the commands.
backend's DATA_DIR volume, then start the backend again. db/managed/README.md has the commands.
Like the in-app restore it records the intent in the audit log first, committed on its own, as
the runtime role — a restore that fails leaves that row behind; one that succeeds replaces the log
+3 -3
View File
@@ -16,7 +16,7 @@ complete rather than clever:
- **Restore runs on the `migrator` engine**, not the runtime one. That is not an optimisation:
the `app` role deliberately cannot DELETE from `audit_log` or `conflict_check`, which is
precisely why it cannot be the role that rewrites them. A process without migrator
credentials (`MIGRATION_DATABASE_URL` empty — what `docker-compose.supabase.yml` gives the
credentials (`MIGRATION_DATABASE_URL` empty — what `docker-compose.managed-db.yml` gives the
long-running backend) refuses to restore, and the one-shot `python -m app.restore` does it
instead, so the backend that faces the network never holds a credential that can rewrite the
audit log.
@@ -153,7 +153,7 @@ class RestoreUnavailable(ConflictError):
def restore_available() -> bool:
"""Whether this process may restore: only with migrator credentials. A deployment keeps them
out of the long-running backend by leaving MIGRATION_DATABASE_URL empty there
(docker-compose.supabase.yml does, by default); restores then run as `python -m app.restore`."""
(docker-compose.managed-db.yml does, by default); restores then run as `python -m app.restore`."""
return bool(settings.migration_database_url.strip())
@@ -163,7 +163,7 @@ def assert_restore_available() -> None:
"Przywracanie jest wyłączone w tym procesie: MIGRATION_DATABASE_URL jest pusty, a "
"przywrócenie nadpisuje każdą tabelę, co może zrobić tylko rola migratora. Zatrzymaj "
"backend i uruchom jednorazowo: python -m app.restore <nazwa kopii> --yes "
"(db/supabase/README.md)."
"(db/managed/README.md)."
)
+1 -1
View File
@@ -45,4 +45,4 @@ cryptography==46.0.3 # AES-256-GCM (Apache-2.0/BSD)
# service, the engine factory, security primitives and the error shapes. Private repo; CI
# needs DREDD_CORE_TOKEN (see .github/workflows/ci.yml). `pip install -e ../dredd-core`
# shadows this pin — do not, without bumping a tag and repinning BOTH apps.
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.8.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.9.0
+79 -68
View File
@@ -7,9 +7,9 @@ test suite never reads docker-compose.yml.
Run it before shipping: python scripts/deploy_check.py
For the family's shared Supabase project, also point it at the real environment file: it checks
the database URLs the way the managed database needs them (verify-full TLS, the session pooler,
per-application roles), without connecting and without printing a password:
For the family's shared managed database, also point it at the real environment file: it checks
the database URLs the way the managed database needs them (verify-full TLS, a pooler's session
mode, per-application roles), without connecting and without printing a password:
python scripts/deploy_check.py --env ../.env
@@ -28,6 +28,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[2]
BACKEND = ROOT / "backend"
problems: list[str] = []
warnings: list[str] = []
notes: list[str] = []
@@ -187,20 +188,21 @@ check("demo.js" in prepare_sh and (ROOT / "frontend/demo.js").exists(),
check("SYGNA_BACKEND_URL" in prepare_sh and "SYGNA_BACKEND_URL" in netlify_toml,
"the Netlify build and its documentation disagree about the backend variable")
# ── the family's shared Supabase project ─────────────────────────────────────
# One managed database for every application of the family, one schema each. What goes wrong
# there goes wrong quietly: a URL without verify-full still connects (pg8000 falls back to
# unverified TLS or plaintext), the transaction pooler still accepts logins, and a runtime role
# whose name DB_APP_ROLE does not match gets its grants on paper only.
# ── the family's shared managed database ─────────────────────────────────────
# One managed PostgreSQL database for every application of the family, one schema each. What
# goes wrong there goes wrong quietly: a URL without verify-full still connects (pg8000 falls back
# to unverified TLS or plaintext), a pooler's transaction mode still accepts logins, and a runtime
# role whose name DB_APP_ROLE does not match gets its grants on paper only.
LOCAL_HOSTS = {"postgres", "localhost", "127.0.0.1", "::1", ""}
ADMIN_ROLES = {"postgres", "postgres_managed", "supabase_admin"}
# Where docker-compose.supabase.yml mounts the project's CA: the URLs are read inside the
# containers, so sslrootcert must name this path.
CA_MOUNT = "/run/certs/supabase-ca.crt"
ADMIN_ROLES = {"postgres", "postgres_managed"}
# Where docker-compose.managed-db.yml mounts the provider's CA: the URLs are read inside the
# containers, so an sslrootcert must name this path (leaving it out verifies against the system
# trust store; the override still bind-mounts the file, so it must exist either way).
CA_MOUNT = "/run/certs/db-ca.crt"
def _role(user: str) -> str:
"""The role part of a pooler user name: `sygna_app.<project-ref>` -> `sygna_app`."""
"""The role part of a pooler user name: `sygna_app.<tenant>` -> `sygna_app`."""
return user.split(".", 1)[0]
@@ -222,12 +224,13 @@ def external_db_problems(env: dict[str, str], source: str, *, real: bool = True)
leftovers = sorted(k for k, v in env.items() if "change_me" in v or re.search(r"<[^>]*>", v))
if leftovers:
found.append(f"{source}: placeholders left in {', '.join(leftovers)}")
ca_file = ROOT / (env.get("SUPABASE_CA_FILE", "").strip() or "certs/supabase-ca.crt")
ca_file = ROOT / (env.get("MANAGED_DB_CA_FILE", "").strip() or "certs/db-ca.crt")
if not ca_file.is_file():
found.append(f"{source}: the project's CA file {ca_file} does not exist "
"(SUPABASE_CA_FILE; docker-compose.supabase.yml mounts it)")
found.append(f"{source}: the provider's CA file {ca_file} does not exist "
"(MANAGED_DB_CA_FILE; docker-compose.managed-db.yml bind-mounts it, and "
"needs the file even when the URLs verify against the system store)")
# Compose interpolates unquoted .env values: `$HOME` in a password silently becomes the
# host's home directory, and the login fails towards an IP ban.
# host's home directory, and the login fails — some providers ban the IP after a few.
dollars = sorted(k for k, v in env.items() if k.endswith("DATABASE_URL") and "$" in v)
if dollars:
found.append(f"{source}: a literal $ in {', '.join(dollars)}; Compose "
@@ -254,30 +257,32 @@ def external_db_problems(env: dict[str, str], source: str, *, real: bool = True)
found.append(f"{source}: {key} must carry sslmode=verify-full (it has "
f"{','.join(query.get('sslmode', [])) or 'no sslmode'})")
root_cert = (query.get("sslrootcert") or [""])[0].strip()
if not root_cert:
found.append(f"{source}: {key} must carry sslrootcert=<the project's CA file>")
elif root_cert != CA_MOUNT:
if root_cert and root_cert != CA_MOUNT:
found.append(f"{source}: {key} has sslrootcert={root_cert}, but the containers read "
f"the CA at {CA_MOUNT} (docker-compose.supabase.yml mounts "
"SUPABASE_CA_FILE there)")
f"the CA at {CA_MOUNT} (docker-compose.managed-db.yml mounts "
"MANAGED_DB_CA_FILE there)")
elif not root_cert:
warnings.append(f"{source}: {key} has no sslrootcert, so verify-full trusts the system "
"store; fine only if the server's certificate chains to a public CA")
if port == 6543:
found.append(f"{source}: {key} uses port 6543, the transaction pooler; use the "
"session pooler (5432) or the direct connection")
found.append(f"{source}: {key} uses port 6543, which on some providers is the "
"pooler's transaction mode; use its session mode (5432) or the direct "
"connection")
user = unquote(parts.username or "")
users[key] = user
host = (parts.hostname or "").lower()
if not user or _role(user) in ADMIN_ROLES:
found.append(f"{source}: {key} logs in as {_role(user) or 'nobody'}; the application "
"never connects as the platform admin, only as its own role")
elif (host.endswith((".supabase.com", ".supabase.co"))
and not _role(user).startswith("sygna_")):
found.append(f"{source}: {key} logs in as {_role(user)}; in the shared Supabase "
"project Sygna's roles are sygna_app and sygna_migrator, and another "
"app's role would be granted Sygna's tables")
if host.endswith(".pooler.supabase.com") and not user.partition(".")[2]:
found.append(f"{source}: {key} logs in as {user or 'nobody'} through Supabase's "
"pooler, which needs <role>.<project-ref>; a refused login counts "
"towards the IP ban")
elif not _role(user).startswith("sygna_"):
found.append(f"{source}: {key} logs in as {_role(user)}; in the family's shared "
"managed database Sygna's roles are sygna_app and sygna_migrator (role "
"names are cluster-wide, and another app's role would be granted "
"Sygna's tables)")
if "pooler" in host and not user.partition(".")[2]:
warnings.append(f"{source}: {key} logs in as {user or 'nobody'} through what looks like "
"a pooler; some poolers need <role>.<tenant> user names, and a refused "
"login may count towards a provider's IP ban")
app_user, migrator_user = users.get("DATABASE_URL"), users.get("MIGRATION_DATABASE_URL")
if app_user and migrator_user and _role(app_user) == _role(migrator_user):
found.append(f"{source}: DATABASE_URL and MIGRATION_DATABASE_URL log in as the same role "
@@ -317,19 +322,19 @@ cli.add_argument("--env", action="append", default=[], metavar="FILE",
help="an environment file to check for the shared managed database (repeatable)")
args = cli.parse_args()
_MARKER = "# ── Database on the family's shared Supabase project"
_MARKER = "# ── Managed PostgreSQL"
_block = env_example.split(_MARKER, 1)[1].split("\n# ── ", 1)[0] if _MARKER in env_example else ""
example = parse_env(_block, commented=True)
check(bool(example), ".env.example has no shared-Supabase-project example block")
check(bool(example), ".env.example has no managed-PostgreSQL example block")
if example:
bad = external_db_problems(example, ".env.example (shared project example)", real=False)
bad = external_db_problems(example, ".env.example (managed PostgreSQL example)", real=False)
problems.extend(bad)
check(_role(_user(example.get("DATABASE_URL", ""))) == "sygna_app"
and _role(_user(example.get("MIGRATION_DATABASE_URL", ""))) == "sygna_migrator",
".env.example's shared-project example does not use sygna_app / sygna_migrator")
".env.example's managed-PostgreSQL example does not use sygna_app / sygna_migrator")
if not bad:
notes.append(".env.example's shared-project example: verify-full, session pooler, "
"sygna_app / sygna_migrator, DB_APP_ROLE matches")
notes.append(".env.example's managed-PostgreSQL example: verify-full against the mounted "
"CA, not 6543, sygna_app / sygna_migrator, DB_APP_ROLE matches")
env_files = [pathlib.Path(p) for p in args.env]
if not env_files and (ROOT / ".env").exists():
@@ -345,47 +350,53 @@ for env_path in env_files:
bad = external_db_problems(real, str(env_path))
problems.extend(bad)
if not bad:
notes.append(f"{env_path}: database URLs fit the managed database (verify-full with the "
"mounted CA, not 6543, sygna_ roles, DB_APP_ROLE matches)")
notes.append(f"{env_path}: database URLs fit the managed database (verify-full, not 6543, "
"sygna_ roles, DB_APP_ROLE matches)")
supabase_compose = read("docker-compose.supabase.yml")
check('profiles: ["local-postgres"]' in supabase_compose,
"docker-compose.supabase.yml does not switch the local postgres off")
check("depends_on: !reset null" in supabase_compose,
"docker-compose.supabase.yml leaves migrate waiting for a postgres that never starts")
check(f"target: {CA_MOUNT}" in supabase_compose
and "create_host_path: false" in supabase_compose,
"docker-compose.supabase.yml does not mount the project's CA where sslrootcert points",
"docker-compose.supabase.yml: local postgres off, CA mounted at /run/certs/supabase-ca.crt")
check("MIGRATION_DATABASE_URL: ${BACKEND_MIGRATION_DATABASE_URL:-}" in supabase_compose,
"docker-compose.supabase.yml hands the long-running backend the migrator credentials",
"on Supabase the long-running backend holds no migrator credentials unless opted in")
managed_compose = read("docker-compose.managed-db.yml")
check('profiles: ["local-postgres"]' in managed_compose,
"docker-compose.managed-db.yml does not switch the local postgres off")
check("depends_on: !reset null" in managed_compose,
"docker-compose.managed-db.yml leaves migrate waiting for a postgres that never starts")
check(f"target: {CA_MOUNT}" in managed_compose
and "create_host_path: false" in managed_compose,
"docker-compose.managed-db.yml does not mount the provider's CA where sslrootcert points",
"docker-compose.managed-db.yml: local postgres off, CA mounted at /run/certs/db-ca.crt")
check("MIGRATION_DATABASE_URL: ${BACKEND_MIGRATION_DATABASE_URL:-}" in managed_compose,
"docker-compose.managed-db.yml hands the long-running backend the migrator credentials",
"on a managed database the long-running backend holds no migrator credentials unless opted in")
for knob in ("DB_POOL_SIZE: ${DB_POOL_SIZE:-", "DB_MAX_OVERFLOW: ${DB_MAX_OVERFLOW:-"):
check(knob in supabase_compose, f"docker-compose.supabase.yml does not pass {knob.split(':')[0]}")
# A literal in both one-shot and long-running containers, so a shell variable cannot switch it off.
check(supabase_compose.count('DB_REQUIRE_VERIFY_FULL: "true"') == 2,
"docker-compose.supabase.yml does not set DB_REQUIRE_VERIFY_FULL for migrate and backend",
"on Supabase, migrate and backend refuse a database URL weaker than verify-full")
check(knob in managed_compose,
f"docker-compose.managed-db.yml does not pass {knob.split(':')[0]}")
# The TLS rule is the settings', unconditional, so no compose literal or shell variable can switch
# it off: every process refuses a URL for a host that is not local without sslmode=verify-full.
check("require_verified_tls(" in config_py and "db_local_hosts" in config_py,
"config.py no longer applies the family's TLS rule (dredd_core.db.require_verified_tls)",
"every process refuses a database URL for a non-local host weaker than verify-full")
check("DB_REQUIRE_VERIFY_FULL" not in managed_compose and "db_require_verify_full" not in config_py,
"DB_REQUIRE_VERIFY_FULL is back: the TLS rule has no switch (DB_LOCAL_HOSTS is its one exception)")
# `environment:` beats env_file, and `${DB_APP_ROLE:-...}` reads the operator's shell: a stray
# export would make 0002 grant Sygna's tables to a role deploy_check never saw.
check(not re.search(r"^\s+DB_APP_ROLE:", supabase_compose, re.MULTILINE),
"docker-compose.supabase.yml sets DB_APP_ROLE, so the shell can override the checked .env",
"on Supabase, DB_APP_ROLE comes from .env only")
provision_sql = read("db/supabase/provision.sql")
check(not re.search(r"^\s+DB_APP_ROLE:", managed_compose, re.MULTILINE),
"docker-compose.managed-db.yml sets DB_APP_ROLE, so the shell can override the checked .env",
"on a managed database, DB_APP_ROLE comes from .env only")
provision_sql = read("db/managed/provision.sql")
check("schema sygna, migrator sygna_migrator, app sygna_app" in provision_sql,
"db/supabase/provision.sql is not Sygna's rendering (schema sygna, sygna_migrator, sygna_app)",
"db/supabase/provision.sql provisions schema sygna with Sygna's own roles")
"db/managed/provision.sql is not Sygna's rendering (schema sygna, sygna_migrator, sygna_app)",
"db/managed/provision.sql provisions schema sygna with Sygna's own roles")
ci_yml = read(".github/workflows/ci.yml")
check("--check-file ../db/supabase/provision.sql" in ci_yml,
"CI does not check that db/supabase/provision.sql is current",
"CI re-renders db/supabase/provision.sql and fails when it is stale")
check("--check-file ../db/managed/provision.sql" in ci_yml,
"CI does not check that db/managed/provision.sql is current",
"CI re-renders db/managed/provision.sql and fails when it is stale")
check("--no-delete conflict_check aml_assessment" in ci_yml
and "--no-delete conflict_check aml_assessment" in read("db/supabase/README.md"),
and "--no-delete conflict_check aml_assessment" in read("db/managed/README.md"),
"the managed check in CI or the runbook forgets the no-delete evidence tables")
# ── report ────────────────────────────────────────────────────────────────────
for note in notes:
print(f" ok {note}")
for warning in warnings:
print(f" WARN {warning}")
if problems:
print()
for problem in problems:
+91 -43
View File
@@ -1,9 +1,11 @@
"""The settings and wiring the family's shared managed database depends on — DB-free.
On the shared Supabase project Sygna's runtime role is `sygna_app`, not `app`, and four apps share
one connection limit. Both are configuration, and both are easy to get quietly wrong: a grant to
the wrong role name only fails at the next migration, and a pool that ignores its settings only
shows up when the project runs out of connections.
In the family's shared managed database Sygna's runtime role is `sygna_app`, not `app`, four apps
share one connection limit, and a database reached over a network must be verified. All three are
configuration, and all three are easy to get quietly wrong: a grant to the wrong role name only
fails at the next migration, a pool that ignores its settings only shows up when the database runs
out of connections, and a URL without sslmode still connects — pg8000 then skips verifying the
server and falls back to plaintext if the server declines TLS.
"""
from __future__ import annotations
@@ -26,7 +28,7 @@ _BYPASS = re.compile(r"\b(create_engine|engine_from_config)\s*\("
@pytest.fixture(autouse=True)
def _no_database_env(monkeypatch):
"""The suite also runs with DB_APP_ROLE and the pool knobs set (the managed-database job)."""
for name in ("DB_APP_ROLE", "DB_POOL_SIZE", "DB_MAX_OVERFLOW", "DB_REQUIRE_VERIFY_FULL"):
for name in ("DB_APP_ROLE", "DB_POOL_SIZE", "DB_MAX_OVERFLOW", "DB_LOCAL_HOSTS"):
monkeypatch.delenv(name, raising=False)
@@ -38,7 +40,7 @@ def test_the_runtime_role_defaults_to_the_local_name():
assert _settings().db_app_role == "app"
@pytest.mark.parametrize("name", ["app", "sygna_app", "supa1_sygna_app", "_x"])
@pytest.mark.parametrize("name", ["app", "sygna_app", "tenant1_sygna_app", "_x"])
def test_a_plain_role_name_is_accepted(name):
assert _settings(db_app_role=name).db_app_role == name
@@ -54,76 +56,122 @@ def test_anything_but_a_plain_role_name_is_refused(name):
def test_pool_knobs_default_and_are_bounded():
s = _settings()
assert (s.db_pool_size, s.db_max_overflow) == (5, 10)
micro = _settings(db_pool_size=3, db_max_overflow=2)
assert (micro.db_pool_size, micro.db_max_overflow) == (3, 2)
small = _settings(db_pool_size=3, db_max_overflow=2)
assert (small.db_pool_size, small.db_max_overflow) == (3, 2)
with pytest.raises(ValidationError):
_settings(db_pool_size=0)
with pytest.raises(ValidationError):
_settings(db_max_overflow=-1)
# ── the family's one TLS rule (dredd_core.db.require_verified_tls) ────────────
# The password holds every character that has to be URL-encoded; no error may ever show it.
_SECRET = "s3cret%@:/?#$pw"
_PW = "s3cret%25%40%3A%2F%3F%23%24pw"
_POOLER = "aws-0-eu-central-1.pooler.supabase.com:5432/postgres"
_CA = "sslrootcert=/run/certs/supabase-ca.crt"
_VERIFY_FULL = f"postgresql+pg8000://sygna_app.ref:{_PW}@{_POOLER}?sslmode=verify-full&{_CA}"
_HOST = "pooler.db.example-provider.com"
_REMOTE = f"{_HOST}:5432/postgres"
_CA = "sslrootcert=/run/certs/db-ca.crt"
_VERIFY_FULL = f"postgresql+pg8000://sygna_app.tenant:{_PW}@{_REMOTE}?sslmode=verify-full&{_CA}"
_MIGRATOR_VERIFY_FULL = _VERIFY_FULL.replace("sygna_app.", "sygna_migrator.")
def test_verify_full_is_not_required_by_default():
"""A local database without TLS keeps working: the requirement is the managed override's."""
s = _settings(database_url="postgresql+pg8000://app:app@postgres:5432/sygna")
assert s.db_require_verify_full is False
def _local(user: str, host: str) -> str:
return f"postgresql+pg8000://{user}:{_PW}@{host}"
def test_verify_full_urls_are_accepted_when_required():
s = _settings(db_require_verify_full=True, database_url=_VERIFY_FULL,
migration_database_url=_MIGRATOR_VERIFY_FULL)
@pytest.mark.parametrize("host", [
"postgres:5432/sygna", # the compose service
"localhost:5432/sygna",
"LOCALHOST:5432/sygna",
"127.0.0.1:5432/sygna",
"[::1]:5432/sygna",
"postgres/sygna", # no port
"/sygna", # no host: a Unix socket
])
def test_a_local_host_needs_no_tls(host):
"""A local database without TLS keeps working; nothing has to be switched on or off for it."""
s = _settings(database_url=_local("app", host), migration_database_url=_local("migrator", host))
assert s.db_local_hosts == ""
def test_remote_verify_full_urls_load():
s = _settings(database_url=_VERIFY_FULL, migration_database_url=_MIGRATOR_VERIFY_FULL)
assert s.database_url == _VERIFY_FULL
# The long-running backend under the override: no migrator credentials at all.
assert _settings(db_require_verify_full=True, database_url=_VERIFY_FULL,
# The long-running backend under the managed override: no migrator credentials at all.
assert _settings(database_url=_VERIFY_FULL,
migration_database_url="").migration_database_url == ""
# sslmode is case-insensitive in make_engine too.
upper = _VERIFY_FULL.replace("verify-full", "VERIFY-FULL")
_settings(db_require_verify_full=True, database_url=upper, migration_database_url="")
_settings(database_url=upper, migration_database_url="")
# verify-full with no sslrootcert verifies against the system trust store.
_settings(database_url=_VERIFY_FULL.replace("&" + _CA, ""), migration_database_url="")
@pytest.mark.parametrize("query, reason", [
("", "no sslmode"),
("?sslmode=require", "it has require"),
("?sslmode=verify-ca&" + _CA, "it has verify-ca"),
("?sslmode=require&" + _CA, "it has require"),
("?sslmode=prefer", "it has prefer"),
("?sslmode=verify-full", "sslrootcert"),
("?sslmode=verify-full&sslrootcert=", "sslrootcert"),
("?sslmode=verify-full&sslrootcert=system", "sslrootcert"),
("?sslmode=verify-full&sslmode=require&" + _CA, "more than once"),
("?" + _CA, "no sslmode"),
("?sslmode=require", "sslmode=require"),
("?sslmode=verify-ca&" + _CA, "sslmode=verify-ca"),
("?sslmode=require&" + _CA, "sslmode=require"),
("?sslmode=prefer", "sslmode=prefer"),
])
@pytest.mark.parametrize("key", ["database_url", "migration_database_url"])
def test_anything_weaker_than_verify_full_is_refused_when_required(key, query, reason):
weak = f"postgresql+pg8000://sygna_app.ref:{_PW}@{_POOLER}{query}"
def test_a_remote_host_needs_verify_full(key, query, reason):
"""Every other mode either skips the host-name check or permits plaintext."""
weak = f"postgresql+pg8000://sygna_app.tenant:{_PW}@{_REMOTE}{query}"
values = {"database_url": _VERIFY_FULL, "migration_database_url": _MIGRATOR_VERIFY_FULL,
key: weak}
with pytest.raises(ValidationError, match="DB_REQUIRE_VERIFY_FULL") as refused:
_settings(db_require_verify_full=True, **values)
with pytest.raises(ValidationError, match=f"{key.upper()}: database host") as refused:
_settings(**values)
message = str(refused.value)
assert key.upper() in message and reason in message
assert _HOST in message and reason in message
assert "sslmode=verify-full" in message and "DB_LOCAL_HOSTS" in message
assert _PW not in message and _SECRET not in message and "s3cret" not in message
def test_the_requirement_comes_from_the_environment(monkeypatch):
"""docker-compose.supabase.yml sets DB_REQUIRE_VERIFY_FULL: "true" for migrate and backend."""
monkeypatch.setenv("DB_REQUIRE_VERIFY_FULL", "true")
with pytest.raises(ValidationError, match="DATABASE_URL must carry sslmode=verify-full"):
_settings(database_url="postgresql+pg8000://sygna_app.ref:pw@db.example.com:5432/postgres",
migration_database_url="")
@pytest.mark.parametrize("host", [
"10.0.0.5:5432/sygna", # a private address is still reached over a network
"postgres.example.com:5432/sygna", # starts with the compose service's name; is not it
"POOLER.DB.EXAMPLE-PROVIDER.COM.:5432/postgres",
])
def test_anything_that_is_not_local_is_remote(host):
with pytest.raises(ValidationError, match="DATABASE_URL: database host"):
_settings(database_url=_local("sygna_app", host), migration_database_url="")
def test_sslmode_given_twice_is_refused():
twice = f"postgresql+pg8000://sygna_app.tenant:{_PW}@{_REMOTE}?sslmode=verify-full&sslmode=require"
with pytest.raises(ValidationError, match="DATABASE_URL: sslmode is given more than once"):
_settings(database_url=twice, migration_database_url="")
def test_db_local_hosts_extends_the_local_list():
host = "db.internal.example:5432/sygna"
with pytest.raises(ValidationError, match="DATABASE_URL: database host 'db.internal.example'"):
_settings(database_url=_local("app", host), migration_database_url="")
# Comma-separated, blanks and case ignored; both URLs are covered.
s = _settings(db_local_hosts=" pg.lan , DB.Internal.Example",
database_url=_local("app", host), migration_database_url=_local("migrator", host))
assert s.db_local_hosts == " pg.lan , DB.Internal.Example"
# An entry covers that host only.
with pytest.raises(ValidationError, match="MIGRATION_DATABASE_URL: database host 'other.lan'"):
_settings(db_local_hosts="db.internal.example", database_url=_local("app", host),
migration_database_url=_local("migrator", "other.lan:5432/sygna"))
def test_db_local_hosts_comes_from_the_environment(monkeypatch):
"""The only exception to the rule is a setting, never a compose literal or a shell flag."""
url = _local("app", "db.internal.example:5432/sygna")
with pytest.raises(ValidationError, match="DB_LOCAL_HOSTS"):
_settings(database_url=url, migration_database_url="")
monkeypatch.setenv("DB_LOCAL_HOSTS", "db.internal.example")
assert _settings(database_url=url, migration_database_url="").db_local_hosts == \
"db.internal.example"
def test_an_unparseable_url_is_refused_without_echoing_it():
with pytest.raises(ValidationError, match="not a parseable database URL") as refused:
_settings(db_require_verify_full=True, database_url=f"not a url {_SECRET}",
migration_database_url="")
with pytest.raises(ValidationError, match="DATABASE_URL is not a parseable database URL") as refused:
_settings(database_url=f"not a url {_SECRET}", migration_database_url="")
assert "s3cret" not in str(refused.value)
+1 -1
View File
@@ -1,5 +1,5 @@
"""The one-shot restore (`python -m app.restore`) and the refusal when a process holds no migrator
credentials — what docker-compose.supabase.yml gives the long-running backend by default.
credentials — what docker-compose.managed-db.yml gives the long-running backend by default.
The DB-free tests never connect: every refusal happens before the first query. The round trips
are gated on a migrated + seeded Postgres (SYGNA_RUN_INTEGRATION=1).
+314
View File
@@ -0,0 +1,314 @@
# 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)
1. **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 `postgres` role, usually not a
superuser there) in your secret store; Sygna uses it only for provisioning.
2. **Download the provider's root CA** from its dashboard, save it as `certs/db-ca.crt` (or wherever
`MANAGED_DB_CA_FILE` points) on every container host, check it with
`openssl x509 -in certs/db-ca.crt -noout -subject -enddate -fingerprint -sha256`, and put its
expiry date in the ops calendar: after it, every `verify-full` connection fails. Skip the file only
if the server's certificate chains to a public CA; `verify-full` then uses the system trust store
and the URLs carry no `sslrootcert`.
3. **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. The backends
connect to Postgres directly, so nothing needs it.
4. **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.
5. **Size the connection budget for four apps** with section 2, including any pooler's per-role pool
size.
6. **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).
```bash
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`](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:
```bash
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`](../../.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):
```dotenv
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-full` against the provider's CA, which the override mounts at
`/run/certs/db-ca.crt` (leave `sslrootcert` out to verify against the system trust store). Every
engine Sygna builds (runtime, Alembic, the seed, restore) goes through `dredd_core.db.make_engine`,
which turns the two parameters into a verifying TLS context. `make_engine` on its own refuses only
`prefer` / `allow` / `disable`: it still takes `require` and `verify-ca`, which do not check the
host name, and a URL with no `sslmode`, 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 of
`DB_LOCAL_HOSTS`) is refused without `sslmode=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 `$HOME` silently becomes a directory name, the
login fails, and some providers ban the host's IP after a few failures). `quote` turns `$` into
`%24`. Alembic uses the URL directly, so an encoded `%` is fine.
- **`DB_APP_ROLE`** is the role in `DATABASE_URL` without `.<tenant>`. Migration `0002` grants it its
privileges; a role that does not exist stops the migration with `runtime grants: role … does not
exist` and rolls it back.
- **Pool.** Each backend process holds up to `DB_POOL_SIZE + DB_MAX_OVERFLOW` connections. The seed,
migrations, restores and `managed check` use 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 a `managed check` or one-shot beside it needs a pool
size of at least `DB_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's
`DB_POOL_SIZE + DB_MAX_OVERFLOW + 1` well under it: with the defaults that is 4 × 16 = 64, 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 × 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).
- **`POSTGRES_PASSWORD` and `DB_*_PASSWORD`** are unused here (no local postgres); remove them.
Then the pre-flight, which reads the files and never connects or prints a password:
```bash
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
```bash
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`](../../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.
- **`migrate`** runs `alembic upgrade head` as `sygna_migrator`. Through the role's `search_path`
every table, enum type and `alembic_version` lands in `sygna`; nothing is schema-qualified in
code, and another app's same-named `audit_log`, `app_user` or enum type in its own schema neither
hides a table from `create_all` nor makes Alembic think Sygna is already migrated. `0002` then
grants `sygna_app` its privileges, keeps the evidence tables protected, strips the API roles and
verifies all of it.
- **The seed** runs as `sygna_app`.
- **`backend`** gets an empty `MIGRATION_DATABASE_URL`, so the long-running process can only log in
as `sygna_app` (see Restore for the opt-in).
- **Never migrate as the platform admin (`postgres`).** `0002` refuses a superuser or the platform
admin (`runtime grants: refusing to migrate as postgres`) and the whole migration rolls back:
objects it created would be owned by `postgres` and sit in `public`, where an auto-generated API
looks.
- **Nothing retries a failed migration**: some providers ban the host's IP after a few wrong
passwords in a row. Fix `.env`, then run `migrate` once 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
```bash
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
```
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`.
## 5. Restore: Sygna specifics
Sygna has its **own app-level backup** (Administracja → Kopie zapasowe: 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:
```bash
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):
```sql
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`, on `postgres:17`**: `dredd_core.managed emulate` (TEST-ONLY: a
non-superuser platform admin, the API roles, an `extensions` schema), provisioning twice, a
refused migration as the platform admin that leaves nothing in `public`, migrate + seed as
`sygna_migrator` with a password holding `% @ : / ? #`, the whole integration suite as `sygna_app`,
the managed check as both roles, `sygna_app` refused on `audit_log`, `conflict_check` and
`aml_assessment`, and a downgrade to base and back. The `backend` job runs on PostgreSQL 16 and 17
and checks that `provision.sql` is 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 and `alembic_version`, with isolation
proven both ways, plus the negative cases (migrating as the admin, `DB_APP_ROLE` naming 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.
@@ -1,22 +1,23 @@
-- =================================================================================================
-- Managed Postgres (Supabase) provisioning for one app of the family, in the shared database:
-- Managed Postgres provisioning for one app of the family, in the shared database:
-- schema sygna, migrator sygna_migrator, app sygna_app, extensions: none, migrator statement_timeout 30min
--
-- Rendered by dredd-core. Do not edit: re-render, and let CI check it is current (exit 1 = stale):
-- python -m dredd_core.managed provision --sql-only \
-- --schema sygna --app-role sygna_app --migrator-role sygna_migrator \
-- --output db/supabase/provision.sql (CI: --check-file db/supabase/provision.sql)
-- --output db/managed/provision.sql (CI: --check-file db/managed/provision.sql)
--
-- Preferred path, from a shell (passwords come from environment variables and are never printed):
-- 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
--
-- SQL editor path (no shell): paste this whole file into the Supabase SQL editor, replace both
-- SQL editor path (no shell): paste this whole file into the provider's SQL editor, replace both
-- change_me passwords in step 2 there (never in the committed file; at least 16 printable ASCII
-- characters, different per role), and run it once as postgres. Re-running is safe: an existing
-- role keeps its password unless reset_passwords is set to true (do that after a restore, which
-- drops custom role passwords). It never touches schema public and never drops anything.
-- characters, different per role), and run it once as the platform admin (postgres). Re-running is
-- safe: an existing role keeps its password unless reset_passwords is set to true (do that after a
-- restore, which may drop custom role passwords). It never touches schema public and never drops
-- anything.
-- =================================================================================================
BEGIN;
@@ -36,18 +37,18 @@ BEGIN
RAISE EXCEPTION USING
MESSAGE = 'provision: connected as ' || quote_ident(current_user::text)
|| ', one of the roles being provisioned',
HINT = 'Run it as the platform admin: postgres on Supabase (postgres_managed in the local emulation).';
HINT = 'Run it as the platform admin: postgres on a managed provider (postgres_managed in the local emulation).';
END IF;
IF (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) THEN
RAISE WARNING USING
MESSAGE = 'provision: connected as the superuser ' || quote_ident(current_user::text),
HINT = 'Fine on a local cluster or in CI; on Supabase run it as postgres, which is not a superuser.';
HINT = 'Fine on a local cluster or in CI; on a managed provider run it as postgres, which is not a superuser there.';
ELSIF NOT (current_user::text = ANY (admin_roles)) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: connected as ' || quote_ident(current_user::text)
|| ', which is neither the platform admin (' || array_to_string(admin_roles, ', ')
|| ') nor a superuser',
HINT = 'Run it as postgres on Supabase (postgres_managed in the local emulation).';
HINT = 'Run it as postgres on a managed provider (postgres_managed in the local emulation).';
ELSIF NOT (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user)
AND EXISTS (SELECT 1 FROM unnest(ARRAY[migrator_role, app_role]) AS n
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = n)) THEN
@@ -58,7 +59,7 @@ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'extensions') THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: schema extensions does not exist',
HINT = 'Supabase always has it. On a plain PostgreSQL test cluster run '
HINT = 'A managed provider has it. On a plain PostgreSQL test cluster run '
|| 'python -m dredd_core.managed emulate (TEST-ONLY) first.';
END IF;
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = target_schema;
-291
View File
@@ -1,291 +0,0 @@
# Sygna on the family's shared Supabase project
The Dredd family runs in **one Supabase project**: one database, EU region, PostgreSQL 17. Atrium is
the hub; Galena, Sygna and Counsel Scorecard are its modules. Supabase 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.
**Project-wide steps come first.** The family runbook,
[Atrium's `deploy/README.md`](https://github.com/Alpaq92/Atrium/blob/main/deploy/README.md), has the
full procedure once Atrium publishes it. Until you have it, do not start Sygna on a project where any
of these is not true:
1. **Created** in a specific EU region (e.g. `eu-central-1`, Frankfurt) on PostgreSQL 17, with
members limited to the people who operate it (section 1, "That last revoke is not a wall").
2. **CA certificate** downloaded from Database Settings → SSL Configuration, saved as
`certs/supabase-ca.crt` (or wherever `SUPABASE_CA_FILE` points), checked with
`openssl x509 -in certs/supabase-ca.crt -noout -subject -enddate -fingerprint -sha256`, and its
expiry date in the ops calendar: after it, every `verify-full` connection fails.
3. **Data API off** for the project and `pg_graphql` disabled. On a project created before
2026-05-30, also revoke the default privileges `anon`, `authenticated` and `service_role` hold on
new objects in `public`.
4. **SSL enforced** on incoming connections (changing it restarts the database), and **network
restrictions** allowing only the backend host, plus the machine you provision from while you do.
5. **Compute and the pooler's Pool Size** sized with the budget in section 2.
6. **A backup decision.** A project backup or PITR rewinds all four apps together; Sygna's own
backup (section 5) rewinds Sygna alone. A project restore means: stop every app's backend,
restore, reset every app's 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 |
| 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 Supabase'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.
## 1. Provision Sygna (once, as `postgres`)
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/supabase-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).
```bash
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.<project-ref>:<url-encoded password>@aws-0-eu-central-1.pooler.supabase.com:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/supabase-ca.crt
DREDD_CORE_TOKEN=github_pat_... \
docker compose -f docker-compose.yml -f docker-compose.supabase.yml build migrate
docker compose -f docker-compose.yml -f docker-compose.supabase.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
```
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/supabase-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
(Supabase's 2-minute cap would cut off a long migration or restore), and finally `postgres`'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. `postgres`
created both roles and keeps `ADMIN OPTION` on them (PostgreSQL 16+), so anyone with the dashboard'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 dashboard SQL access as full
control over Sygna's data: keep the project's members to the few who operate it, and rely on
Supabase's own records of their access, not on this revoke.
**From the Supabase SQL editor (no shell).** Paste the whole of [`provision.sql`](provision.sql),
replace the two `change_me` passwords in step 2 there (never in the committed file) and run it once.
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:
```bash
cd backend
python -m dredd_core.managed provision --sql-only --schema sygna --app-role sygna_app \
--migrator-role sygna_migrator --output ../db/supabase/provision.sql
```
CI runs the same command with `--check-file ../db/supabase/provision.sql` and fails when the file
is stale.
## 2. Configure `.env`
Take the commented "shared Supabase project" block from [`.env.example`](../../.env.example) in
place of the Database settings, and put the project's CA at `./certs/supabase-ca.crt` (or point
`SUPABASE_CA_FILE` at it):
```dotenv
DATABASE_URL=postgresql+pg8000://sygna_app.<project-ref>:<url-encoded password>@aws-0-eu-central-1.pooler.supabase.com:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/supabase-ca.crt
MIGRATION_DATABASE_URL=postgresql+pg8000://sygna_migrator.<project-ref>:<url-encoded password>@aws-0-eu-central-1.pooler.supabase.com:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/supabase-ca.crt
DB_APP_ROLE=sygna_app
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=10
SUPABASE_CA_FILE=./certs/supabase-ca.crt
```
- **Connection.** The shared pooler in **session mode, port 5432**, user `<role>.<project-ref>`; or
the direct `db.<project-ref>.supabase.co:5432` with the plain role name (IPv6-only without the
IPv4 add-on). **Never 6543**, the transaction mode.
- **TLS.** `sslmode=verify-full` against the project's CA, which the override mounts at
`/run/certs/supabase-ca.crt`. Every engine Sygna builds (runtime, Alembic, the seed, restore) goes
through `dredd_core.db.make_engine`, which turns the two parameters into a verifying TLS context.
`make_engine` on its own refuses only `prefer` / `allow` / `disable`: it still takes `require` and
`verify-ca`, which do not check the host name, and a URL with no `sslmode`, where pg8000 does not
verify the server and falls back to plaintext if the server allows it. So the override sets
`DB_REQUIRE_VERIFY_FULL=true` for `migrate` and `backend`, whatever `.env` says, and Sygna's
settings then refuse to load unless both URLs carry `sslmode=verify-full` and `sslrootcert`:
migrations, the seed, the restore and the backend stop before connecting.
- **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 `$HOME` silently becomes a directory name, the
login fails, and two failures ban the host). `quote` turns `$` into `%24`. Alembic uses the URL
directly, so an encoded `%` is fine.
- **`DB_APP_ROLE`** is the role in `DATABASE_URL` without `.<project-ref>`. Migration `0002` grants it
its privileges; a role that does not exist stops the migration with `runtime grants: role … does
not exist` and rolls it back.
- **Pool.** Each backend process holds up to `DB_POOL_SIZE + DB_MAX_OVERFLOW` connections. The seed,
migrations, restores and `managed check` use one unpooled connection each. Two limits apply:
- **The pooler's Pool Size** (Database Settings). Supavisor keeps a separate pool for each role +
database + mode, and in session mode a pool admits at most Pool Size clients; one more waits up
to a minute and is then refused. `sygna_app`'s backend plus a `managed check` or one-shot beside
it needs Pool Size ≥ `DB_POOL_SIZE + DB_MAX_OVERFLOW + 1` (16 with the defaults). The setting is
project-wide, so the largest app's pool decides it.
- **The compute's connection limit** (Micro 60, Small 90), shared by all four apps' pools, the
migrator sessions and Supabase's own services. Keep the sum of every app's
`DB_POOL_SIZE + DB_MAX_OVERFLOW + 1` well under it: with the defaults that is 4 × 16 = 64, so use
**Small**. On **Micro** set `DB_POOL_SIZE=3` and `DB_MAX_OVERFLOW=2` in every app (4 × 6 = 24).
How much Supabase's services take, and whether these numbers hold under load, has not been
measured yet (see the end of this page).
- **`POSTGRES_PASSWORD` and `DB_*_PASSWORD`** are unused here (no local postgres); remove them.
Then the pre-flight, which reads the files and never connects or prints a password:
```bash
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/supabase-ca.crt`, port 6543, a user that is `postgres` (or
another platform role), a Supabase user whose role does not start with `sygna_`, a pooler user
without `.<project-ref>`, the same role in both URLs, `DB_APP_ROLE` not matching the runtime user
before `.<project-ref>`, an unencoded `@`, `#`, `$` or bare `%`, a leftover `<placeholder>` or
`change_me`, and a missing CA file.
## 3. Migrate, seed, run
```bash
DREDD_CORE_TOKEN=github_pat_... \
docker compose -f docker-compose.yml -f docker-compose.supabase.yml up -d --build
```
[`docker-compose.supabase.yml`](../../docker-compose.supabase.yml) switches the local `postgres`
off, stops `migrate` waiting for it, mounts the CA into `migrate` and `backend`, sets
`DB_REQUIRE_VERIFY_FULL=true` in both, and passes the pool knobs to `backend`. It does **not** set
`DB_APP_ROLE`: 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.
- **`migrate`** runs `alembic upgrade head` as `sygna_migrator`. Through the role's `search_path`
every table, enum type and `alembic_version` lands in `sygna`; nothing is schema-qualified in
code, and another app's same-named `audit_log`, `app_user` or enum type in its own schema neither
hides a table from `create_all` nor makes Alembic think Sygna is already migrated. `0002` then
grants `sygna_app` its privileges, keeps the evidence tables protected, strips the Data API roles
and verifies all of it.
- **The seed** runs as `sygna_app`.
- **`backend`** gets an empty `MIGRATION_DATABASE_URL`, so the long-running process can only log in
as `sygna_app` (see Restore for the opt-in).
- **Never migrate as `postgres`.** `0002` refuses a superuser or the platform admin (`runtime grants:
refusing to migrate as postgres`) and the whole migration rolls back: objects it created would be
owned by `postgres` and sit in `public`, where the Data API looks.
- **Nothing retries a failed migration**: two wrong passwords in a row get the host's IP banned for
30 minutes. Fix `.env`, then run `migrate` once 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
```bash
for url in DATABASE_URL MIGRATION_DATABASE_URL; do
docker compose -f docker-compose.yml -f docker-compose.supabase.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
```
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 (`deploy_check.py` and
`DB_REQUIRE_VERIFY_FULL` refuse such a URL anyway). Through the 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), and that `anon`, `authenticated` and `service_role` hold
nothing in `sygna`.
## 5. Restore: Sygna specifics
Sygna has its **own app-level backup** (Administracja → Kopie zapasowe: one archive of every table
plus `DATA_DIR`, in `DATA_DIR/backups`). It restores Sygna alone, which a project backup or PITR
cannot: those rewind all four apps together. Copy the archives off the host; they are not in
Supabase.
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:
```bash
docker compose -f docker-compose.yml -f docker-compose.supabase.yml stop backend
docker compose -f docker-compose.yml -f docker-compose.supabase.yml run --rm migrate \
python -m app.restore # list the archives
docker compose -f docker-compose.yml -f docker-compose.supabase.yml run --rm migrate \
python -m app.restore <backup name> --yes # restore one
docker compose -f docker-compose.yml -f docker-compose.supabase.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 project 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` (daily backups do not keep custom-role passwords);
`up -d` (`migrate` is a no-op at head); run the check in section 4.
## 6. Removing Sygna from the project
As `postgres`, in one transaction (after taking a backup):
```sql
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`, on `postgres:17`**: `dredd_core.managed emulate` (TEST-ONLY), provisioning
twice, a refused migration as the platform admin that leaves nothing in `public`, migrate + seed as
`sygna_migrator` with a password holding `% @ : / ? #`, the whole integration suite as `sygna_app`,
the managed check as both roles, `sygna_app` refused on `audit_log`, `conflict_check` and
`aml_assessment`, and a downgrade to base and back. The `backend` job runs on PostgreSQL 16 and 17
and checks that `provision.sql` is 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 and `alembic_version`, with isolation
proven both ways, plus the negative cases (migrating as the admin, `DB_APP_ROLE` naming a missing
role, `sslmode=prefer`).
Not yet confirmed on a real Supabase project: hosted `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 Supabase's own configuration; `sygna_app.<ref>` logins through Supavisor session
mode and after a restore; certificate host-name checks against the pooler host; pg8000 through
Supavisor with a 15-connection pool; the connection budget in section 2: the default Pool Size per
compute, how session mode behaves at the Pool Size cap, how many connections Supabase's own services
hold, and whether four apps at their defaults really fit on Small; what `--require-tls` reports
through the pooler; real latency.
+68
View File
@@ -0,0 +1,68 @@
# Sygna on a managed PostgreSQL database (the family's shared one, or any Postgres 16/17 reached
# over a network): an override for docker-compose.yml.
#
# DREDD_CORE_TOKEN=github_pat_... \
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
#
# The database lives elsewhere, so the local postgres service is switched off and nothing waits
# for it; migrate (+seed), backend and caddy otherwise run as in docker-compose.yml. Before the
# first start, Sygna must be provisioned in the database (schema sygna, roles sygna_migrator /
# sygna_app) and .env must carry its URLs: the provider's host and port (through a pooler, its
# session mode, never transaction mode), <role>.<tenant> user names where the pooler wants them,
# URL-encoded passwords and ?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt. Runbook:
# db/managed/README.md.
#
# Pass -f with BOTH files on every command (ps, logs, run, down), or Compose falls back to the
# local-postgres stack. The !reset tag needs a Docker Compose release that implements the merge
# rules documented at docs.docker.com/reference/compose-file/merge/ (2.24.4 or later).
services:
postgres:
# Off: a profile nobody activates keeps the service defined but never starts it.
profiles: ["local-postgres"]
migrate:
# docker-compose.yml makes migrate wait for the local postgres healthcheck; there is none here.
# (backend depends only on migrate, and caddy only on backend, so both keep their ordering.)
# It does not retry either: some providers ban the host's IP after a few failed logins in a
# row, so a wrong password must fail once and loudly.
depends_on: !reset null
# Nothing here switches TLS on: Sygna's settings refuse, before connecting, a DATABASE_URL or
# MIGRATION_DATABASE_URL for a host that is not local without sslmode=verify-full (config.py,
# the family's one TLS rule; DB_LOCAL_HOSTS in .env is the only exception). That covers
# Alembic, the seed and the one-shot restore, which all run in migrate, and the backend.
#
# DB_APP_ROLE is deliberately NOT set here: a `${DB_APP_ROLE:-...}` entry would take a value
# exported in the operator's shell over the .env that deploy_check.py validates, and 0002
# would grant Sygna's tables to whatever role that names. It comes from env_file (.env) only.
volumes:
- &managed_db_ca
# The provider's root CA (downloaded from its dashboard), read-only, at the path the
# URLs' sslrootcert names. create_host_path: false makes a missing file an error at
# start-up instead of an empty directory in its place.
type: bind
source: ${MANAGED_DB_CA_FILE:-./certs/db-ca.crt}
target: /run/certs/db-ca.crt
read_only: true
bind:
create_host_path: false
backend:
environment:
# The runtime pool per backend process. Every app in the shared database draws on one
# connection limit: size these with the budget in db/managed/README.md.
DB_POOL_SIZE: ${DB_POOL_SIZE:-5}
DB_MAX_OVERFLOW: ${DB_MAX_OVERFLOW:-10}
# The long-running backend holds no migrator credentials: this empty value overrides the
# MIGRATION_DATABASE_URL that env_file loads from .env (migrate keeps it). The console's
# restore (Administracja -> Kopie zapasowe) is then refused with a clear message; restore
# with the one-shot 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 migrate \
# python -m app.restore <backup name> --yes
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml start backend
# Opt in to the console's restore instead: set BACKEND_MIGRATION_DATABASE_URL in .env to the
# migrator URL. The running backend then holds credentials that can rewrite the audit log
# and delete conflict checks — the very thing the runtime role is built not to have.
MIGRATION_DATABASE_URL: ${BACKEND_MIGRATION_DATABASE_URL:-}
volumes:
- *managed_db_ca
-69
View File
@@ -1,69 +0,0 @@
# Sygna on the family's shared Supabase project (managed Postgres): an override for
# docker-compose.yml.
#
# DREDD_CORE_TOKEN=github_pat_... \
# docker compose -f docker-compose.yml -f docker-compose.supabase.yml up -d --build
#
# The database is the shared Supabase project, so the local postgres service is switched off and
# nothing waits for it; migrate (+seed), backend and caddy otherwise run as in docker-compose.yml.
# Before the first start, Sygna must be provisioned in the project (schema sygna, roles
# sygna_migrator / sygna_app) and .env must carry the Supabase URLs: session pooler port 5432
# (never 6543), <role>.<project-ref> user names, URL-encoded passwords and
# ?sslmode=verify-full&sslrootcert=/run/certs/supabase-ca.crt. Runbook: db/supabase/README.md.
#
# Pass -f with BOTH files on every command (ps, logs, run, down), or Compose falls back to the
# local-postgres stack. The !reset tag needs a Docker Compose release that implements the merge
# rules documented at docs.docker.com/reference/compose-file/merge/ (2.24.4 or later).
services:
postgres:
# Off: a profile nobody activates keeps the service defined but never starts it.
profiles: ["local-postgres"]
migrate:
# docker-compose.yml makes migrate wait for the local postgres healthcheck; there is none here.
# (backend depends only on migrate, and caddy only on backend, so both keep their ordering.)
# It does not retry either: two failed logins in a row get the host's IP banned by Supabase
# for 30 minutes, so a wrong password must fail once and loudly.
depends_on: !reset null
environment:
# Refuse, before connecting, a DATABASE_URL or MIGRATION_DATABASE_URL without
# sslmode=verify-full and sslrootcert (config.py). A literal, so no shell variable can turn
# it off. That covers Alembic, the seed and the one-shot restore, which all run in migrate.
#
# DB_APP_ROLE is deliberately NOT set here: a `${DB_APP_ROLE:-...}` entry would take a value
# exported in the operator's shell over the .env that deploy_check.py validates, and 0002
# would grant Sygna's tables to whatever role that names. It comes from env_file (.env) only.
DB_REQUIRE_VERIFY_FULL: "true"
volumes:
- &supabase_ca
# The project's root CA (Database Settings -> SSL Configuration), read-only, at the path
# the URLs' sslrootcert names. create_host_path: false makes a missing file an error at
# start-up instead of an empty directory in its place.
type: bind
source: ${SUPABASE_CA_FILE:-./certs/supabase-ca.crt}
target: /run/certs/supabase-ca.crt
read_only: true
bind:
create_host_path: false
backend:
environment:
DB_REQUIRE_VERIFY_FULL: "true"
# The runtime pool per backend process. Every app in the shared project draws on one
# connection limit: size these with the budget in db/supabase/README.md.
DB_POOL_SIZE: ${DB_POOL_SIZE:-5}
DB_MAX_OVERFLOW: ${DB_MAX_OVERFLOW:-10}
# The long-running backend holds no migrator credentials: this empty value overrides the
# MIGRATION_DATABASE_URL that env_file loads from .env (migrate keeps it). The console's
# restore (Administracja -> Kopie zapasowe) is then refused with a clear message; restore
# with the one-shot instead:
# docker compose -f docker-compose.yml -f docker-compose.supabase.yml stop backend
# docker compose -f docker-compose.yml -f docker-compose.supabase.yml run --rm migrate \
# python -m app.restore <backup name> --yes
# docker compose -f docker-compose.yml -f docker-compose.supabase.yml start backend
# Opt in to the console's restore instead: set BACKEND_MIGRATION_DATABASE_URL in .env to the
# migrator URL. The running backend then holds credentials that can rewrite the audit log
# and delete conflict checks — the very thing the runtime role is built not to have.
MIGRATION_DATABASE_URL: ${BACKEND_MIGRATION_DATABASE_URL:-}
volumes:
- *supabase_ca
+4 -4
View File
@@ -71,11 +71,11 @@ If you intend to sell a hosted product, the licence of whatever you fork determi
| Project | Licence | Stack | Verdict for a legal CRM |
|---|---|---|---|
| **Atomic CRM** (marmelab) | **MIT** | React, shadcn/ui, react-admin, Supabase/PostgreSQL | **Strongest starting point.** ~15k LOC — small enough to read in a weekend and bend into a matter-centric model. Built by the react-admin authors as a reference implementation, so it's a *template*, not a product you fight. Ships SSO/SAML free, good mobile UI, MCP server for AI. Weak on built-in features (no email/calendar sync, no workflow engine) — but you were going to rewrite those for legal anyway. |
| **Atomic CRM** (marmelab) | **MIT** | React, shadcn/ui, react-admin, a hosted Postgres BaaS | **Strongest starting point.** ~15k LOC — small enough to read in a weekend and bend into a matter-centric model. Built by the react-admin authors as a reference implementation, so it's a *template*, not a product you fight. Ships SSO/SAML free, good mobile UI, MCP server for AI. Weak on built-in features (no email/calendar sync, no workflow engine) — but you were going to rewrite those for legal anyway. |
| **Krayin CRM** | **MIT** | PHP 8, Laravel, Vue.js, MySQL | The right answer **only if your team is a Laravel shop**. Genuinely MIT, decent docs, marketing automation included. Independent benchmarks call the UI "clunky and slow" with poor mobile — you'd be paying a UI-rewrite tax immediately. |
| **Corteza** | **Apache-2.0** | Go backend, Vue frontend, PostgreSQL | The low-code play: model entities, ACLs and workflows through configuration rather than code. Apache-2.0 with an explicit patent grant. Attractive if you expect every firm to want a slightly different matter schema. Cost: you inherit someone else's abstraction layer, and the developer community is small. Actively maintained as of mid-2026. |
| **iDURAR / BottleCRM** | MIT | MERN / various | Small MIT CRM starters. Useful to read for ideas; too thin to be a foundation for a regulated vertical. |
| **react-admin + Shadcn Admin Kit** | **MIT** | React/TS | The "no CRM at all" option — a mature CRUD/admin framework, and the substrate Atomic CRM sits on. Combine with PostgreSQL + PostgREST/Supabase. |
| **react-admin + Shadcn Admin Kit** | **MIT** | React/TS | The "no CRM at all" option — a mature CRUD/admin framework, and the substrate Atomic CRM sits on. Combine with PostgreSQL + PostgREST or a hosted Postgres BaaS. |
| **Laravel + Filament** | MIT | PHP | The PHP-world equivalent of the above. |
| **Django + Django REST Framework** | **BSD** | Python | Boring, permissive, excellent for register integrations and background jobs; pairs naturally with docassemble (below). |
@@ -105,7 +105,7 @@ Worth installing to steal UX ideas and data-model decisions — just don't build
| **Durable workflows / deadline engine** | **Temporal** (MIT) | permissive | Deadlines, reminder escalation, retrying government-API calls. (n8n is *not* open source; Windmill is AGPL.) |
| **Analytics / reporting** | **Apache Superset** (Apache-2.0) | permissive | Metabase and Grafana are AGPL. |
| **Database** | **PostgreSQL** (PostgreSQL licence) + `pgaudit` | permissive | Row-level security is the natural implementation of ethical walls. |
| **BaaS layer (optional)** | **Supabase** (Apache-2.0) | permissive | Self-hostable; what Atomic CRM assumes. Gives auth + RLS + storage + realtime out of the box. |
| **BaaS layer (optional)** | a self-hostable Postgres BaaS (Apache-2.0) | permissive | What Atomic CRM assumes. Gives auth + RLS + storage + realtime out of the box. |
### 2.5 Commercial products to benchmark (not to copy code from)
@@ -207,7 +207,7 @@ An international product cannot ship these quickly. This is where a local produc
**Recommended stack:**
- **PostgreSQL** (row-level security = ethical walls) + **Apache-2.0 Supabase** or plain PostgREST/FastAPI.
- **PostgreSQL** (row-level security = ethical walls) + an **Apache-2.0 Postgres BaaS** or plain PostgREST/FastAPI.
- **react-admin / Shadcn Admin Kit** (MIT) for the CRUD surface, using **Atomic CRM (MIT)** as the skeleton you cannibalise — it is ~15k LOC, MIT, and already wires auth, storage and a decent mobile UI.
- **docassemble (MIT)** as a separate service for document assembly.
- **Temporal (MIT)** for the deadline/reminder engine and for retrying flaky government APIs.