#!/usr/bin/env python3 """Build, describe, and check release images of the Lincodex Compose stack. Subcommands (deploy/Makefile is the supported interface): tag print the release tag of the working tree build build the release images with base images pinned to the digests resolved from the local image store require-images fail unless every image a release run needs is local record-evidence record that a check passed against a running project manifest write deploy/release//manifest.json verify compare running containers of a project with a manifest check check a manifest's structure and scan it for machine secrets clean-images remove the local lincodex.invalid/* release images Only the standard library is used. Docker is called through the CLI; no command here pulls an image unless it is `build`, and `build` pulls only base or service images that are missing locally (or all of them with --pull always). The manifest and evidence never copy environment values, labels, mounts, or local paths from Docker; every written file passes forbidden_findings() first. """ from __future__ import annotations import argparse import base64 import datetime as _dt import getpass import hashlib import io import json import os import re import secrets as _secrets import socket import subprocess import sys import tarfile import tempfile from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Iterable ROOT = Path(__file__).resolve().parents[2] RELEASE_DIR_NAME = "deploy/release" MANIFEST_SCHEMA = "lincodex.release-manifest/v1" BUILD_SCHEMA = "lincodex.release-build/v1" EVIDENCE_SCHEMA = "lincodex.release-evidence/v1" RELEASE_REGISTRY = "lincodex.invalid" # Project name used only to render Compose files; nothing is started under it. RENDER_PROJECT = "lincodex-release" CHECKS = ("smoke", "e2e") CHECK_SCOPE = { "smoke": ( "deploy/scripts/smoke.sh: Compose startup and health, API routing, PostgreSQL, Redis, and " "SeaweedFS readiness and recovery, Redis and storage access rules, disabled mail transport. " "Not a business-flow test; Kafka publishing is not checked." ), "e2e": ( "deploy/scripts/e2e.sh: the Playwright technical browser suite against the stack. " "No candidate or employer workflows." ), } @dataclass(frozen=True) class Group: name: str compose_file: str release_overlay: str | None # Groups whose images a passing smoke or E2E run can verify. verifiable: bool unverified_reason: str GROUPS = ( Group("core", "deploy/docker/docker-compose.yml", "deploy/docker/docker-compose.release.yml", True, ""), Group( "ml", "deploy/docker/docker-compose.ml.yml", "deploy/docker/docker-compose.ml.release.yml", False, "Built by release-build, but no release check starts the ML service, and it has no inference model.", ), Group( "monitoring", "deploy/docker/docker-compose.monitoring.yml", None, False, "Monitoring is a separate project that no release check starts; images are recorded only if present locally.", ), ) # Planned components with no service, image, or Compose file in this repository. MISSING_COMPONENTS = { "gpu-inference": "Local model inference on a separate GPU host. The ML service has no model, and no GPU runtime or image exists.", "judge0": "Isolated code execution host. No service, image, or Compose file exists in this repository.", "qdrant": "Vector search. No service, image, or Compose file exists in this repository.", } # Only these image metadata keys are copied; everything else stays out. VERSION_ENV_KEYS = ( "GOLANG_VERSION", "JAVA_VERSION", "NGINX_VERSION", "NODE_VERSION", "PG_MAJOR", "PG_VERSION", "PYTHON_VERSION", "REDIS_VERSION", ) VERSION_LABEL_KEYS = ("org.opencontainers.image.revision", "org.opencontainers.image.version") LOCKFILES = ( "backend/go.mod", "backend/go.sum", "frontend/package.json", "frontend/pnpm-lock.yaml", "ml/pyproject.toml", "ml/uv.lock", ) class ReleaseError(RuntimeError): """A release step cannot continue; the message is safe to print.""" # --------------------------------------------------------------------------- # Secret and machine data scanning SECRET_NAME = re.compile( r"(PASS|PWD|SECRET|TOKEN|KEY|AUTH|DSN|COOKIE|SESSION|SIGN|PRIVATE|CREDENTIAL)", re.IGNORECASE ) FORBIDDEN_PATTERNS = ( ("private key block", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")), ("credentials in a URL", re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://[^/\s:@\"]+:[^/\s@\"]+@")), ("secret assignment", re.compile(r"\b[A-Z0-9_]*(PASSWORD|SECRET|TOKEN|API_KEY)[A-Z0-9_]*=")), ("AWS access key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")), ("Resend API key", re.compile(r"\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9_]{8,}")), ("GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}")), ("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")), ("JSON web token", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.")), ("absolute local path", re.compile(r"(? dict[str, str]: values: dict[str, str] = {} try: text = path.read_text(encoding="utf-8") except OSError: return values for line in text.splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue name, value = line.split("=", 1) values[name.strip()] = value.strip().strip("'\"") return values def sensitive_values(root: Path = ROOT, environ: dict[str, str] | None = None) -> dict[str, str]: """Return label -> value for values that must never appear in output. Labels name the source (variable name, user, host) and never the value. """ environ = dict(os.environ if environ is None else environ) found: dict[str, str] = {} def add(label: str, value: str, minimum: int = 6) -> None: value = value.strip() if len(value) >= minimum and value.lower() not in NEUTRAL_WORDS: found.setdefault(label, value) for source, values in (("root .env", env_file_values(root / ".env")), ("environment", environ)): for name, value in values.items(): if SECRET_NAME.search(name): add(f"value of {name} from {source}", value) try: add("local user name", getpass.getuser(), minimum=3) except (KeyError, OSError): pass host = socket.gethostname() add("local host name", host, minimum=3) add("local host name", host.split(".", 1)[0], minimum=3) home = environ.get("HOME", "") if home not in ("", "/"): add("home directory", home, minimum=3) add("repository path", str(root), minimum=3) return found def _walk_keys(value: Any, path: str = "$") -> Iterable[tuple[str, str]]: if isinstance(value, dict): for key, item in value.items(): yield path, str(key) yield from _walk_keys(item, f"{path}.{key}") elif isinstance(value, list): for index, item in enumerate(value): yield from _walk_keys(item, f"{path}[{index}]") def value_forms(value: str) -> list[str]: """Return the value and, for long values, its base64 encodings without padding.""" forms = [value] if len(value) >= 8: raw = value.encode("utf-8") for encoded in (base64.b64encode(raw), base64.urlsafe_b64encode(raw)): forms.append(encoded.decode("ascii").rstrip("=")) return forms def contains_value(text: str, value: str) -> bool: # Long values are searched as substrings; short ones need word boundaries # so that, for example, a three-letter user name inside a digest is not a hit. if len(value) >= 8: lowered = text.lower() return any(form.lower() in lowered if form == value else form in text for form in value_forms(value)) return bool(re.search(rf"(? list[str]: """Describe forbidden content in a JSON document without echoing it.""" text = json.dumps(document, sort_keys=True) if not isinstance(document, str) else document findings: list[str] = [] for name, pattern in FORBIDDEN_PATTERNS: if pattern.search(text): findings.append(name) for label, value in sorted((sensitive or {}).items()): if contains_value(text, value): findings.append(label) if not isinstance(document, str): for where, key in _walk_keys(document): if key.lower() in FORBIDDEN_KEYS: findings.append(f"configuration key '{key}' at {where}") return sorted(set(findings)) def write_json(path: Path, document: dict[str, Any], root: Path = ROOT) -> None: findings = forbidden_findings(document, sensitive_values(root)) if findings: raise ReleaseError(f"Refusing to write {display(path, root)}: " + "; ".join(findings)) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp") temporary.write_text(json.dumps(document, indent=2, sort_keys=True) + "\n", encoding="utf-8") temporary.replace(path) # --------------------------------------------------------------------------- # Source state def run(args: list[str], *, cwd: Path = ROOT, env: dict[str, str] | None = None, check: bool = True) -> bytes: try: result = subprocess.run(args, cwd=cwd, env=env, capture_output=True, check=False) except OSError as error: raise ReleaseError(f"{args[0]} could not run: {error}") from error if check and result.returncode != 0: message = result.stderr.decode("utf-8", errors="replace").strip().splitlines() tail = message[-1] if message else f"exit status {result.returncode}" raise ReleaseError(f"{' '.join(args[:3])} failed: {tail}") return result.stdout @dataclass(frozen=True) class Source: commit: str dirty: bool fingerprint: str | None @property def tag(self) -> str: return self.commit[:12] + ("-dirty" if self.dirty else "") # Settings that change how git add records content; pinned so that the # working tree fingerprint does not depend on local or global git config. GIT_PINNED = ( "-c", "core.autocrlf=false", "-c", "core.safecrlf=false", "-c", "core.filemode=true", "-c", "core.symlinks=true", "-c", "core.fsmonitor=false", ) def read_source(root: Path = ROOT) -> Source: """Return the commit and, for a changed tree, the Git tree ID of the working tree. The tree is written from a temporary index (seeded from HEAD, then git add -A), so it covers modified, deleted, and untracked files that Git does not ignore, leaves the real index alone, and does not depend on diff settings. """ git = ["git", *GIT_PINNED] commit = run([*git, "rev-parse", "--verify", "HEAD"], cwd=root).decode().strip() head_tree = run([*git, "rev-parse", "--verify", "HEAD^{tree}"], cwd=root).decode().strip() with tempfile.TemporaryDirectory(prefix="lincodex-release-index-") as directory: env = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")} env["GIT_INDEX_FILE"] = str(Path(directory) / "index") env["GIT_OPTIONAL_LOCKS"] = "0" run([*git, "read-tree", "HEAD"], cwd=root, env=env) run([*git, "add", "-A", "--", "."], cwd=root, env=env) tree = run([*git, "write-tree"], cwd=root, env=env).decode().strip() if tree == head_tree: return Source(commit, False, None) return Source(commit, True, f"git-tree:{tree}") def release_dir(tag: str, root: Path = ROOT) -> Path: if not re.fullmatch(r"[0-9a-f]{12}(-dirty)?", tag): raise ReleaseError(f"Unexpected release tag {tag!r}.") return root / RELEASE_DIR_NAME / tag def relative(path: Path, root: Path = ROOT) -> str: try: return path.resolve().relative_to(root.resolve()).as_posix() except ValueError as error: raise ReleaseError("A path outside the repository was referenced.") from error def display(path: Path, root: Path = ROOT) -> str: """Name a file for messages without revealing where the repository lives.""" try: return path.resolve().relative_to(root.resolve()).as_posix() except ValueError: return path.name def file_digest(path: Path) -> str | None: try: return "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest() except OSError: return None def utc_now() -> str: return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") # --------------------------------------------------------------------------- # Dockerfile and toolchain policy ARG_LINE = re.compile(r"^\s*ARG\s+([A-Za-z_][A-Za-z0-9_]*)(?:=(\S+))?\s*$", re.IGNORECASE) FROM_LINE = re.compile(r"^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)(?:\s+AS\s+(\S+))?\s*$", re.IGNORECASE) ARG_REFERENCE = re.compile(r"^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$") COPY_FROM = re.compile(r"^\s*(?:COPY|ADD)\b.*?\s--from=(\S+)", re.IGNORECASE) MOUNT_FROM = re.compile(r"--mount=\S*?\bfrom=([^,\s]+)", re.IGNORECASE) def logical_lines(text: str) -> list[tuple[int, str]]: """Join backslash continuations and drop comments, keeping first line numbers.""" result: list[tuple[int, str]] = [] buffer: list[str] = [] start = 0 for number, line in enumerate(text.splitlines(), start=1): if not buffer and line.lstrip().startswith("#"): continue if not buffer: start = number stripped = line.rstrip() if stripped.endswith("\\"): buffer.append(stripped[:-1]) continue buffer.append(stripped) result.append((start, " ".join(buffer))) buffer = [] if buffer: result.append((start, " ".join(buffer))) return result @dataclass(frozen=True) class BaseImage: arg: str default: str def dockerfile_bases(text: str, source: str = "Dockerfile") -> list[BaseImage]: """Return the base image arguments; fail on any base that cannot be pinned. Every FROM must name an earlier stage or a global ARG ending in _IMAGE with a default, so release-build can replace each base with a digest. """ global_args: dict[str, str | None] = {} stages: set[str] = set() bases: dict[str, BaseImage] = {} seen_from = False stage_count = 0 for number, line in logical_lines(text): if not seen_from: match = ARG_LINE.match(line) if match: global_args[match.group(1)] = match.group(2) continue match = FROM_LINE.match(line) if not match: for source_ref in COPY_FROM.findall(line) + MOUNT_FROM.findall(line): if source_ref not in stages and not (source_ref.isdigit() and int(source_ref) < stage_count): raise ReleaseError( f"{source}:{number}: --from={source_ref} is not an earlier stage; external images cannot be pinned." ) continue seen_from = True stage_count += 1 image, stage = match.group(1), match.group(2) if image in stages: pass else: reference = ARG_REFERENCE.match(image) if not reference or not reference.group(1).endswith("_IMAGE"): raise ReleaseError(f"{source}:{number}: FROM {image} is not a pinnable *_IMAGE build argument.") name = reference.group(1) default = global_args.get(name) if not default: raise ReleaseError(f"{source}:{number}: build argument {name} has no default before the first FROM.") bases[name] = BaseImage(name, default) if stage: stages.add(stage) if not bases: raise ReleaseError(f"{source}: no base image found.") return [bases[name] for name in sorted(bases)] def go_policy(root: Path = ROOT) -> dict[str, Any]: """Describe the Go pin and whether go.mod and the build image agree.""" go_mod = (root / "backend/go.mod").read_text(encoding="utf-8") directive = re.search(r"^go\s+(\S+)\s*$", go_mod, re.MULTILINE) toolchain = re.search(r"^toolchain\s+(\S+)\s*$", go_mod, re.MULTILINE) dockerfile = (root / "backend/Dockerfile").read_text(encoding="utf-8") bases = {base.arg: base.default for base in dockerfile_bases(dockerfile, "backend/Dockerfile")} image = bases.get("GO_IMAGE", "") image_version = re.match(r"^golang:([0-9]+\.[0-9]+\.[0-9]+)-", image) build_stage = dockerfile.split("FROM ${GO_IMAGE}", 1)[-1].split("\nFROM ", 1)[0] version = directive.group(1) if directive else None policy = { "go_mod": version, "toolchain_directive": toolchain.group(1) if toolchain else None, "dockerfile_image": image or None, "gotoolchain_local": bool(re.search(r"^ENV\s+GOTOOLCHAIN=local\s*$", build_stage, re.MULTILINE)), } policy["consistent"] = bool( version and re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version) and image_version and image_version.group(1) == version and policy["toolchain_directive"] in (None, f"go{version}") and policy["gotoolchain_local"] ) return policy def text_match(path: Path, pattern: str) -> str | None: try: match = re.search(pattern, path.read_text(encoding="utf-8"), re.MULTILINE) except OSError: return None return match.group(1) if match else None # --------------------------------------------------------------------------- # Go build information def go_build_version(binary: bytes) -> str | None: """Return the Go version recorded in a Go 1.18+ binary, or None.""" magic = b"\xff Go buildinf:" start = 0 while True: index = binary.find(magic, start) if index < 0: return None if index % 16 == 0 and len(binary) >= index + 32: break start = index + 1 flags = binary[index + 15] if not flags & 0x2: # Pre-1.18 pointer layout; the release build never produces it. return None position = index + 32 length, shift = 0, 0 while position < len(binary): byte = binary[position] position += 1 length |= (byte & 0x7F) << shift if not byte & 0x80: break shift += 7 version = binary[position : position + length] try: decoded = version.decode("ascii") except UnicodeDecodeError: return None return decoded if re.fullmatch(r"go[0-9][0-9A-Za-z.+-]*", decoded) else None # --------------------------------------------------------------------------- # Docker access def docker_env(extra: dict[str, str] | None = None) -> dict[str, str]: """Return a minimal environment so shell secrets never reach Compose.""" env = {name: value for name, value in os.environ.items() if name in ("PATH", "HOME", "TMPDIR")} env.update({name: value for name, value in os.environ.items() if name.startswith(("DOCKER_", "BUILDKIT_"))}) env.update(extra or {}) return env class Docker: """Thin CLI wrapper; tests replace it with a fake.""" def __init__(self, binary: str | None = None) -> None: self.binary = binary or os.environ.get("DOCKER", "docker") def inspect_image(self, reference: str) -> dict[str, Any] | None: result = subprocess.run( [self.binary, "image", "inspect", reference], capture_output=True, check=False, env=docker_env() ) if result.returncode != 0: return None data = json.loads(result.stdout) return data[0] if data else None def compose_config(self, files: list[str], tag: str, root: Path = ROOT) -> dict[str, Any]: args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT] for name in files: args += ["-f", str(root / name)] args += ["config", "--format", "json"] env = docker_env( {"APP_PROJECT": RENDER_PROJECT, "APP_NETWORK": f"{RENDER_PROJECT}_default", "LINCODEX_RELEASE_TAG": tag} ) return json.loads(run(args, cwd=root, env=env)) def project_containers(self, project: str) -> list[dict[str, Any]]: ids = run( [self.binary, "ps", "-q", "--filter", f"label=com.docker.compose.project={project}"], env=docker_env() ).split() if not ids: return [] return json.loads(run([self.binary, "inspect", *[item.decode() for item in ids]], env=docker_env())) def read_file(self, image_id: str, path: str) -> bytes | None: """Copy one file out of an image through a created, never started container.""" name = f"lincodex-release-inspect-{_secrets.token_hex(6)}" created = subprocess.run( [self.binary, "create", "--pull", "never", "--name", name, image_id], capture_output=True, check=False, env=docker_env(), ) if created.returncode != 0: return None try: archive = subprocess.run( [self.binary, "cp", f"{name}:{path}", "-"], capture_output=True, check=False, env=docker_env() ) if archive.returncode != 0: return None with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as tar: for member in tar.getmembers(): if member.isfile(): handle = tar.extractfile(member) return handle.read() if handle else None return None finally: subprocess.run([self.binary, "rm", "-f", name], capture_output=True, check=False, env=docker_env()) def pull(self, reference: str) -> None: print(f"Pulling {reference}", flush=True) if subprocess.run([self.binary, "pull", reference], check=False, env=docker_env()).returncode != 0: raise ReleaseError(f"Could not pull {reference}.") def compose_build(self, files: list[str], tag: str, service: str, build_args: dict[str, str], root: Path = ROOT) -> None: args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT] for name in files: args += ["-f", str(root / name)] args += ["build"] for name, value in sorted(build_args.items()): args += ["--build-arg", f"{name}={value}"] args.append(service) env = docker_env( {"APP_PROJECT": RENDER_PROJECT, "APP_NETWORK": f"{RENDER_PROJECT}_default", "LINCODEX_RELEASE_TAG": tag} ) print(f"Building {service} for release {tag}", flush=True) if subprocess.run(args, cwd=root, env=env, check=False).returncode != 0: raise ReleaseError(f"Building {service} failed.") def normalize_repository(reference: str) -> str: """Return the repository of an image reference in docker.io long form.""" name = reference.split("@", 1)[0] last = name.rsplit("/", 1)[-1] if ":" in last: name = name[: name.rfind(":")] first = name.split("/", 1)[0] if "/" not in name: name = f"docker.io/library/{name}" elif not ("." in first or ":" in first or first == "localhost"): name = f"docker.io/{name}" return name def repo_digest(info: dict[str, Any], reference: str) -> str | None: wanted = normalize_repository(reference) for item in sorted(info.get("RepoDigests") or []): if "@" in item and normalize_repository(item) == wanted: return item.split("@", 1)[1] return None def image_versions(info: dict[str, Any], labels: bool = True) -> dict[str, str]: """Copy allowlisted version metadata; built images inherit base labels, so skip them there.""" versions: dict[str, str] = {} for entry in (info.get("Config") or {}).get("Env") or []: name, _, value = entry.partition("=") if name in VERSION_ENV_KEYS and value: versions[name] = value image_labels = ((info.get("Config") or {}).get("Labels") or {}) if labels else {} for name in VERSION_LABEL_KEYS: if image_labels.get(name): versions[name] = image_labels[name] return versions def image_record(info: dict[str, Any] | None, reference: str, built: bool = False) -> dict[str, Any]: if info is None: return {"reference": reference, "present": False} platform = "/".join(part for part in (info.get("Os"), info.get("Architecture"), info.get("Variant")) if part) return { "reference": reference, "present": True, "image_id": info.get("Id"), # A local build has no registry digest; its image ID identifies it. "repo_digest": None if built else repo_digest(info, reference), "repo_digests": [] if built else sorted(item for item in info.get("RepoDigests") or [] if isinstance(item, str)), "platform": platform or None, "versions": image_versions(info, labels=not built), } # --------------------------------------------------------------------------- # Compose services @dataclass class Service: group: str name: str reference: str dockerfile: str | None = None context: str | None = None compose_file: str = "" overlay: str | None = None def group_services(docker: Docker, group: Group, tag: str, root: Path = ROOT) -> list[Service]: files = [group.compose_file] + ([group.release_overlay] if group.release_overlay else []) config = docker.compose_config(files, tag, root) services: list[Service] = [] for name, spec in sorted((config.get("services") or {}).items()): if spec.get("profiles"): continue build = spec.get("build") reference = spec.get("image") if build: if not group.release_overlay or not reference: raise ReleaseError(f"Built service {name} has no release image name.") context = Path(build["context"]) dockerfile = context / build.get("dockerfile", "Dockerfile") services.append( Service(group.name, name, reference, relative(dockerfile, root), relative(context, root) or ".", group.compose_file, group.release_overlay) ) elif reference: services.append(Service(group.name, name, reference, compose_file=group.compose_file)) return services def release_reference(service: str, tag: str) -> str: return f"{RELEASE_REGISTRY}/{service}:{tag}" # --------------------------------------------------------------------------- # build def ensure_local(docker: Docker, reference: str, pull: str) -> dict[str, Any]: info = None if pull == "always" else docker.inspect_image(reference) if info is None: docker.pull(reference) info = docker.inspect_image(reference) if info is None: raise ReleaseError(f"{reference} is not available locally after pulling.") return info def command_build(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: docker = docker or Docker() source = read_source(root) policy = go_policy(root) if not policy["consistent"]: raise ReleaseError( "The Go pin is inconsistent: backend/go.mod, the toolchain directive, the GO_IMAGE default, " "and ENV GOTOOLCHAIN=local in backend/Dockerfile must agree." ) record: dict[str, Any] = { "schema": BUILD_SCHEMA, "tag": source.tag, "commit": source.commit, "dirty": source.dirty, "source_fingerprint": source.fingerprint, "built_at": utc_now(), "services": {}, } for group in GROUPS: if group.release_overlay is None: continue for service in group_services(docker, group, source.tag, root): if service.dockerfile is None: ensure_local(docker, service.reference, args.pull) continue text = (root / service.dockerfile).read_text(encoding="utf-8") build_args: dict[str, str] = {} bases = [] for base in dockerfile_bases(text, service.dockerfile): info = ensure_local(docker, base.default, args.pull) digest = repo_digest(info, base.default) if not digest: raise ReleaseError(f"{base.default} has no repository digest; pull it from its registry first.") pinned = f"{base.default}@{digest}" build_args[base.arg] = pinned bases.append( {"arg": base.arg, "reference": base.default, "digest": digest, "versions": image_versions(info)} ) files = [service.compose_file] + ([service.overlay] if service.overlay else []) docker.compose_build(files, source.tag, service.name, build_args, root) info = docker.inspect_image(service.reference) if info is None: raise ReleaseError(f"{service.reference} is missing after the build.") record["services"][service.name] = { "reference": service.reference, "image_id": info.get("Id"), "dockerfile": service.dockerfile, "dockerfile_digest": file_digest(root / service.dockerfile), "context": service.context, "build_args": build_args, "base_images": bases, } after = read_source(root) if (after.commit, after.fingerprint) != (source.commit, source.fingerprint): raise ReleaseError( "The source changed during the build, so the images may not match any one source state; " "build.json was not written. Rebuild from a tree that does not change." ) path = release_dir(source.tag, root) / "build.json" write_json(path, record, root) print(f"Release images built for {source.tag}; build record: {display(path, root)}") if source.dirty: print("The working tree is dirty: a manifest for these images stays unverified.") return 0 # --------------------------------------------------------------------------- # require-images and record-evidence def command_require_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: docker = docker or Docker() source = read_source(root) expect_tag(args, source) group = next(item for item in GROUPS if item.name == args.group) missing = [ service.reference for service in group_services(docker, group, source.tag, root) if docker.inspect_image(service.reference) is None ] if missing: raise ReleaseError( "Missing local images: " + ", ".join(missing) + ". Run make -C deploy release-build first." ) return 0 def expect_tag(args: argparse.Namespace, source: Source) -> None: if getattr(args, "tag", None) and args.tag != source.tag: raise ReleaseError(f"The working tree is now release {source.tag}, not {args.tag}; rebuild and rerun.") def running_services(containers: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: services: dict[str, dict[str, Any]] = {} for container in containers: labels = (container.get("Config") or {}).get("Labels") or {} if labels.get("com.docker.compose.oneoff", "False") == "True": continue if not (container.get("State") or {}).get("Running"): continue name = labels.get("com.docker.compose.service") if name: services[name] = { "reference": (container.get("Config") or {}).get("Image"), "image_id": container.get("Image"), } return services def command_record_evidence(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: docker = docker or Docker() source = read_source(root) expect_tag(args, source) group = next(item for item in GROUPS if item.name == "core") expected = group_services(docker, group, source.tag, root) running = running_services(docker.project_containers(args.project)) services: dict[str, Any] = {} for service in expected: actual = running.get(service.name) if actual is None: raise ReleaseError(f"Service {service.name} is not running in project {args.project}.") if actual["reference"] != service.reference: raise ReleaseError(f"Service {service.name} runs {actual['reference']}, not {service.reference}.") services[service.name] = actual tools: dict[str, Any] = {} for item in args.tool_image or []: name, _, reference = item.partition("=") info = docker.inspect_image(reference) if info is None: raise ReleaseError(f"Tool image {reference} is not present locally.") tools[name] = {"reference": reference, "image_id": info.get("Id")} evidence = { "schema": EVIDENCE_SCHEMA, "check": args.check, "result": "passed", "tag": source.tag, "commit": source.commit, "source_fingerprint": source.fingerprint, "finished_at": utc_now(), "services": services, "tool_images": tools, } path = release_dir(source.tag, root) / f"evidence-{args.check}.json" write_json(path, evidence, root) print(f"Recorded passing {args.check} evidence for {source.tag}: {display(path, root)}") return 0 # --------------------------------------------------------------------------- # manifest def load_json(path: Path) -> dict[str, Any] | None: try: document = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return None return document if isinstance(document, dict) else None IMAGE_ID = re.compile(r"sha256:[0-9a-f]+") def _is_str_map(value: Any) -> bool: return isinstance(value, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in value.items()) def _is_image_map(value: Any) -> bool: return isinstance(value, dict) and all( isinstance(name, str) and isinstance(item, dict) and isinstance(item.get("reference"), str) and isinstance(item.get("image_id"), str) and IMAGE_ID.fullmatch(item["image_id"]) for name, item in value.items() ) def evidence_problem(document: dict[str, Any], check: str, source: Source) -> str | None: """Return why an evidence document cannot count for this source, or None.""" if ( document.get("schema") != EVIDENCE_SCHEMA or document.get("check") != check or document.get("result") != "passed" or not isinstance(document.get("finished_at"), str) or not isinstance(document.get("tag"), str) or not isinstance(document.get("commit"), str) or not isinstance(document.get("source_fingerprint"), (str, type(None))) or not _is_image_map(document.get("services")) or not _is_image_map(document.get("tool_images", {})) ): return "The evidence file is malformed." if document["tag"] != source.tag: return "The evidence was recorded for another release tag." if document["commit"] != source.commit: return "The evidence was recorded for another commit." if document["source_fingerprint"] != source.fingerprint: return "The evidence was recorded for another working tree state." return None def accept_evidence( documents: dict[str, dict[str, Any] | None], source: Source ) -> tuple[dict[str, dict[str, Any]], dict[str, str]]: """Split evidence into documents bound to this exact source and rejected ones.""" accepted: dict[str, dict[str, Any]] = {} rejected: dict[str, str] = {} for check, document in sorted(documents.items()): if document is None: continue problem = evidence_problem(document, check, source) if problem: rejected[check] = problem else: accepted[check] = document return accepted, rejected def build_record_problem(document: dict[str, Any]) -> str | None: services = document.get("services") if ( document.get("schema") != BUILD_SCHEMA or not isinstance(document.get("commit"), str) or not isinstance(document.get("source_fingerprint"), (str, type(None))) or not isinstance(services, dict) ): return "The build record is malformed." for item in services.values(): bases = item.get("base_images") if isinstance(item, dict) else None if ( not isinstance(item, dict) or not isinstance(item.get("image_id"), str) or not _is_str_map(item.get("build_args")) or not isinstance(bases, list) or not all( isinstance(base, dict) and all(isinstance(base.get(key), str) for key in ("arg", "reference", "digest")) and _is_str_map(base.get("versions", {})) for base in bases ) ): return "The build record is malformed." return None @dataclass class Inputs: """Everything the manifest is derived from, so tests can supply fakes.""" source: Source services: list[Service] images: dict[str, dict[str, Any] | None] build_record: dict[str, Any] | None evidence: dict[str, dict[str, Any]] go_binary: str | None go: dict[str, Any] files: dict[str, str | None] = field(default_factory=dict) rejected_checks: dict[str, str] = field(default_factory=dict) build_problem: str | None = None def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs: source = read_source(root) services: list[Service] = [] for group in GROUPS: services.extend(group_services(docker, group, source.tag, root)) images = {service.reference: docker.inspect_image(service.reference) for service in services} directory = release_dir(source.tag, root) evidence, rejected = accept_evidence( {check: load_json(directory / f"evidence-{check}.json") for check in CHECKS}, source ) build = load_json(directory / "build.json") build_problem = build_record_problem(build) if build is not None else None if build_problem: build = None go_binary = None backend = images.get(release_reference("backend", source.tag)) if backend: entrypoint = (backend.get("Config") or {}).get("Entrypoint") or [] if entrypoint: content = docker.read_file(backend["Id"], entrypoint[0]) go_binary = go_build_version(content) if content else None files = {name: file_digest(root / name) for name in LOCKFILES} files[".node-version"] = text_match(root / "frontend/.node-version", r"^\s*(\S+)\s*$") files["packageManager"] = text_match(root / "frontend/package.json", r'"packageManager":\s*"([^"]+)"') files["dockerfile_pnpm"] = text_match(root / "frontend/Dockerfile", r"pnpm@([0-9][^\s\"]*)") files["playwright"] = text_match(root / "frontend/package.json", r'"@playwright/test":\s*"([^"]+)"') files[".python-version"] = text_match(root / "ml/.python-version", r"^\s*(\S+)\s*$") files["requires-python"] = text_match(root / "ml/pyproject.toml", r'^requires-python\s*=\s*"([^"]+)"') files["dockerfile_uv"] = text_match(root / "ml/Dockerfile", r"uv==([0-9][^\s\"]*)") for service in services: if service.dockerfile: files[service.dockerfile] = file_digest(root / service.dockerfile) return Inputs( source, services, images, build, evidence, go_binary, go_policy(root), files, rejected, build_problem ) def base_version(build: dict[str, Any] | None, service: str, key: str) -> str | None: if not build: return None for base in (build.get("services", {}).get(service) or {}).get("base_images", []): if key in (base.get("versions") or {}): return base["versions"][key] return None def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: source = inputs.source build = inputs.build_record files = inputs.files build_matches_source = bool( build and build.get("commit") == source.commit and build.get("source_fingerprint") == source.fingerprint ) components: list[dict[str, Any]] = [] reasons: list[str] = [] for service in inputs.services: image = image_record(inputs.images.get(service.reference), service.reference, built=bool(service.dockerfile)) component: dict[str, Any] = { "name": service.name, "group": service.group, "kind": "built" if service.dockerfile else "pulled", "compose_file": service.compose_file, "image": image, } if service.dockerfile: recorded = (build or {}).get("services", {}).get(service.name) matches = bool(recorded and image.get("present") and recorded.get("image_id") == image.get("image_id")) component["build"] = { "dockerfile": service.dockerfile, "dockerfile_digest": files.get(service.dockerfile), "context": service.context, "recorded_by_release_build": matches, "build_args": recorded.get("build_args", {}) if matches else {}, "base_images": recorded.get("base_images", []) if matches else [], } if not matches: component["build"]["reason"] = "The local image was not built by release-build for this tag." if component["build"]["dockerfile_digest"] is None: reasons.append(f"The Dockerfile of {service.name} is missing.") group = next(item for item in GROUPS if item.name == service.group) if not image.get("present"): verification = {"status": "not_verified", "reason": "The image is not present locally.", "checks": []} elif not group.verifiable: verification = {"status": "not_verified", "reason": group.unverified_reason, "checks": []} else: passed = sorted( check for check, document in inputs.evidence.items() if (document.get("services", {}).get(service.name) or {}).get("image_id") == image.get("image_id") ) if passed: verification = {"status": "verified", "checks": passed} else: verification = { "status": "not_verified", "reason": "No passing smoke or E2E run of this source state is recorded for this image ID.", "checks": [], } component["verification"] = verification components.append(component) if service.group == "core": if verification["status"] != "verified": reasons.append(f"Core component {service.name} is not verified.") elif set(verification["checks"]) != set(CHECKS): reasons.append("Smoke and E2E were not both recorded for the current core images.") if service.dockerfile and not component["build"]["recorded_by_release_build"]: reasons.append(f"Core image {service.name} was not built by release-build.") if not service.dockerfile and image.get("present") and not image.get("repo_digest"): reasons.append(f"Core image {service.name} has no registry digest.") for name, reason in sorted(MISSING_COMPONENTS.items()): components.append( { "name": name, "group": "missing", "kind": "absent", "image": None, "verification": {"status": "missing", "reason": reason, "checks": []}, } ) components.sort(key=lambda item: (["core", "ml", "monitoring", "missing"].index(item["group"]), item["name"])) go = dict(inputs.go) go["build_image_version"] = base_version(build, "backend", "GOLANG_VERSION") go["binary"] = inputs.go_binary go["binary_matches"] = bool(go["go_mod"] and inputs.go_binary == f"go{go['go_mod']}") if not go["consistent"]: reasons.append("The Go pin in go.mod and backend/Dockerfile is inconsistent.") if not go["binary_matches"]: reasons.append("The backend binary was not confirmed to be built with the go.mod Go version.") node_image = base_version(build, "frontend", "NODE_VERSION") node_matches = bool(node_image and node_image == files.get(".node-version")) if node_image and not node_matches: reasons.append("Node in the frontend build image differs from frontend/.node-version.") python_image = base_version(build, "ml", "PYTHON_VERSION") # ML is outside the release scope, so a Python mismatch is reported but # does not keep the core release unverified. python_matches = bool(python_image and python_image == files.get(".python-version")) for name in LOCKFILES: if files.get(name) is None: reasons.append(f"Lockfile {name} is missing.") if source.dirty: reasons.append("The working tree has uncommitted changes.") if inputs.build_problem: reasons.append(inputs.build_problem) if not build_matches_source: reasons.append("The build record does not match the current source state.") for check, problem in sorted(inputs.rejected_checks.items()): reasons.append(f"{check} evidence was not accepted: {problem}") checks = {} for name, document in sorted(inputs.evidence.items()): checks[name] = { "scope": CHECK_SCOPE[name], "finished_at": document.get("finished_at"), "commit": document.get("commit"), "source_fingerprint": document.get("source_fingerprint"), "tool_images": document.get("tool_images", {}), } return { "schema": MANIFEST_SCHEMA, "generated_at": generated_at, "release": { "tag": source.tag, "status": "unverified" if reasons else "verified", "scope": "core", "required_checks": list(CHECKS), "reasons": sorted(set(reasons)), }, "source": { "commit": source.commit, "dirty": source.dirty, "fingerprint": source.fingerprint, "build_matches_source": build_matches_source, }, "toolchains": { "go": go, "node": { "node_version_file": files.get(".node-version"), "package_manager": files.get("packageManager"), "dockerfile_pnpm": files.get("dockerfile_pnpm"), "build_image_version": node_image, "matches_version_file": node_matches, }, "python": { "python_version_file": files.get(".python-version"), "requires_python": files.get("requires-python"), "dockerfile_uv": files.get("dockerfile_uv"), "build_image_version": python_image, "matches_version_file": python_matches, }, "playwright": {"package_version": files.get("playwright")}, }, "lockfiles": {name: files.get(name) for name in LOCKFILES}, "checks": checks, "rejected_checks": dict(sorted(inputs.rejected_checks.items())), "components": components, } def comparable(document: dict[str, Any] | None) -> dict[str, Any] | None: if document is None: return None return {key: value for key, value in document.items() if key != "generated_at"} def command_manifest(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: docker = docker or Docker() inputs = collect_inputs(docker, root) manifest = build_manifest(inputs, utc_now()) path = release_dir(inputs.source.tag, root) / "manifest.json" previous = load_json(path) write_json(path, manifest, root) print(f"Release manifest: {display(path, root)}") print(f"Release {manifest['release']['tag']}: {manifest['release']['status']}") for reason in manifest["release"]["reasons"]: print(f" - {reason}") for component in manifest["components"]: image = component["image"] or {} status = component["verification"]["status"] presence = "" if component["image"] is None or image.get("present") else " (image missing locally)" print(f" {component['group']:<10} {component['name']:<20} {status}{presence}") if previous is not None: if comparable(previous) == comparable(manifest): print("Unchanged from the previous manifest apart from generated_at.") else: changed = sorted( key for key in set(previous) | set(manifest) if key != "generated_at" and previous.get(key) != manifest.get(key) ) print("Changed from the previous manifest: " + ", ".join(changed)) return 0 # --------------------------------------------------------------------------- # verify and check def default_manifest(root: Path = ROOT) -> Path: return release_dir(read_source(root).tag, root) / "manifest.json" def compare_running(manifest: dict[str, Any], running: dict[str, dict[str, Any]]) -> tuple[bool, list[str]]: components = { item["name"]: item for item in manifest.get("components", []) if item.get("group") != "missing" } groups = {components[name]["group"] for name in running if name in components} ok = True lines: list[str] = [] if not running: return False, ["No running containers found in the project."] for name in sorted(running): if name not in components: ok = False lines.append(f"{name:<16} UNKNOWN runs {running[name]['reference']}, which the manifest does not list") for name, component in sorted(components.items()): if component["group"] not in groups: continue image = component.get("image") or {} versions = " ".join(f"{key}={value}" for key, value in sorted((image.get("versions") or {}).items())) if name not in running: ok = False lines.append(f"{name:<16} MISSING not running") continue actual = running[name] if not image.get("present"): ok = False lines.append(f"{name:<16} MISMATCH the manifest has no image ID for {image.get('reference')}") elif actual["image_id"] != image.get("image_id"): ok = False lines.append( f"{name:<16} MISMATCH runs {actual['image_id']}, manifest {image.get('image_id')} ({image.get('reference')})" ) else: note = "" if actual["reference"] == image.get("reference") else f" (started as {actual['reference']})" lines.append( f"{name:<16} OK {image.get('reference')} {image.get('image_id')}{note}" + (f" {versions}" if versions else "") ) go_binary = (manifest.get("toolchains", {}).get("go") or {}).get("binary") if "backend" in running and go_binary: lines.append(f"backend binary built with {go_binary} (from the manifest)") return ok, lines def command_verify(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: docker = docker or Docker() path = Path(args.manifest) if args.manifest else default_manifest(root) manifest = load_json(path) if manifest is None or manifest.get("schema") != MANIFEST_SCHEMA: raise ReleaseError(f"No readable release manifest at {display(path, root)}; run make -C deploy release-manifest.") running = running_services(docker.project_containers(args.project)) ok, lines = compare_running(manifest, running) release_info = manifest.get("release") or {} print( f"Project {args.project} against {display(path, root)} " f"(release {release_info.get('tag')}, status {release_info.get('status')}):" ) for line in lines: print(f" {line}") print("All running containers match the manifest." if ok else "Running containers differ from the manifest.") return 0 if ok else 1 REQUIRED_KEYS = ( "schema", "generated_at", "release", "source", "toolchains", "lockfiles", "checks", "rejected_checks", "components" ) STATUSES = frozenset({"verified", "not_verified", "missing"}) def structure_errors(manifest: dict[str, Any]) -> list[str]: errors = [f"missing key {key}" for key in REQUIRED_KEYS if key not in manifest] if manifest.get("schema") != MANIFEST_SCHEMA: errors.append("unexpected schema") for component in manifest.get("components", []): status = (component.get("verification") or {}).get("status") if status not in STATUSES: errors.append(f"component {component.get('name')} has status {status!r}") if status == "verified" and not component["verification"].get("checks"): errors.append(f"component {component.get('name')} is verified without a check") if status == "verified" and any( check not in manifest.get("checks", {}) for check in component["verification"]["checks"] ): errors.append(f"component {component.get('name')} names an unrecorded check") if not any(item.get("group") == "missing" for item in manifest.get("components", [])): errors.append("missing components are not listed") return errors def command_check(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: path = Path(args.manifest) if args.manifest else default_manifest(root) try: text = path.read_text(encoding="utf-8") manifest = json.loads(text) except (OSError, ValueError) as error: raise ReleaseError(f"No readable release manifest at {display(path, root)}.") from error problems = structure_errors(manifest) problems += forbidden_findings(text, sensitive_values(root)) problems += [item for item in forbidden_findings(manifest) if item.startswith("configuration key")] if problems: print(f"{display(path, root)} failed the check:") for problem in sorted(set(problems)): print(f" - {problem}") return 1 print(f"{display(path, root)}: structure valid; no secrets, local paths, user or host names found.") return 0 def command_clean_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: """Remove every local release image; nothing else is touched.""" docker = docker or Docker() listing = run([docker.binary, "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"], env=docker_env()) references = sorted( {line for line in listing.decode().splitlines() if line.startswith(f"{RELEASE_REGISTRY}/")} ) if not references: print("No release images to remove.") return 0 run([docker.binary, "image", "rm", *references], env=docker_env()) for reference in references: print(f"Removed {reference}") return 0 def command_tag(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: print(read_source(root).tag) return 0 def parser() -> argparse.ArgumentParser: result = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) commands = result.add_subparsers(dest="command", required=True) commands.add_parser("tag").set_defaults(handler=command_tag) commands.add_parser("clean-images").set_defaults(handler=command_clean_images) build = commands.add_parser("build") build.add_argument("--pull", choices=("missing", "always"), default="missing") build.set_defaults(handler=command_build) require = commands.add_parser("require-images") require.add_argument("--group", choices=("core",), default="core") require.add_argument("--tag") require.set_defaults(handler=command_require_images) record = commands.add_parser("record-evidence") record.add_argument("--check", choices=CHECKS, required=True) record.add_argument("--project", required=True) record.add_argument("--tag") record.add_argument("--tool-image", action="append", help="name=reference of a test tool image") record.set_defaults(handler=command_record_evidence) commands.add_parser("manifest").set_defaults(handler=command_manifest) verify = commands.add_parser("verify") verify.add_argument("--project", required=True) verify.add_argument("--manifest") verify.set_defaults(handler=command_verify) check = commands.add_parser("check") check.add_argument("--manifest") check.set_defaults(handler=command_check) return result def main(argv: list[str] | None = None) -> int: args = parser().parse_args(argv) handler: Callable[[argparse.Namespace], int] = args.handler try: return handler(args) except ReleaseError as error: print(f"release: {error}", file=sys.stderr) return 2 if __name__ == "__main__": sys.exit(main())