CI / compose-smoke (push) Successful in 2m17s
CI / deploy-kit-tests (push) Successful in 2m55s
CI / backend (16) (push) Successful in 4m0s
CI / backend (17) (push) Successful in 3m59s
CI / managed-db (push) Successful in 3m55s
deploy kit / preflight (push) Successful in 1m27s
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>
333 lines
19 KiB
Python
333 lines
19 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, an
|
||
image that stops running the front door. 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 a local host (the compose `postgres` service, this machine, or a DB_LOCAL_HOSTS
|
||
entry), the database is external — a managed PostgreSQL provider, the family's shared database — and
|
||
the URLs are checked for what that needs: verify-full TLS against the mounted CA, Atrium's own roles
|
||
(atrium_app / atrium_migrator — never the platform admin, another app's roles or a generic app /
|
||
migrator), session mode rather than a transaction pooler's port 6543, the tenant suffix some poolers
|
||
need in the user name (<role>.<tenant> — a warning, because only the provider knows), and DB_APP_ROLE
|
||
naming the runtime role.
|
||
"""
|
||
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 Atrium 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] = []
|
||
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")
|
||
frontdoor_py = read("backend/app/frontdoor.py")
|
||
# The image's CMD is `python -m app.serve`, which builds the uvicorn command line (app/serve.py).
|
||
serve_py = read("backend/app/serve.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 = {"otel_service_name", "otel_exporter_otlp_endpoint",
|
||
"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: atrium-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")
|
||
# Any host port onto the backend's :8000, so moving the published port (two stacks, one host) passes.
|
||
# There is no Caddy: the backend is the edge, and postgres stays expose-only.
|
||
check(bool(re.search(r'"\d+:8000"', compose)) and "expose:" in compose
|
||
and not re.search(r'"\d+:5432"', compose),
|
||
"expected the backend published on :8000 and postgres expose-only",
|
||
"the backend is published (the edge); postgres is expose-only")
|
||
check("caddy" not in compose.lower().replace("no caddy", ""),
|
||
"docker-compose.yml still mentions a caddy service",
|
||
"no reverse proxy in front: the backend is the edge")
|
||
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")
|
||
# Either trust a named proxy, or - the front door, which IS the edge - trust no forwarded header.
|
||
check("FORWARDED_ALLOW_IPS" in dockerfile or "--no-proxy-headers" in serve_py,
|
||
"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 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 front door serves Atrium the way the platform does ───────────────────
|
||
check('"app.serve"' in dockerfile and '"app.frontdoor:outer"' in serve_py,
|
||
"the image does not run the front door (app.frontdoor:outer)",
|
||
"the image runs the front door")
|
||
check("app.main:app" not in compose,
|
||
"docker-compose.yml overrides the image's CMD with the bare app",
|
||
"no compose command override: the stack runs the image's CMD")
|
||
check('Mount(f"/{ATRIUM}"' in frontdoor_py and 'b"/atrium/"' in frontdoor_py,
|
||
"the front door no longer mounts Atrium at /atrium or redirects / there",
|
||
"Atrium is mounted at /atrium; / redirects there")
|
||
check("COPY --from=frontend" in dockerfile and "frontend: ./frontend" in compose,
|
||
"the console is not built into the image (COPY --from=frontend + additional_contexts)",
|
||
"the console ships in the image")
|
||
check('StaticFiles(directory=str(_FRONTEND), html=True)' in main_py,
|
||
"the backend no longer serves the console",
|
||
"the backend serves the console")
|
||
for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy"):
|
||
check(header in main_py, f"main.py does not set {header}")
|
||
notes.append("the backend sets nosniff / frame / CSP headers on the console itself")
|
||
|
||
# ── secrets and least privilege ───────────────────────────────────────────────
|
||
check("app" in roles_sh and "migrator" in roles_sh,
|
||
"db/init does not create both roles")
|
||
check("REVOKE UPDATE, DELETE ON audit_log" in read(
|
||
"backend/alembic/versions/0001_initial.py"),
|
||
"the migration no longer makes audit_log append-only",
|
||
"audit_log is append-only for the runtime role")
|
||
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")
|
||
|
||
# ── a managed PostgreSQL provider: the compose override ───────────────────────
|
||
override = read("docker-compose.managed-db.yml")
|
||
CA_TARGET = "/run/certs/db-ca.crt"
|
||
#: A managed provider's platform admin (`postgres`, not a superuser there) and the local emulation's.
|
||
PLATFORM_ROLES = ("postgres", "postgres_managed")
|
||
#: Atrium's roles in the shared database (db/managed/README.md) — the names provision.sql is rendered for.
|
||
SHARED_ROLES = {"DATABASE_URL": "atrium_app", "MIGRATION_DATABASE_URL": "atrium_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<rest>[^/?#]*)(?P<tail>.*)$", value)
|
||
if not match:
|
||
problems.append(f"{name} is not a database URL")
|
||
return None
|
||
authority, tail = match.group("rest"), 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().strip("[]"), "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 rule (dredd_core.db.is_local_host): the compose postgres service, this machine, or a
|
||
# host the deployment lists in DB_LOCAL_HOSTS — not external.
|
||
LOCAL_HOSTS = {"postgres", "localhost", "127.0.0.1", "::1", ""} | {
|
||
host.strip().lower().strip("[]") for host in settings.get("DB_LOCAL_HOSTS", "").split(",")}
|
||
if runtime and runtime["host"] not in LOCAL_HOSTS:
|
||
# The family's shared managed database (db/managed/README.md), or another external database.
|
||
notes.append(f"DATABASE_URL points at an external database ({runtime['host']}): "
|
||
"managed-database checks")
|
||
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 = {}
|
||
for name, url in (("DATABASE_URL", runtime), ("MIGRATION_DATABASE_URL", migration)):
|
||
if not url:
|
||
continue
|
||
role, dot, ref = url["user"].partition(".")
|
||
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)")
|
||
check(url["query"].get("sslrootcert") == [CA_TARGET],
|
||
f"{name} must set sslrootcert={CA_TARGET}, where docker-compose.managed-db.yml mounts the CA",
|
||
f"{name} trusts the mounted provider CA")
|
||
check(role not in PLATFORM_ROLES and role != "",
|
||
f"{name} logs in as {role or 'no user'}: never the platform admin — use Atrium's own role",
|
||
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 Atrium'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 — another app's role, or a generic app / migrator, would carry "
|
||
"privileges between the apps' schemas",
|
||
f"{name} logs in as Atrium's own role ({role})")
|
||
check(url["port"] != 6543,
|
||
f"{name} uses port 6543, the usual transaction-pooling port: use session mode on 5432",
|
||
f"{name} avoids the transaction pooler (port {url['port']})")
|
||
if "pooler" in url["host"] and not (dot and ref):
|
||
# Only the provider knows: some poolers need <role>.<tenant>, others take the plain role. A
|
||
# wrong form is a failed login, and some providers ban the client IP after a few of those.
|
||
warnings.append(f"{name}: the host looks like a pooler ({url['host']}) and the user carries no "
|
||
f"tenant suffix (got {url['user'] or 'no user'}) — some poolers need "
|
||
"<role>.<tenant>; the provider's dashboard shows the exact form")
|
||
elif dot and ref:
|
||
notes.append(f"{name} carries the tenant in the user name (<role>.<tenant>)")
|
||
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")
|
||
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"))}
|
||
check(all(value.isdigit() for value in pool.values()),
|
||
f"DB_POOL_SIZE / DB_MAX_OVERFLOW must be whole numbers (got {pool})",
|
||
f"the backend pool takes at most {sum(int(v) for v in pool.values() if v.isdigit())} "
|
||
"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}")
|
||
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"
|
||
+ (f", {len(warnings)} warning(s)." if warnings else "."))
|