Files
Workflow/backend/scripts/deploy_check.py
T
adminandClaude Opus 5.5 962dde69a4
CI / backend (16) (push) Successful in 1m47s
CI / backend (17) (push) Successful in 1m43s
CI / managed-db (push) Successful in 1m47s
CI / compose-smoke (push) Successful in 1m33s
Fetch private dredd-core from the Haski Gitea, not GitHub
The Dockerfiles still rewrote credentials for github.com only, so the build
token never reached Gitea and installs worked only while dredd-core was
public. Rewrite http://77.216.148.202:3000/ instead, give every workflow
that pip-installs the same rewrite (org secret DREDD_CORE_TOKEN, the
read-only haski-reader token), and drop the GitHub PAT leftovers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:18:45 +01:00

335 lines
20 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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
reverse-proxy service creeping back in. 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 [--env PATH]
`--env` names the settings file to check (default: the repository's `.env`). When its DATABASE_URL
points anywhere but the compose `postgres` service, this machine or a DB_LOCAL_HOSTS entry, the
database is external — the family's shared managed database — and both URLs are checked for what that
needs: verify-full TLS (against the mounted CA, or the system trust store), exactly this app's own
roles (workflow_app / workflow_migrator: no platform-admin user, no sibling app's role), a
pooler's session mode rather than its transaction-mode port 6543, distinct migrator and runtime roles,
DB_APP_ROLE naming the runtime role, and a bounded pool.
"""
from __future__ import annotations
import argparse
import pathlib
import re
import sys
from urllib.parse import parse_qs, unquote
ROOT = pathlib.Path(__file__).resolve().parents[2]
_parser = argparse.ArgumentParser(description="Deployment pre-flight for the Workflow stack.")
_parser.add_argument("--env", type=pathlib.Path, default=ROOT / ".env",
help="the settings file to check (default: .env at the repository root)")
ENV_PATH: pathlib.Path = _parser.parse_args().env
problems: 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")
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",
"seed_demo", "login_max_attempts", "login_lockout_minutes",
"session_ttl_hours", "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: workflow-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(':-8141}:8000"' in compose and "expose:" in compose,
"expected the backend published on :8141 (WORKFLOW_PORT) and postgres expose-only",
"only the backend is published; postgres is expose-only")
# No reverse proxy: the backend is its own edge (app/edge.py). A proxy service or config file coming
# back would mean two places deciding headers and routing again.
check("caddy" not in compose.lower() and not (ROOT / "Caddyfile").exists(),
"a reverse-proxy service or Caddyfile is back — the backend is its own edge (app/edge.py)",
"no reverse proxy: the backend is the edge")
check(compose.count("frontend: ./frontend") >= 2,
"compose does not pass the console to every build as the `frontend` build context",
"every build gets the console as the `frontend` build context")
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("/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:-127.0.0.1" in dockerfile and "FORWARDED_ALLOW_IPS=*" not in env_example,
"uvicorn must trust X-Forwarded-For only from 127.0.0.1 by default, never `*`",
"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 image can install the private core ────────────────────────────────────
requirements = read("backend/requirements.txt")
if "dredd-core @ git+" in requirements:
# Not `"git" in dockerfile` — the secret-mount RUN names git in its URL rewrite, so that could never fail.
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
installs_git = re.search(r"\b(?:apt-get|apt|apk)\b[^&;|\n]*?(?<![\w-])(?:install|add)(?![\w-])"
r"[^&;|\n]*(?<![\w-])git(?![\w-])", run_text)
check("--mount=type=secret,id=dredd_core_token" in dockerfile and bool(installs_git),
"requirements pin private dredd-core, but the Dockerfile has no git + BuildKit token secret "
"— `docker compose build` cannot fetch it",
"Dockerfile installs private dredd-core via git + a BuildKit secret")
check(compose.count("dredd_core_token") >= 3,
"compose does not pass the dredd_core_token build secret to every service that builds",
"compose passes the dredd_core_token build secret")
if ENV_PATH.exists() and "DREDD_CORE_TOKEN" in ENV_PATH.read_text(encoding="utf-8"):
problems.append("DREDD_CORE_TOKEN is in .env — every container loads .env at runtime; "
"export it in the shell for `docker compose build` instead")
# ── the backend's own edge is wired as documented ─────────────────────────────
edge_py = read("backend/app/edge.py")
check(bool(re.search(r'API_PREFIX = "([^"]+)"', main_py)), "cannot find API_PREFIX in main.py")
check("app.add_middleware(SecurityHeaders" in main_py,
"main.py does not add the edge's SecurityHeaders middleware",
"SecurityHeaders stamps every response")
check("ConsoleUnlessApi(SpaStaticFiles(" in main_py,
"the console is not mounted behind ConsoleUnlessApi with the SPA fallback",
"console mounted behind ConsoleUnlessApi, with the SPA fallback (deep links survive a reload)")
for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy"):
check(header in edge_py, f"app/edge.py does not set {header}")
check("--no-server-header" in dockerfile, "uvicorn announces itself (no --no-server-header)",
"uvicorn runs with --no-server-header")
# ── secrets and least privilege ───────────────────────────────────────────────
check("app" in roles_sh and "migrator" in roles_sh,
"db/init does not create both roles")
grants_revision = read("backend/alembic/versions/0002_runtime_grants.py")
models_init = read("backend/app/models/__init__.py")
check("runtime_grants_sql(get_settings().db_app_role" in grants_revision
and bool(re.search(r'^APPEND_ONLY_TABLES\b[^=\n]*=\s*\([^)]*"audit_log"', models_init, re.M)),
"the runtime-grants migration no longer makes audit_log append-only for DB_APP_ROLE "
"(0002_runtime_grants.py / APPEND_ONLY_TABLES in app/models/__init__.py)",
"audit_log is append-only for the runtime role DB_APP_ROLE names (0002_runtime_grants)")
check("change_me" in env_example,
".env.example should ship obvious placeholder passwords")
if ENV_PATH.exists():
real = ENV_PATH.read_text(encoding="utf-8")
if "change_me" in real:
problems.append(".env still contains a change_me placeholder password")
if real.startswith(""):
problems.append(".env has a UTF-8 BOM — pydantic folds it into the first key name")
else:
notes.append(".env present, BOM-free")
# ── the shared managed database: provisioning and the compose override ────────
provision_sql = read("db/managed/provision.sql")
check("--schema workflow --app-role workflow_app --migrator-role workflow_migrator"
in provision_sql,
"db/managed/provision.sql is not dredd-core's rendering for schema workflow "
"(re-render it: see db/managed/README.md)",
"db/managed/provision.sql provisions schema workflow (CI checks it is current)")
override = read("docker-compose.managed-db.yml")
CA_TARGET = "/run/certs/db-ca.crt"
# The platform admin at a provider, and its stand-in in dredd-core's emulation.
PLATFORM_ROLES = ("postgres", "postgres_managed")
#: Workflow's roles in the shared database (db/managed/README.md), the names provision.sql is rendered for.
SHARED_ROLES = {"DATABASE_URL": "workflow_app", "MIGRATION_DATABASE_URL": "workflow_migrator"}
def service_block(name: str) -> str:
"""The indented body of one top-level service in the override ("" when absent)."""
found = re.search(rf"(?ms)^ {name}:\n(.*?)(?=^ \S|^\S|\Z)", override)
return found.group(1) if found else ""
check("profiles:" in service_block("postgres"),
"docker-compose.managed-db.yml does not switch the local postgres service off (profiles)",
"the managed-db override switches the local postgres off")
check("depends_on: !reset" in service_block("migrate"),
"docker-compose.managed-db.yml still makes migrate wait for the local postgres",
"the managed-db override stops migrate waiting for the local postgres")
check(f"target: {CA_TARGET}" in override and "create_host_path: false" in override,
f"docker-compose.managed-db.yml does not mount the provider's CA at {CA_TARGET}",
f"the managed-db override mounts the provider's CA at {CA_TARGET}")
check('MIGRATION_DATABASE_URL: ""' in service_block("backend"),
"docker-compose.managed-db.yml leaves the migrator's URL in the long-running backend",
"the managed-db override keeps migrator credentials out of the backend")
def env_settings(text: str) -> dict[str, str]:
"""KEY=VALUE lines of a compose env file (comments and blank lines skipped, outer quotes removed)."""
values = {}
for line in text.lstrip("\ufeff").splitlines():
if "=" not in line or line.lstrip().startswith("#"):
continue
key, value = line.split("=", 1)
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
value = value[1:-1]
values[key.strip().upper()] = value
return values
def db_url(name: str, value: str) -> dict | None:
"""User, host, port and query of a database URL — or None, after recording why it is unusable."""
match = re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://(?P<authority>[^/?#]*)(?P<tail>.*)$", value)
if not match:
problems.append(f"{name} is not a database URL")
return None
authority, tail = match.group("authority"), match.group("tail")
userinfo, _, hostport = authority.rpartition("@")
user, _, password = userinfo.partition(":")
# An unencoded @ : / ? # (or a stray %) in a password splits or decodes the URL wrongly.
if ("@" in userinfo or ":" in password or re.search(r"%(?![0-9A-Fa-f]{2})", userinfo)
or "@" in tail.split("?", 1)[0] or (tail[:1] in ("?", "#") and "@" in tail)):
problems.append(f"{name}: percent-encode the password "
"(@ as %40, : as %3A, / as %2F, ? as %3F, # as %23, % as %25)")
return None
host, _, port = hostport.rpartition(":") if re.search(r":[^\]]*$", hostport) else (hostport, "", "")
if port and not port.isdigit():
problems.append(f"{name}: the port is not a number (an unencoded character in the password?)")
return None
query = tail.split("?", 1)[1].split("#", 1)[0] if "?" in tail else ""
return {"user": unquote(user), "host": host.lower(), "port": int(port) if port else 5432,
"query": parse_qs(query), "raw": value}
settings = env_settings(ENV_PATH.read_text(encoding="utf-8")) if ENV_PATH.exists() else {}
runtime = db_url("DATABASE_URL", settings["DATABASE_URL"]) if settings.get("DATABASE_URL") else None
# The family's TLS rule (dredd_core.db.require_verified_tls, applied by config.py): the compose
# postgres service, this machine, or a DB_LOCAL_HOSTS entry is local; every other host is external.
LOCAL_HOSTS = {"postgres", "localhost", "127.0.0.1", "[::1]", "::1", ""}
LOCAL_HOSTS |= {h.strip().lower().strip("[]") for h in settings.get("DB_LOCAL_HOSTS", "").split(",")}
if runtime and runtime["host"].strip("[]") not in LOCAL_HOSTS:
notes.append(f"DATABASE_URL points at an external database ({runtime['host']}): "
"managed-database checks (db/managed/README.md)")
migration = None
if settings.get("MIGRATION_DATABASE_URL"):
migration = db_url("MIGRATION_DATABASE_URL", settings["MIGRATION_DATABASE_URL"])
else:
problems.append("MIGRATION_DATABASE_URL is not set: the migrate service runs alembic as the migrator")
roles = {}
names_ca = False
for name, url in (("DATABASE_URL", runtime), ("MIGRATION_DATABASE_URL", migration)):
if not url:
continue
role = url["user"].split(".", 1)[0]
roles[name] = role
check(not re.search(r"<[^>]*>", url["raw"]), f"{name} still contains a <placeholder>")
modes = url["query"].get("sslmode", [])
check(modes == ["verify-full"],
f"{name} must set sslmode=verify-full (it has {', '.join(modes) or 'no sslmode'}): anything "
"weaker does not check who answers, and without it pg8000 falls back to plaintext",
f"{name} verifies TLS (sslmode=verify-full)")
# verify-full without sslrootcert verifies against the system trust store (a server certificate
# that chains to a public CA); with it, the file must be where the override mounts the CA.
root_certs = url["query"].get("sslrootcert", [])
names_ca = names_ca or bool(root_certs)
check(not root_certs or root_certs == [CA_TARGET],
f"{name} must set sslrootcert={CA_TARGET}, where docker-compose.managed-db.yml mounts the "
"CA (or leave it out to verify against the system trust store)",
f"{name} verifies the server against "
f"{'the mounted provider CA' if root_certs else 'the system trust store'}")
check(role not in PLATFORM_ROLES and role != "",
f"{name} logs in as {role or 'no user'}: never the platform admin — use Workflow's "
"own roles (workflow_app / workflow_migrator)",
f"{name} does not log in as the platform admin ({role})")
check(role == SHARED_ROLES[name],
f"{name} logs in as {role or 'no user'}, but Workflow's role there is {SHARED_ROLES[name]}: "
"role names are cluster-wide in the shared database, and the runtime-grants migration grants "
"whichever role it is given, so another app's role would carry privileges between schemas",
f"{name} logs in as Workflow's own role ({role})")
check(url["port"] != 6543,
f"{name} uses port 6543, a pooler's transaction mode: use session mode (5432)",
f"{name} avoids a transaction-mode pooler port (port {url['port']})")
if "pooler" in url["host"] and "." not in url["user"]:
notes.append(f"{name} logs in through a pooler as plain {role}: some poolers require the "
"tenant in the user name (<role>.<tenant>) — check the provider's connection details")
if len(roles) == 2:
check(roles["DATABASE_URL"] != roles["MIGRATION_DATABASE_URL"],
f"DATABASE_URL and MIGRATION_DATABASE_URL both log in as {roles['DATABASE_URL']}: "
"the runtime role must not be the migrator",
"the runtime and migrator roles differ")
if names_ca:
ca_file = settings.get("MANAGED_DB_CA_FILE") or "./certs/db-ca.crt"
ca_path = pathlib.Path(ca_file) if pathlib.Path(ca_file).is_absolute() else ROOT / ca_file
check(ca_path.is_file(),
f"the provider's CA file {ca_file} (MANAGED_DB_CA_FILE) does not exist, and the override "
"mounts it",
"the provider's CA file exists")
pool = {knob: settings.get(knob, default) for knob, default in
(("DB_POOL_SIZE", "5"), ("DB_MAX_OVERFLOW", "10"))}
bounded = (all(re.fullmatch(r"[0-9]+", value) for value in pool.values())
and int(pool["DB_POOL_SIZE"]) >= 1)
check(bounded,
f"DB_POOL_SIZE must be a whole number of at least 1 and DB_MAX_OVERFLOW one of at least 0 "
f"(got {pool}): SQLAlchemy reads DB_POOL_SIZE=0 or DB_MAX_OVERFLOW=-1 as no limit at all",
f"the backend pool takes at most {sum(int(v) for v in pool.values()) if bounded else '?'} "
"connections of the shared database's limit")
if runtime:
app_role = settings.get("DB_APP_ROLE") or "app"
runtime_role = runtime["user"].split(".", 1)[0]
check(app_role == runtime_role,
f"DB_APP_ROLE is {app_role}, but DATABASE_URL logs in as {runtime_role}: the runtime-grants "
"migration would grant the wrong role, or fail",
f"DB_APP_ROLE matches the role DATABASE_URL logs in as ({app_role})")
# ── report ────────────────────────────────────────────────────────────────────
for note in notes:
print(f" ok {note}")
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.")