diff --git a/deploy/Makefile b/deploy/Makefile index 54f281b..33d1609 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -24,8 +24,14 @@ RELEASE := PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" RELEASE_PULL ?= missing # Compose project whose running containers release-manifest-verify compares. RELEASE_VERIFY_PROJECT ?= $(APP_PROJECT) -# Optional manifest path for release-manifest-verify; empty means the current tag. +# Optional manifest path for release-manifest-check, verify, and restore. +# Empty selects RELEASE_ID when set, otherwise the current commit-based ID. RELEASE_MANIFEST ?= +# Optional immutable delivery ID; empty keeps the current commit-based ID. +RELEASE_ID ?= +# Optional repository-relative manifest describing bank, policy, and seed inputs. +RELEASE_DATA_MANIFEST ?= +RELEASE_MANIFEST_ARG = $(if $(strip $(RELEASE_MANIFEST)),--manifest "$(RELEASE_MANIFEST)",$(if $(strip $(RELEASE_ID)),--manifest "deploy/release/$(RELEASE_ID)/manifest.json",)) # Recursive on purpose: git is asked only by the targets that use the tag. The # project-specific name keeps a generic RELEASE_TAG from enabling release mode. LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" tag) @@ -137,23 +143,22 @@ release-smoke: ## Run the smoke against the release images and record passing ev release-e2e: ## Run the Playwright suite against the release images and record passing evidence @LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" bash scripts/e2e.sh -release-manifest: ## Write deploy/release//manifest.json from local images and recorded evidence - @$(RELEASE) manifest +release-manifest: ## Publish an immutable deploy/release//manifest.json from local images and data versions + @$(RELEASE) manifest $(if $(strip $(RELEASE_ID)),--release-id "$(RELEASE_ID)",) $(if $(strip $(RELEASE_DATA_MANIFEST)),--data-manifest "$(RELEASE_DATA_MANIFEST)",) release-manifest-verify: ## Compare running containers of RELEASE_VERIFY_PROJECT with the manifest (or RELEASE_MANIFEST) - @$(RELEASE) verify --project "$(RELEASE_VERIFY_PROJECT)" $(if $(RELEASE_MANIFEST),--manifest "$(RELEASE_MANIFEST)") + @$(RELEASE) verify --project "$(RELEASE_VERIFY_PROJECT)" $(RELEASE_MANIFEST_ARG) release-manifest-check: ## Check the manifest structure and scan it for secrets and machine data - @$(RELEASE) check + @$(RELEASE) check $(RELEASE_MANIFEST_ARG) -release-up: ## Start the core stack from the release images without building or pulling +release-up: ## Restore the core stack from an immutable release manifest without building or pulling @test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; } - @$(RELEASE) require-images --tag "$(LINCODEX_RELEASE_TAG)" - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" up -d --no-build --pull never --wait --wait-timeout 180 + @$(RELEASE) restore --action up --project "$(APP_PROJECT)" --env-file "$(ENV_FILE)" $(RELEASE_MANIFEST_ARG) -release-down: ## Stop the core stack started by release-up and keep named volumes +release-down: ## Stop the release project selected by the immutable manifest and keep named volumes @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" down + @$(RELEASE) restore --action down --project "$(APP_PROJECT)" --env-file "$(ENV_FILE)" $(RELEASE_MANIFEST_ARG) -release-clean: ## Remove the local lincodex.invalid/* release images; keep deploy/release files +release-clean: ## Remove local release image references not retained by an immutable manifest @$(RELEASE) clean-images diff --git a/deploy/scripts/release_manifest.py b/deploy/scripts/release_manifest.py index d013b67..adda759 100644 --- a/deploy/scripts/release_manifest.py +++ b/deploy/scripts/release_manifest.py @@ -8,10 +8,11 @@ Subcommands (deploy/Makefile is the supported interface): 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 + manifest publish deploy/release//manifest.json once + restore preflight and restore exact images for a selected manifest 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 + clean-images remove unretained 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 @@ -25,7 +26,9 @@ from __future__ import annotations import argparse import base64 +import contextlib import datetime as _dt +import fcntl import getpass import hashlib import io @@ -33,27 +36,40 @@ import json import os import re import secrets as _secrets +import stat import socket import subprocess import sys import tarfile import tempfile from dataclasses import dataclass, field -from pathlib import Path +from pathlib import Path, PurePosixPath from typing import Any, Callable, Iterable ROOT = Path(__file__).resolve().parents[2] RELEASE_DIR_NAME = "deploy/release" -MANIFEST_SCHEMA = "lincodex.release-manifest/v1" +MANIFEST_SCHEMA = "lincodex.release-manifest/v2" BUILD_SCHEMA = "lincodex.release-build/v1" EVIDENCE_SCHEMA = "lincodex.release-evidence/v1" +DATA_SCHEMA = "lincodex.release-data/v1" RELEASE_REGISTRY = "lincodex.invalid" +POLICY_SOURCE_ARTIFACT = "backend/internal/domain/policy_demo.go" # Project name used only to render Compose files; nothing is started under it. RENDER_PROJECT = "lincodex-release" # Compose requires IDENTITY_KEY_SECRET and .env.example has none; this value only # lets a render or build go through and is never deployed. RENDER_ONLY_IDENTITY_KEY = "render-only-identity-key-secret-not-for-deployment" CHECKS = ("smoke", "e2e") +DATA_COMPONENTS = ("bank", "policy", "seed") +RELEASE_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}") +DATA_MANIFEST_LIMIT = 1024 * 1024 +DATA_ARTIFACT_LIMIT = 64 +DATA_ARTIFACT_SIZE_LIMIT = 64 * 1024 * 1024 +DATA_TOTAL_SIZE_LIMIT = 256 * 1024 * 1024 +CORE_COMPOSE_FILES = ( + "deploy/docker/docker-compose.yml", + "deploy/docker/docker-compose.release.yml", +) CHECK_SCOPE = { "smoke": ( "deploy/scripts/smoke.sh: Compose startup and health, API routing, PostgreSQL, Redis, and " @@ -260,6 +276,293 @@ def write_json(path: Path, document: dict[str, Any], root: Path = ROOT) -> None: temporary.replace(path) +def validate_release_id(value: str) -> str: + if not RELEASE_ID_PATTERN.fullmatch(value): + raise ReleaseError("Release ID must be 1-64 letters, digits, dots, underscores, or hyphens and start with a letter or digit.") + return value + + +def release_artifact_dir(release_id: str, root: Path = ROOT) -> Path: + validate_release_id(release_id) + base = root / RELEASE_DIR_NAME + target = base / release_id + resolved_root = root.resolve() + for path in (root / "deploy", base, target): + if path.is_symlink(): + raise ReleaseError("Release artifact paths cannot contain symlinks.") + try: + target.resolve(strict=False).relative_to(resolved_root) + except ValueError as error: + raise ReleaseError("Release artifact path escapes the repository.") from error + return target + + +def project_file(path_text: str, root: Path, *, maximum_size: int, label: str) -> Path: + if not isinstance(path_text, str) or not path_text or len(path_text) > 512: + raise ReleaseError(f"{label} path is invalid.") + if "\\" in path_text or "\0" in path_text: + raise ReleaseError(f"{label} path must use relative POSIX separators.") + candidate_name = PurePosixPath(path_text) + if candidate_name.is_absolute() or str(candidate_name) != path_text or any( + part in ("", ".", "..") for part in candidate_name.parts + ): + raise ReleaseError(f"{label} path must be a normalized repository-relative path.") + if any(part == ".git" or part.startswith(".env") for part in candidate_name.parts): + raise ReleaseError(f"{label} cannot read repository metadata or environment files.") + + root_path = root.resolve() + candidate = root_path.joinpath(*candidate_name.parts) + current = root_path + for part in candidate_name.parts: + current = current / part + if current.is_symlink(): + raise ReleaseError(f"{label} cannot follow symlinks: {path_text}.") + try: + resolved = candidate.resolve(strict=True) + resolved.relative_to(root_path) + metadata = resolved.stat() + except (OSError, ValueError) as error: + raise ReleaseError(f"{label} file is missing or outside the repository: {path_text}.") from error + if not stat.S_ISREG(metadata.st_mode): + raise ReleaseError(f"{label} must reference a regular file: {path_text}.") + if metadata.st_size > maximum_size: + raise ReleaseError(f"{label} file exceeds the {maximum_size}-byte limit: {path_text}.") + return resolved + + +def bounded_digest(path: Path, *, maximum_size: int, total_limit: int | None = None) -> tuple[str, int]: + digest = hashlib.sha256() + size = 0 + try: + with path.open("rb") as stream: + while chunk := stream.read(1024 * 1024): + size += len(chunk) + if size > maximum_size or (total_limit is not None and size > total_limit): + raise ReleaseError(f"Data artifact exceeds its size limit: {path.name}.") + digest.update(chunk) + except OSError as error: + raise ReleaseError(f"Could not read data artifact {path.name}.") from error + return "sha256:" + digest.hexdigest(), size + + +def default_data_versions(root: Path = ROOT) -> dict[str, Any]: + result = { + name: { + "status": "unavailable", + "version": None, + "artifacts": [], + "reason": "No accepted versioned release data was supplied.", + } + for name in DATA_COMPONENTS + } + policy_path = root / POLICY_SOURCE_ARTIFACT + if policy_path.is_symlink(): + raise ReleaseError("Demo policy source cannot be a symlink.") + if policy_path.is_file(): + policy_file = project_file( + POLICY_SOURCE_ARTIFACT, + root, + maximum_size=DATA_ARTIFACT_SIZE_LIMIT, + label="Demo policy source", + ) + digest, size = bounded_digest(policy_file, maximum_size=DATA_ARTIFACT_SIZE_LIMIT) + result["policy"] = { + "status": "available", + "version": "1", + "source_kind": "bundled_source", + "artifacts": [{"path": POLICY_SOURCE_ARTIFACT, "sha256": digest, "size_bytes": size}], + } + else: + result["policy"]["reason"] = "No versioned demo policy source is present." + result["bank"]["reason"] = "No accepted assessment bank release snapshot is present." + result["seed"]["reason"] = "No versioned demo seed release snapshot is present." + return result + + +def read_data_versions(path_text: str | None, root: Path = ROOT) -> dict[str, Any]: + if not path_text: + return default_data_versions(root) + path = project_file(path_text, root, maximum_size=DATA_MANIFEST_LIMIT, label="Release data manifest") + try: + with path.open("rb") as stream: + raw = stream.read(DATA_MANIFEST_LIMIT + 1) + if len(raw) > DATA_MANIFEST_LIMIT: + raise ReleaseError(f"Release data manifest exceeds the {DATA_MANIFEST_LIMIT}-byte limit.") + document = json.loads(raw.decode("utf-8")) + except ReleaseError: + raise + except (OSError, UnicodeError, ValueError) as error: + raise ReleaseError("Release data manifest is unreadable or invalid JSON.") from error + if not isinstance(document, dict) or document.get("schema") != DATA_SCHEMA: + raise ReleaseError(f"Release data manifest must use schema {DATA_SCHEMA}.") + if set(document) != {"schema", *DATA_COMPONENTS}: + raise ReleaseError("Release data manifest must contain only bank, policy, and seed entries.") + + result: dict[str, Any] = {} + artifact_count = 0 + total_size = 0 + for name in DATA_COMPONENTS: + entry = document.get(name) + if not isinstance(entry, dict): + raise ReleaseError(f"Release data entry {name} is malformed.") + status = entry.get("status") + if status == "unavailable": + if set(entry) != {"status", "reason"} or not isinstance(entry.get("reason"), str) or not entry["reason"].strip(): + raise ReleaseError(f"Unavailable release data entry {name} needs a reason.") + result[name] = { + "status": "unavailable", + "version": None, + "artifacts": [], + "reason": entry["reason"].strip()[:200], + } + continue + allowed_fields = {"status", "version", "artifacts", "source_kind"} + if status != "available" or set(entry) not in (allowed_fields - {"source_kind"}, allowed_fields): + raise ReleaseError(f"Release data entry {name} must be available with a version and artifacts, or unavailable with a reason.") + source_kind = entry.get("source_kind", "snapshot") + if source_kind not in {"snapshot", "bundled_source"}: + raise ReleaseError(f"Release data source kind for {name} is invalid.") + version = entry.get("version") + if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:+-]{0,127}", version): + raise ReleaseError(f"Release data version for {name} is invalid.") + artifacts = entry.get("artifacts") + if not isinstance(artifacts, list) or not artifacts: + raise ReleaseError(f"Release data entry {name} needs at least one artifact.") + recorded: list[dict[str, Any]] = [] + for artifact in artifacts: + artifact_count += 1 + if artifact_count > DATA_ARTIFACT_LIMIT: + raise ReleaseError(f"Release data manifest exceeds the {DATA_ARTIFACT_LIMIT}-artifact limit.") + if not isinstance(artifact, dict) or set(artifact) != {"path"}: + raise ReleaseError(f"Release data artifact in {name} must contain only a path.") + artifact_path = project_file( + artifact["path"], root, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, label="Release data artifact" + ) + remaining = DATA_TOTAL_SIZE_LIMIT - total_size + if remaining <= 0: + raise ReleaseError(f"Release data artifacts exceed the {DATA_TOTAL_SIZE_LIMIT}-byte total limit.") + digest, size = bounded_digest( + artifact_path, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, total_limit=remaining + ) + total_size += size + recorded.append({"path": artifact["path"], "sha256": digest, "size_bytes": size}) + result[name] = {"status": "available", "version": version, "source_kind": source_kind, "artifacts": recorded} + return result + + +def verify_data_artifacts(data_versions: dict[str, Any], root: Path = ROOT) -> None: + total_size = 0 + artifact_count = 0 + for name in DATA_COMPONENTS: + entry = data_versions.get(name) + if not isinstance(entry, dict): + raise ReleaseError(f"Manifest data entry {name} is malformed.") + if entry.get("status") == "unavailable": + continue + if entry.get("status") != "available" or not isinstance(entry.get("artifacts"), list): + raise ReleaseError(f"Manifest data entry {name} has an unknown status.") + for artifact in entry["artifacts"]: + artifact_count += 1 + if artifact_count > DATA_ARTIFACT_LIMIT or not isinstance(artifact, dict): + raise ReleaseError("Manifest data artifacts exceed their limit or are malformed.") + path = project_file( + artifact.get("path"), root, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, label="Manifest data artifact" + ) + remaining = DATA_TOTAL_SIZE_LIMIT - total_size + if remaining <= 0: + raise ReleaseError(f"Manifest data artifacts exceed the {DATA_TOTAL_SIZE_LIMIT}-byte total limit.") + digest, size = bounded_digest(path, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, total_limit=remaining) + if digest != artifact.get("sha256") or size != artifact.get("size_bytes"): + raise ReleaseError(f"Release data artifact is missing or changed: {artifact.get('path')}.") + total_size += size + + +def write_json_immutable(path: Path, document: dict[str, Any], root: Path = ROOT) -> bool: + """Publish once; return False for an identical rerun without touching the file.""" + findings = forbidden_findings(document, sensitive_values(root)) + if findings: + raise ReleaseError(f"Refusing to write {display(path, root)}: " + "; ".join(findings)) + if path.is_symlink(): + raise ReleaseError("Refusing to publish through a manifest symlink.") + encoded = json.dumps(document, indent=2, sort_keys=True).encode("utf-8") + b"\n" + + def existing_matches() -> bool: + try: + previous = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, ValueError) as error: + raise ReleaseError(f"An unreadable immutable manifest already exists at {display(path, root)}; it was preserved.") from error + if not isinstance(previous, dict): + raise ReleaseError(f"An invalid immutable manifest already exists at {display(path, root)}; it was preserved.") + if comparable(previous) == comparable(document): + return True + raise ReleaseError( + f"Immutable release {document.get('release', {}).get('id')} already exists at {display(path, root)}. " + "Use a new RELEASE_ID for a separate delivery." + ) + + if path.exists(): + existing_matches() + return False + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.{_secrets.token_hex(8)}.tmp") + try: + file_descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(file_descriptor, "wb") as stream: + stream.write(encoded) + stream.flush() + os.fsync(stream.fileno()) + try: + os.link(temporary, path) + except FileExistsError: + existing_matches() + return False + try: + directory_fd = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + except OSError: + pass + return True + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + + +@contextlib.contextmanager +def immutable_release_lock(release_id: str, root: Path = ROOT): + """Serialize image retention and manifest publication for one release ID.""" + validate_release_id(release_id) + release_root = root / RELEASE_DIR_NAME + lock_dir = release_root / ".locks" + for path in (root / "deploy", release_root, lock_dir): + if path.is_symlink(): + raise ReleaseError("Release lock paths cannot contain symlinks.") + lock_dir.mkdir(parents=True, exist_ok=True) + lock_path = lock_dir / f"{release_id}.lock" + flags = os.O_CREAT | os.O_RDWR + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + try: + descriptor = os.open(lock_path, flags, 0o600) + except OSError as error: + raise ReleaseError("Could not open the release publication lock.") from error + try: + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode): + raise ReleaseError("Release publication lock is not a regular file.") + fcntl.flock(descriptor, fcntl.LOCK_EX) + yield + finally: + try: + fcntl.flock(descriptor, fcntl.LOCK_UN) + finally: + os.close(descriptor) + + # --------------------------------------------------------------------------- # Source state @@ -326,6 +629,18 @@ def release_dir(tag: str, root: Path = ROOT) -> Path: return root / RELEASE_DIR_NAME / tag +def release_image_reference(service: str, release_id: str) -> str: + validate_release_id(release_id) + if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", service): + raise ReleaseError(f"Unexpected service name {service!r}.") + return f"{RELEASE_REGISTRY}/release/{service}:{release_id}" + + +def manifest_restore_command(release_id: str) -> str: + validate_release_id(release_id) + return f"make -C deploy release-up RELEASE_MANIFEST=deploy/release/{release_id}/manifest.json" + + def relative(path: Path, root: Path = ROOT) -> str: try: return path.resolve().relative_to(root.resolve()).as_posix() @@ -609,6 +924,62 @@ class Docker: if subprocess.run(args, cwd=root, env=env, check=False).returncode != 0: raise ReleaseError(f"Building {service} failed.") + def tag_image(self, image_id: str, reference: str) -> None: + result = subprocess.run( + [self.binary, "image", "tag", image_id, reference], capture_output=True, check=False, env=docker_env() + ) + if result.returncode != 0: + raise ReleaseError("Could not retain the exact local release image.") + + def compose_restore_config( + self, project: str, env_file: Path, tag: str, override: Path, root: Path = ROOT + ) -> dict[str, Any]: + args = [self.binary, "compose", "--env-file", str(env_file), "-p", project] + for name in (*CORE_COMPOSE_FILES, str(override)): + args += ["-f", str(root / name) if not Path(name).is_absolute() else name] + args += ["config", "--format", "json"] + env = docker_env( + { + "APP_PROJECT": project, + "APP_NETWORK": f"{project}_default", + "LINCODEX_RELEASE_TAG": tag, + } + ) + result = subprocess.run(args, cwd=root, env=env, capture_output=True, check=False) + if result.returncode != 0: + raise ReleaseError("Compose could not render the pinned release configuration.") + try: + return json.loads(result.stdout) + except (UnicodeError, ValueError) as error: + raise ReleaseError("Compose returned an invalid pinned release configuration.") from error + + def compose_restore( + self, + action: str, + project: str, + env_file: Path, + tag: str, + override: Path, + root: Path = ROOT, + ) -> None: + args = [self.binary, "compose", "--env-file", str(env_file), "-p", project] + for name in (*CORE_COMPOSE_FILES, str(override)): + args += ["-f", str(root / name) if not Path(name).is_absolute() else name] + if action == "up": + args += ["up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "180"] + else: + args += ["down"] + env = docker_env( + { + "APP_PROJECT": project, + "APP_NETWORK": f"{project}_default", + "LINCODEX_RELEASE_TAG": tag, + } + ) + result = subprocess.run(args, cwd=root, env=env, capture_output=True, check=False) + if result.returncode != 0: + raise ReleaseError(f"Compose release {action} failed with exit status {result.returncode}.") + def normalize_repository(reference: str) -> str: """Return the repository of an image reference in docker.io long form.""" @@ -662,6 +1033,17 @@ def image_record(info: dict[str, Any] | None, reference: str, built: bool = Fals } +def immutable_image_references(service: Service, image: dict[str, Any], release_id: str) -> tuple[str | None, str | None]: + if not image.get("present") or not image.get("image_id"): + return None, None + if service.dockerfile: + return image["image_id"], release_image_reference(service.name, release_id) + digest = image.get("repo_digest") + if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest): + return None, None + return f"{normalize_repository(service.reference)}@{digest}", None + + # --------------------------------------------------------------------------- # Compose services @@ -1024,7 +1406,19 @@ def base_version(build: dict[str, Any] | None, service: str, key: str) -> str | return None -def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: +def build_manifest( + inputs: Inputs, + generated_at: str, + release_id: str | None = None, + data_versions: dict[str, Any] | None = None, + compose_files: dict[str, str | None] | None = None, + root: Path = ROOT, +) -> dict[str, Any]: + release_id = validate_release_id(release_id or inputs.source.tag) + data_versions = data_versions if data_versions is not None else default_data_versions(root) + compose_files = compose_files if compose_files is not None else { + name: file_digest(root / name) for name in CORE_COMPOSE_FILES + } source = inputs.source build = inputs.build_record files = inputs.files @@ -1033,8 +1427,12 @@ def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: ) components: list[dict[str, Any]] = [] reasons: list[str] = [] + restore_reasons: list[str] = [] for service in inputs.services: image = image_record(inputs.images.get(service.reference), service.reference, built=bool(service.dockerfile)) + image["restore_reference"], image["retention_reference"] = immutable_image_references(service, image, release_id) + if service.group == "core" and image["restore_reference"] is None: + restore_reasons.append(f"Core component {service.name} has no immutable local image reference.") component: dict[str, Any] = { "name": service.name, "group": service.group, @@ -1129,6 +1527,15 @@ def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: for check, problem in sorted(inputs.rejected_checks.items()): reasons.append(f"{check} evidence was not accepted: {problem}") + for name, digest in sorted(compose_files.items()): + if digest is None: + restore_reasons.append(f"Compose file {name} is missing.") + data_states = [data_versions[name]["status"] for name in DATA_COMPONENTS] + product_data_status = "versioned" if all(state == "available" for state in data_states) else ( + "partial" if any(state == "available" for state in data_states) else "unavailable" + ) + restore_command = manifest_restore_command(release_id) + checks = {} for name, document in sorted(inputs.evidence.items()): checks[name] = { @@ -1137,18 +1544,30 @@ def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: "commit": document.get("commit"), "source_fingerprint": document.get("source_fingerprint"), "tool_images": document.get("tool_images", {}), + "image_ids": { + service: evidence.get("image_id") + for service, evidence in sorted((document.get("services") or {}).items()) + }, } return { "schema": MANIFEST_SCHEMA, "generated_at": generated_at, "release": { + "id": release_id, "tag": source.tag, "status": "unverified" if reasons else "verified", "scope": "core", + "product_data_status": product_data_status, "required_checks": list(CHECKS), "reasons": sorted(set(reasons)), }, + "restore": { + "status": "blocked" if restore_reasons else "available", + "scope": "core", + "command": restore_command, + "reasons": sorted(set(restore_reasons)), + }, "source": { "commit": source.commit, "dirty": source.dirty, @@ -1174,6 +1593,8 @@ def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: "playwright": {"package_version": files.get("playwright")}, }, "lockfiles": {name: files.get(name) for name in LOCKFILES}, + "configuration": {"compose_files": dict(sorted(compose_files.items()))}, + "data_versions": data_versions, "checks": checks, "rejected_checks": dict(sorted(inputs.rejected_checks.items())), "components": components, @@ -1186,32 +1607,130 @@ def comparable(document: dict[str, Any] | None) -> dict[str, Any] | None: return {key: value for key, value in document.items() if key != "generated_at"} +def add_restore_problem(manifest: dict[str, Any], problem: str) -> None: + restore = manifest["restore"] + restore["status"] = "blocked" + restore["reasons"] = sorted(set(restore["reasons"] + [problem])) + + +def prepare_manifest_images(manifest: dict[str, Any], docker: Docker) -> None: + """Retain built core image IDs and confirm pulled digests before publication.""" + for component in manifest["components"]: + if component.get("group") != "core": + continue + image = component.get("image") or {} + reference = image.get("restore_reference") + retention_reference = image.get("retention_reference") + image_id = image.get("image_id") + if not image.get("present") or not isinstance(image_id, str) or not reference: + add_restore_problem(manifest, f"Core component {component.get('name')} has no immutable local image reference.") + continue + if component.get("kind") == "built": + if reference != image_id or not retention_reference: + add_restore_problem(manifest, f"Built image {component.get('name')} is not pinned to its image ID.") + continue + existing = docker.inspect_image(retention_reference) + if existing is None: + source = docker.inspect_image(image_id) + if source is None or source.get("Id") != image_id: + add_restore_problem(manifest, f"Exact local image {image_id} for {component.get('name')} is missing.") + continue + docker.tag_image(image_id, retention_reference) + existing = docker.inspect_image(retention_reference) + if existing is None or existing.get("Id") != image_id: + raise ReleaseError(f"Retained image reference for {component.get('name')} does not match {image_id}.") + else: + existing = docker.inspect_image(reference) + if existing is None or existing.get("Id") != image_id: + add_restore_problem(manifest, f"Pulled digest for {component.get('name')} does not resolve to the recorded image ID.") + if manifest["restore"]["reasons"]: + manifest["restore"]["status"] = "blocked" + + +def manifest_file(path_text: str | None, root: Path = ROOT) -> Path: + if not path_text: + return default_manifest(root) + path = Path(path_text) + candidates = [path] if path.is_absolute() else [root / path, root / "deploy" / path] + for candidate in candidates: + if candidate.exists(): + try: + candidate.resolve(strict=True).relative_to(root.resolve()) + except (OSError, ValueError) as error: + raise ReleaseError("Release manifest must be inside the repository.") from error + if candidate.is_symlink(): + raise ReleaseError("Release manifest cannot be a symlink.") + return candidate + return candidates[0] + + +def validate_manifest_location(path: Path, manifest: dict[str, Any], root: Path = ROOT) -> None: + release_info = manifest.get("release") or {} + release_id = release_info.get("id") if isinstance(release_info, dict) else None + try: + expected = release_artifact_dir(release_id, root) / "manifest.json" + actual = path.resolve(strict=True) + expected_path = expected.resolve(strict=False) + except (OSError, ReleaseError, TypeError, ValueError) as error: + raise ReleaseError("Release manifest is not stored under its immutable release ID.") from error + if actual != expected_path: + raise ReleaseError("Release manifest is not stored under its immutable release ID.") + + +def load_manifest(path: Path, root: Path = ROOT) -> dict[str, Any]: + try: + if path.stat().st_size > 4 * 1024 * 1024: + raise ReleaseError("Release manifest exceeds the 4 MiB limit.") + document = json.loads(path.read_text(encoding="utf-8")) + except ReleaseError: + raise + except (OSError, UnicodeError, ValueError) as error: + raise ReleaseError(f"No readable release manifest at {display(path, root)}.") from error + if not isinstance(document, dict): + raise ReleaseError(f"No readable release manifest at {display(path, root)}.") + return document + + 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) + release_id = validate_release_id(args.release_id or inputs.source.tag) + data_versions = read_data_versions(args.data_manifest, root) + compose_files = {name: file_digest(root / name) for name in CORE_COMPOSE_FILES} + manifest = build_manifest(inputs, utc_now(), release_id, data_versions, compose_files, root) + path = release_artifact_dir(release_id, root) / "manifest.json" + with immutable_release_lock(release_id, root): + if path.exists(): + previous = load_manifest(path, root) + if comparable(previous) != comparable(manifest): + raise ReleaseError( + f"Immutable release {release_id} already exists at {display(path, root)}. " + "Use a new RELEASE_ID for a separate delivery." + ) + print(f"Release manifest: {display(path, root)} (unchanged)") + print( + f"Release {release_id}: core {manifest['release']['status']}; " + f"product data {manifest['release']['product_data_status']}; restore {manifest['restore']['status']}" + ) + return 0 + prepare_manifest_images(manifest, docker) + published = write_json_immutable(path, manifest, root) print(f"Release manifest: {display(path, root)}") - print(f"Release {manifest['release']['tag']}: {manifest['release']['status']}") + print( + f"Release {release_id} ({manifest['release']['tag']}): core {manifest['release']['status']}; " + f"product data {manifest['release']['product_data_status']}; restore {manifest['restore']['status']}" + ) for reason in manifest["release"]["reasons"]: print(f" - {reason}") + for reason in manifest["restore"]["reasons"]: + print(f" - restore blocked: {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)) + if not published: + print("The existing manifest was preserved unchanged.") return 0 @@ -1220,7 +1739,7 @@ def command_manifest(args: argparse.Namespace, docker: Docker | None = None, roo def default_manifest(root: Path = ROOT) -> Path: - return release_dir(read_source(root).tag, root) / "manifest.json" + return release_artifact_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]]: @@ -1268,10 +1787,12 @@ def compare_running(manifest: dict[str, Any], running: dict[str, dict[str, Any]] 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.") + path = manifest_file(args.manifest, root) + manifest = load_manifest(path, root) + validate_manifest_location(path, manifest, root) + problems = structure_errors(manifest, root) + if problems: + raise ReleaseError(f"Release manifest at {display(path, root)} is invalid: " + "; ".join(problems)) running = running_services(docker.project_containers(args.project)) ok, lines = compare_running(manifest, running) release_info = manifest.get("release") or {} @@ -1286,38 +1807,270 @@ def command_verify(args: argparse.Namespace, docker: Docker | None = None, root: REQUIRED_KEYS = ( - "schema", "generated_at", "release", "source", "toolchains", "lockfiles", "checks", "rejected_checks", "components" + "schema", + "generated_at", + "release", + "restore", + "source", + "toolchains", + "lockfiles", + "configuration", + "data_versions", + "checks", + "rejected_checks", + "components", ) STATUSES = frozenset({"verified", "not_verified", "missing"}) +SHA256_PATTERN = re.compile(r"sha256:[0-9a-f]{64}") +IMAGE_ID_PATTERN = SHA256_PATTERN -def structure_errors(manifest: dict[str, Any]) -> list[str]: +def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]: + if not isinstance(manifest, dict): + return ["manifest must be a JSON object"] 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") + release = manifest.get("release") + if not isinstance(release, dict): + errors.append("release must be an object") + release = {} + try: + validate_release_id(release.get("id")) + except (ReleaseError, TypeError): + errors.append("release ID is invalid") + if release.get("product_data_status") not in {"versioned", "partial", "unavailable"}: + errors.append("product data status is invalid") + if release.get("status") not in {"verified", "unverified"} or release.get("scope") != "core": + errors.append("release status or scope is invalid") + if release.get("required_checks") != list(CHECKS): + errors.append("required release checks are invalid") + tag = release.get("tag") + if not isinstance(tag, str) or not re.fullmatch(r"[0-9a-f]{12}(-dirty)?", tag): + errors.append("release source tag is invalid") + try: + expected_restore_command = manifest_restore_command(release.get("id")) + except (ReleaseError, TypeError): + expected_restore_command = None + + components = manifest.get("components") + if not isinstance(components, list): + errors.append("components must be a list") + components = [] + checks = manifest.get("checks") + if not isinstance(checks, dict): + errors.append("checks must be an object") + checks = {} + seen: set[str] = set() + core_components: list[dict[str, Any]] = [] + for component in components: + if not isinstance(component, dict): + errors.append("component entry must be an object") + continue + name = component.get("name") + if not isinstance(name, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", name): + errors.append("component name is invalid") + elif name in seen: + errors.append(f"duplicate component {name}") + else: + seen.add(name) + if component.get("group") == "core": + core_components.append(component) + verification = component.get("verification") + if not isinstance(verification, dict): + errors.append(f"component {component.get('name')} verification must be an object") + verification = {} + status = verification.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"): + verified_checks = verification.get("checks", []) + if not isinstance(verified_checks, list): + errors.append(f"component {component.get('name')} checks must be a list") + verified_checks = [] + if status == "verified" and not 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"] + check not in checks for check in verified_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", [])): + image = component.get("image") + if component.get("group") == "missing": + if image is not None: + errors.append(f"missing component {name} must not name an image") + continue + if not isinstance(image, dict): + errors.append(f"component {name} image must be an object") + continue + if image.get("present"): + image_id = image.get("image_id") + if not isinstance(image_id, str) or not IMAGE_ID_PATTERN.fullmatch(image_id): + errors.append(f"component {name} image ID is invalid") + restore_reference = image.get("restore_reference") + if restore_reference is not None and (not isinstance(restore_reference, str) or not restore_reference.strip()): + errors.append(f"component {name} restore reference is invalid") + if status == "verified" and isinstance(image_id, str): + for check in verified_checks: + evidence = checks.get(check) + ids = evidence.get("image_ids") if isinstance(evidence, dict) else None + if not isinstance(ids, dict) or ids.get(name) != image_id: + errors.append(f"verified component {name} does not match the recorded {check} image ID") + if component.get("group") == "core": + if component.get("kind") == "built": + if image.get("restore_reference") != image_id: + errors.append(f"built core component {name} is not pinned to its exact image ID") + try: + expected_retention = release_image_reference(name, release.get("id")) + except (ReleaseError, TypeError): + expected_retention = None + if image.get("retention_reference") != expected_retention: + errors.append(f"built core component {name} has an invalid retention reference") + elif component.get("kind") == "pulled": + digest = image.get("repo_digest") + if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest): + errors.append(f"pulled core component {name} has no repository digest") + else: + try: + expected_reference = f"{normalize_repository(image.get('reference', ''))}@{digest}" + except (AttributeError, TypeError): + expected_reference = None + if image.get("restore_reference") != expected_reference: + errors.append(f"pulled core component {name} is not pinned to its repository digest") + if image.get("retention_reference") is not None: + errors.append(f"pulled core component {name} has an unexpected retention reference") + else: + errors.append(f"core component {name} has an unsupported image kind") + elif image.get("restore_reference") is not None or image.get("retention_reference") is not None: + errors.append(f"component {name} without an image must not have immutable image references") + if not any(item.get("group") == "missing" for item in components if isinstance(item, dict)): errors.append("missing components are not listed") + + restore = manifest.get("restore") + if not isinstance(restore, dict): + errors.append("restore must be an object") + restore = {} + if restore.get("scope") != "core" or restore.get("status") not in {"available", "blocked"}: + errors.append("restore scope or status is invalid") + if ( + not isinstance(restore.get("command"), str) + or restore.get("command") != expected_restore_command + or not isinstance(restore.get("reasons"), list) + or not all(isinstance(reason, str) for reason in restore.get("reasons", [])) + ): + errors.append("restore command or reasons are malformed") + if restore.get("status") == "available": + if restore.get("reasons"): + errors.append("available restore has blocking reasons") + for component in core_components: + image = component.get("image") or {} + if not image.get("present") or not image.get("restore_reference"): + errors.append(f"available restore has no exact image for {component.get('name')}") + elif restore.get("status") == "blocked" and not restore.get("reasons"): + errors.append("blocked restore has no reason") + + config = manifest.get("configuration") + if not isinstance(config, dict) or not isinstance(config.get("compose_files"), dict): + errors.append("Compose file digests are malformed") + else: + files = config["compose_files"] + if set(files) != set(CORE_COMPOSE_FILES): + errors.append("Compose file digest inventory is incomplete") + for name, digest in files.items(): + if digest is not None and (not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest)): + errors.append(f"Compose file digest for {name} is invalid") + + data = manifest.get("data_versions") + if not isinstance(data, dict) or set(data) != set(DATA_COMPONENTS): + errors.append("bank, policy, and seed version entries are required") + else: + states: list[str] = [] + artifact_count = 0 + total_size = 0 + for name in DATA_COMPONENTS: + entry = data[name] + if not isinstance(entry, dict): + errors.append(f"data entry {name} must be an object") + continue + state = entry.get("status") + states.append(state) + if state == "unavailable": + if ( + set(entry) != {"status", "version", "artifacts", "reason"} + or entry.get("version") is not None + or entry.get("artifacts") != [] + or not isinstance(entry.get("reason"), str) + or not entry["reason"].strip() + ): + errors.append(f"unavailable data entry {name} is malformed") + continue + if state != "available": + errors.append(f"data entry {name} status is invalid") + continue + if set(entry) != {"status", "version", "source_kind", "artifacts"}: + errors.append(f"available data entry {name} has unexpected fields") + if entry.get("source_kind") not in {"snapshot", "bundled_source"}: + errors.append(f"data source kind for {name} is invalid") + version = entry.get("version") + if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:+-]{0,127}", version): + errors.append(f"data version for {name} is invalid") + artifacts = entry.get("artifacts") + if not isinstance(artifacts, list) or not artifacts: + errors.append(f"available data entry {name} needs artifacts") + continue + for artifact in artifacts: + artifact_count += 1 + if not isinstance(artifact, dict): + errors.append(f"data artifact in {name} is malformed") + continue + if set(artifact) != {"path", "sha256", "size_bytes"}: + errors.append(f"data artifact in {name} has unexpected fields") + artifact_path = artifact.get("path") + digest = artifact.get("sha256") + size = artifact.get("size_bytes") + if not isinstance(artifact_path, str) or not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest): + errors.append(f"data artifact in {name} has an invalid path or hash") + if not isinstance(size, int) or isinstance(size, bool) or size < 0: + errors.append(f"data artifact in {name} has an invalid size") + else: + if size > DATA_ARTIFACT_SIZE_LIMIT: + errors.append(f"data artifact in {name} exceeds the per-file limit") + total_size += size + if isinstance(artifact_path, str): + try: + project_file( + artifact_path, + root, + maximum_size=DATA_ARTIFACT_SIZE_LIMIT, + label="Manifest data artifact", + ) + except ReleaseError: + errors.append(f"data artifact in {name} has an unsafe or missing path") + if artifact_count > DATA_ARTIFACT_LIMIT or total_size > DATA_TOTAL_SIZE_LIMIT: + errors.append("data artifact inventory exceeds its limit") + expected_data_status = "versioned" if states and all(state == "available" for state in states) else ( + "partial" if any(state == "available" for state in states) else "unavailable" + ) + if release.get("product_data_status") != expected_data_status: + errors.append("product data status does not match the recorded versions") 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) + path = manifest_file(args.manifest, root) try: + load_manifest(path, root) text = path.read_text(encoding="utf-8") manifest = json.loads(text) - except (OSError, ValueError) as error: + except (OSError, UnicodeError, ValueError) as error: raise ReleaseError(f"No readable release manifest at {display(path, root)}.") from error - problems = structure_errors(manifest) + try: + validate_manifest_location(path, manifest, root) + except ReleaseError as error: + return_code_problem = str(error) + else: + return_code_problem = None + problems = structure_errors(manifest, root) + if return_code_problem: + problems.append(return_code_problem) problems += forbidden_findings(text, sensitive_values(root)) problems += [item for item in forbidden_findings(manifest) if item.startswith("configuration key")] if problems: @@ -1329,15 +2082,180 @@ def command_check(args: argparse.Namespace, docker: Docker | None = None, root: return 0 +def check_compose_files(manifest: dict[str, Any], root: Path = ROOT) -> None: + expected = (manifest.get("configuration") or {}).get("compose_files") or {} + for name in CORE_COMPOSE_FILES: + want = expected.get(name) + actual = file_digest(root / name) + if not want or actual != want: + raise ReleaseError(f"Compose file {name} differs from the immutable release manifest.") + + +def restore_images(manifest: dict[str, Any], docker: Docker, root: Path = ROOT) -> dict[str, str]: + release_info = manifest["release"] + release_id = release_info["id"] + source_tag = release_info["tag"] + expected_services = {item.name for item in group_services(docker, next(g for g in GROUPS if g.name == "core"), source_tag, root)} + components = {item["name"]: item for item in manifest["components"] if item.get("group") == "core"} + if set(components) != expected_services: + raise ReleaseError("Core Compose services differ from the immutable release manifest.") + + result: dict[str, str] = {} + to_tag: list[tuple[str, str, str]] = [] + for name, component in sorted(components.items()): + image = component.get("image") or {} + image_id = image.get("image_id") + if not image.get("present") or not isinstance(image_id, str): + raise ReleaseError(f"Core image {name} is missing from the manifest.") + if component.get("kind") == "built": + expected_reference = image_id + retention_reference = release_image_reference(name, release_id) + if image.get("restore_reference") != expected_reference or image.get("retention_reference") != retention_reference: + raise ReleaseError(f"Built image reference for {name} is not the manifest's immutable release reference.") + local = docker.inspect_image(image_id) + if local is None or local.get("Id") != image_id: + raise ReleaseError(f"Exact local image {image_id} for {name} is missing; restore will not rebuild it.") + retained = docker.inspect_image(retention_reference) + if retained is not None and retained.get("Id") != image_id: + raise ReleaseError(f"Retained release reference for {name} points to a different image ID.") + if retained is None: + to_tag.append((image_id, retention_reference, name)) + elif component.get("kind") == "pulled": + digest = image.get("repo_digest") + if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest): + raise ReleaseError(f"Pulled core image {name} has no recorded repository digest.") + expected_reference = f"{normalize_repository(image.get('reference', ''))}@{digest}" + if image.get("restore_reference") != expected_reference: + raise ReleaseError(f"Pulled image reference for {name} is not the recorded repository digest.") + exact = docker.inspect_image(expected_reference) + if exact is None or exact.get("Id") != image_id: + raise ReleaseError(f"Recorded digest for {name} is missing or resolves to a different image ID.") + actual_digest = repo_digest(exact, image.get("reference", "")) + if actual_digest != digest: + raise ReleaseError(f"Recorded digest for {name} does not match its local image metadata.") + else: + raise ReleaseError(f"Core component {name} has an unsupported image kind.") + result[name] = expected_reference + + for image_id, reference, name in to_tag: + docker.tag_image(image_id, reference) + retained = docker.inspect_image(reference) + if retained is None or retained.get("Id") != image_id: + raise ReleaseError(f"Could not retain exact image {image_id} for {name}.") + result[name] = image_id + return result + + +def write_compose_override(directory: Path, images: dict[str, str]) -> Path: + if any(not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", name) for name in images): + raise ReleaseError("Compose override contains an invalid service name.") + lines = ["services:"] if images else ["services: {}"] + for name, reference in sorted(images.items()): + if not isinstance(reference, str) or any(character.isspace() for character in reference): + raise ReleaseError(f"Compose override contains an invalid image reference for {name}.") + lines.extend((f" {name}:", f" image: {json.dumps(reference)}", " pull_policy: never")) + path = directory / "release-restore.yml" + try: + file_descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(file_descriptor, "w", encoding="utf-8") as stream: + stream.write("\n".join(lines) + "\n") + except OSError as error: + raise ReleaseError("Could not create the temporary pinned Compose override.") from error + return path + + +def command_restore(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + docker = docker or Docker() + project = args.project + if not isinstance(project, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,62}", project): + raise ReleaseError("Compose project name is invalid.") + env_file = Path(args.env_file) + if not env_file.is_absolute(): + env_file = root / env_file + if not env_file.is_file(): + raise ReleaseError("The explicit Compose environment file is missing.") + path = manifest_file(args.manifest, root) + manifest = load_manifest(path, root) + validate_manifest_location(path, manifest, root) + problems = structure_errors(manifest, root) + problems += forbidden_findings(manifest) + if problems: + raise ReleaseError(f"Release manifest at {display(path, root)} is invalid: " + "; ".join(sorted(set(problems)))) + + source_tag = manifest["release"]["tag"] + if args.action == "down": + images: dict[str, str] = {} + else: + if manifest["restore"]["status"] != "available": + reasons = "; ".join(manifest["restore"]["reasons"]) + raise ReleaseError("Manifest restore is blocked" + (f": {reasons}" if reasons else ".")) + check_compose_files(manifest, root) + verify_data_artifacts(manifest["data_versions"], root) + images = restore_images(manifest, docker, root) + + with tempfile.TemporaryDirectory(prefix="lincodex-release-") as temporary: + override = write_compose_override(Path(temporary), images) + if args.action == "up": + configuration = docker.compose_restore_config(project, env_file, source_tag, override, root) + actual = configuration.get("services") or {} + for name, reference in images.items(): + if (actual.get(name) or {}).get("image") != reference: + raise ReleaseError(f"Compose did not retain the pinned image reference for {name}.") + docker.compose_restore(args.action, project, env_file, source_tag, override, root) + + if args.action == "up": + running = running_services(docker.project_containers(project)) + matches, lines = compare_running(manifest, running) + if not matches: + raise ReleaseError("Compose started, but running images do not match the manifest: " + "; ".join(lines)) + print(f"Restored {display(path, root)} in project {project} using recorded image IDs.") + if manifest["release"]["product_data_status"] != "versioned": + print(f"Product data status: {manifest['release']['product_data_status']}; this is not a full MVP readiness result.") + else: + print(f"Stopped release project {project}.") + return 0 + + +def retained_image_references(root: Path = ROOT) -> set[str]: + release_root = root / RELEASE_DIR_NAME + if release_root.is_symlink(): + raise ReleaseError("Release artifact directory cannot be a symlink.") + retained: set[str] = set() + if not release_root.is_dir(): + return retained + for path in sorted(release_root.glob("*/manifest.json")): + if path.is_symlink(): + raise ReleaseError(f"Cannot clean images while an immutable manifest is a symlink: {display(path, root)}.") + manifest = load_manifest(path, root) + components = manifest.get("components") + if not isinstance(components, list): + raise ReleaseError(f"Cannot clean images; {display(path, root)} has no component inventory.") + for component in components: + if not isinstance(component, dict): + raise ReleaseError(f"Cannot clean images; {display(path, root)} has a malformed component.") + image = component.get("image") + if not isinstance(image, dict): + continue + for reference in (image.get("reference"), image.get("retention_reference")): + if isinstance(reference, str) and reference.startswith(f"{RELEASE_REGISTRY}/"): + retained.add(reference) + return retained + + def command_clean_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: - """Remove every local release image; nothing else is touched.""" + """Remove local release references that no immutable manifest retains.""" docker = docker or Docker() listing = run([docker.binary, "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"], env=docker_env()) + retained = retained_image_references(root) references = sorted( - {line for line in listing.decode().splitlines() if line.startswith(f"{RELEASE_REGISTRY}/")} + { + line + for line in listing.decode().splitlines() + if line.startswith(f"{RELEASE_REGISTRY}/") and line not in retained + } ) if not references: - print("No release images to remove.") + print("No unretained release images to remove.") return 0 run([docker.binary, "image", "rm", *references], env=docker_env()) for reference in references: @@ -1368,7 +2286,16 @@ def parser() -> argparse.ArgumentParser: 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) + manifest = commands.add_parser("manifest") + manifest.add_argument("--release-id") + manifest.add_argument("--data-manifest") + manifest.set_defaults(handler=command_manifest) + restore = commands.add_parser("restore") + restore.add_argument("--action", choices=("up", "down"), required=True) + restore.add_argument("--project", required=True) + restore.add_argument("--env-file", required=True) + restore.add_argument("--manifest") + restore.set_defaults(handler=command_restore) verify = commands.add_parser("verify") verify.add_argument("--project", required=True) verify.add_argument("--manifest") diff --git a/deploy/scripts/test_release_manifest.py b/deploy/scripts/test_release_manifest.py index ea194d9..108fbdf 100644 --- a/deploy/scripts/test_release_manifest.py +++ b/deploy/scripts/test_release_manifest.py @@ -9,6 +9,7 @@ image fails make -C deploy check. from __future__ import annotations import importlib.util +import hashlib import json import sys import unittest @@ -27,6 +28,16 @@ COMMIT = "0123456789abcdef0123456789abcdef01234567" FAKE_PASSWORD = "fake-password-7f3c9a" +def fake_id(char: str) -> str: + return "sha256:" + char * 64 + + +BACKEND_ID = fake_id("b") +FRONTEND_ID = fake_id("f") +POSTGRES_ID = fake_id("e") +ML_ID = fake_id("c") + + def image(image_id: str, *, env: list[str] | None = None, digests: list[str] | None = None) -> dict: return { "Id": image_id, @@ -67,12 +78,12 @@ def evidence_doc(check: str, source, ids: dict) -> dict: } -CURRENT_IDS = {"backend": "sha256:b1", "frontend": "sha256:f1", "postgres": "sha256:e1"} +CURRENT_IDS = {"backend": BACKEND_ID, "frontend": FRONTEND_ID, "postgres": POSTGRES_ID} def all_files() -> dict: - files = {name: "sha256:00" for name in release.LOCKFILES} - files.update({"backend/Dockerfile": "sha256:01", "frontend/Dockerfile": "sha256:02", "ml/Dockerfile": "sha256:03"}) + files = {name: fake_id("0") for name in release.LOCKFILES} + files.update({"backend/Dockerfile": fake_id("1"), "frontend/Dockerfile": fake_id("2"), "ml/Dockerfile": fake_id("3")}) files.update({".node-version": "26.10.0", ".python-version": "3.14.8"}) return files @@ -91,12 +102,12 @@ def inputs( source = release.Source(COMMIT, dirty, "git-tree:" + "ab" * 20 if dirty else None) tag = source.tag images = { - f"lincodex.invalid/backend:{tag}": image("sha256:b1"), - f"lincodex.invalid/frontend:{tag}": image("sha256:f1", env=["NGINX_VERSION=1.29.0"]), + f"lincodex.invalid/backend:{tag}": image(BACKEND_ID), + f"lincodex.invalid/frontend:{tag}": image(FRONTEND_ID, env=["NGINX_VERSION=1.29.0"]), "postgres:alpine": image( - "sha256:e1", env=["PG_VERSION=18.6"], digests=["postgres@sha256:e1"] if postgres_digests is None else postgres_digests + POSTGRES_ID, env=["PG_VERSION=18.6"], digests=[f"postgres@{POSTGRES_ID}"] if postgres_digests is None else postgres_digests ), - f"lincodex.invalid/ml:{tag}": image("sha256:c1", env=["PYTHON_VERSION=3.14.8"]), + f"lincodex.invalid/ml:{tag}": image(ML_ID, env=["PYTHON_VERSION=3.14.8"]), "prom/prometheus:latest": None, } build = { @@ -105,21 +116,21 @@ def inputs( "source_fingerprint": source.fingerprint, "services": { "backend": { - "image_id": "sha256:b1", - "build_args": {"GO_IMAGE": "golang:1.26.8-alpine@sha256:g1"}, + "image_id": BACKEND_ID, + "build_args": {"GO_IMAGE": f"golang:1.26.8-alpine@{fake_id('a')}"}, "base_images": [ - {"arg": "GO_IMAGE", "reference": "golang:1.26.8-alpine", "digest": "sha256:g1", "versions": {"GOLANG_VERSION": "1.26.8"}} + {"arg": "GO_IMAGE", "reference": "golang:1.26.8-alpine", "digest": fake_id("a"), "versions": {"GOLANG_VERSION": "1.26.8"}} ], }, "frontend": { - "image_id": "sha256:f1", + "image_id": FRONTEND_ID, "build_args": {}, - "base_images": [{"arg": "NODE_IMAGE", "reference": "node:alpine", "digest": "sha256:n1", "versions": {"NODE_VERSION": node_version}}], + "base_images": [{"arg": "NODE_IMAGE", "reference": "node:alpine", "digest": fake_id("d"), "versions": {"NODE_VERSION": node_version}}], }, "ml": { - "image_id": "sha256:c1", + "image_id": ML_ID, "build_args": {}, - "base_images": [{"arg": "PYTHON_IMAGE", "reference": "python:alpine", "digest": "sha256:y1", "versions": {"PYTHON_VERSION": python_version}}], + "base_images": [{"arg": "PYTHON_IMAGE", "reference": "python:alpine", "digest": fake_id("9"), "versions": {"PYTHON_VERSION": python_version}}], }, }, } @@ -203,16 +214,16 @@ class ManifestTest(unittest.TestCase): manifest = release.build_manifest(inputs(), "2026-10-06T00:00:00Z") self.assertEqual(manifest["release"]["status"], "verified", manifest["release"]["reasons"]) self.assertEqual(component(manifest, "backend")["verification"], {"status": "verified", "checks": ["e2e", "smoke"]}) - self.assertEqual(component(manifest, "postgres")["image"]["repo_digest"], "sha256:e1") + self.assertEqual(component(manifest, "postgres")["image"]["repo_digest"], POSTGRES_ID) self.assertEqual(component(manifest, "postgres")["image"]["versions"], {"PG_VERSION": "18.6"}) self.assertEqual(manifest["toolchains"]["go"]["binary"], "go1.26.8") self.assertEqual(manifest["toolchains"]["go"]["build_image_version"], "1.26.8") self.assertTrue(manifest["toolchains"]["node"]["matches_version_file"]) - self.assertEqual(component(manifest, "postgres")["image"]["repo_digests"], ["postgres@sha256:e1"]) + self.assertEqual(component(manifest, "postgres")["image"]["repo_digests"], [f"postgres@{POSTGRES_ID}"]) self.assertEqual(release.structure_errors(manifest), []) def test_built_images_do_not_inherit_base_labels_as_versions(self) -> None: - info = image("sha256:f1", env=["NGINX_VERSION=1.29.0"], digests=["x@sha256:f1"]) + info = image(FRONTEND_ID, env=["NGINX_VERSION=1.29.0"], digests=[f"x@{FRONTEND_ID}"]) info["Config"]["Labels"]["org.opencontainers.image.version"] = "base-1.0" self.assertEqual(release.image_record(info, "x", built=True)["versions"], {"NGINX_VERSION": "1.29.0"}) self.assertIsNone(release.image_record(info, "x", built=True)["repo_digest"]) @@ -230,7 +241,7 @@ class ManifestTest(unittest.TestCase): self.assertIsNone(component(manifest, name)["image"]) def test_evidence_for_other_images_does_not_verify(self) -> None: - manifest = release.build_manifest(inputs(evidence_ids={"backend": "sha256:0d"}), "t") + manifest = release.build_manifest(inputs(evidence_ids={"backend": fake_id("4")}), "t") self.assertEqual(component(manifest, "backend")["verification"]["status"], "not_verified") self.assertEqual(component(manifest, "frontend")["verification"]["status"], "not_verified") self.assertEqual(manifest["release"]["status"], "unverified") @@ -327,13 +338,24 @@ class ScannerTest(unittest.TestCase): class ReferenceTest(unittest.TestCase): def test_repo_digest_matches_normalized_repository(self) -> None: - info = {"RepoDigests": ["other@sha256:1", "postgres@sha256:2"]} - self.assertEqual(release.repo_digest(info, "postgres:alpine"), "sha256:2") - self.assertEqual(release.repo_digest(info, "docker.io/library/postgres:alpine"), "sha256:2") - info = {"RepoDigests": ["gcr.io/distroless/static-debian12@sha256:3"]} - self.assertEqual(release.repo_digest(info, "gcr.io/distroless/static-debian12:nonroot"), "sha256:3") + info = {"RepoDigests": [f"other@{fake_id('1')}", f"postgres@{fake_id('2')}"]} + self.assertEqual(release.repo_digest(info, "postgres:alpine"), fake_id("2")) + self.assertEqual(release.repo_digest(info, "docker.io/library/postgres:alpine"), fake_id("2")) + info = {"RepoDigests": [f"gcr.io/distroless/static-debian12@{fake_id('3')}"]} + self.assertEqual(release.repo_digest(info, "gcr.io/distroless/static-debian12:nonroot"), fake_id("3")) self.assertIsNone(release.repo_digest({"RepoDigests": []}, "redis:alpine")) + def test_manifest_rejects_short_image_ids_and_repository_digests(self) -> None: + manifest = release.build_manifest(inputs(), "t") + component(manifest, "backend")["image"]["image_id"] = "sha256:b1" + errors = release.structure_errors(manifest) + self.assertIn("component backend image ID is invalid", errors) + + manifest = release.build_manifest(inputs(), "t") + component(manifest, "postgres")["image"]["repo_digest"] = "sha256:e1" + errors = release.structure_errors(manifest) + self.assertTrue(any("pulled core component postgres has no repository digest" in error for error in errors), errors) + def test_release_tag_is_validated_before_it_becomes_a_path(self) -> None: with self.assertRaises(release.ReleaseError): release.release_dir("../../etc") @@ -404,7 +426,7 @@ class ReleaseRequirementsTest(unittest.TestCase): def test_e2e_on_other_images_does_not_verify_the_release(self) -> None: data = inputs() - data.evidence["e2e"] = evidence_doc("e2e", data.source, {**CURRENT_IDS, "backend": "sha256:0d"}) + data.evidence["e2e"] = evidence_doc("e2e", data.source, {**CURRENT_IDS, "backend": fake_id("4")}) manifest = release.build_manifest(data, "t") self.assertEqual(manifest["release"]["status"], "unverified") self.assertEqual(component(manifest, "backend")["verification"]["checks"], ["smoke"]) @@ -449,7 +471,7 @@ class FakeDocker: def inspect_image(self, reference): base = reference.split(":")[0] - return image("sha256:" + "1" * 8, digests=[f"{base}@sha256:{'2' * 8}"]) + return image(fake_id("1"), digests=[f"{base}@{fake_id('2')}"]) def pull(self, reference): raise AssertionError("no pull expected") @@ -500,7 +522,7 @@ class BuildStabilityTest(unittest.TestCase): self.assertIsNone(error) self.assertTrue(written) backend_args = dict(docker.built)["backend"] - self.assertEqual(backend_args["GO_IMAGE"], "golang:1.26.8-alpine@sha256:" + "2" * 8) + self.assertEqual(backend_args["GO_IMAGE"], f"golang:1.26.8-alpine@{fake_id('2')}") class FingerprintTest(unittest.TestCase): @@ -576,9 +598,9 @@ class VerifyTest(unittest.TestCase): def test_matching_project_passes(self) -> None: tag = release.Source(COMMIT, False, None).tag running = { - "backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": "sha256:b1"}, - "frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": "sha256:f1"}, - "postgres": {"reference": "postgres:alpine", "image_id": "sha256:e1"}, + "backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": BACKEND_ID}, + "frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": FRONTEND_ID}, + "postgres": {"reference": "postgres:alpine", "image_id": POSTGRES_ID}, } ok, lines = release.compare_running(self.manifest(), running) self.assertTrue(ok, lines) @@ -586,9 +608,9 @@ class VerifyTest(unittest.TestCase): def test_changed_digest_missing_or_unknown_service_fails(self) -> None: tag = release.Source(COMMIT, False, None).tag running = { - "backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": "sha256:other"}, - "frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": "sha256:f1"}, - "extra": {"reference": "busybox:latest", "image_id": "sha256:x"}, + "backend": {"reference": f"lincodex.invalid/backend:{tag}", "image_id": fake_id("8")}, + "frontend": {"reference": f"lincodex.invalid/frontend:{tag}", "image_id": FRONTEND_ID}, + "extra": {"reference": "busybox:latest", "image_id": fake_id("7")}, } ok, lines = release.compare_running(self.manifest(), running) self.assertFalse(ok) @@ -600,7 +622,7 @@ class VerifyTest(unittest.TestCase): def test_running_services_skip_one_off_and_stopped_containers(self) -> None: def container(service: str, running: bool = True, oneoff: str = "False") -> dict: return { - "Image": f"sha256:{service}", + "Image": fake_id(service), "Config": {"Image": f"{service}:x", "Labels": {"com.docker.compose.service": service, "com.docker.compose.oneoff": oneoff}}, "State": {"Running": running}, } @@ -609,5 +631,340 @@ class VerifyTest(unittest.TestCase): self.assertEqual(sorted(found), ["a"]) +class ImmutableReleaseTest(unittest.TestCase): + def test_release_ids_are_bounded_slugs(self) -> None: + for release_id in ("..", "../outside", "a/b", " space", "a" * 65): + with self.subTest(release_id=release_id), self.assertRaises(release.ReleaseError): + release.release_artifact_dir(release_id, ROOT) + self.assertEqual(release.release_artifact_dir("stage-2.1", ROOT).name, "stage-2.1") + + def test_atomic_publication_preserves_bytes_and_mtime_on_idempotent_rerun(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root / "deploy/release/stage-one/manifest.json" + document = {"release": {"id": "stage-one"}, "generated_at": "first"} + self.assertTrue(release.write_json_immutable(path, document, root)) + original = path.read_bytes() + original_mtime = path.stat().st_mtime_ns + rerun = {**document, "generated_at": "later"} + self.assertFalse(release.write_json_immutable(path, rerun, root)) + self.assertEqual(path.read_bytes(), original) + self.assertEqual(path.stat().st_mtime_ns, original_mtime) + with self.assertRaises(release.ReleaseError): + release.write_json_immutable(path, {"release": {"id": "stage-one", "data": 2}}, root) + self.assertEqual(path.read_bytes(), original) + + def test_concurrent_create_if_absent_never_replaces_the_winner(self) -> None: + import tempfile + import threading + from concurrent.futures import ThreadPoolExecutor + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root / "deploy/release/stage-one/manifest.json" + documents = ( + {"release": {"id": "stage-one", "source": "first"}}, + {"release": {"id": "stage-one", "source": "second"}}, + ) + barrier = threading.Barrier(2) + + def publish(document: dict) -> str: + barrier.wait() + try: + return "created" if release.write_json_immutable(path, document, root) else "same" + except release.ReleaseError: + return "collision" + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(publish, documents)) + self.assertCountEqual(results, ["created", "collision"]) + self.assertIn(json.loads(path.read_text(encoding="utf-8")), documents) + + def test_command_reread_is_unchanged_and_changed_data_needs_a_new_id(self) -> None: + import tempfile + from argparse import Namespace + from unittest import mock + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + descriptor = root / "data/release.json" + descriptor.parent.mkdir() + + def write_descriptor(reason: str) -> None: + document = { + "schema": release.DATA_SCHEMA, + **{ + name: {"status": "unavailable", "reason": reason} + for name in release.DATA_COMPONENTS + }, + } + descriptor.write_text(json.dumps(document), encoding="utf-8") + + data = inputs() + args = Namespace(release_id="stage-one", data_manifest="data/release.json") + write_descriptor("No accepted snapshot.") + with mock.patch.object(release, "collect_inputs", return_value=data), mock.patch.object( + release, "prepare_manifest_images" + ): + self.assertEqual(release.command_manifest(args, object(), root), 0) + path = root / "deploy/release/stage-one/manifest.json" + original = path.read_bytes() + mtime = path.stat().st_mtime_ns + self.assertEqual(release.command_manifest(args, object(), root), 0) + self.assertEqual(path.read_bytes(), original) + self.assertEqual(path.stat().st_mtime_ns, mtime) + write_descriptor("A newer seed was supplied.") + with self.assertRaises(release.ReleaseError): + release.command_manifest(args, object(), root) + args.release_id = "stage-two" + self.assertEqual(release.command_manifest(args, object(), root), 0) + self.assertEqual(path.read_bytes(), original) + + +class ReleaseDataTest(unittest.TestCase): + def test_default_manifest_records_source_policy_and_missing_bank_seed(self) -> None: + manifest = release.build_manifest(inputs(), "t") + versions = manifest["data_versions"] + self.assertEqual(versions["policy"]["version"], "1") + self.assertEqual(versions["policy"]["source_kind"], "bundled_source") + self.assertEqual(versions["policy"]["artifacts"][0]["path"], release.POLICY_SOURCE_ARTIFACT) + self.assertEqual(versions["bank"]["status"], "unavailable") + self.assertEqual(versions["seed"]["status"], "unavailable") + self.assertEqual(manifest["release"]["product_data_status"], "partial") + + def test_versioned_data_inputs_are_hashed_and_restore_rejects_tampering(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + artifact = root / "data/policy.json" + artifact.parent.mkdir() + artifact.write_text('{"policy":"v1"}\n', encoding="utf-8") + descriptor = { + "schema": release.DATA_SCHEMA, + **{ + name: {"status": "available", "version": f"{name}-v1", "artifacts": [{"path": "data/policy.json"}]} + for name in release.DATA_COMPONENTS + }, + } + source = root / "data/release.json" + source.write_text(json.dumps(descriptor), encoding="utf-8") + versions = release.read_data_versions("data/release.json", root) + self.assertEqual(versions["policy"]["source_kind"], "snapshot") + self.assertEqual(versions["policy"]["artifacts"][0]["sha256"], "sha256:" + hashlib.sha256(artifact.read_bytes()).hexdigest()) + release.verify_data_artifacts(versions, root) + artifact.write_text('{"policy":"changed"}\n', encoding="utf-8") + with self.assertRaisesRegex(release.ReleaseError, "missing or changed"): + release.verify_data_artifacts(versions, root) + artifact.unlink() + with self.assertRaises(release.ReleaseError): + release.verify_data_artifacts(versions, root) + + def test_data_inputs_reject_traversal_and_environment_paths(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for path in ("../outside.json", ".env", "backend/.env.local"): + with self.subTest(path=path), self.assertRaises(release.ReleaseError): + release.project_file(path, root, maximum_size=1024, label="test") + + def test_verified_component_must_match_each_check_fake_id(self) -> None: + manifest = release.build_manifest(inputs(), "t") + component(manifest, "backend")["image"]["image_id"] = fake_id("6") + errors = release.structure_errors(manifest) + self.assertTrue(any("does not match the recorded smoke image ID" in error for error in errors), errors) + + +class RestoreImageTest(unittest.TestCase): + class Docker: + def __init__(self, manifest: dict) -> None: + self.manifest = manifest + self.lookups: list[str] = [] + self.restore_config_calls = 0 + self.restore_actions: list[str] = [] + self.images: dict[str, dict] = {} + for item in manifest["components"]: + image_info = item.get("image") + if not item.get("present") and not isinstance(image_info, dict): + continue + if not isinstance(image_info, dict) or not image_info.get("present"): + continue + image_id = image_info["image_id"] + metadata = image(image_id, digests=image_info.get("repo_digests", [])) + self.images[image_id] = metadata + for reference in (image_info.get("restore_reference"), image_info.get("retention_reference")): + if reference: + self.images[reference] = metadata + if item["name"] == "backend": + self.images[image_info["reference"]] = image(fake_id("0")) + + def compose_config(self, files, tag, root=ROOT): + return { + "services": { + "backend": {"image": f"lincodex.invalid/backend:{tag}", "build": {"context": str(root / "backend"), "dockerfile": "Dockerfile"}}, + "frontend": {"image": f"lincodex.invalid/frontend:{tag}", "build": {"context": str(root / "frontend"), "dockerfile": "Dockerfile"}}, + "postgres": {"image": "postgres:alpine"}, + } + } + + def inspect_image(self, reference: str): + self.lookups.append(reference) + return self.images.get(reference) + + def tag_image(self, image_id: str, reference: str) -> None: + self.images[reference] = self.images[image_id] + + def compose_restore_config(self, project, env_file, tag, override, root=ROOT): + self.restore_config_calls += 1 + return { + "services": { + item["name"]: {"image": item["image"]["restore_reference"]} + for item in self.manifest["components"] + if item.get("group") == "core" + } + } + + def compose_restore(self, action, project, env_file, tag, override, root=ROOT): + self.restore_actions.append(action) + + def project_containers(self, project): + return [ + { + "Image": item["image"]["image_id"], + "Config": { + "Image": item["image"]["restore_reference"], + "Labels": {"com.docker.compose.service": item["name"]}, + }, + "State": {"Running": True}, + } + for item in self.manifest["components"] + if item.get("group") == "core" + ] + + def manifest(self) -> dict: + return release.build_manifest(inputs(), "t", release_id="stage-restore") + + def write_restore_fixture(self, root: Path) -> tuple[Path, Path, dict]: + for name in release.CORE_COMPOSE_FILES: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"# {Path(name).name}\n", encoding="utf-8") + artifact = root / "data/state.json" + artifact.parent.mkdir(parents=True, exist_ok=True) + artifact.write_text('{"release":"v1"}\n', encoding="utf-8") + descriptor = { + "schema": release.DATA_SCHEMA, + **{ + name: {"status": "available", "version": f"{name}-v1", "artifacts": [{"path": "data/state.json"}]} + for name in release.DATA_COMPONENTS + }, + } + data_source = root / "data/release.json" + data_source.write_text(json.dumps(descriptor), encoding="utf-8") + data_versions = release.read_data_versions("data/release.json", root) + compose_files = {name: release.file_digest(root / name) for name in release.CORE_COMPOSE_FILES} + manifest = release.build_manifest( + inputs(), + "2026-10-07T00:00:00Z", + "restore-case", + data_versions, + compose_files, + root, + ) + manifest_path = root / "deploy/release/restore-case/manifest.json" + manifest_path.parent.mkdir(parents=True) + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + env_file = root / "restore.env" + env_file.write_text("SYNTHETIC=1\n", encoding="utf-8") + return manifest_path, env_file, manifest + + def restore_args(self, manifest_path: Path, env_file: Path): + from argparse import Namespace + + return Namespace( + action="up", + project="release-restore-test", + env_file=str(env_file), + manifest=str(manifest_path), + ) + + def test_restore_uses_image_ids_and_digest_references_not_moving_tags(self) -> None: + manifest = self.manifest() + docker = self.Docker(manifest) + resolved = release.restore_images(manifest, docker, ROOT) + self.assertEqual(resolved["backend"], BACKEND_ID) + self.assertEqual(resolved["frontend"], FRONTEND_ID) + self.assertEqual(resolved["postgres"], f"docker.io/library/postgres@{POSTGRES_ID}") + self.assertNotIn(component(manifest, "backend")["image"]["reference"], docker.lookups) + + def test_missing_exact_image_and_digest_mismatch_fail_before_compose(self) -> None: + manifest = self.manifest() + docker = self.Docker(manifest) + docker.images.pop(BACKEND_ID) + with self.assertRaisesRegex(release.ReleaseError, "Exact local image"): + release.restore_images(manifest, docker, ROOT) + + manifest = self.manifest() + docker = self.Docker(manifest) + docker.images[component(manifest, "postgres")["image"]["restore_reference"]] = image( + fake_id("5"), digests=[f"postgres@{POSTGRES_ID}"] + ) + with self.assertRaisesRegex(release.ReleaseError, "different image ID"): + release.restore_images(manifest, docker, ROOT) + + def test_compose_override_uses_exact_ids_and_mode_0600(self) -> None: + import os + import tempfile + + with tempfile.TemporaryDirectory() as directory: + override = release.write_compose_override(Path(directory), {"backend": fake_id("a")}) + self.assertIn('image: "sha256:' + "a" * 64, override.read_text(encoding="utf-8")) + self.assertIn("pull_policy: never", override.read_text(encoding="utf-8")) + self.assertEqual(os.stat(override).st_mode & 0o777, 0o600) + down_directory = Path(directory) / "down" + down_directory.mkdir() + down_override = release.write_compose_override(down_directory, {}) + self.assertEqual(down_override.read_text(encoding="utf-8"), "services: {}\n") + + def test_tampered_data_and_component_mismatch_fail_before_compose_start(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + manifest_path, env_file, manifest = self.write_restore_fixture(root) + artifact = root / "data/state.json" + artifact.write_text('{"release":"changed"}\n', encoding="utf-8") + docker = self.Docker(manifest) + with self.assertRaisesRegex(release.ReleaseError, "missing or changed"): + release.command_restore(self.restore_args(manifest_path, env_file), docker, root) + self.assertEqual(docker.restore_config_calls, 0) + self.assertEqual(docker.restore_actions, []) + + artifact.write_text('{"release":"v1"}\n', encoding="utf-8") + component(manifest, "backend")["image"]["image_id"] = fake_id("6") + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + docker = self.Docker(manifest) + with self.assertRaisesRegex(release.ReleaseError, "verified component backend"): + release.command_restore(self.restore_args(manifest_path, env_file), docker, root) + self.assertEqual(docker.restore_config_calls, 0) + self.assertEqual(docker.restore_actions, []) + + def test_missing_exact_image_fails_before_compose_start(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + manifest_path, env_file, manifest = self.write_restore_fixture(root) + docker = self.Docker(manifest) + docker.images.pop(BACKEND_ID) + with self.assertRaisesRegex(release.ReleaseError, "Exact local image"): + release.command_restore(self.restore_args(manifest_path, env_file), docker, root) + self.assertEqual(docker.restore_config_calls, 0) + self.assertEqual(docker.restore_actions, []) + + if __name__ == "__main__": unittest.main() diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index cc3891b..2426c13 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -461,6 +461,10 @@ Referencing a version (planned): tables that record a decision built under a pol Test fixtures use their own values. Since `product` is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy. +## Release artifacts and restoration + +The local release manifest separates core image verification from product data availability. It records immutable release IDs, source and Compose file hashes, exact built image IDs, registry digests for pulled images, and bounded hashes for versioned data artifacts. Restoration checks these references and hashes before Compose starts and never resolves a moving tag again. The bundled demo policy source is version 1, but that does not establish which policy row is active in PostgreSQL. The assessment bank and demo seed remain unavailable until accepted snapshots exist, so `product_data_status` is partial. Named Compose volumes persist across a release restart, but the manifest is not a database backup or data snapshot. See [DEPLOY.md](DEPLOY.md#release-manifest) for the commands and manifest schema. + ## Repository map and package purpose ```text diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 82162f8..d967b37 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -540,36 +540,41 @@ The backend builds with Go 1.26.8; its runtime image is selected in backend/Dock ## Release manifest -A release manifest records what a verified local release consists of: the commit, the toolchain versions, the lockfile hashes, the image of every service with its actual digest, and which components a check really ran. Moving `latest` and `alpine` tags stay in Compose and in the Dockerfiles by agreement; the manifest pins what they resolved to at release time. The interface is `make -C deploy release-manifest`; the other `release-*` targets prepare its inputs and check its result: +A release manifest records the source, toolchains, lockfile hashes, Compose file hashes, image IDs and digests, and versioned data inputs for one local delivery. Compose may keep moving `latest` and `alpine` tags; restoring a release uses the image IDs or repository digests recorded in its manifest, never a fresh lookup of those tags. The default release ID is the commit-based tag. Use a short `RELEASE_ID` when the same source has more than one delivery or when its data or stage changes: make -C deploy release-build make -C deploy release-smoke make -C deploy release-e2e - make -C deploy release-manifest - make -C deploy release-manifest-check + make -C deploy release-manifest RELEASE_ID=demo-stage-1 + make -C deploy release-manifest-check RELEASE_ID=demo-stage-1 - `release-build` builds `backend`, `frontend`, and `ml` from their Dockerfiles and lockfiles through Compose and tags them `lincodex.invalid/:`. The `.invalid` domain never resolves, and the release overlays set `pull_policy: never`, so a missing release image is never pulled from a registry. Each Dockerfile takes its base images as `*_IMAGE` build arguments whose defaults are the agreed tags; the target resolves each base to its repository digest in the local image store and builds with `@`. A base image used through `COPY --from` or `RUN --mount=from` that is not an earlier stage is refused, because it could not be pinned. Base and core service images are pulled only when missing locally; `RELEASE_PULL=always` refreshes every tag first. The target reads the source state again after the build and writes `build.json` (build arguments, base digests, image IDs) only if the commit and the working tree did not change during the build. - `release-smoke` and `release-e2e` run `deploy/scripts/smoke.sh` and `deploy/scripts/e2e.sh` with `LINCODEX_RELEASE_TAG`, which only these targets set: the stack starts from the release images with `--no-build --pull never`, and only after every check passes does the script write `evidence-smoke.json` or `evidence-e2e.json` with the release tag, commit, working tree fingerprint, and the image IDs of the running containers. A failed run writes nothing. Evidence written after the checks passed stays even if the stack cleanup fails afterwards; the script still exits with an error then. -- `release-manifest` reads only local images, the build record, and the evidence; it pulls nothing. A missing image is listed as not present. Evidence or a build record that is malformed or was recorded for another tag, commit, or working tree state is not used; the manifest lists the rejected evidence under `rejected_checks`. -- `release-manifest-check` checks the structure of the manifest and scans it for secrets and machine data. -- `release-up` and `release-down` run the core stack from the release images with `ENV_FILE` and `APP_PROJECT`, without building or pulling. `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=` compares every running container of that Compose project with the manifest of the current tag, or with `RELEASE_MANIFEST=`, by image ID. It prints the release status and exits with status 1 on a different digest, a missing service, or a service the manifest does not list. -- `release-clean` removes the local `lincodex.invalid/*` images and keeps the files in `deploy/release/`. +- `release-manifest` reads local images, the build record, evidence, and optionally a data descriptor. It pulls nothing. `RELEASE_DATA_MANIFEST=` selects a repository-relative JSON file using schema `lincodex.release-data/v1`; it describes `bank`, `policy`, and `seed` as either available with a version and artifact paths, or unavailable with a reason. Artifact paths must be normalized repository-relative paths without symlinks or environment files. The manifest stores their SHA-256 hashes and sizes; restore checks the files still match. Descriptors, artifact counts, and sizes have explicit limits. +- Without a data descriptor, the manifest records bundled demo policy source version `1` and hashes `backend/internal/domain/policy_demo.go`. This identifies the shipped definition only; it does not report the policy row currently stored in PostgreSQL, because startup leaves an existing row unchanged. The assessment bank has no accepted release snapshot and the demo seed is not yet versioned, so both remain unavailable and `product_data_status` is `partial`. This is not a full MVP readiness result. +- The manifest is published once at `deploy/release//manifest.json`. A release ID is a validated 1-64 character slug. A second run with identical content leaves the original bytes and modification time unchanged; changed data or stage under the same ID fails and requires a new ID. Publication is serialized per ID and creates the file atomically, without replacing an existing manifest. Build and evidence records remain under `deploy/release//`. +- `release-manifest-check` checks the manifest location and structure and scans it for secrets and machine data. `RELEASE_MANIFEST=` selects an exact artifact for check, verify, restore, or down; otherwise `RELEASE_ID` selects it, falling back to the current commit-based ID. +- `release-up` verifies the Compose file hashes, data artifact hashes, local built image IDs, pulled image digests, and recorded image IDs for verified checks before starting Compose. It writes a private temporary Compose override with each built service pinned directly to its image ID, then uses `--no-build --pull never`; the retained image tag is not used to resolve the service. After startup it checks each running container against the manifest. Use the same `APP_PROJECT`, `ENV_FILE`, and manifest for `release-down`. Named volumes remain in the project and are not database backups or snapshots. +- `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=` compares running container image IDs with the selected manifest and exits with status 1 on a mismatch, missing service, or unknown service. +- `release-clean` removes local release image references that no immutable manifest retains and keeps the files in `deploy/release/`. -The release tag is the first 12 characters of the commit, with `-dirty` when the working tree differs from it. The working tree fingerprint is the Git tree ID written from a temporary index (seeded from HEAD, then `git add -A`), with line ending, file mode, symlink, and fsmonitor settings pinned. It covers modified, deleted, and untracked files, does not depend on diff settings, and leaves the real index untouched. All files go to `deploy/release//`, which Git and the root `.dockerignore` ignore. Manifests are not committed: built image IDs depend on the machine, platform, and build time, and the manifest describes what this machine built and checked. Attach the manifest to the release instead. +The source tag is the first 12 characters of the commit, with `-dirty` when the working tree differs from it. The working tree fingerprint is the Git tree ID written from a temporary index (seeded from HEAD, then `git add -A`), with line ending, file mode, symlink, and fsmonitor settings pinned. It covers modified, deleted, and untracked files, does not depend on diff settings, and leaves the real index untouched. Build and evidence records go to `deploy/release//`; immutable manifests go to `deploy/release//`. Git and the root `.dockerignore` ignore these local artifacts. Manifests are not committed: built image IDs depend on the machine, platform, and build time, and each manifest describes what this machine built and checked. Attach a manifest to the delivery when needed. ### Format -The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v1`: +The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v2`: | Key | Content | | --- | --- | | `schema`, `generated_at` | Schema version and UTC generation time | -| `release` | `tag`, `status` (`verified` or `unverified`), `scope` (`core`), `required_checks` (`smoke`, `e2e`), and the `reasons` that keep it unverified | +| `release` | Immutable `id`, source `tag`, core `status` (`verified` or `unverified`), `product_data_status` (`versioned`, `partial`, or `unavailable`), `required_checks` (`smoke`, `e2e`), and reasons | +| `restore` | Whether the core Compose project can be restored, its command, and any preflight blocking reasons | | `source` | `commit`, `dirty`, the working tree `fingerprint` (`git-tree:`, or null for a clean tree), and `build_matches_source` | | `toolchains` | Go from go.mod, its `toolchain` directive, the `GO_IMAGE` default, `GOTOOLCHAIN=local`, the base image version, and the version recorded in the backend binary; Node and pnpm from `.node-version`, `packageManager`, the Dockerfile, and the base image; Python and uv from `.python-version`, `requires-python`, the Dockerfile, and the base image; `matches_version_file` for Node and Python; the Playwright package version | | `lockfiles` | SHA-256 of `backend/go.mod`, `backend/go.sum`, `frontend/package.json`, `frontend/pnpm-lock.yaml`, `ml/pyproject.toml`, and `ml/uv.lock` | -| `checks`, `rejected_checks` | Accepted evidence with its scope, finish time, commit, fingerprint, and tool image, such as the Playwright image; rejected evidence with the reason | -| `components` | Each Compose service of core, ML, and monitoring and each missing component: `group`, `kind` (`built`, `pulled`, `absent`), the image (`reference`, `present`, `image_id`, `repo_digest` for the tag's repository, all `repo_digests`, `platform`, and allowlisted `versions`), for built images the Dockerfile, its hash, build arguments, and base images, and `verification` | +| `configuration`, `data_versions` | SHA-256 hashes of the core Compose files; bank, policy, and seed versions with bounded artifact paths, hashes, sizes, or an explicit unavailable reason | +| `checks`, `rejected_checks` | Accepted evidence with its scope, finish time, commit, fingerprint, tool image, and image IDs; rejected evidence with the reason | +| `components` | Each Compose service of core, ML, and monitoring and each missing component: `group`, `kind` (`built`, `pulled`, `absent`), image metadata, exact `restore_reference`, optional built-image retention reference, build details, and `verification` | `verification.status` is one of: @@ -588,7 +593,7 @@ The release is `verified` only when all of the following hold; otherwise `releas A Python version that differs from `ml/.python-version` is reported in `matches_version_file` but does not block the release, because ML is outside the verified scope. A moving `node:alpine` tag can therefore make a release unverified until `.node-version` is updated. A dirty tree is not refused: the manifest is written with `unverified` and the reason, so a local candidate can be checked before the commit. -Generating the manifest again for the same source, images, and evidence gives the same document apart from `generated_at`; the target says whether anything else changed since the previous manifest of the tag. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, `.env` content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and `release-manifest-check` repeats the scan. +Generating the manifest again for the same ID, source, images, evidence, and data leaves the submitted file unchanged. A new data snapshot or stage gets a new ID. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, `.env` content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and `release-manifest-check` repeats the scan. ### Go pin @@ -596,7 +601,7 @@ go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO ### Not covered -- The manifest is not an SBOM, a license inventory, a signature, or a provenance attestation, and it is not pushed to a registry. +- The manifest is not an SBOM, a license inventory, a signature, or a provenance attestation, and it is not pushed to a registry. A restore reinstates images and Compose configuration; it does not restore or validate database contents or persistent volume backups. - The files in `deploy/release/` are local and not tamper-proof; evidence is not signed and proves only what this machine recorded. - Git-ignored files are not part of the fingerprint. A build context still receives such files unless `.dockerignore` excludes them. - Images are built for the local platform only. Versions without an image variable or label, such as Kafka, are identified only by digest. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 2d80686..fa6e3dc 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -461,6 +461,10 @@ Offsets и партиции. Каждый обработчик - один уча Тестовые фикстуры используют собственные значения. Поскольку `product` - единственное семейство, интеграционные тесты дают каждому случаю отдельную базу данных, и ни одна фикстура не подменяет демонстрационную политику. +## Артефакты выпуска и восстановление + +Локальный манифест разделяет проверку core-образов и наличие продуктовых данных. Он записывает неизменяемый ID выпуска, хеши исходников и Compose-файлов, точные image ID собранных образов, registry digest скачанных образов и ограниченные хеши версионированных артефактов данных. До старта Compose восстановление сверяет эти ссылки и хеши и не разрешает плавающие теги заново. Исходник демонстрационной политики в составе проекта имеет версию 1, но это не показывает, какая строка политики активна в PostgreSQL. Банк оценивания и демонстрационный seed пока недоступны до появления принятых снимков, поэтому `product_data_status` равен `partial`. Именованные Compose volumes сохраняются при перезапуске выпуска, но манифест не является резервной копией базы или снимком данных. Команды и схема описаны в [DEPLOY.md](DEPLOY.md#манифест-выпуска). + ## Структура репозитория и назначение пакетов ```text diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index ab8e7bc..76b3d59 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -542,36 +542,41 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen ## Манифест выпуска -Манифест выпуска фиксирует, из чего состоит проверенный локальный выпуск: коммит, версии toolchain, хеши lockfiles, образ каждого сервиса с фактическим digest и компоненты, на которых проверка действительно выполнялась. Плавающие теги `latest` и `alpine` по договоренности остаются в Compose и Dockerfile; манифест закрепляет, во что они разрешились в момент выпуска. Интерфейс - `make -C deploy release-manifest`; остальные цели `release-*` готовят его входные данные и проверяют результат: +Манифест фиксирует исходники, toolchain, lockfiles, Compose-файлы, image ID и digest образов, а также версионированные входные данные одной локальной поставки. Плавающие теги `latest` и `alpine` могут оставаться в Compose: восстановление использует записанные image ID или repository digest, не разрешая эти теги заново. По умолчанию ID выпуска строится из коммита. Для разных поставок одного исходника, этапов или набора данных задайте короткий `RELEASE_ID`: make -C deploy release-build make -C deploy release-smoke make -C deploy release-e2e - make -C deploy release-manifest - make -C deploy release-manifest-check + make -C deploy release-manifest RELEASE_ID=demo-stage-1 + make -C deploy release-manifest-check RELEASE_ID=demo-stage-1 - `release-build` собирает `backend`, `frontend` и `ml` через Compose из их Dockerfile и lockfiles и помечает образы `lincodex.invalid/:`. Домен `.invalid` никогда не разрешается, а release-overlay задает `pull_policy: never`, поэтому отсутствующий образ выпуска не скачивается из registry. Каждый Dockerfile принимает базовые образы как build-аргументы `*_IMAGE`, по умолчанию равные согласованным тегам; цель разрешает каждый базовый образ в его repository digest из локального хранилища образов и собирает с `@`. Образ в `COPY --from` или `RUN --mount=from`, который не является предыдущим этапом, отклоняется, потому что его нельзя закрепить. Базовые образы и образы core-сервисов скачиваются, только если их нет локально; `RELEASE_PULL=always` сначала обновляет все теги. После сборки цель снова читает состояние исходников и пишет `build.json` (build-аргументы, digest базовых образов, image ID), только если коммит и рабочее дерево за время сборки не изменились. - `release-smoke` и `release-e2e` запускают `deploy/scripts/smoke.sh` и `deploy/scripts/e2e.sh` с `LINCODEX_RELEASE_TAG`, который задают только эти цели: стек поднимается из образов выпуска с `--no-build --pull never`, и только после прохождения всех проверок скрипт пишет `evidence-smoke.json` или `evidence-e2e.json` с тегом выпуска, коммитом, отпечатком рабочего дерева и image ID запущенных контейнеров. Неуспешный прогон ничего не пишет. Evidence, записанный после успешных проверок, остается, даже если затем не удалась очистка стека; скрипт при этом все равно завершается ошибкой. -- `release-manifest` читает только локальные образы, запись сборки и evidence; ничего не скачивает. Отсутствующий образ указывается как отсутствующий. Evidence или запись сборки с неверной структурой или записанные для другого тега, коммита или состояния рабочего дерева не используются; отклоненный evidence перечисляется в `rejected_checks`. -- `release-manifest-check` проверяет структуру манифеста и ищет в нем секреты и данные машины. -- `release-up` и `release-down` запускают core-стек из образов выпуска с `ENV_FILE` и `APP_PROJECT` без сборки и скачивания. `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=` сравнивает каждый запущенный контейнер этого Compose-проекта по image ID с манифестом текущего тега или с `RELEASE_MANIFEST=`. Цель печатает статус выпуска и завершается со статусом 1 при другом digest, незапущенном сервисе или сервисе, которого нет в манифесте. -- `release-clean` удаляет локальные образы `lincodex.invalid/*` и оставляет файлы в `deploy/release/`. +- `release-manifest` читает локальные образы, запись сборки, evidence и необязательное описание данных; ничего не скачивает. `RELEASE_DATA_MANIFEST=` выбирает JSON внутри репозитория со схемой `lincodex.release-data/v1`. Он описывает `bank`, `policy` и `seed` как доступные с версией и путями к артефактам либо недоступные с причиной. Пути нормализованы, относительны к репозиторию, не проходят через symlink и env-файлы. Манифест записывает SHA-256 и размер каждого файла, а восстановление проверяет их; для данных заданы пределы количества и размера. +- Без описания данных манифест записывает версию `1` встроенного исходника демонстрационной политики и хеш `backend/internal/domain/policy_demo.go`. Это только определение из исходников; оно не сообщает версию строки политики в PostgreSQL, потому что старт не заменяет существующую строку. У банка оценивания нет принятого снимка, а демонстрационный seed пока не версионирован, поэтому оба недоступны и `product_data_status` равен `partial`. Это не означает готовность всего MVP. +- Публикация выполняется один раз в `deploy/release//manifest.json`. ID - проверяемый slug длиной от 1 до 64 символов. Повтор с тем же содержимым сохраняет исходные байты и mtime. Изменение данных или этапа под тем же ID завершается ошибкой; используйте новый ID. Публикация сериализована для каждого ID и атомарно создает файл без замены существующего. Записи сборки и evidence остаются в `deploy/release//`. +- `release-manifest-check` проверяет расположение и структуру манифеста, а также ищет секреты и данные машины. `RELEASE_MANIFEST=` выбирает точный артефакт для check, verify, restore или down; иначе его выбирает `RELEASE_ID`, по умолчанию равный текущему ID на основе коммита. +- `release-up` до запуска Compose сверяет хеши Compose-файлов и входных данных, локальные image ID собранных образов, digest скачанных образов и image ID из принятых проверок. Для собранных сервисов создается закрытый временный Compose override с точными image ID, затем Compose запускается с `--no-build --pull never`; тег удержания образа не выбирает сервис. После старта сверяются image ID контейнеров. Для `release-down` выберите те же `APP_PROJECT`, `ENV_FILE` и манифест. Именованные volumes сохраняются, но не являются снимком или резервной копией базы. +- `make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=` сравнивает image ID запущенных контейнеров с выбранным манифестом и завершается со статусом 1 при несовпадении, отсутствии сервиса или неизвестном сервисе. +- `release-clean` удаляет ссылки на образы выпуска, которые не удерживает ни один неизменяемый манифест; файлы в `deploy/release/` остаются. -Тег выпуска - первые 12 символов коммита, с суффиксом `-dirty`, если рабочее дерево отличается от коммита. Отпечаток рабочего дерева - Git tree ID, записанный из временного индекса (заполняется из HEAD, затем `git add -A`) с закрепленными настройками переводов строк, режима файлов, symlink и fsmonitor. Он учитывает измененные, удаленные и неотслеживаемые файлы, не зависит от настроек diff и не меняет настоящий индекс. Все файлы пишутся в `deploy/release//`, который игнорируют Git и корневой `.dockerignore`. Манифесты не коммитятся: image ID собранных образов зависят от машины, платформы и времени сборки, а манифест описывает то, что собрала и проверила эта машина. Прикладывайте манифест к выпуску. +Тег исходников - первые 12 символов коммита с суффиксом `-dirty`, если рабочее дерево отличается от коммита. Отпечаток рабочего дерева - Git tree ID из временного индекса (заполняется из HEAD, затем `git add -A`) с закрепленными настройками переводов строк, режима файлов, symlink и fsmonitor. Он учитывает измененные, удаленные и неотслеживаемые файлы, не зависит от настроек diff и не меняет настоящий индекс. Записи сборки и evidence хранятся в `deploy/release//`, неизменяемые манифесты - в `deploy/release//`. Git и корневой `.dockerignore` игнорируют эти локальные файлы. Манифест не коммитится: image ID собранных образов зависят от машины, платформы и времени сборки, а файл описывает конкретную локальную поставку. ### Формат -Манифест - JSON с отсортированными ключами и схемой `lincodex.release-manifest/v1`: +Манифест - JSON с отсортированными ключами и схемой `lincodex.release-manifest/v2`: | Ключ | Содержимое | | --- | --- | | `schema`, `generated_at` | Версия схемы и время генерации в UTC | -| `release` | `tag`, `status` (`verified` или `unverified`), `scope` (`core`), `required_checks` (`smoke`, `e2e`) и `reasons`, по которым выпуск не проверен | +| `release` | Неизменяемый `id`, source `tag`, статус core (`verified` или `unverified`), `product_data_status` (`versioned`, `partial` или `unavailable`), обязательные проверки (`smoke`, `e2e`) и причины | | `source` | `commit`, `dirty`, отпечаток рабочего дерева `fingerprint` (`git-tree:` или null для чистого дерева) и `build_matches_source` | | `toolchains` | Go из go.mod, его директива `toolchain`, значение `GO_IMAGE` по умолчанию, `GOTOOLCHAIN=local`, версия базового образа и версия, записанная в бинарнике backend; Node и pnpm из `.node-version`, `packageManager`, Dockerfile и базового образа; Python и uv из `.python-version`, `requires-python`, Dockerfile и базового образа; `matches_version_file` для Node и Python; версия пакета Playwright | | `lockfiles` | SHA-256 `backend/go.mod`, `backend/go.sum`, `frontend/package.json`, `frontend/pnpm-lock.yaml`, `ml/pyproject.toml` и `ml/uv.lock` | -| `checks`, `rejected_checks` | Принятый evidence с охватом, временем завершения, коммитом, отпечатком и образом инструмента, например Playwright; отклоненный evidence с причиной | -| `components` | Каждый Compose-сервис core, ML и monitoring и каждый отсутствующий компонент: `group`, `kind` (`built`, `pulled`, `absent`), образ (`reference`, `present`, `image_id`, `repo_digest` для репозитория тега, все `repo_digests`, `platform` и разрешенные `versions`), для собранных образов - Dockerfile, его хеш, build-аргументы и базовые образы, а также `verification` | +| `restore` | Можно ли восстановить core Compose-проект, точная команда и причины блокировки preflight | +| `configuration`, `data_versions` | SHA-256 core Compose-файлов; версии bank, policy и seed с ограниченными относительными путями артефактов, SHA-256, размерами, `source_kind` либо с явной причиной недоступности | +| `checks`, `rejected_checks` | Принятые проверки с охватом, временем, коммитом, отпечатком, образом инструмента и image ID; отклоненные проверки с причиной | +| `components` | Сервисы Compose core, ML и monitoring и отсутствующие компоненты: `group`, `kind` (`built`, `pulled`, `absent`), метаданные образа, точный `restore_reference`, необязательная ссылка удержания собранного образа, данные сборки и `verification` | `verification.status` принимает значения: @@ -590,7 +595,7 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen Версия Python, отличная от `ml/.python-version`, отражается в `matches_version_file`, но не блокирует выпуск: ML вне проверяемого охвата. Поэтому плавающий тег `node:alpine` может сделать выпуск непроверенным, пока не обновлен `.node-version`. Грязное дерево не отклоняется: манифест пишется со статусом `unverified` и причиной, чтобы локального кандидата можно было проверить до коммита. -Повторная генерация для тех же исходников, образов и evidence дает тот же документ, кроме `generated_at`; цель сообщает, изменилось ли что-то еще по сравнению с предыдущим манифестом тега. Поля версий копируются только из разрешенного списка переменных образа и OCI labels. Манифест никогда не содержит значений окружения, содержимого `.env`, labels контейнеров, mounts, локальных путей, имен пользователя или хоста; перед записью каждый файл проверяется на них, на значения переменных с именами, похожими на секреты (в том числе как подстроки и в base64), и на шаблоны секретов, а `release-manifest-check` повторяет проверку. +`source_kind` равен `bundled_source` для исходника демонстрационной политики и `snapshot` для входного снимка данных. `bundled_source` не доказывает, какая версия политики находится в runtime-базе. Bank и seed остаются недоступны, пока для них нет принятых снимков. Поля версий образа копируются только из разрешенных переменных и OCI labels. Манифест не содержит значения окружения, содержимое `.env`, labels контейнеров, mounts, локальные пути, имя пользователя или хоста. До публикации он проверяется на эти данные и секреты; `release-manifest-check` повторяет сканирование. ### Go pin