explanation deployersecurity-reviewer

Deployment Architecture (per-country, self-hosted)

Status: living reference (engineer-facing). Last updated 2026-06-08. Design records (rationale, point-in-time): docs/specs/2026-06-07-per-country-deployment-automation.md, docs/specs/2026-06-07-host-based-spa-serving-design.md. Operator steps: docs/runbooks/provision-deployment.md.

OpenGov runs one isolated instance per country deployment (a country × project, keyed by code, e.g. let-cob). Each instance is a self-hosted Docker-Compose stack. This doc explains how a deployment is described, boots itself, gets routed, and is onboarded.


1. A deployment is a committed git artifact

Everything country-specific lives in deployments/<code>/, committed to the repo (so it ships inside the image and there is one source of truth):

deployments/<code>/
├── config.yaml      # identity + wildcard_base + Coolify target (non-secret)
└── secrets.env      # SOPS+age encrypted (POSTGRES_PASSWORD, OIDC client secret, KEK, …)

config.yaml (src/opengov/platform/deployments/artifact.py → DeploymentArtifact):

FieldPurpose
code, country_iso2, project_slug, display_name, timezone, default_locale, supported_locales, statusIdentity — byte-identical to the deployments registry row
wildcard_basee.g. services.example.gov. Every component host derives from this
coolify.{project_uuid,server_uuid,github_app_uuid,git_repository,git_branch,compose_service_name}Coolify deployment coordinates

Derivation (fixed platform convention). From wildcard_base, the artifact derives the five component hosts, the login host, the assistants door host and all OIDC env — there is no per-host hand-wiring:

SubdomainServesKC clientOPENGOV_*_URL
smartrules.<base>SmartRules editor SPAopengov-editorOPENGOV_EDITOR_URL
approval.<base>eApproval SPAopengov-approvalOPENGOV_APPROVAL_URL
applicant.<base>eRnext portal SPAopengov-portalOPENGOV_PORTAL_URL
smartlink.<base>SmartLink admin SPAopengov-smartlink-adminOPENGOV_SMARTLINK_URL
studio.<base>Registers Studio SPAopengov-studioOPENGOV_STUDIO_URL
login.<base>Keycloak (oidc service)—OPENGOV_OIDC_ISSUER / OIDC_HOSTNAME
mcp.<base>The assistants door (/mcp) — no SPAopengov-mcp (loopback PKCE)OPENGOV_MCP_PUBLIC_URL

The component label → SPA map is enforced to match spa_router.HOST_SPA by a test, so the artifact, the app host-router, and the Keycloak redirect URIs cannot drift.

Secrets are SOPS-encrypted with age (no cloud KMS → air-gap-safe; .sops.yaml). They split into two tiers: Coolify-tier (pushed to Coolify) and KEK-tier (OPENGOV_ENCRYPTION_KEY, OPENGOV_ANON_HASH_SALT, OPENGOV_VAULT_KEK_V*) which are never sent to Coolify — the operator injects them out-of-band, mirroring backup.sh’s “DB dump and KEK never in the same place” design. A pre-commit guard refuses to commit a plaintext secrets.env or any *.agekey.


2. The compose stack self-bootstraps at boot

docker-compose.yml services:

postgres → { opengov, worker }        each waits for the database, then one of
                                      them migrates while the other waits
oidc (Keycloak) → init-keycloak       blocks nobody
  • Each service that needs a migrated schema boots itself (opengov.entrypoint, in front of the real command): wait until Postgres accepts a connection → take a Postgres advisory lock, a lock held in the database itself so exactly one container proceeds → run python -m alembic upgrade heads → apply the Procrastinate schema (not in the Alembic migrations; see dev.sh) → seed this deployment’s registry row from its committed artifact (keyed by OPENGOV_DEPLOYMENT_CODE) → release the lock → become uvicorn (or the worker). Every step is idempotent, so the container that waits finds the work done.
  • This fixes three things that otherwise made a fresh prod stack un-bootable:
    1. the main.py sys.exit(78) deadlock (no deployments row → fail-loud boot, PR #237),
    2. no migrations ever ran in the bare prod compose,
    3. opengov+worker racing to create the schema.
  • Why not a separate one-shot container? It was one until 2026-08-11 (an init service the app waited on via depends_on). Docker Swarm discards depends_on entirely, so “wait for that one to finish” is an instruction it cannot follow — and D47 moves the sandbox to Swarm. The lock expresses the same guarantee without needing an orchestrator to order anything, and behaves identically under plain Compose, which is where it runs first. Spec: docs/specs/2026-08-10-docker-swarm-default-deployment.md §4.2.
  • First admin login (opt-in). The realm imports with zero users, so init-keycloak seeds a first Keycloak login when OPENGOV_SEED_ADMIN_PASSWORD is set — creating OPENGOV_SEED_ADMIN_EMAIL (default admin@opengov.local) with OPENGOV_SEED_ADMIN_ROLES (default admin). It is non-fatal (a KC error is logged, never blocks boot — only the registry-row seed is a hard gate) and idempotent (KC-26 sequence: create → reset-password → assign roles). This is why init-keycloak depends_on oidc: service_healthy — and why it is a separate container: nothing waits for it, so it is free to be slow. Under Swarm, where depends_on is discarded, it waits for Keycloak itself (bootstrap_deployment._wait_for_keycloak, 120s bound).
  • oidc builds from keycloak/Dockerfile (FROM keycloak/keycloak:26.8) and copies the realm JSON into the image. A ./keycloak bind-mount does not survive a PaaS deploy because it resolves to the orchestrator’s app directory, not the repo. The image runs kc.sh build at build time and boots start --optimized --import-realm (production mode, strict hostname). The import still substitutes ${OPENGOV_*_URL} from runtime env, so each deployment receives its redirect URIs.
  • Rights administration (spec 2026-07-28-user-rights-admin). The rights API (/api/v1/platform/rights/*) logs into Keycloak as the opengov-rights-admin service-account client, configured on the opengov service via OPENGOV_KC_ADMIN_CLIENT_ID (default opengov-rights-admin) and OPENGOV_KC_ADMIN_CLIENT_SECRET (no default — when unset the rights routes answer 503 “not configured” in plain words, never a silent fallback). The client is created two ways, both idempotent: --import-realm on fresh deployments (secret substituted from the oidc service’s env), and init-keycloak’s realm reconcile on existing ones (secret substituted from that container’s env — keep all three services on the same value). The reconcile also wires the service account’s realm-management view-users + manage-users roles — no operator step in Keycloak is required. Secret rotation: set the new value on the Keycloak client’s Credentials tab (or delete the client and let the next init-keycloak run recreate it), then update the env on opengov and init-keycloak together.

No service publishes a host port. Containers expose internal ports only; a reverse proxy (Coolify’s Traefik, or a standalone proxy on a bare VPS) terminates TLS and routes the deployment’s domains to internal ports. Publishing fixed host ports collides on a shared/multi-tenant host and bypasses TLS termination (PR #252).

The login host refuses /admin to the internet. The admin console and the admin API of the login service are under /admin. An additive proxy route (scripts/render_login_admin_route.py) refuses them on login.<base> with 403. All other paths stay public, for example /realms/ and /resources/. The app and init-keycloak call the admin API at http://oidc:8080, so the route does not touch them.

Admins open the console through an SSH tunnel to http://localhost:18088. The provisioning env gives Keycloak this address as KC_HOSTNAME_ADMIN. The Credentials tab of the rights paragraph above is in this console too. Procedure: docs/runbooks/provision-deployment.md steps 8 and 9. Design note: docs/specs/2026-10-13-login-admin-console-not-public.md.

When the application container cannot answer, the proxy shows a designed page, not bare error text. The SPAs are served by the opengov container, so while it is down there is no application left to render a friendly message — the proxy has to. The page (deploy/error-page/unavailable.html, this country’s wordmark and emblem baked in) is served by a host systemd service (deploy/error-page/opengov-offline-page.service, installed by scripts/install-offline-page.sh, #2686) — deliberately OUTSIDE the application’s own compose stack, so a redeploy of the application does not tear the page down with it. scripts/render_offline_page.py renders the page and its Traefik dynamic-config route from the deployment’s own committed config.yaml; the installer copies the route to /data/coolify/proxy/dynamic/ (a host-side step, like the registry route, not part of the compose up) and proves the page answers before reporting success. The page reloads itself once /health answers again. Full procedure: docs/runbooks/offline-page.md.

The in-app errorpage compose service (the sentinel image serving the same static file) is kept running until the host service is confirmed serving on the sandbox, then removed — see the comment above it in docker-compose.yml.

Honest limit: if the container engine itself is down on the host, there is no proxy and no page — this design covers a redeploy or crash of the application, not the whole host going dark.

Boot invariants (fail-loud)

The opengov lifespan (src/opengov/main.py) refuses to boot on misconfig, in order:

  1. OIDC consistency — OPENGOV_OIDC_ISSUER + OPENGOV_OIDC_AUDIENCE must be set (auth-on).
  2. Deployment row — OPENGOV_DEPLOYMENT_CODE must resolve a deployments row (else exit 78).
  3. Timezone — ZoneInfo(timezone) must resolve → the runtime image bundles tzdata (the minimal Chainguard image ships none; PR #252).

3. Host-based SPA serving (one image, five SPAs, by Host)

The opengov container serves all five SPAs and /api. Which SPA is served is chosen by the request Host (src/opengov/platform/spa_router.py):

  • A middleware (after CORS, GET/HEAD only) maps the Host’s first label → that SPA’s static/<dir>.
  • Passthrough (never intercepted): /api, /health, /version, /config.json, /docs, /redoc, /openapi.json. (All backend routes live under these.) /metrics is deliberately NOT passthrough — the public app owns no such path at all; the measurements are served on a separate internal listener (§8), never routed here.
  • A known SPA host serves the requested file, else index.html (200) — this resolves client routes, /callback, and deep links. Path traversal is blocked.
  • Unknown host fails closed (404 + WARNING).
  • Installed only when a SPA build exists, so dev/test (no static/) are unaffected.

The SPAs are built with base = VITE_BASE ?? '/' and <BrowserRouter basename={import.meta.env.BASE_URL}>, so they serve at a subdomain root. static_root resolves from CWD (/app/static), not the package path (__file__ is /install/... in the image).

Runtime OIDC config — GET /config.json

The SPAs do not bake OIDC config at build time (that shipped the authoring SPAs auth-bypassed when the build var was missing, because AuthProvider treated a missing authority as dev mode). Instead:

  • The backend serves GET /config.json (public, no secrets) from its runtime OPENGOV_OIDC_* env, returning a per-Host client_id (smartrules. → opengov-editor, etc.).
  • AuthProvider fetches it before initializing OIDC and hard-fails on a missing/broken config — never the dev stub. redirect_uri auto-derives from window.location.origin/callback per subdomain.
  • Result: one image serves all 11 countries; the only per-deployment input is runtime env.

4. Onboarding a deployment (Coolify)

scripts/provision_country.py deployments/<code> (CLI over coolify_client.py + onboard.py):

  1. loads the artifact + sops-decrypts secrets.env (splitting KEK out);
  2. find-or-creates the dockercompose app from the artifact’s git_repository/git_branch;
  3. pushes the Coolify-tier env (deployment code + the five OPENGOV_*_URL + OIDC issuer/hostname, all derived from wildcard_base) — never the KEK tier;
  4. sets the Coolify domains: the five SPA hosts as one comma-separated value → the opengov service, and login.<base> → the oidc service (Coolify routes multiple FQDNs per service only via a comma-separated domain);
  5. deploys and waits for a terminal status.

Manual, browser-only (cannot be scripted): the Coolify API token, the GitHub App connection, and injecting the KEK-tier secrets out-of-band. See the runbook.

Coolify gotchas (learned the hard way)

  • Coolify caches the parsed compose at app-creation — a compose change needs the app recreated, not just redeployed.
  • docker_compose_domains set before the first deploy don’t persist (compose-parse nulls them) — set them after the first deploy, then redeploy.
  • The deploy branch must be pushed to origin (Coolify clones from GitHub).
  • docker pull keycloak/keycloak:26.8 pulls the official KC image from Docker Hub. The :26.8 tag floats to the latest patch. Pin :26.8.x@sha256:<digest> if reproducible KC builds matter.
  • Webhook auto-deploy is OFF for the sandbox (wave 5): the post-deploy-smoke workflow is the sole deploy owner (stamp SOURCE_COMMIT → /deploy → smoke, one build per merge). Rollback and the manual /deploy path: docs/runbooks/post-deploy-smoke.md §Deploy topology.
  • Coolify 4.1.2 compose builds never export SOURCE_COMMIT to the build env — the app env is the only channel (stamped by the workflow per above); the in-image gitsha stage is the fallback and stamps unknown when the PaaS checkout hides .git from the build.

5. Day-2 ops

  • Backups: scripts/backup.sh (pg_dump custom-format + the world-model volume + KC realm export; KEK kept out-of-band) / scripts/restore.sh. Scheduled by scripts/install-backup-timer.sh (systemd timer, nightly, verifies its own first run). Postgres holds nearly everything, including the Procrastinate queue — but not the generated migration files an approved model publish writes into the world-model folder, which is why that volume travels in the same bundle (issue #1788). Runbook: docs/runbooks/backup-restore.md.
  • Provisioning the host: scripts/vps_bootstrap.sh (idempotent).
  • TLS: the reverse proxy (Coolify/Traefik ACME, or step-ca for air-gap) — see the deployment- automation spec for the fleet/day-2 roadmap (Phases 2–4: fleet CD, object-storage backups, k3s).

6. Where things live

ConcernModule / file
Artifact schema + derivationsrc/opengov/platform/deployments/artifact.py
Registry upsert (seam)src/opengov/platform/deployments/service.py
Boot bootstrap (per-container)src/opengov/entrypoint.py, src/opengov/bootstrap_deployment.py
Host-based SPA routersrc/opengov/platform/spa_router.py
Runtime OIDC configGET /config.json in src/opengov/main.py
Coolify clientsrc/opengov/platform/deployments/coolify_client.py
Onboard orchestration + CLI…/deployments/provision.py, scripts/provision_country.py
Secrets tiering + guard…/deployments/secrets.py, scripts/check_secrets_encrypted.py, .sops.yaml
Compose + imagesdocker-compose.yml, Dockerfile, keycloak/Dockerfile
Frontend OIDCfrontend/shared/auth/AuthProvider.tsx; per-SPA vite.config.ts + main.tsx

PR trail: #237 (init self-seed) · #240 (worker async connector) · #245 (procrastinate schema) · #252 (drop host ports + tzdata) · #275 (host-based SPA serving + runtime OIDC + KC realm bake + wildcard_base wiring).


8. Reading a deployment’s own numbers (the metrics listener)

In plain words: the opengov app and the worker each open a small extra doorway, reachable only from inside the deployment’s own Docker network, where a country’s own monitoring can read the counts the platform already keeps. Full detail (per-target ownership, labels, the two traps): docs/reference/metrics-scrape-contract.md.

  • One listener per process, both on port 9100, both bound 0.0.0.0 inside their own container: src/opengov/platform/metrics_server.py::start_metrics_listener, called from main.py’s lifespan (component="app") and worker.py’s main() (component="worker"). Gated by OPENGOV_METRICS_ENABLED (default False; docker-compose.yml sets it true on both services).
  • The worker’s listener is not optional. Most of the interesting numbers — every queue-depth and payment-hold gauge — are counted in the worker, never the app. An app-only listener would answer with mostly zeros and hide exactly the backlog an operator needs at 3am.
  • Published nowhere, routed by nothing — two independent layers, both required:
    1. docker-compose.yml adds nothing to expose: for port 9100. Compose’s expose publishes no reachability by itself (any container on the network already reaches a listening port); what it WOULD do is make coolify_client.py’s docker_compose_domains (which carries no port) ambiguous about which port the four SPA hostnames route to. The wrong answer there is the exposition served on a public hostname.
    2. spa_router.py’s PASSTHROUGH_PREFIXES deliberately excludes /metrics (§3) — the public app has no such route at all, so there is nothing for a passthrough entry to route to, and a future accidental mount on a known SPA host still resolves to the SPA shell rather than the exposition (defence in depth).
  • No authentication on the listener. The exposure model rests entirely on the port being unreachable from outside the deployment’s network — read the scrape contract before trusting the 0.0.0.0 default in any topology where that assumption might not hold.
  • Reading it from a shell-less container (same idiom the healthcheck uses):
    docker compose exec worker python3 -c \
      "import urllib.request as u; print(u.urlopen('http://127.0.0.1:9100/metrics').read().decode())"
    
  • Single-uvicorn-worker is load-bearing. docker-compose.yml’s opengov command has no --workers flag, so exactly one process holds the one Prometheus registry behind port 9100. Adding --workers N would put N processes behind one port, scraping one arbitrary worker’s numbers.