Files
Sygna/backend/scripts/deploy_check.py
T
adminandClaude Opus 5.5 aac6b1e11a Be our own edge: headers and the console from the backend, no Caddy
The platform is dropping Caddy (Atrium's backend becomes the front door and
forwards /sygna/* with the prefix stripped), and the standalone stack drops
it too, so the backend now answers for everything Caddy added.

- app/edge.py: SecurityHeaders, pure ASGI and outermost, sets the full
  set on every response, errors included: nosniff, Referrer-Policy
  same-origin (the family's value), COOP same-origin, X-Frame-Options DENY
  or SAMEORIGIN, and on the console Caddy's CSP (frame-ancestors from
  FRAME_ANCESTORS) plus no-cache. The CSP stays console-only, as Caddy had
  it: on the API it would break the Swagger UI at /api/v1/docs.
- FRAME_ANCESTORS is 'none' (default) or 'self'; anything else refuses to
  start.
- SpaStaticFiles is try_files {path} /index.html; ConsoleUnlessApi keeps
  everything under /api and /healthz off the console (404 or 405 with
  Allow), comparing route paths.
- BodySizeLimit caps a request at 100 MB; GZipMiddleware; /healthz answers
  HEAD too.
- Dockerfile: frontend as a named build context; uvicorn with
  --proxy-headers, --forwarded-allow-ips and --no-server-header.
- Standalone compose publishes the backend on :80; Caddyfile deleted;
  deploy_check and compose-smoke check the new shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:07:14 +02:00

418 lines
24 KiB
Python

"""Pre-flight for a deployment: does the stack definition actually hold together?
The failures this catches are the boring ones that cost an evening — a setting the code reads
but `.env.example` never mentions, a healthcheck pointing at a route that no longer exists, a
console mount that would swallow the API. None of them show up in the test suite, because the
test suite never reads docker-compose.yml.
Run it before shipping: python scripts/deploy_check.py
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
A `.env` at the repository root is checked the same way whenever it points at a database other
than the local compose/loopback one.
"""
from __future__ import annotations
import argparse
import pathlib
import re
import sys
from urllib.parse import parse_qs, unquote, urlsplit
ROOT = pathlib.Path(__file__).resolve().parents[2]
BACKEND = ROOT / "backend"
problems: list[str] = []
warnings: list[str] = []
notes: list[str] = []
def check(condition: bool, failure: str, ok: str | None = None) -> None:
if condition:
if ok:
notes.append(ok)
else:
problems.append(failure)
def read(rel: str) -> str:
path = ROOT / rel
if not path.exists():
problems.append(f"missing file: {rel}")
return ""
return path.read_text(encoding="utf-8")
compose = read("docker-compose.yml")
dockerfile = read("backend/Dockerfile")
edge_py = read("backend/app/edge.py")
env_example = read(".env.example")
config_py = read("backend/app/config.py")
main_py = read("backend/app/main.py")
roles_sh = read("db/init/01-roles.sh")
# ── every Settings field is documented in .env.example ────────────────────────
# A field the code reads but nobody knows to set is a deploy that comes up misconfigured and
# silently wrong, which is worse than one that fails to start.
fields = set(re.findall(r"^ ([a-z][a-z0-9_]*): ", config_py, re.M))
documented = {line.split("=", 1)[0].strip().lower()
for line in env_example.splitlines()
if "=" in line and not line.strip().startswith("#")}
# Fields with a sensible default that a deployment rarely overrides.
OPTIONAL = {"app_base_url", "otel_service_name", "otel_exporter_otlp_endpoint",
"galena_timeout_seconds", "reminder_interval_hours", "seed_demo",
"login_max_attempts", "login_lockout_minutes", "session_ttl_hours",
"galena_casefile_parent_id", "galena_console_url", "cors_allow_origins"}
undocumented = sorted(fields - documented - OPTIONAL)
check(not undocumented,
f"settings read by config.py but absent from .env.example: {undocumented}",
f"all {len(fields)} settings either documented or deliberately defaulted")
# ── compose wiring ────────────────────────────────────────────────────────────
check("env_file: .env" in compose,
"compose services do not load .env", "compose loads .env")
check(compose.count("image: sygna-backend:local") >= 2,
"migrate and backend should share one built image",
"migrate and backend share one image (no double build)")
check("condition: service_completed_successfully" in compose,
"backend does not wait for migrate to finish",
"backend waits for migrations to complete")
check("condition: service_healthy" in compose,
"nothing waits on the postgres healthcheck",
"migrate waits for a healthy postgres")
check('ports: ["80:8000"]' in compose and compose.count("ports:") == 1,
"expected only the backend published (80:8000) and postgres expose-only",
"only the backend is published; postgres is expose-only")
check("caddy" not in compose.lower() and not (ROOT / "Caddyfile").exists(),
"a Caddy service or Caddyfile is back — the backend is its own edge (app/edge.py)",
"no reverse proxy in the stack; the backend is its own edge")
check(compose.count("frontend: ./frontend") >= 2 and "COPY --from=frontend" in dockerfile,
"the console is not built into the image (additional_contexts + COPY --from=frontend)",
"the console is baked into the image from the frontend build context")
check("exec uvicorn" not in compose and "--no-server-header" in dockerfile
and "--proxy-headers" in dockerfile,
"uvicorn's edge flags (--proxy-headers, --no-server-header) are missing from the Dockerfile CMD",
"uvicorn runs with --proxy-headers and --no-server-header (Dockerfile CMD only)")
check("/docker-entrypoint-initdb.d" in compose,
"db/init is not mounted, so the least-privilege roles are never created",
"db/init mounted — app + migrator roles created on first start")
# ── the Dockerfile matches reality ────────────────────────────────────────────
health_path = re.search(r"urlopen\('([^']+)'\)", dockerfile)
check(bool(health_path), "Dockerfile healthcheck has no URL")
if health_path:
route = health_path.group(1).split("localhost:8000", 1)[-1]
check(f'"{route.replace("/api/v1", "")}"' in read("backend/app/routers/health.py")
or "/health" in route,
f"healthcheck hits {route} but no such route is registered",
f"healthcheck target {route} matches a registered route")
check("FORWARDED_ALLOW_IPS" in dockerfile,
"uvicorn not told which proxy to trust for X-Forwarded-For",
"forwarded-for handling pinned (audit-log IPs cannot be spoofed)")
check("USER app" in dockerfile, "container runs as root",
"container drops to a non-root user")
# The private dependency's credential. The tempting fix for a failing build is `ARG
# DREDD_CORE_TOKEN`, and it works — and it bakes the token into the image history, where
# `docker history` prints it for anyone who can pull the image. It has to be a secret mount.
check("--mount=type=secret,id=dredd_core_token" in dockerfile,
"the Dockerfile does not take DREDD_CORE_TOKEN as a BuildKit secret",
"the dredd-core credential is a build secret, never a layer")
check("ARG DREDD_CORE_TOKEN" not in dockerfile and "ENV DREDD_CORE_TOKEN" not in dockerfile,
"DREDD_CORE_TOKEN is an ARG or ENV — it would be readable in any pushed image's history")
check("dredd_core_token" in compose and "environment: DREDD_CORE_TOKEN" in compose,
"compose does not pass DREDD_CORE_TOKEN to the build as a secret")
# ── the backend's own edge matches what Caddy did ─────────────────────────────
prefix = re.search(r'API_PREFIX = "([^"]+)"', main_py)
check(bool(prefix), "cannot find API_PREFIX in main.py")
if prefix:
check(prefix.group(1).startswith("/api"),
f"API_PREFIX {prefix.group(1)} is outside /api, so ConsoleUnlessApi would not guard it",
f"{prefix.group(1)} is guarded from the console by ConsoleUnlessApi")
check("ConsoleUnlessApi(SpaStaticFiles(" in main_py,
"the console is not mounted behind ConsoleUnlessApi with the SPA fallback",
"SPA fallback present (deep links survive a reload); the API never falls to the console")
check("app.add_middleware(SecurityHeaders" in main_py and "GZipMiddleware" in main_py
and "app.add_middleware(BodySizeLimit)" in main_py,
"main.py does not install SecurityHeaders / GZip / BodySizeLimit")
for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy",
"Referrer-Policy", "Cross-Origin-Opener-Policy", "Cache-Control"):
check(header in edge_py, f"app/edge.py does not set {header}")
notes.append("the backend sets nosniff / frame / CSP / referrer / COOP headers itself")
# ── secrets and least privilege ───────────────────────────────────────────────
check("app" in roles_sh and "migrator" in roles_sh,
"db/init does not create both roles")
grants_rev = read("backend/alembic/versions/0002_runtime_grants.py")
check("runtime_grants_sql(get_settings().db_app_role" in grants_rev
and 'APPEND_ONLY = ("audit_log",)' in grants_rev,
"the runtime-grants migration no longer makes audit_log append-only for DB_APP_ROLE",
"audit_log is append-only for the runtime role (0002, DB_APP_ROLE)")
check('NO_DELETE = ("conflict_check", "aml_assessment")' in grants_rev,
"the runtime-grants migration no longer protects conflict_check and aml_assessment",
"conflict_check and aml_assessment can never be deleted by the runtime role")
check("change_me" in env_example,
".env.example should ship obvious placeholder passwords")
# ── the shared substrate is a pinned package, not a copy ─────────────────────
# The one thing that must never quietly become an editable install: `pip install -e ../dredd-core`
# shadows the pin, and a local edit to core then changes this application's behaviour with nothing
# in the repository recording it — which is the drift SHARED.md existed to stop, returning by a
# side door.
requirements = read("backend/requirements.txt")
check("dredd-core @ git+" in requirements,
"dredd-core is not pinned to a git ref in requirements.txt",
"dredd-core is pinned to an immutable ref")
check("@v" in requirements.split("dredd-core @ git+")[1].split("\n")[0],
"dredd-core is pinned to a branch rather than a tag — core could change under a deploy")
check("DREDD_CORE_TOKEN" in read(".github/workflows/ci.yml"),
"CI cannot install dredd-core: the private repo needs DREDD_CORE_TOKEN",
"CI authenticates to the private dredd-core repo")
# SHARED.md quotes the pin. A quoted version that has fallen behind the real one is worse than no
# quote — it is documentation that reads as current and is wrong, which is how somebody ends up
# debugging against the wrong core. Found exactly that way: SHARED.md said v0.6.0 for a while
# after requirements.txt moved to v0.7.0.
_pin = requirements.split("dredd-core @ git+")[1].splitlines()[0].strip()
check(_pin in read("SHARED.md"),
f"SHARED.md quotes a different dredd-core pin than requirements.txt ({_pin})",
"SHARED.md quotes the pin that is actually installed")
# ── the Netlify front door stays honest ──────────────────────────────────────
# It publishes the console alone. The demo mock is what makes a backend-less deploy worth having,
# and prepare.sh injects it by filename — so a rename that the build cannot see would produce a
# console that loads and then cannot log in.
netlify_toml = read("netlify.toml")
prepare_sh = read("netlify/prepare.sh")
check('publish = "frontend"' in netlify_toml,
"netlify.toml no longer publishes frontend/",
"netlify publishes the console only")
check("demo.js" in prepare_sh and (ROOT / "frontend/demo.js").exists(),
"netlify/prepare.sh injects a demo mock that does not exist",
"the demo mock is present and injected when no backend is configured")
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 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"}
# 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.<tenant>` -> `sygna_app`."""
return user.split(".", 1)[0]
def _user(url: str) -> str:
try:
return unquote(urlsplit(url).username or "")
except ValueError:
return ""
def external_db_problems(env: dict[str, str], source: str, *, real: bool = True) -> list[str]:
"""What is wrong with `env`'s database settings for a managed database (empty = fine).
`real` = a file somebody deploys with, not the documented example: placeholders, unencoded
passwords and a missing CA file count there. Never includes a password: only keys, roles,
ports and sslmode appear in a message."""
found: list[str] = []
users: dict[str, str] = {}
if real:
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("MANAGED_DB_CA_FILE", "").strip() or "certs/db-ca.crt")
if not ca_file.is_file():
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 — 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 "
"substitutes $NAME in .env values, so percent-encode it as %24 "
"(urllib.parse.quote(password, safe=\"\"))")
for key in ("DATABASE_URL", "MIGRATION_DATABASE_URL"):
raw = env.get(key, "").strip()
if not raw:
found.append(f"{source}: {key} is empty")
continue
if real and (raw.split("://", 1)[-1].split("/", 1)[0].count("@") > 1 or "#" in raw
or re.search(r"%(?![0-9A-Fa-f]{2})", raw)):
found.append(f"{source}: {key} has an unencoded character in it (@ # or a bare %); "
"percent-encode the password")
continue
try:
parts = urlsplit(raw)
port = parts.port
except ValueError:
found.append(f"{source}: {key} is not a parseable URL (is the password URL-encoded?)")
continue
query = parse_qs(parts.query)
if query.get("sslmode") != ["verify-full"]:
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 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.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, 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 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 "
f"({_role(app_user)}); the runtime role must not be the migrator")
app_role = env.get("DB_APP_ROLE", "").strip() or "app"
if app_user and _role(app_user) != app_role:
found.append(f"{source}: DB_APP_ROLE is {app_role} but DATABASE_URL logs in as "
f"{_role(app_user)}; the grants migration would grant the wrong role")
return found
def parse_env(text: str, *, commented: bool = False) -> dict[str, str]:
"""KEY=value lines; with `commented`, only `# KEY=value` lines (the documented example)."""
out: dict[str, str] = {}
for line in text.splitlines():
line = line.strip()
if commented:
if not re.match(r"^# [A-Z][A-Z0-9_]*=", line):
continue
line = line[2:]
elif line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
out[key.strip()] = value.strip()
return out
def is_external(env: dict[str, str]) -> bool:
try:
return (urlsplit(env.get("DATABASE_URL", "")).hostname or "") not in LOCAL_HOSTS
except ValueError:
return True
cli = argparse.ArgumentParser(description="Deployment pre-flight for Sygna.")
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 = "# ── 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 managed-PostgreSQL example block")
if example:
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 managed-PostgreSQL example does not use sygna_app / sygna_migrator")
if not bad:
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():
env_files.append(ROOT / ".env")
for env_path in env_files:
if not env_path.exists():
problems.append(f"--env {env_path}: no such file")
continue
real = parse_env(env_path.read_text(encoding="utf-8-sig"))
if not args.env and not is_external(real):
notes.append(f"{env_path.name} points at a local database; managed-database checks skipped")
continue
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, not 6543, "
"sygna_ roles, DB_APP_ROLE matches)")
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 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:", 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/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/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/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:
print(f" FAIL {problem}")
print(f"\n{len(problems)} problem(s) — this deployment would not behave as documented.")
sys.exit(1)
print(f"\nDeploy check passed — {len(notes)} checks, no problems.")