diff --git a/.dockerignore b/.dockerignore index 1e77157..2da3552 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,6 +6,10 @@ Thumbs.db .env .env.example +**/.env +**/.env.* +# Release manifests, build records, and evidence stay out of build contexts. +deploy/release **/node_modules **/dist **/coverage diff --git a/backend/Dockerfile b/backend/Dockerfile index 581959e..0984181 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,13 @@ -FROM golang:1.26.8-alpine AS build +# Base images are build arguments so that make -C deploy release-build can pin +# each one to the digest it resolved; the defaults keep the agreed tags. +ARG GO_IMAGE=golang:1.26.8-alpine +ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot + +FROM ${GO_IMAGE} AS build + +# Never download another Go toolchain: a go.mod that asks for a newer Go +# fails the build instead of silently replacing 1.26.8. +ENV GOTOOLCHAIN=local WORKDIR /src/backend COPY go.mod go.sum ./ @@ -7,7 +16,7 @@ RUN go mod download COPY . ./ RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app -FROM gcr.io/distroless/static-debian12:nonroot +FROM ${RUNTIME_IMAGE} WORKDIR / COPY --from=build /out/app /app diff --git a/deploy/.gitignore b/deploy/.gitignore new file mode 100644 index 0000000..a2406ca --- /dev/null +++ b/deploy/.gitignore @@ -0,0 +1 @@ +/release/ diff --git a/deploy/Makefile b/deploy/Makefile index 1bb8f1c..15dcd96 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -12,12 +12,25 @@ CORE_FILE := $(ROOT)/deploy/docker/docker-compose.yml ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml +RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml +ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml +RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py +RELEASE := PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" +# Pull policy of release-build for base and service images: missing or always. +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. +RELEASE_MANIFEST ?= +# 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) PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json") -.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows smoke test-e2e +.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release smoke test-e2e release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean help: ## Show deployment commands - @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST) + @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST) config: ## Render all Compose files with safe example values @test -f "$(ROOT)/backend/Dockerfile" || { printf 'Missing backend/Dockerfile.\n' >&2; exit 2; } @@ -26,6 +39,8 @@ config: ## Render all Compose files with safe example values APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" config --quiet APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet build: ## Build local frontend and backend images @@ -76,13 +91,46 @@ ml-logs: ## Follow ML service logs @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" logs -f -check: config check-workflows ## Validate Compose files and CI workflow aggregates without starting services +check: config check-workflows check-release ## Validate Compose files, CI workflow aggregates, and release tooling without starting services check-workflows: ## Check that each workflow aggregate job requires every other job PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py' +check-release: ## Test the release manifest tooling, its secret scan, and the Go and base image pins + PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_release_manifest.py' + smoke: ## Start an isolated stack and check infrastructure health routes @bash scripts/smoke.sh test-e2e: ## Run the Playwright suite against an isolated throwaway stack @bash scripts/e2e.sh + +release-build: ## Build release images with every base image pinned to its resolved digest + @$(RELEASE) build --pull "$(RELEASE_PULL)" + +release-smoke: ## Run the smoke against the release images and record passing evidence + @LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" bash scripts/smoke.sh + +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-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-manifest-check: ## Check the manifest structure and scan it for secrets and machine data + @$(RELEASE) check + +release-up: ## Start the core stack from the release images 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-down: ## Stop the core stack started by release-up 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-clean: ## Remove the local lincodex.invalid/* release images; keep deploy/release files + @$(RELEASE) clean-images diff --git a/deploy/README.en.md b/deploy/README.en.md index 2c3b78a..1a9cb07 100644 --- a/deploy/README.en.md +++ b/deploy/README.en.md @@ -8,8 +8,11 @@ Configuration for running the application with Docker Compose and Nginx. - `docker/docker-compose.ml.yml` and `docker/docker-compose.monitoring.yml` run ML and monitoring as separate projects. - `nginx/` configures frontend serving and API proxying. - `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner. -- `scripts/` contains the isolated stack smoke check and the browser E2E runner. +- `docker/docker-compose.release.yml` and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/:` and never pull them from a registry. +- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images. Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; see [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite). +`make -C deploy release-build`, `release-smoke`, and `release-manifest` build the release images with pinned base image digests, check them, and write the manifest to `deploy/release//`, which Git ignores; `make -C deploy release-manifest-verify` compares running containers with the manifest, and `make -C deploy release-clean` removes the release images. See the [release manifest](../docs/en/DEPLOY.md#release-manifest). + See the [deployment guide](../docs/en/DEPLOY.md). diff --git a/deploy/README.md b/deploy/README.md index 7341042..17cf75a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -8,8 +8,11 @@ - `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами. - `nginx/` содержит конфигурацию раздачи frontend и проксирования API. - `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright. -- `scripts/` содержит smoke-проверку изолированного стека и запуск браузерных E2E. +- `docker/docker-compose.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/:` без скачивания из registry. +- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска. Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; см. [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор). +`make -C deploy release-build`, `release-smoke` и `release-manifest` собирают образы выпуска с закрепленными digest базовых образов, проверяют их и пишут манифест в `deploy/release//` (игнорируется Git); `make -C deploy release-manifest-verify` сверяет запущенные контейнеры с манифестом, а `make -C deploy release-clean` удаляет образы выпуска. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска). + Подробнее: [развертывание](../docs/ru/DEPLOY.md). diff --git a/deploy/docker/docker-compose.ml.release.yml b/deploy/docker/docker-compose.ml.release.yml new file mode 100644 index 0000000..3519231 --- /dev/null +++ b/deploy/docker/docker-compose.ml.release.yml @@ -0,0 +1,6 @@ +# Overlay that names the ML image built by make -C deploy release-build. See +# docker-compose.release.yml for the naming and pull rules. +services: + ml: + image: lincodex.invalid/ml:${LINCODEX_RELEASE_TAG:?Set LINCODEX_RELEASE_TAG} + pull_policy: never diff --git a/deploy/docker/docker-compose.release.yml b/deploy/docker/docker-compose.release.yml new file mode 100644 index 0000000..10fe449 --- /dev/null +++ b/deploy/docker/docker-compose.release.yml @@ -0,0 +1,15 @@ +# Overlay that names the core images built by make -C deploy release-build. +# deploy/Makefile and deploy/scripts combine it with docker-compose.yml so the +# release build, the smoke and E2E runs, and release-up use the same image IDs. +# +# The .invalid domain is reserved and never resolves, so a missing release +# image can never be pulled from a registry under this name; pull_policy keeps +# Compose from trying. +services: + backend: + image: lincodex.invalid/backend:${LINCODEX_RELEASE_TAG:?Set LINCODEX_RELEASE_TAG} + pull_policy: never + + frontend: + image: lincodex.invalid/frontend:${LINCODEX_RELEASE_TAG:?Set LINCODEX_RELEASE_TAG} + pull_policy: never diff --git a/deploy/scripts/e2e.sh b/deploy/scripts/e2e.sh index 791e391..c218806 100644 --- a/deploy/scripts/e2e.sh +++ b/deploy/scripts/e2e.sh @@ -9,11 +9,25 @@ # Optional environment: # E2E_SPEC_DIR directory with specs to run instead of frontend/e2e, for # example a scratch copy while debugging the suite. +# LINCODEX_RELEASE_TAG run against the release images of this tag (built +# by make -C deploy release-build) without building or pulling, +# keep those images, and record passing evidence for the +# release manifest. Specs must be the committed frontend/e2e. +# Only make -C deploy release-e2e sets it. set -euo pipefail root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) compose_file="$root/deploy/docker/docker-compose.yml" e2e_file="$root/deploy/docker/docker-compose.e2e.yml" +release_file="$root/deploy/docker/docker-compose.release.yml" +release_script="$root/deploy/scripts/release_manifest.py" +release_tag="${LINCODEX_RELEASE_TAG:-}" +compose_files=(-f "$compose_file" -f "$e2e_file") +up_args=(--build) +if [[ -n "$release_tag" ]]; then + compose_files+=(-f "$release_file") + up_args=(--no-build --pull never) +fi frontend_dir="$root/frontend" artifacts_dir="$frontend_dir/test-results/e2e" spec_dir="${E2E_SPEC_DIR:-$frontend_dir/e2e}" @@ -46,6 +60,9 @@ installed=$(sed -n 's/^ *"version": "\([^"]*\)",\{0,1\}$/\1/p' "$installed_manif fail "Installed @playwright/test $installed differs from $declared. Run make -C frontend install." [[ -d "$spec_dir" ]] || fail "Spec directory $spec_dir does not exist." spec_dir=$(cd "$spec_dir" && pwd) +if [[ -n "$release_tag" && "$spec_dir" != "$frontend_dir/e2e" ]]; then + fail 'Release evidence needs the committed suite; unset E2E_SPEC_DIR.' +fi for dockerfile in "$root/backend/Dockerfile" "$root/frontend/Dockerfile"; do [[ -f "$dockerfile" ]] || fail "Missing required build file $dockerfile." done @@ -65,12 +82,11 @@ compose() { APP_PROJECT="$project" APP_NETWORK="$network" APP_STORAGE_NETWORK="$storage_network" \ PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \ E2E_UID="$(id -u)" E2E_GID="$(id -g)" \ - E2E_SPEC_DIR="$spec_dir" E2E_ARTIFACTS_DIR="$artifacts_dir" \ + E2E_SPEC_DIR="$spec_dir" E2E_ARTIFACTS_DIR="$artifacts_dir" LINCODEX_RELEASE_TAG="$release_tag" \ docker compose \ --env-file "$env_file" \ -p "$project" \ - -f "$compose_file" \ - -f "$e2e_file" \ + "${compose_files[@]}" \ "$@" } @@ -87,6 +103,9 @@ done if [[ -n "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ]]; then fail "Refusing to use existing Compose project $project." fi +if [[ -n "$release_tag" ]]; then + PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" require-images --tag "$release_tag" +fi cleanup() { local result=$? @@ -138,7 +157,7 @@ printf 'E2E project: %s (Playwright %s)\n' "$project" "$declared" compose config --quiet compose --profile e2e config --quiet started=1 -compose up --build -d --wait --wait-timeout 180 +compose up "${up_args[@]}" -d --wait --wait-timeout 180 # The backend has no Compose health check; wait until it reports PostgreSQL, # Redis, and SeaweedFS ready before the browser starts. @@ -162,5 +181,9 @@ set -e if ((status != 0)); then printf 'Playwright failed with exit code %s; traces and screenshots are in %s/results.\n' \ "$status" "$artifacts_dir" >&2 +elif [[ -n "$release_tag" ]]; then + # The suite passed; bind the result to the image IDs that ran. + PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" record-evidence --check e2e --project "$project" \ + --tag "$release_tag" --tool-image "playwright=mcr.microsoft.com/playwright:v$declared-noble" fi exit "$status" diff --git a/deploy/scripts/release_manifest.py b/deploy/scripts/release_manifest.py new file mode 100644 index 0000000..45be762 --- /dev/null +++ b/deploy/scripts/release_manifest.py @@ -0,0 +1,1380 @@ +#!/usr/bin/env python3 +"""Build, describe, and check release images of the Lincodex Compose stack. + +Subcommands (deploy/Makefile is the supported interface): + + tag print the release tag of the working tree + build build the release images with base images pinned to the + digests resolved from the local image store + require-images fail unless every image a release run needs is local + record-evidence record that a check passed against a running project + manifest write deploy/release//manifest.json + verify compare running containers of a project with a manifest + check check a manifest's structure and scan it for machine secrets + clean-images remove the local lincodex.invalid/* release images + +Only the standard library is used. Docker is called through the CLI; no +command here pulls an image unless it is `build`, and `build` pulls only base +or service images that are missing locally (or all of them with --pull +always). The manifest and evidence never copy environment values, labels, +mounts, or local paths from Docker; every written file passes +forbidden_findings() first. +""" + +from __future__ import annotations + +import argparse +import base64 +import datetime as _dt +import getpass +import hashlib +import io +import json +import os +import re +import secrets as _secrets +import socket +import subprocess +import sys +import tarfile +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Iterable + +ROOT = Path(__file__).resolve().parents[2] +RELEASE_DIR_NAME = "deploy/release" +MANIFEST_SCHEMA = "lincodex.release-manifest/v1" +BUILD_SCHEMA = "lincodex.release-build/v1" +EVIDENCE_SCHEMA = "lincodex.release-evidence/v1" +RELEASE_REGISTRY = "lincodex.invalid" +# Project name used only to render Compose files; nothing is started under it. +RENDER_PROJECT = "lincodex-release" +CHECKS = ("smoke", "e2e") +CHECK_SCOPE = { + "smoke": ( + "deploy/scripts/smoke.sh: Compose startup and health, API routing, PostgreSQL, Redis, and " + "SeaweedFS readiness and recovery, Redis and storage access rules, disabled mail transport. " + "Not a business-flow test; Kafka publishing is not checked." + ), + "e2e": ( + "deploy/scripts/e2e.sh: the Playwright technical browser suite against the stack. " + "No candidate or employer workflows." + ), +} + + +@dataclass(frozen=True) +class Group: + name: str + compose_file: str + release_overlay: str | None + # Groups whose images a passing smoke or E2E run can verify. + verifiable: bool + unverified_reason: str + + +GROUPS = ( + Group("core", "deploy/docker/docker-compose.yml", "deploy/docker/docker-compose.release.yml", True, ""), + Group( + "ml", + "deploy/docker/docker-compose.ml.yml", + "deploy/docker/docker-compose.ml.release.yml", + False, + "Built by release-build, but no release check starts the ML service, and it has no inference model.", + ), + Group( + "monitoring", + "deploy/docker/docker-compose.monitoring.yml", + None, + False, + "Monitoring is a separate project that no release check starts; images are recorded only if present locally.", + ), +) + +# Planned components with no service, image, or Compose file in this repository. +MISSING_COMPONENTS = { + "gpu-inference": "Local model inference on a separate GPU host. The ML service has no model, and no GPU runtime or image exists.", + "judge0": "Isolated code execution host. No service, image, or Compose file exists in this repository.", + "qdrant": "Vector search. No service, image, or Compose file exists in this repository.", +} + +# Only these image metadata keys are copied; everything else stays out. +VERSION_ENV_KEYS = ( + "GOLANG_VERSION", + "JAVA_VERSION", + "NGINX_VERSION", + "NODE_VERSION", + "PG_MAJOR", + "PG_VERSION", + "PYTHON_VERSION", + "REDIS_VERSION", +) +VERSION_LABEL_KEYS = ("org.opencontainers.image.revision", "org.opencontainers.image.version") + +LOCKFILES = ( + "backend/go.mod", + "backend/go.sum", + "frontend/package.json", + "frontend/pnpm-lock.yaml", + "ml/pyproject.toml", + "ml/uv.lock", +) + + +class ReleaseError(RuntimeError): + """A release step cannot continue; the message is safe to print.""" + + +# --------------------------------------------------------------------------- +# Secret and machine data scanning + + +SECRET_NAME = re.compile( + r"(PASS|PWD|SECRET|TOKEN|KEY|AUTH|DSN|COOKIE|SESSION|SIGN|PRIVATE|CREDENTIAL)", re.IGNORECASE +) +FORBIDDEN_PATTERNS = ( + ("private key block", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")), + ("credentials in a URL", re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://[^/\s:@\"]+:[^/\s@\"]+@")), + ("secret assignment", re.compile(r"\b[A-Z0-9_]*(PASSWORD|SECRET|TOKEN|API_KEY)[A-Z0-9_]*=")), + ("AWS access key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")), + ("Resend API key", re.compile(r"\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9_]{8,}")), + ("GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}")), + ("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")), + ("JSON web token", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.")), + ("absolute local path", re.compile(r"(? dict[str, str]: + values: dict[str, str] = {} + try: + text = path.read_text(encoding="utf-8") + except OSError: + return values + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + name, value = line.split("=", 1) + values[name.strip()] = value.strip().strip("'\"") + return values + + +def sensitive_values(root: Path = ROOT, environ: dict[str, str] | None = None) -> dict[str, str]: + """Return label -> value for values that must never appear in output. + + Labels name the source (variable name, user, host) and never the value. + """ + environ = dict(os.environ if environ is None else environ) + found: dict[str, str] = {} + + def add(label: str, value: str, minimum: int = 6) -> None: + value = value.strip() + if len(value) >= minimum and value.lower() not in NEUTRAL_WORDS: + found.setdefault(label, value) + + for source, values in (("root .env", env_file_values(root / ".env")), ("environment", environ)): + for name, value in values.items(): + if SECRET_NAME.search(name): + add(f"value of {name} from {source}", value) + try: + add("local user name", getpass.getuser(), minimum=3) + except (KeyError, OSError): + pass + host = socket.gethostname() + add("local host name", host, minimum=3) + add("local host name", host.split(".", 1)[0], minimum=3) + home = environ.get("HOME", "") + if home not in ("", "/"): + add("home directory", home, minimum=3) + add("repository path", str(root), minimum=3) + return found + + +def _walk_keys(value: Any, path: str = "$") -> Iterable[tuple[str, str]]: + if isinstance(value, dict): + for key, item in value.items(): + yield path, str(key) + yield from _walk_keys(item, f"{path}.{key}") + elif isinstance(value, list): + for index, item in enumerate(value): + yield from _walk_keys(item, f"{path}[{index}]") + + +def value_forms(value: str) -> list[str]: + """Return the value and, for long values, its base64 encodings without padding.""" + forms = [value] + if len(value) >= 8: + raw = value.encode("utf-8") + for encoded in (base64.b64encode(raw), base64.urlsafe_b64encode(raw)): + forms.append(encoded.decode("ascii").rstrip("=")) + return forms + + +def contains_value(text: str, value: str) -> bool: + # Long values are searched as substrings; short ones need word boundaries + # so that, for example, a three-letter user name inside a digest is not a hit. + if len(value) >= 8: + lowered = text.lower() + return any(form.lower() in lowered if form == value else form in text for form in value_forms(value)) + return bool(re.search(rf"(? list[str]: + """Describe forbidden content in a JSON document without echoing it.""" + text = json.dumps(document, sort_keys=True) if not isinstance(document, str) else document + findings: list[str] = [] + for name, pattern in FORBIDDEN_PATTERNS: + if pattern.search(text): + findings.append(name) + for label, value in sorted((sensitive or {}).items()): + if contains_value(text, value): + findings.append(label) + if not isinstance(document, str): + for where, key in _walk_keys(document): + if key.lower() in FORBIDDEN_KEYS: + findings.append(f"configuration key '{key}' at {where}") + return sorted(set(findings)) + + +def write_json(path: Path, document: dict[str, Any], root: Path = ROOT) -> None: + findings = forbidden_findings(document, sensitive_values(root)) + if findings: + raise ReleaseError(f"Refusing to write {display(path, root)}: " + "; ".join(findings)) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp") + temporary.write_text(json.dumps(document, indent=2, sort_keys=True) + "\n", encoding="utf-8") + temporary.replace(path) + + +# --------------------------------------------------------------------------- +# Source state + + +def run(args: list[str], *, cwd: Path = ROOT, env: dict[str, str] | None = None, check: bool = True) -> bytes: + try: + result = subprocess.run(args, cwd=cwd, env=env, capture_output=True, check=False) + except OSError as error: + raise ReleaseError(f"{args[0]} could not run: {error}") from error + if check and result.returncode != 0: + message = result.stderr.decode("utf-8", errors="replace").strip().splitlines() + tail = message[-1] if message else f"exit status {result.returncode}" + raise ReleaseError(f"{' '.join(args[:3])} failed: {tail}") + return result.stdout + + +@dataclass(frozen=True) +class Source: + commit: str + dirty: bool + fingerprint: str | None + + @property + def tag(self) -> str: + return self.commit[:12] + ("-dirty" if self.dirty else "") + + +# Settings that change how git add records content; pinned so that the +# working tree fingerprint does not depend on local or global git config. +GIT_PINNED = ( + "-c", "core.autocrlf=false", + "-c", "core.safecrlf=false", + "-c", "core.filemode=true", + "-c", "core.symlinks=true", + "-c", "core.fsmonitor=false", +) + + +def read_source(root: Path = ROOT) -> Source: + """Return the commit and, for a changed tree, the Git tree ID of the working tree. + + The tree is written from a temporary index (seeded from HEAD, then git add -A), + so it covers modified, deleted, and untracked files that Git does not ignore, + leaves the real index alone, and does not depend on diff settings. + """ + git = ["git", *GIT_PINNED] + commit = run([*git, "rev-parse", "--verify", "HEAD"], cwd=root).decode().strip() + head_tree = run([*git, "rev-parse", "--verify", "HEAD^{tree}"], cwd=root).decode().strip() + with tempfile.TemporaryDirectory(prefix="lincodex-release-index-") as directory: + env = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")} + env["GIT_INDEX_FILE"] = str(Path(directory) / "index") + env["GIT_OPTIONAL_LOCKS"] = "0" + run([*git, "read-tree", "HEAD"], cwd=root, env=env) + run([*git, "add", "-A", "--", "."], cwd=root, env=env) + tree = run([*git, "write-tree"], cwd=root, env=env).decode().strip() + if tree == head_tree: + return Source(commit, False, None) + return Source(commit, True, f"git-tree:{tree}") + + +def release_dir(tag: str, root: Path = ROOT) -> Path: + if not re.fullmatch(r"[0-9a-f]{12}(-dirty)?", tag): + raise ReleaseError(f"Unexpected release tag {tag!r}.") + return root / RELEASE_DIR_NAME / tag + + +def relative(path: Path, root: Path = ROOT) -> str: + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except ValueError as error: + raise ReleaseError("A path outside the repository was referenced.") from error + + +def display(path: Path, root: Path = ROOT) -> str: + """Name a file for messages without revealing where the repository lives.""" + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except ValueError: + return path.name + + +def file_digest(path: Path) -> str | None: + try: + return "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest() + except OSError: + return None + + +def utc_now() -> str: + return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") + + +# --------------------------------------------------------------------------- +# Dockerfile and toolchain policy + +ARG_LINE = re.compile(r"^\s*ARG\s+([A-Za-z_][A-Za-z0-9_]*)(?:=(\S+))?\s*$", re.IGNORECASE) +FROM_LINE = re.compile(r"^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)(?:\s+AS\s+(\S+))?\s*$", re.IGNORECASE) +ARG_REFERENCE = re.compile(r"^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$") +COPY_FROM = re.compile(r"^\s*(?:COPY|ADD)\b.*?\s--from=(\S+)", re.IGNORECASE) +MOUNT_FROM = re.compile(r"--mount=\S*?\bfrom=([^,\s]+)", re.IGNORECASE) + + +def logical_lines(text: str) -> list[tuple[int, str]]: + """Join backslash continuations and drop comments, keeping first line numbers.""" + result: list[tuple[int, str]] = [] + buffer: list[str] = [] + start = 0 + for number, line in enumerate(text.splitlines(), start=1): + if not buffer and line.lstrip().startswith("#"): + continue + if not buffer: + start = number + stripped = line.rstrip() + if stripped.endswith("\\"): + buffer.append(stripped[:-1]) + continue + buffer.append(stripped) + result.append((start, " ".join(buffer))) + buffer = [] + if buffer: + result.append((start, " ".join(buffer))) + return result + + +@dataclass(frozen=True) +class BaseImage: + arg: str + default: str + + +def dockerfile_bases(text: str, source: str = "Dockerfile") -> list[BaseImage]: + """Return the base image arguments; fail on any base that cannot be pinned. + + Every FROM must name an earlier stage or a global ARG ending in _IMAGE with + a default, so release-build can replace each base with a digest. + """ + global_args: dict[str, str | None] = {} + stages: set[str] = set() + bases: dict[str, BaseImage] = {} + seen_from = False + stage_count = 0 + for number, line in logical_lines(text): + if not seen_from: + match = ARG_LINE.match(line) + if match: + global_args[match.group(1)] = match.group(2) + continue + match = FROM_LINE.match(line) + if not match: + for source_ref in COPY_FROM.findall(line) + MOUNT_FROM.findall(line): + if source_ref not in stages and not (source_ref.isdigit() and int(source_ref) < stage_count): + raise ReleaseError( + f"{source}:{number}: --from={source_ref} is not an earlier stage; external images cannot be pinned." + ) + continue + seen_from = True + stage_count += 1 + image, stage = match.group(1), match.group(2) + if image in stages: + pass + else: + reference = ARG_REFERENCE.match(image) + if not reference or not reference.group(1).endswith("_IMAGE"): + raise ReleaseError(f"{source}:{number}: FROM {image} is not a pinnable *_IMAGE build argument.") + name = reference.group(1) + default = global_args.get(name) + if not default: + raise ReleaseError(f"{source}:{number}: build argument {name} has no default before the first FROM.") + bases[name] = BaseImage(name, default) + if stage: + stages.add(stage) + if not bases: + raise ReleaseError(f"{source}: no base image found.") + return [bases[name] for name in sorted(bases)] + + +def go_policy(root: Path = ROOT) -> dict[str, Any]: + """Describe the Go pin and whether go.mod and the build image agree.""" + go_mod = (root / "backend/go.mod").read_text(encoding="utf-8") + directive = re.search(r"^go\s+(\S+)\s*$", go_mod, re.MULTILINE) + toolchain = re.search(r"^toolchain\s+(\S+)\s*$", go_mod, re.MULTILINE) + dockerfile = (root / "backend/Dockerfile").read_text(encoding="utf-8") + bases = {base.arg: base.default for base in dockerfile_bases(dockerfile, "backend/Dockerfile")} + image = bases.get("GO_IMAGE", "") + image_version = re.match(r"^golang:([0-9]+\.[0-9]+\.[0-9]+)-", image) + build_stage = dockerfile.split("FROM ${GO_IMAGE}", 1)[-1].split("\nFROM ", 1)[0] + version = directive.group(1) if directive else None + policy = { + "go_mod": version, + "toolchain_directive": toolchain.group(1) if toolchain else None, + "dockerfile_image": image or None, + "gotoolchain_local": bool(re.search(r"^ENV\s+GOTOOLCHAIN=local\s*$", build_stage, re.MULTILINE)), + } + policy["consistent"] = bool( + version + and re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version) + and image_version + and image_version.group(1) == version + and policy["toolchain_directive"] in (None, f"go{version}") + and policy["gotoolchain_local"] + ) + return policy + + +def text_match(path: Path, pattern: str) -> str | None: + try: + match = re.search(pattern, path.read_text(encoding="utf-8"), re.MULTILINE) + except OSError: + return None + return match.group(1) if match else None + + +# --------------------------------------------------------------------------- +# Go build information + + +def go_build_version(binary: bytes) -> str | None: + """Return the Go version recorded in a Go 1.18+ binary, or None.""" + magic = b"\xff Go buildinf:" + start = 0 + while True: + index = binary.find(magic, start) + if index < 0: + return None + if index % 16 == 0 and len(binary) >= index + 32: + break + start = index + 1 + flags = binary[index + 15] + if not flags & 0x2: + # Pre-1.18 pointer layout; the release build never produces it. + return None + position = index + 32 + length, shift = 0, 0 + while position < len(binary): + byte = binary[position] + position += 1 + length |= (byte & 0x7F) << shift + if not byte & 0x80: + break + shift += 7 + version = binary[position : position + length] + try: + decoded = version.decode("ascii") + except UnicodeDecodeError: + return None + return decoded if re.fullmatch(r"go[0-9][0-9A-Za-z.+-]*", decoded) else None + + +# --------------------------------------------------------------------------- +# Docker access + + +def docker_env(extra: dict[str, str] | None = None) -> dict[str, str]: + """Return a minimal environment so shell secrets never reach Compose.""" + env = {name: value for name, value in os.environ.items() if name in ("PATH", "HOME", "TMPDIR")} + env.update({name: value for name, value in os.environ.items() if name.startswith(("DOCKER_", "BUILDKIT_"))}) + env.update(extra or {}) + return env + + +class Docker: + """Thin CLI wrapper; tests replace it with a fake.""" + + def __init__(self, binary: str | None = None) -> None: + self.binary = binary or os.environ.get("DOCKER", "docker") + + def inspect_image(self, reference: str) -> dict[str, Any] | None: + result = subprocess.run( + [self.binary, "image", "inspect", reference], capture_output=True, check=False, env=docker_env() + ) + if result.returncode != 0: + return None + data = json.loads(result.stdout) + return data[0] if data else None + + def compose_config(self, files: list[str], tag: str, root: Path = ROOT) -> dict[str, Any]: + args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT] + for name in files: + args += ["-f", str(root / name)] + args += ["config", "--format", "json"] + env = docker_env( + {"APP_PROJECT": RENDER_PROJECT, "APP_NETWORK": f"{RENDER_PROJECT}_default", "LINCODEX_RELEASE_TAG": tag} + ) + return json.loads(run(args, cwd=root, env=env)) + + def project_containers(self, project: str) -> list[dict[str, Any]]: + ids = run( + [self.binary, "ps", "-q", "--filter", f"label=com.docker.compose.project={project}"], env=docker_env() + ).split() + if not ids: + return [] + return json.loads(run([self.binary, "inspect", *[item.decode() for item in ids]], env=docker_env())) + + def read_file(self, image_id: str, path: str) -> bytes | None: + """Copy one file out of an image through a created, never started container.""" + name = f"lincodex-release-inspect-{_secrets.token_hex(6)}" + created = subprocess.run( + [self.binary, "create", "--pull", "never", "--name", name, image_id], + capture_output=True, + check=False, + env=docker_env(), + ) + if created.returncode != 0: + return None + try: + archive = subprocess.run( + [self.binary, "cp", f"{name}:{path}", "-"], capture_output=True, check=False, env=docker_env() + ) + if archive.returncode != 0: + return None + with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as tar: + for member in tar.getmembers(): + if member.isfile(): + handle = tar.extractfile(member) + return handle.read() if handle else None + return None + finally: + subprocess.run([self.binary, "rm", "-f", name], capture_output=True, check=False, env=docker_env()) + + def pull(self, reference: str) -> None: + print(f"Pulling {reference}", flush=True) + if subprocess.run([self.binary, "pull", reference], check=False, env=docker_env()).returncode != 0: + raise ReleaseError(f"Could not pull {reference}.") + + def compose_build(self, files: list[str], tag: str, service: str, build_args: dict[str, str], root: Path = ROOT) -> None: + args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT] + for name in files: + args += ["-f", str(root / name)] + args += ["build"] + for name, value in sorted(build_args.items()): + args += ["--build-arg", f"{name}={value}"] + args.append(service) + env = docker_env( + {"APP_PROJECT": RENDER_PROJECT, "APP_NETWORK": f"{RENDER_PROJECT}_default", "LINCODEX_RELEASE_TAG": tag} + ) + print(f"Building {service} for release {tag}", flush=True) + if subprocess.run(args, cwd=root, env=env, check=False).returncode != 0: + raise ReleaseError(f"Building {service} failed.") + + +def normalize_repository(reference: str) -> str: + """Return the repository of an image reference in docker.io long form.""" + name = reference.split("@", 1)[0] + last = name.rsplit("/", 1)[-1] + if ":" in last: + name = name[: name.rfind(":")] + first = name.split("/", 1)[0] + if "/" not in name: + name = f"docker.io/library/{name}" + elif not ("." in first or ":" in first or first == "localhost"): + name = f"docker.io/{name}" + return name + + +def repo_digest(info: dict[str, Any], reference: str) -> str | None: + wanted = normalize_repository(reference) + for item in sorted(info.get("RepoDigests") or []): + if "@" in item and normalize_repository(item) == wanted: + return item.split("@", 1)[1] + return None + + +def image_versions(info: dict[str, Any], labels: bool = True) -> dict[str, str]: + """Copy allowlisted version metadata; built images inherit base labels, so skip them there.""" + versions: dict[str, str] = {} + for entry in (info.get("Config") or {}).get("Env") or []: + name, _, value = entry.partition("=") + if name in VERSION_ENV_KEYS and value: + versions[name] = value + image_labels = ((info.get("Config") or {}).get("Labels") or {}) if labels else {} + for name in VERSION_LABEL_KEYS: + if image_labels.get(name): + versions[name] = image_labels[name] + return versions + + +def image_record(info: dict[str, Any] | None, reference: str, built: bool = False) -> dict[str, Any]: + if info is None: + return {"reference": reference, "present": False} + platform = "/".join(part for part in (info.get("Os"), info.get("Architecture"), info.get("Variant")) if part) + return { + "reference": reference, + "present": True, + "image_id": info.get("Id"), + # A local build has no registry digest; its image ID identifies it. + "repo_digest": None if built else repo_digest(info, reference), + "repo_digests": [] if built else sorted(item for item in info.get("RepoDigests") or [] if isinstance(item, str)), + "platform": platform or None, + "versions": image_versions(info, labels=not built), + } + + +# --------------------------------------------------------------------------- +# Compose services + + +@dataclass +class Service: + group: str + name: str + reference: str + dockerfile: str | None = None + context: str | None = None + compose_file: str = "" + overlay: str | None = None + + +def group_services(docker: Docker, group: Group, tag: str, root: Path = ROOT) -> list[Service]: + files = [group.compose_file] + ([group.release_overlay] if group.release_overlay else []) + config = docker.compose_config(files, tag, root) + services: list[Service] = [] + for name, spec in sorted((config.get("services") or {}).items()): + if spec.get("profiles"): + continue + build = spec.get("build") + reference = spec.get("image") + if build: + if not group.release_overlay or not reference: + raise ReleaseError(f"Built service {name} has no release image name.") + context = Path(build["context"]) + dockerfile = context / build.get("dockerfile", "Dockerfile") + services.append( + Service(group.name, name, reference, relative(dockerfile, root), relative(context, root) or ".", group.compose_file, group.release_overlay) + ) + elif reference: + services.append(Service(group.name, name, reference, compose_file=group.compose_file)) + return services + + +def release_reference(service: str, tag: str) -> str: + return f"{RELEASE_REGISTRY}/{service}:{tag}" + + +# --------------------------------------------------------------------------- +# build + + +def ensure_local(docker: Docker, reference: str, pull: str) -> dict[str, Any]: + info = None if pull == "always" else docker.inspect_image(reference) + if info is None: + docker.pull(reference) + info = docker.inspect_image(reference) + if info is None: + raise ReleaseError(f"{reference} is not available locally after pulling.") + return info + + +def command_build(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + docker = docker or Docker() + source = read_source(root) + policy = go_policy(root) + if not policy["consistent"]: + raise ReleaseError( + "The Go pin is inconsistent: backend/go.mod, the toolchain directive, the GO_IMAGE default, " + "and ENV GOTOOLCHAIN=local in backend/Dockerfile must agree." + ) + record: dict[str, Any] = { + "schema": BUILD_SCHEMA, + "tag": source.tag, + "commit": source.commit, + "dirty": source.dirty, + "source_fingerprint": source.fingerprint, + "built_at": utc_now(), + "services": {}, + } + for group in GROUPS: + if group.release_overlay is None: + continue + for service in group_services(docker, group, source.tag, root): + if service.dockerfile is None: + ensure_local(docker, service.reference, args.pull) + continue + text = (root / service.dockerfile).read_text(encoding="utf-8") + build_args: dict[str, str] = {} + bases = [] + for base in dockerfile_bases(text, service.dockerfile): + info = ensure_local(docker, base.default, args.pull) + digest = repo_digest(info, base.default) + if not digest: + raise ReleaseError(f"{base.default} has no repository digest; pull it from its registry first.") + pinned = f"{base.default}@{digest}" + build_args[base.arg] = pinned + bases.append( + {"arg": base.arg, "reference": base.default, "digest": digest, "versions": image_versions(info)} + ) + files = [service.compose_file] + ([service.overlay] if service.overlay else []) + docker.compose_build(files, source.tag, service.name, build_args, root) + info = docker.inspect_image(service.reference) + if info is None: + raise ReleaseError(f"{service.reference} is missing after the build.") + record["services"][service.name] = { + "reference": service.reference, + "image_id": info.get("Id"), + "dockerfile": service.dockerfile, + "dockerfile_digest": file_digest(root / service.dockerfile), + "context": service.context, + "build_args": build_args, + "base_images": bases, + } + after = read_source(root) + if (after.commit, after.fingerprint) != (source.commit, source.fingerprint): + raise ReleaseError( + "The source changed during the build, so the images may not match any one source state; " + "build.json was not written. Rebuild from a tree that does not change." + ) + path = release_dir(source.tag, root) / "build.json" + write_json(path, record, root) + print(f"Release images built for {source.tag}; build record: {display(path, root)}") + if source.dirty: + print("The working tree is dirty: a manifest for these images stays unverified.") + return 0 + + +# --------------------------------------------------------------------------- +# require-images and record-evidence + + +def command_require_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + docker = docker or Docker() + source = read_source(root) + expect_tag(args, source) + group = next(item for item in GROUPS if item.name == args.group) + missing = [ + service.reference + for service in group_services(docker, group, source.tag, root) + if docker.inspect_image(service.reference) is None + ] + if missing: + raise ReleaseError( + "Missing local images: " + ", ".join(missing) + ". Run make -C deploy release-build first." + ) + return 0 + + +def expect_tag(args: argparse.Namespace, source: Source) -> None: + if getattr(args, "tag", None) and args.tag != source.tag: + raise ReleaseError(f"The working tree is now release {source.tag}, not {args.tag}; rebuild and rerun.") + + +def running_services(containers: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: + services: dict[str, dict[str, Any]] = {} + for container in containers: + labels = (container.get("Config") or {}).get("Labels") or {} + if labels.get("com.docker.compose.oneoff", "False") == "True": + continue + if not (container.get("State") or {}).get("Running"): + continue + name = labels.get("com.docker.compose.service") + if name: + services[name] = { + "reference": (container.get("Config") or {}).get("Image"), + "image_id": container.get("Image"), + } + return services + + +def command_record_evidence(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + docker = docker or Docker() + source = read_source(root) + expect_tag(args, source) + group = next(item for item in GROUPS if item.name == "core") + expected = group_services(docker, group, source.tag, root) + running = running_services(docker.project_containers(args.project)) + services: dict[str, Any] = {} + for service in expected: + actual = running.get(service.name) + if actual is None: + raise ReleaseError(f"Service {service.name} is not running in project {args.project}.") + if actual["reference"] != service.reference: + raise ReleaseError(f"Service {service.name} runs {actual['reference']}, not {service.reference}.") + services[service.name] = actual + tools: dict[str, Any] = {} + for item in args.tool_image or []: + name, _, reference = item.partition("=") + info = docker.inspect_image(reference) + if info is None: + raise ReleaseError(f"Tool image {reference} is not present locally.") + tools[name] = {"reference": reference, "image_id": info.get("Id")} + evidence = { + "schema": EVIDENCE_SCHEMA, + "check": args.check, + "result": "passed", + "tag": source.tag, + "commit": source.commit, + "source_fingerprint": source.fingerprint, + "finished_at": utc_now(), + "services": services, + "tool_images": tools, + } + path = release_dir(source.tag, root) / f"evidence-{args.check}.json" + write_json(path, evidence, root) + print(f"Recorded passing {args.check} evidence for {source.tag}: {display(path, root)}") + return 0 + + +# --------------------------------------------------------------------------- +# manifest + + +def load_json(path: Path) -> dict[str, Any] | None: + try: + document = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return document if isinstance(document, dict) else None + + +IMAGE_ID = re.compile(r"sha256:[0-9a-f]+") + + +def _is_str_map(value: Any) -> bool: + return isinstance(value, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in value.items()) + + +def _is_image_map(value: Any) -> bool: + return isinstance(value, dict) and all( + isinstance(name, str) + and isinstance(item, dict) + and isinstance(item.get("reference"), str) + and isinstance(item.get("image_id"), str) + and IMAGE_ID.fullmatch(item["image_id"]) + for name, item in value.items() + ) + + +def evidence_problem(document: dict[str, Any], check: str, source: Source) -> str | None: + """Return why an evidence document cannot count for this source, or None.""" + if ( + document.get("schema") != EVIDENCE_SCHEMA + or document.get("check") != check + or document.get("result") != "passed" + or not isinstance(document.get("finished_at"), str) + or not isinstance(document.get("tag"), str) + or not isinstance(document.get("commit"), str) + or not isinstance(document.get("source_fingerprint"), (str, type(None))) + or not _is_image_map(document.get("services")) + or not _is_image_map(document.get("tool_images", {})) + ): + return "The evidence file is malformed." + if document["tag"] != source.tag: + return "The evidence was recorded for another release tag." + if document["commit"] != source.commit: + return "The evidence was recorded for another commit." + if document["source_fingerprint"] != source.fingerprint: + return "The evidence was recorded for another working tree state." + return None + + +def accept_evidence( + documents: dict[str, dict[str, Any] | None], source: Source +) -> tuple[dict[str, dict[str, Any]], dict[str, str]]: + """Split evidence into documents bound to this exact source and rejected ones.""" + accepted: dict[str, dict[str, Any]] = {} + rejected: dict[str, str] = {} + for check, document in sorted(documents.items()): + if document is None: + continue + problem = evidence_problem(document, check, source) + if problem: + rejected[check] = problem + else: + accepted[check] = document + return accepted, rejected + + +def build_record_problem(document: dict[str, Any]) -> str | None: + services = document.get("services") + if ( + document.get("schema") != BUILD_SCHEMA + or not isinstance(document.get("commit"), str) + or not isinstance(document.get("source_fingerprint"), (str, type(None))) + or not isinstance(services, dict) + ): + return "The build record is malformed." + for item in services.values(): + bases = item.get("base_images") if isinstance(item, dict) else None + if ( + not isinstance(item, dict) + or not isinstance(item.get("image_id"), str) + or not _is_str_map(item.get("build_args")) + or not isinstance(bases, list) + or not all( + isinstance(base, dict) + and all(isinstance(base.get(key), str) for key in ("arg", "reference", "digest")) + and _is_str_map(base.get("versions", {})) + for base in bases + ) + ): + return "The build record is malformed." + return None + + +@dataclass +class Inputs: + """Everything the manifest is derived from, so tests can supply fakes.""" + + source: Source + services: list[Service] + images: dict[str, dict[str, Any] | None] + build_record: dict[str, Any] | None + evidence: dict[str, dict[str, Any]] + go_binary: str | None + go: dict[str, Any] + files: dict[str, str | None] = field(default_factory=dict) + rejected_checks: dict[str, str] = field(default_factory=dict) + build_problem: str | None = None + + +def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs: + source = read_source(root) + services: list[Service] = [] + for group in GROUPS: + services.extend(group_services(docker, group, source.tag, root)) + images = {service.reference: docker.inspect_image(service.reference) for service in services} + directory = release_dir(source.tag, root) + evidence, rejected = accept_evidence( + {check: load_json(directory / f"evidence-{check}.json") for check in CHECKS}, source + ) + build = load_json(directory / "build.json") + build_problem = build_record_problem(build) if build is not None else None + if build_problem: + build = None + go_binary = None + backend = images.get(release_reference("backend", source.tag)) + if backend: + entrypoint = (backend.get("Config") or {}).get("Entrypoint") or [] + if entrypoint: + content = docker.read_file(backend["Id"], entrypoint[0]) + go_binary = go_build_version(content) if content else None + files = {name: file_digest(root / name) for name in LOCKFILES} + files[".node-version"] = text_match(root / "frontend/.node-version", r"^\s*(\S+)\s*$") + files["packageManager"] = text_match(root / "frontend/package.json", r'"packageManager":\s*"([^"]+)"') + files["dockerfile_pnpm"] = text_match(root / "frontend/Dockerfile", r"pnpm@([0-9][^\s\"]*)") + files["playwright"] = text_match(root / "frontend/package.json", r'"@playwright/test":\s*"([^"]+)"') + files[".python-version"] = text_match(root / "ml/.python-version", r"^\s*(\S+)\s*$") + files["requires-python"] = text_match(root / "ml/pyproject.toml", r'^requires-python\s*=\s*"([^"]+)"') + files["dockerfile_uv"] = text_match(root / "ml/Dockerfile", r"uv==([0-9][^\s\"]*)") + for service in services: + if service.dockerfile: + files[service.dockerfile] = file_digest(root / service.dockerfile) + return Inputs( + source, services, images, build, evidence, go_binary, go_policy(root), files, rejected, build_problem + ) + + +def base_version(build: dict[str, Any] | None, service: str, key: str) -> str | None: + if not build: + return None + for base in (build.get("services", {}).get(service) or {}).get("base_images", []): + if key in (base.get("versions") or {}): + return base["versions"][key] + return None + + +def build_manifest(inputs: Inputs, generated_at: str) -> dict[str, Any]: + source = inputs.source + build = inputs.build_record + files = inputs.files + build_matches_source = bool( + build and build.get("commit") == source.commit and build.get("source_fingerprint") == source.fingerprint + ) + components: list[dict[str, Any]] = [] + reasons: list[str] = [] + for service in inputs.services: + image = image_record(inputs.images.get(service.reference), service.reference, built=bool(service.dockerfile)) + component: dict[str, Any] = { + "name": service.name, + "group": service.group, + "kind": "built" if service.dockerfile else "pulled", + "compose_file": service.compose_file, + "image": image, + } + if service.dockerfile: + recorded = (build or {}).get("services", {}).get(service.name) + matches = bool(recorded and image.get("present") and recorded.get("image_id") == image.get("image_id")) + component["build"] = { + "dockerfile": service.dockerfile, + "dockerfile_digest": files.get(service.dockerfile), + "context": service.context, + "recorded_by_release_build": matches, + "build_args": recorded.get("build_args", {}) if matches else {}, + "base_images": recorded.get("base_images", []) if matches else [], + } + if not matches: + component["build"]["reason"] = "The local image was not built by release-build for this tag." + if component["build"]["dockerfile_digest"] is None: + reasons.append(f"The Dockerfile of {service.name} is missing.") + group = next(item for item in GROUPS if item.name == service.group) + if not image.get("present"): + verification = {"status": "not_verified", "reason": "The image is not present locally.", "checks": []} + elif not group.verifiable: + verification = {"status": "not_verified", "reason": group.unverified_reason, "checks": []} + else: + passed = sorted( + check + for check, document in inputs.evidence.items() + if (document.get("services", {}).get(service.name) or {}).get("image_id") == image.get("image_id") + ) + if passed: + verification = {"status": "verified", "checks": passed} + else: + verification = { + "status": "not_verified", + "reason": "No passing smoke or E2E run of this source state is recorded for this image ID.", + "checks": [], + } + component["verification"] = verification + components.append(component) + if service.group == "core": + if verification["status"] != "verified": + reasons.append(f"Core component {service.name} is not verified.") + elif set(verification["checks"]) != set(CHECKS): + reasons.append("Smoke and E2E were not both recorded for the current core images.") + if service.dockerfile and not component["build"]["recorded_by_release_build"]: + reasons.append(f"Core image {service.name} was not built by release-build.") + if not service.dockerfile and image.get("present") and not image.get("repo_digest"): + reasons.append(f"Core image {service.name} has no registry digest.") + for name, reason in sorted(MISSING_COMPONENTS.items()): + components.append( + { + "name": name, + "group": "missing", + "kind": "absent", + "image": None, + "verification": {"status": "missing", "reason": reason, "checks": []}, + } + ) + components.sort(key=lambda item: (["core", "ml", "monitoring", "missing"].index(item["group"]), item["name"])) + + go = dict(inputs.go) + go["build_image_version"] = base_version(build, "backend", "GOLANG_VERSION") + go["binary"] = inputs.go_binary + go["binary_matches"] = bool(go["go_mod"] and inputs.go_binary == f"go{go['go_mod']}") + if not go["consistent"]: + reasons.append("The Go pin in go.mod and backend/Dockerfile is inconsistent.") + if not go["binary_matches"]: + reasons.append("The backend binary was not confirmed to be built with the go.mod Go version.") + + node_image = base_version(build, "frontend", "NODE_VERSION") + node_matches = bool(node_image and node_image == files.get(".node-version")) + if node_image and not node_matches: + reasons.append("Node in the frontend build image differs from frontend/.node-version.") + python_image = base_version(build, "ml", "PYTHON_VERSION") + # ML is outside the release scope, so a Python mismatch is reported but + # does not keep the core release unverified. + python_matches = bool(python_image and python_image == files.get(".python-version")) + + for name in LOCKFILES: + if files.get(name) is None: + reasons.append(f"Lockfile {name} is missing.") + if source.dirty: + reasons.append("The working tree has uncommitted changes.") + if inputs.build_problem: + reasons.append(inputs.build_problem) + if not build_matches_source: + reasons.append("The build record does not match the current source state.") + for check, problem in sorted(inputs.rejected_checks.items()): + reasons.append(f"{check} evidence was not accepted: {problem}") + + checks = {} + for name, document in sorted(inputs.evidence.items()): + checks[name] = { + "scope": CHECK_SCOPE[name], + "finished_at": document.get("finished_at"), + "commit": document.get("commit"), + "source_fingerprint": document.get("source_fingerprint"), + "tool_images": document.get("tool_images", {}), + } + + return { + "schema": MANIFEST_SCHEMA, + "generated_at": generated_at, + "release": { + "tag": source.tag, + "status": "unverified" if reasons else "verified", + "scope": "core", + "required_checks": list(CHECKS), + "reasons": sorted(set(reasons)), + }, + "source": { + "commit": source.commit, + "dirty": source.dirty, + "fingerprint": source.fingerprint, + "build_matches_source": build_matches_source, + }, + "toolchains": { + "go": go, + "node": { + "node_version_file": files.get(".node-version"), + "package_manager": files.get("packageManager"), + "dockerfile_pnpm": files.get("dockerfile_pnpm"), + "build_image_version": node_image, + "matches_version_file": node_matches, + }, + "python": { + "python_version_file": files.get(".python-version"), + "requires_python": files.get("requires-python"), + "dockerfile_uv": files.get("dockerfile_uv"), + "build_image_version": python_image, + "matches_version_file": python_matches, + }, + "playwright": {"package_version": files.get("playwright")}, + }, + "lockfiles": {name: files.get(name) for name in LOCKFILES}, + "checks": checks, + "rejected_checks": dict(sorted(inputs.rejected_checks.items())), + "components": components, + } + + +def comparable(document: dict[str, Any] | None) -> dict[str, Any] | None: + if document is None: + return None + return {key: value for key, value in document.items() if key != "generated_at"} + + +def command_manifest(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + docker = docker or Docker() + inputs = collect_inputs(docker, root) + manifest = build_manifest(inputs, utc_now()) + path = release_dir(inputs.source.tag, root) / "manifest.json" + previous = load_json(path) + write_json(path, manifest, root) + print(f"Release manifest: {display(path, root)}") + print(f"Release {manifest['release']['tag']}: {manifest['release']['status']}") + for reason in manifest["release"]["reasons"]: + print(f" - {reason}") + for component in manifest["components"]: + image = component["image"] or {} + status = component["verification"]["status"] + presence = "" if component["image"] is None or image.get("present") else " (image missing locally)" + print(f" {component['group']:<10} {component['name']:<20} {status}{presence}") + if previous is not None: + if comparable(previous) == comparable(manifest): + print("Unchanged from the previous manifest apart from generated_at.") + else: + changed = sorted( + key + for key in set(previous) | set(manifest) + if key != "generated_at" and previous.get(key) != manifest.get(key) + ) + print("Changed from the previous manifest: " + ", ".join(changed)) + return 0 + + +# --------------------------------------------------------------------------- +# verify and check + + +def default_manifest(root: Path = ROOT) -> Path: + return release_dir(read_source(root).tag, root) / "manifest.json" + + +def compare_running(manifest: dict[str, Any], running: dict[str, dict[str, Any]]) -> tuple[bool, list[str]]: + components = { + item["name"]: item for item in manifest.get("components", []) if item.get("group") != "missing" + } + groups = {components[name]["group"] for name in running if name in components} + ok = True + lines: list[str] = [] + if not running: + return False, ["No running containers found in the project."] + for name in sorted(running): + if name not in components: + ok = False + lines.append(f"{name:<16} UNKNOWN runs {running[name]['reference']}, which the manifest does not list") + for name, component in sorted(components.items()): + if component["group"] not in groups: + continue + image = component.get("image") or {} + versions = " ".join(f"{key}={value}" for key, value in sorted((image.get("versions") or {}).items())) + if name not in running: + ok = False + lines.append(f"{name:<16} MISSING not running") + continue + actual = running[name] + if not image.get("present"): + ok = False + lines.append(f"{name:<16} MISMATCH the manifest has no image ID for {image.get('reference')}") + elif actual["image_id"] != image.get("image_id"): + ok = False + lines.append( + f"{name:<16} MISMATCH runs {actual['image_id']}, manifest {image.get('image_id')} ({image.get('reference')})" + ) + else: + note = "" if actual["reference"] == image.get("reference") else f" (started as {actual['reference']})" + lines.append( + f"{name:<16} OK {image.get('reference')} {image.get('image_id')}{note}" + + (f" {versions}" if versions else "") + ) + go_binary = (manifest.get("toolchains", {}).get("go") or {}).get("binary") + if "backend" in running and go_binary: + lines.append(f"backend binary built with {go_binary} (from the manifest)") + return ok, lines + + +def command_verify(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + docker = docker or Docker() + path = Path(args.manifest) if args.manifest else default_manifest(root) + manifest = load_json(path) + if manifest is None or manifest.get("schema") != MANIFEST_SCHEMA: + raise ReleaseError(f"No readable release manifest at {display(path, root)}; run make -C deploy release-manifest.") + running = running_services(docker.project_containers(args.project)) + ok, lines = compare_running(manifest, running) + release_info = manifest.get("release") or {} + print( + f"Project {args.project} against {display(path, root)} " + f"(release {release_info.get('tag')}, status {release_info.get('status')}):" + ) + for line in lines: + print(f" {line}") + print("All running containers match the manifest." if ok else "Running containers differ from the manifest.") + return 0 if ok else 1 + + +REQUIRED_KEYS = ( + "schema", "generated_at", "release", "source", "toolchains", "lockfiles", "checks", "rejected_checks", "components" +) +STATUSES = frozenset({"verified", "not_verified", "missing"}) + + +def structure_errors(manifest: dict[str, Any]) -> list[str]: + errors = [f"missing key {key}" for key in REQUIRED_KEYS if key not in manifest] + if manifest.get("schema") != MANIFEST_SCHEMA: + errors.append("unexpected schema") + for component in manifest.get("components", []): + status = (component.get("verification") or {}).get("status") + if status not in STATUSES: + errors.append(f"component {component.get('name')} has status {status!r}") + if status == "verified" and not component["verification"].get("checks"): + errors.append(f"component {component.get('name')} is verified without a check") + if status == "verified" and any( + check not in manifest.get("checks", {}) for check in component["verification"]["checks"] + ): + errors.append(f"component {component.get('name')} names an unrecorded check") + if not any(item.get("group") == "missing" for item in manifest.get("components", [])): + errors.append("missing components are not listed") + return errors + + +def command_check(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + path = Path(args.manifest) if args.manifest else default_manifest(root) + try: + text = path.read_text(encoding="utf-8") + manifest = json.loads(text) + except (OSError, ValueError) as error: + raise ReleaseError(f"No readable release manifest at {display(path, root)}.") from error + problems = structure_errors(manifest) + problems += forbidden_findings(text, sensitive_values(root)) + problems += [item for item in forbidden_findings(manifest) if item.startswith("configuration key")] + if problems: + print(f"{display(path, root)} failed the check:") + for problem in sorted(set(problems)): + print(f" - {problem}") + return 1 + print(f"{display(path, root)}: structure valid; no secrets, local paths, user or host names found.") + return 0 + + +def command_clean_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + """Remove every local release image; nothing else is touched.""" + docker = docker or Docker() + listing = run([docker.binary, "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"], env=docker_env()) + references = sorted( + {line for line in listing.decode().splitlines() if line.startswith(f"{RELEASE_REGISTRY}/")} + ) + if not references: + print("No release images to remove.") + return 0 + run([docker.binary, "image", "rm", *references], env=docker_env()) + for reference in references: + print(f"Removed {reference}") + return 0 + + +def command_tag(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int: + print(read_source(root).tag) + return 0 + + +def parser() -> argparse.ArgumentParser: + result = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = result.add_subparsers(dest="command", required=True) + commands.add_parser("tag").set_defaults(handler=command_tag) + commands.add_parser("clean-images").set_defaults(handler=command_clean_images) + build = commands.add_parser("build") + build.add_argument("--pull", choices=("missing", "always"), default="missing") + build.set_defaults(handler=command_build) + require = commands.add_parser("require-images") + require.add_argument("--group", choices=("core",), default="core") + require.add_argument("--tag") + require.set_defaults(handler=command_require_images) + record = commands.add_parser("record-evidence") + record.add_argument("--check", choices=CHECKS, required=True) + record.add_argument("--project", required=True) + record.add_argument("--tag") + record.add_argument("--tool-image", action="append", help="name=reference of a test tool image") + record.set_defaults(handler=command_record_evidence) + commands.add_parser("manifest").set_defaults(handler=command_manifest) + verify = commands.add_parser("verify") + verify.add_argument("--project", required=True) + verify.add_argument("--manifest") + verify.set_defaults(handler=command_verify) + check = commands.add_parser("check") + check.add_argument("--manifest") + check.set_defaults(handler=command_check) + return result + + +def main(argv: list[str] | None = None) -> int: + args = parser().parse_args(argv) + handler: Callable[[argparse.Namespace], int] = args.handler + try: + return handler(args) + except ReleaseError as error: + print(f"release: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/deploy/scripts/smoke.sh b/deploy/scripts/smoke.sh index 1467c20..a967657 100644 --- a/deploy/scripts/smoke.sh +++ b/deploy/scripts/smoke.sh @@ -1,9 +1,25 @@ #!/usr/bin/env bash +# Isolated technical smoke of the core stack. +# +# Optional environment: +# LINCODEX_RELEASE_TAG run against the release images of this tag (built +# by make -C deploy release-build) without building or +# pulling, and record passing evidence for the release +# manifest. Only make -C deploy release-smoke sets it. set -euo pipefail root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) compose_file="$root/deploy/docker/docker-compose.yml" +release_file="$root/deploy/docker/docker-compose.release.yml" +release_script="$root/deploy/scripts/release_manifest.py" env_file="$root/.env.example" +release_tag="${LINCODEX_RELEASE_TAG:-}" +compose_files=(-f "$compose_file") +up_args=(--build) +if [[ -n "$release_tag" ]]; then + compose_files+=(-f "$release_file") + up_args=(--no-build --pull never) +fi project=lincodex-smoke app_network="${project}_default" port=18080 @@ -15,10 +31,10 @@ started=0 # .env.example and points mail links at its own loopback port. compose() { APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \ - APP_PUBLIC_URL="http://localhost:$port" docker compose \ + APP_PUBLIC_URL="http://localhost:$port" LINCODEX_RELEASE_TAG="$release_tag" docker compose \ --env-file "$env_file" \ -p "$project" \ - -f "$compose_file" \ + "${compose_files[@]}" \ "$@" } @@ -44,6 +60,9 @@ if [[ -n "$(compose ps -q 2>/dev/null || true)" ]]; then printf 'Refusing to use existing Compose project %s.\n' "$project" >&2 exit 2 fi +if [[ -n "$release_tag" ]]; then + PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" require-images --tag "$release_tag" +fi cleanup() { local result=$? @@ -60,7 +79,7 @@ trap cleanup EXIT compose config --quiet started=1 -compose up --build -d --wait --wait-timeout 120 +compose up "${up_args[@]}" -d --wait --wait-timeout 120 wait_for() { local url=$1 @@ -165,4 +184,8 @@ fi curl --fail --silent --show-error "http://127.0.0.1:$port/api/v1/healthz" >/dev/null compose up -d --wait --wait-timeout 90 seaweedfs wait_for_readiness +if [[ -n "$release_tag" ]]; then + # Every check above passed; bind the result to the image IDs that ran. + PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" record-evidence --check smoke --project "$project" --tag "$release_tag" +fi printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, storage authentication and network isolation, and the disabled mail transport.' diff --git a/deploy/scripts/test_release_manifest.py b/deploy/scripts/test_release_manifest.py new file mode 100644 index 0000000..ea194d9 --- /dev/null +++ b/deploy/scripts/test_release_manifest.py @@ -0,0 +1,613 @@ +"""Tests for release_manifest.py and the pins it relies on. + +They use only the standard library and never call Docker: image, Compose, and +container data come from fakes. The pin tests read the checked-in go.mod and +Dockerfiles, so an implicit change of the Go version or an unpinnable base +image fails make -C deploy check. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +SPEC = importlib.util.spec_from_file_location("release_manifest", HERE / "release_manifest.py") +assert SPEC and SPEC.loader +release = importlib.util.module_from_spec(SPEC) +sys.modules["release_manifest"] = release +SPEC.loader.exec_module(release) + +AGREED_GO = "1.26.8" +COMMIT = "0123456789abcdef0123456789abcdef01234567" +FAKE_PASSWORD = "fake-password-7f3c9a" + + +def image(image_id: str, *, env: list[str] | None = None, digests: list[str] | None = None) -> dict: + return { + "Id": image_id, + "RepoDigests": digests or [], + "Os": "linux", + "Architecture": "arm64", + # Fields below must never reach the manifest. + "Config": { + "Env": (env or []) + [f"POSTGRES_PASSWORD={FAKE_PASSWORD}", "HOME=/home/someone"], + "Labels": {"com.docker.compose.project.working_dir": "/Users/someone/lincodex"}, + "Entrypoint": ["/app"], + }, + } + + +def services(tag: str) -> list: + service = release.Service + return [ + service("core", "backend", f"lincodex.invalid/backend:{tag}", "backend/Dockerfile", "backend", "deploy/docker/docker-compose.yml"), + service("core", "frontend", f"lincodex.invalid/frontend:{tag}", "frontend/Dockerfile", ".", "deploy/docker/docker-compose.yml"), + service("core", "postgres", "postgres:alpine", compose_file="deploy/docker/docker-compose.yml"), + service("ml", "ml", f"lincodex.invalid/ml:{tag}", "ml/Dockerfile", ".", "deploy/docker/docker-compose.ml.yml"), + service("monitoring", "prometheus", "prom/prometheus:latest", compose_file="deploy/docker/docker-compose.monitoring.yml"), + ] + + +def evidence_doc(check: str, source, ids: dict) -> dict: + return { + "schema": release.EVIDENCE_SCHEMA, + "check": check, + "result": "passed", + "tag": source.tag, + "commit": source.commit, + "source_fingerprint": source.fingerprint, + "finished_at": "2026-10-06T00:00:00Z", + "services": {name: {"reference": f"{name}:x", "image_id": value} for name, value in ids.items()}, + "tool_images": {}, + } + + +CURRENT_IDS = {"backend": "sha256:b1", "frontend": "sha256:f1", "postgres": "sha256:e1"} + + +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.update({".node-version": "26.10.0", ".python-version": "3.14.8"}) + return files + + +def inputs( + *, + dirty: bool = False, + evidence_ids: dict | None = None, + checks: tuple = ("smoke", "e2e"), + go_binary: str | None = "go1.26.8", + files: dict | None = None, + postgres_digests: list | None = None, + node_version: str = "26.10.0", + python_version: str = "3.14.8", +) -> object: + 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"]), + "postgres:alpine": image( + "sha256:e1", env=["PG_VERSION=18.6"], digests=["postgres@sha256:e1"] if postgres_digests is None else postgres_digests + ), + f"lincodex.invalid/ml:{tag}": image("sha256:c1", env=["PYTHON_VERSION=3.14.8"]), + "prom/prometheus:latest": None, + } + build = { + "schema": release.BUILD_SCHEMA, + "commit": COMMIT, + "source_fingerprint": source.fingerprint, + "services": { + "backend": { + "image_id": "sha256:b1", + "build_args": {"GO_IMAGE": "golang:1.26.8-alpine@sha256:g1"}, + "base_images": [ + {"arg": "GO_IMAGE", "reference": "golang:1.26.8-alpine", "digest": "sha256:g1", "versions": {"GOLANG_VERSION": "1.26.8"}} + ], + }, + "frontend": { + "image_id": "sha256:f1", + "build_args": {}, + "base_images": [{"arg": "NODE_IMAGE", "reference": "node:alpine", "digest": "sha256:n1", "versions": {"NODE_VERSION": node_version}}], + }, + "ml": { + "image_id": "sha256:c1", + "build_args": {}, + "base_images": [{"arg": "PYTHON_IMAGE", "reference": "python:alpine", "digest": "sha256:y1", "versions": {"PYTHON_VERSION": python_version}}], + }, + }, + } + ids = CURRENT_IDS if evidence_ids is None else evidence_ids + evidence = {check: evidence_doc(check, source, ids) for check in checks} + go = {"go_mod": "1.26.8", "toolchain_directive": None, "dockerfile_image": "golang:1.26.8-alpine", "gotoolchain_local": True, "consistent": True} + return release.Inputs(source, services(tag), images, build, evidence, go_binary, go, all_files() if files is None else files) + + +def component(manifest: dict, name: str) -> dict: + return next(item for item in manifest["components"] if item["name"] == name) + + +class PinTest(unittest.TestCase): + def test_go_is_pinned_to_the_agreed_version_without_toolchain_drift(self) -> None: + policy = release.go_policy(ROOT) + self.assertEqual(policy["go_mod"], AGREED_GO) + self.assertIn(policy["toolchain_directive"], (None, f"go{AGREED_GO}")) + self.assertEqual(policy["dockerfile_image"], f"golang:{AGREED_GO}-alpine") + self.assertTrue(policy["gotoolchain_local"], "backend/Dockerfile must set ENV GOTOOLCHAIN=local in the build stage") + self.assertTrue(policy["consistent"]) + + def test_every_service_base_image_is_a_pinnable_argument(self) -> None: + for name in ("backend/Dockerfile", "frontend/Dockerfile", "ml/Dockerfile"): + with self.subTest(dockerfile=name): + bases = release.dockerfile_bases((ROOT / name).read_text(encoding="utf-8"), name) + self.assertTrue(bases) + + def test_external_copy_or_mount_source_is_rejected(self) -> None: + for line in ("COPY --from=alpine:3 /a /b", "RUN --mount=type=bind,from=evil/image,target=/x true", "COPY --chown=1:1 --from=2 /a /b"): + with self.subTest(line=line): + with self.assertRaises(release.ReleaseError): + release.dockerfile_bases(f"ARG A_IMAGE=a:1\nFROM ${{A_IMAGE}} AS base\n{line}\n") + text = ( + "ARG A_IMAGE=a:1\nFROM ${A_IMAGE} AS base\nFROM base\nCOPY --from=base /a /b\nCOPY --from=0 /a /b\n" + "RUN --mount=type=bind,from=base,target=/s \\\n true\n" + ) + self.assertEqual([base.arg for base in release.dockerfile_bases(text)], ["A_IMAGE"]) + + def test_literal_or_undefined_base_is_rejected(self) -> None: + with self.assertRaises(release.ReleaseError): + release.dockerfile_bases("FROM alpine:latest\n") + with self.assertRaises(release.ReleaseError): + release.dockerfile_bases("FROM ${NODE_IMAGE}\n") + bases = release.dockerfile_bases("ARG A_IMAGE=a:1\nFROM ${A_IMAGE} AS base\nFROM base AS build\nFROM base\n") + self.assertEqual([base.default for base in bases], ["a:1"]) + + def test_inconsistent_go_pin_is_reported(self) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "backend").mkdir() + (root / "backend/go.mod").write_text("module x\n\ngo 1.26.8\n\ntoolchain go1.27.0\n", encoding="utf-8") + (root / "backend/Dockerfile").write_text( + "ARG GO_IMAGE=golang:1.26.8-alpine\nFROM ${GO_IMAGE} AS build\nENV GOTOOLCHAIN=local\n", encoding="utf-8" + ) + self.assertFalse(release.go_policy(root)["consistent"]) + (root / "backend/go.mod").write_text("module x\n\ngo 1.26.8\n", encoding="utf-8") + self.assertTrue(release.go_policy(root)["consistent"]) + (root / "backend/Dockerfile").write_text("ARG GO_IMAGE=golang:1.26.8-alpine\nFROM ${GO_IMAGE} AS build\n", encoding="utf-8") + self.assertFalse(release.go_policy(root)["consistent"]) + + +class BuildInfoTest(unittest.TestCase): + def blob(self, version: bytes, offset: int = 64) -> bytes: + header = b"\xff Go buildinf:" + bytes([8, 0x2]) + b"\0" * 16 + body = bytes([len(version)]) + version + bytes([3]) + b"mod" + return b"\0" * offset + header + body + + def test_reads_inline_version(self) -> None: + self.assertEqual(release.go_build_version(self.blob(b"go1.26.8")), "go1.26.8") + + def test_ignores_unaligned_or_missing_header(self) -> None: + self.assertIsNone(release.go_build_version(self.blob(b"go1.26.8", offset=63))) + self.assertIsNone(release.go_build_version(b"no build info")) + + +class ManifestTest(unittest.TestCase): + def test_clean_verified_release(self) -> None: + 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"]["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(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["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"]) + self.assertIn("org.opencontainers.image.version", release.image_record(info, "x")["versions"]) + + def test_ml_monitoring_and_missing_components_are_never_verified(self) -> None: + manifest = release.build_manifest(inputs(), "t") + self.assertEqual(component(manifest, "ml")["verification"]["status"], "not_verified") + prometheus = component(manifest, "prometheus") + self.assertEqual(prometheus["verification"]["status"], "not_verified") + self.assertFalse(prometheus["image"]["present"]) + for name in ("gpu-inference", "judge0", "qdrant"): + with self.subTest(component=name): + self.assertEqual(component(manifest, name)["verification"]["status"], "missing") + 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") + self.assertEqual(component(manifest, "backend")["verification"]["status"], "not_verified") + self.assertEqual(component(manifest, "frontend")["verification"]["status"], "not_verified") + self.assertEqual(manifest["release"]["status"], "unverified") + + def test_dirty_tree_or_wrong_go_binary_keeps_the_release_unverified(self) -> None: + dirty = release.build_manifest(inputs(dirty=True), "t") + self.assertEqual(dirty["release"]["status"], "unverified") + self.assertIn("The working tree has uncommitted changes.", dirty["release"]["reasons"]) + self.assertEqual(component(dirty, "backend")["verification"]["status"], "verified") + self.assertEqual(dirty["source"]["fingerprint"], "git-tree:" + "ab" * 20) + go = release.build_manifest(inputs(go_binary="go1.27.0"), "t") + self.assertEqual(go["release"]["status"], "unverified") + self.assertFalse(go["toolchains"]["go"]["binary_matches"]) + + def test_manifest_is_deterministic_apart_from_generated_at(self) -> None: + first = release.build_manifest(inputs(), "2026-10-06T00:00:00Z") + second = release.build_manifest(inputs(), "2026-10-07T12:00:00Z") + self.assertNotEqual(first, second) + self.assertEqual(release.comparable(first), release.comparable(second)) + + def test_manifest_carries_no_environment_labels_or_paths(self) -> None: + manifest = release.build_manifest(inputs(), "t") + text = json.dumps(manifest) + self.assertNotIn(FAKE_PASSWORD, text) + self.assertNotIn("/Users/", text) + self.assertNotIn("/home/", text) + self.assertEqual(release.forbidden_findings(manifest, {"fake": FAKE_PASSWORD, "user": "someone"}), []) + + +class ScannerTest(unittest.TestCase): + def test_detects_secrets_and_machine_data_without_echoing_them(self) -> None: + cases = { + "private key block": "-----BEGIN OPENSSH PRIVATE KEY-----", + "credentials in a URL": "postgres://lincodex:hunter22@postgres:5432/db", + "secret assignment": "REDIS_PASSWORD=abc", + "AWS access key": "AKIAABCDEFGHIJKLMNOP", + "GitHub token": "ghp_" + "a" * 30, + "absolute local path": "context /Users/someone/project", + "home directory shorthand": "~/project", + } + for name, text in cases.items(): + with self.subTest(pattern=name): + findings = release.forbidden_findings({"value": text}) + self.assertIn(name, findings) + self.assertFalse(any(text in finding for finding in findings)) + + def test_detects_known_sensitive_values_and_configuration_keys(self) -> None: + document = {"image": {"note": f"built by someone with {FAKE_PASSWORD}"}, "Env": []} + findings = release.forbidden_findings(document, {"value of X_PASSWORD from root .env": FAKE_PASSWORD, "local user name": "someone"}) + self.assertIn("value of X_PASSWORD from root .env", findings) + self.assertIn("local user name", findings) + self.assertIn("configuration key 'Env' at $", findings) + self.assertFalse(any(FAKE_PASSWORD in finding for finding in findings)) + + def test_accepts_ordinary_release_data(self) -> None: + document = { + "reference": "gcr.io/distroless/static-debian12:nonroot@sha256:" + "0" * 64, + "image": "lincodex.invalid/backend:0123456789ab-dirty", + "dockerfile": "frontend/Dockerfile", + "versions": {"PG_VERSION": "18.6"}, + "url": "https://github.com/seaweedfs/seaweedfs", + } + self.assertEqual(release.forbidden_findings(document, {"local user name": "someone"}), []) + + def test_secret_names_cover_common_variants(self) -> None: + for name in ("GPG_PASSPHRASE", "SSHPASS", "JWT_SIGNING_KEY", "SENTRY_DSN", "DB_PWD", "SESSION_COOKIE", "BASIC_AUTH"): + with self.subTest(name=name): + values = release.sensitive_values(ROOT, {name: "value-123456"}) + self.assertIn(f"value of {name} from environment", values) + self.assertNotIn("value of POSTGRES_DB from environment", release.sensitive_values(ROOT, {"POSTGRES_DB": "value-123456"})) + self.assertEqual( + [label for label in release.sensitive_values(ROOT, {"SHORT_TOKEN": "abc"}) if "SHORT_TOKEN" in label], [] + ) + + def test_long_values_are_found_as_substrings_and_in_base64(self) -> None: + import base64 + + secret = "Sup3rS3cretValue" + sensitive = {"value of X_TOKEN from environment": secret} + self.assertTrue(release.forbidden_findings({"v": f"prefix{secret}suffix"}, sensitive)) + encoded = base64.b64encode(secret.encode()).decode().rstrip("=") + self.assertTrue(release.forbidden_findings({"v": f"x{encoded}y"}, sensitive)) + self.assertEqual(release.forbidden_findings({"v": "nothing here"}, sensitive), []) + + def test_sensitive_values_come_from_secret_names_only(self) -> None: + values = release.sensitive_values( + ROOT, {"HOME": "/home/someone", "APP_TOKEN": "tok-123456", "POSTGRES_DB": "lincodexdb", "EMPTY_SECRET": ""} + ) + found = set(values.values()) + self.assertIn("tok-123456", found) + self.assertNotIn("lincodexdb", found) + self.assertNotIn("", found) + + +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") + self.assertIsNone(release.repo_digest({"RepoDigests": []}, "redis:alpine")) + + def test_release_tag_is_validated_before_it_becomes_a_path(self) -> None: + with self.assertRaises(release.ReleaseError): + release.release_dir("../../etc") + self.assertEqual(release.release_dir("0123456789ab-dirty", ROOT).name, "0123456789ab-dirty") + + +class EvidenceBindingTest(unittest.TestCase): + """S1: evidence counts only for the exact tag, commit, and tree state.""" + + source = release.Source(COMMIT, True, "git-tree:" + "ab" * 20) + + def check(self, field: str, value, expected: str) -> None: + document = evidence_doc("smoke", self.source, CURRENT_IDS) + document[field] = value + accepted, rejected = release.accept_evidence({"smoke": document, "e2e": None}, self.source) + self.assertEqual(accepted, {}) + self.assertEqual(rejected, {"smoke": expected}) + + def test_other_tag_is_rejected(self) -> None: + self.check("tag", "fedcba987654-dirty", "The evidence was recorded for another release tag.") + + def test_other_commit_is_rejected(self) -> None: + self.check("commit", "f" * 40, "The evidence was recorded for another commit.") + + def test_other_fingerprint_is_rejected(self) -> None: + self.check("source_fingerprint", "git-tree:" + "cd" * 20, "The evidence was recorded for another working tree state.") + + def test_malformed_evidence_is_rejected(self) -> None: + self.check("services", {"backend": {"image_id": "not-an-id", "reference": "x"}}, "The evidence file is malformed.") + self.check("result", "failed", "The evidence file is malformed.") + + def test_matching_evidence_is_accepted(self) -> None: + document = evidence_doc("smoke", self.source, CURRENT_IDS) + accepted, rejected = release.accept_evidence({"smoke": document}, self.source) + self.assertEqual(list(accepted), ["smoke"]) + self.assertEqual(rejected, {}) + + def test_rejected_evidence_is_reported_in_the_manifest(self) -> None: + data = inputs() + data.rejected_checks = {"e2e": "The evidence was recorded for another commit."} + data.evidence.pop("e2e") + manifest = release.build_manifest(data, "t") + self.assertEqual(manifest["rejected_checks"], {"e2e": "The evidence was recorded for another commit."}) + self.assertEqual(manifest["release"]["status"], "unverified") + self.assertIn("e2e evidence was not accepted: The evidence was recorded for another commit.", manifest["release"]["reasons"]) + + def test_malformed_build_record_is_detected(self) -> None: + build = inputs().build_record + self.assertIsNone(release.build_record_problem(build)) + build["services"]["backend"]["build_args"] = {"GO_IMAGE": 1} + self.assertEqual(release.build_record_problem(build), "The build record is malformed.") + self.assertEqual(release.build_record_problem({"schema": "other"}), "The build record is malformed.") + + +class ReleaseRequirementsTest(unittest.TestCase): + """S2 and S3: what keeps a release unverified.""" + + def reasons(self, **kwargs) -> list: + manifest = release.build_manifest(inputs(**kwargs), "t") + self.assertEqual(manifest["release"]["status"], "unverified") + return manifest["release"]["reasons"] + + def test_smoke_alone_does_not_verify_the_release(self) -> None: + reasons = self.reasons(checks=("smoke",)) + self.assertIn("Smoke and E2E were not both recorded for the current core images.", reasons) + manifest = release.build_manifest(inputs(checks=("smoke",)), "t") + self.assertEqual(component(manifest, "backend")["verification"], {"status": "verified", "checks": ["smoke"]}) + + 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"}) + manifest = release.build_manifest(data, "t") + self.assertEqual(manifest["release"]["status"], "unverified") + self.assertEqual(component(manifest, "backend")["verification"]["checks"], ["smoke"]) + self.assertIn("Smoke and E2E were not both recorded for the current core images.", manifest["release"]["reasons"]) + + def test_core_pulled_image_without_registry_digest(self) -> None: + self.assertIn("Core image postgres has no registry digest.", self.reasons(postgres_digests=[])) + + def test_missing_lockfile(self) -> None: + files = all_files() + files["frontend/pnpm-lock.yaml"] = None + self.assertIn("Lockfile frontend/pnpm-lock.yaml is missing.", self.reasons(files=files)) + + def test_missing_dockerfile_digest(self) -> None: + files = all_files() + files["ml/Dockerfile"] = None + self.assertIn("The Dockerfile of ml is missing.", self.reasons(files=files)) + + def test_node_version_drift_keeps_the_release_unverified(self) -> None: + self.assertIn("Node in the frontend build image differs from frontend/.node-version.", self.reasons(node_version="27.0.0")) + + def test_python_drift_is_reported_without_blocking_the_core_release(self) -> None: + manifest = release.build_manifest(inputs(python_version="3.15.0"), "t") + self.assertEqual(manifest["release"]["status"], "verified", manifest["release"]["reasons"]) + self.assertFalse(manifest["toolchains"]["python"]["matches_version_file"]) + + +class FakeDocker: + def __init__(self, tag_holder: list) -> None: + self.tag_holder = tag_holder + self.built: list = [] + + def compose_config(self, files, tag, root): + if files[0].endswith("docker-compose.ml.yml"): + return {"services": {"ml": {"image": f"lincodex.invalid/ml:{tag}", "build": {"context": str(ROOT), "dockerfile": "ml/Dockerfile"}}}} + return { + "services": { + "backend": {"image": f"lincodex.invalid/backend:{tag}", "build": {"context": str(ROOT / "backend"), "dockerfile": "Dockerfile"}}, + "postgres": {"image": "postgres:alpine"}, + } + } + + def inspect_image(self, reference): + base = reference.split(":")[0] + return image("sha256:" + "1" * 8, digests=[f"{base}@sha256:{'2' * 8}"]) + + def pull(self, reference): + raise AssertionError("no pull expected") + + def compose_build(self, files, tag, service, build_args, root): + self.built.append((service, dict(build_args))) + + +class BuildStabilityTest(unittest.TestCase): + """S7: a source change during the build refuses the build record.""" + + def run_build(self, sources: list) -> tuple: + import tempfile + from argparse import Namespace + from unittest import mock + + docker = FakeDocker([]) + with tempfile.TemporaryDirectory() as directory, mock.patch.object(release, "read_source", side_effect=sources), mock.patch.object( + release, "release_dir", lambda tag, root=ROOT: Path(directory) / tag + ): + try: + release.command_build(Namespace(pull="missing"), docker, ROOT) + error = None + except release.ReleaseError as caught: + error = caught + written = (Path(directory) / sources[0].tag / "build.json").exists() + return docker, error, written + + def test_changed_fingerprint_fails_without_writing(self) -> None: + before = release.Source(COMMIT, True, "git-tree:" + "ab" * 20) + after = release.Source(COMMIT, True, "git-tree:" + "cd" * 20) + docker, error, written = self.run_build([before, after]) + self.assertIsNotNone(error) + self.assertIn("changed during the build", str(error)) + self.assertFalse(written) + self.assertEqual([service for service, _ in docker.built], ["backend", "ml"]) + + def test_changed_commit_fails_without_writing(self) -> None: + before = release.Source(COMMIT, False, None) + after = release.Source("f" * 40, False, None) + _, error, written = self.run_build([before, after]) + self.assertIsNotNone(error) + self.assertFalse(written) + + def test_stable_source_writes_pinned_build_args(self) -> None: + source = release.Source(COMMIT, False, None) + docker, error, written = self.run_build([source, source]) + 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) + + +class FingerprintTest(unittest.TestCase): + """S4: the working tree fingerprint ignores git diff and line ending config.""" + + def git(self, root: Path, *args: str) -> None: + import subprocess + + subprocess.run(["git", *args], cwd=root, check=True, capture_output=True, env=self.env) + + def setUp(self) -> None: + import os + import tempfile + + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + self.env.update({"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"}) + self.git(self.root, "init", "-q") + (self.root / "a.txt").write_text("one\n", encoding="utf-8") + self.git(self.root, "add", "a.txt") + self.git(self.root, "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "init") + + def tearDown(self) -> None: + self.directory.cleanup() + + def source(self): + from unittest import mock + + with mock.patch.dict("os.environ", {"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"}): + return release.read_source(self.root) + + def test_clean_tree_has_no_fingerprint(self) -> None: + source = self.source() + self.assertFalse(source.dirty) + self.assertIsNone(source.fingerprint) + + def test_fingerprint_covers_changes_and_untracked_files_and_ignores_config(self) -> None: + (self.root / "a.txt").write_text("two\n", encoding="utf-8") + first = self.source() + self.assertTrue(first.dirty) + for key, value in ( + ("diff.noprefix", "true"), + ("diff.mnemonicPrefix", "true"), + ("diff.algorithm", "histogram"), + ("diff.context", "10"), + ("core.autocrlf", "true"), + ): + self.git(self.root, "config", key, value) + with self.subTest(setting=key): + self.assertEqual(self.source(), first) + (self.root / "new.txt").write_text("untracked\n", encoding="utf-8") + with_untracked = self.source() + self.assertNotEqual(with_untracked.fingerprint, first.fingerprint) + (self.root / ".gitignore").write_text("ignored.txt\n", encoding="utf-8") + ignore_only = self.source() + (self.root / "ignored.txt").write_text("local\n", encoding="utf-8") + self.assertEqual(self.source(), ignore_only) + + def test_real_index_is_not_changed(self) -> None: + (self.root / "b.txt").write_text("b\n", encoding="utf-8") + self.source() + import subprocess + + staged = subprocess.run(["git", "diff", "--cached", "--name-only"], cwd=self.root, capture_output=True, env=self.env, check=True) + self.assertEqual(staged.stdout, b"") + + +class VerifyTest(unittest.TestCase): + def manifest(self) -> dict: + return release.build_manifest(inputs(), "t") + + 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"}, + } + ok, lines = release.compare_running(self.manifest(), running) + self.assertTrue(ok, lines) + + 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"}, + } + ok, lines = release.compare_running(self.manifest(), running) + self.assertFalse(ok) + text = "\n".join(lines) + self.assertIn("backend MISMATCH", text) + self.assertIn("postgres MISSING", text) + self.assertIn("extra UNKNOWN", text) + + 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}", + "Config": {"Image": f"{service}:x", "Labels": {"com.docker.compose.service": service, "com.docker.compose.oneoff": oneoff}}, + "State": {"Running": running}, + } + + found = release.running_services([container("a"), container("b", running=False), container("c", oneoff="True")]) + self.assertEqual(sorted(found), ["a"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index f62daf0..298e10d 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -311,7 +311,7 @@ For remote ML scraping, set ML_METRICS_TARGET to hostname:port or IPv4:port and ## Services and images -Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; resolve and record actual image digests and an SBOM for a release. Application dependency lockfiles remain checked in separately. +Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately. | Component | Current image source | Principal upstream license | | --- | --- | --- | @@ -333,6 +333,71 @@ These entries name the principal upstream project's license; they are not a comp The backend builds with Go 1.26.8; its runtime image is selected in backend/Dockerfile. Frontend and ML base images are selected in their Dockerfiles. Upstream sources include [Docker Official Images](https://github.com/docker-library), [Distroless](https://github.com/GoogleContainerTools/distroless), and [NGINX unprivileged images](https://github.com/nginxinc/docker-nginx-unprivileged); inspect exact tags and layers before distribution. +## 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: + + 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 + +- `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/`. + +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. + +### Format + +The manifest is JSON with sorted keys and schema `lincodex.release-manifest/v1`: + +| 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 | +| `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` | + +`verification.status` is one of: + +- `verified`: at least one accepted smoke or E2E run recorded this exact image ID for the service. `verification.checks` lists which. Only core services can be verified. +- `not_verified`: the image is absent, was not in an accepted passing run, or belongs to a group no release check starts. ML is built but no check starts it and it has no model; monitoring images are recorded only when present locally. +- `missing`: the component is planned but has no service or image in this repository: GPU inference, Judge0, and Qdrant. + +The release is `verified` only when all of the following hold; otherwise `release.reasons` names each failed condition: + +- the working tree is clean and the build record is well formed and matches the current source; +- every core image was built by `release-build`, and every core pulled image has a registry digest; +- both smoke and E2E evidence for the current source passed on the current image ID of every core component; +- every lockfile and every service Dockerfile exists; +- the Go pin is consistent and the backend binary reports the go.mod Go version; +- Node in the frontend build image equals `frontend/.node-version`. + +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. + +### Go pin + +go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO_IMAGE` is `golang:1.26.8-alpine`, and the build stage sets `GOTOOLCHAIN=local`, so a go.mod that asks for a newer Go fails the build instead of downloading another toolchain. `make -C deploy check` fails when these pins disagree or when a Dockerfile uses a base image that is not a pinnable build argument. The manifest also records the version read from the build information of the backend binary; to read it, the generator creates a container from the image without starting it, copies the binary out, and removes the container. + +### 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 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. +- `verified` means the image passed the recorded technical checks. Kafka publication, product workflows, ML, monitoring, backups, and production hosts are not checked. +- CI runs `check-release` as part of `make -C deploy check`, but not the release build, the release runs, or the manifest targets. + ## Observability configuration Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, Redis exporter on port 9121, SeaweedFS on port 9327, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index af0383f..c470608 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -25,7 +25,7 @@ Useful focused commands: | make -C ml check | Ruff, mypy, pytest, and wheel build | | make -C ml check-generated | Pydantic models match the ML bundle without rewriting files | | make -C deploy config | Render Compose configurations without starting them | -| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()` | +| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()`, and `check-release`; see [Release manifest tests](#release-manifest-tests) | | make -C deploy smoke | Isolated technical smoke of service health routes | | make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack | | make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON | @@ -60,6 +60,20 @@ The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` The suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. +## Release manifest tests + +`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that: + +- the manifest copies no environment values, labels, or local paths, and two generations differ only in `generated_at`; +- evidence counts only for the same tag, commit, and working tree fingerprint, and malformed evidence or build records are not used; +- a component is `verified` only with evidence for its exact image ID, ML, monitoring, and missing components are never verified, and the release stays unverified without both smoke and E2E on the current images, on a dirty tree, with a core pulled image without a registry digest, a missing lockfile or Dockerfile, another Go version in the binary, or another Node version in the build image; +- `release-build` refuses to write the build record when the commit or the working tree changes during the build; +- the working tree fingerprint of a temporary Git repository ignores diff and line ending settings, covers untracked files, skips ignored ones, and leaves the real index unchanged; +- the secret scan finds key blocks, tokens, credentials in URLs, local paths, user and host names, and values of secret-like variables, also as substrings and in base64, without echoing them; +- the running-container comparison reports a different digest, a missing service, and an unknown service. + +The test does not build images or start containers. The end-to-end path is `release-build`, `release-smoke` and `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify`, and `release-manifest-check`; see [DEPLOY.md](DEPLOY.md#release-manifest). + ## Integration test bootstrap The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling `env := bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, waits for adapter readiness, and returns an environment with configuration and clients. To test one adapter, use `bootstrap(t, postgresService)`, `bootstrap(t, redisService)`, or `bootstrap(t, seaweedfsService)`. Multiple services can be selected. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index e7d7539..853142b 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -313,7 +313,7 @@ Frontend телеметрия пока не подключена в React-при ## Сервисы и образы -Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; для выпуска фиксируйте фактические image digests и SBOM. Lockfiles прикладных зависимостей сохраняются отдельно. +Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно. | Компонент | Текущий источник образа | Основной upstream license | | --- | --- | --- | @@ -335,6 +335,71 @@ Frontend телеметрия пока не подключена в React-при Backend строится с Go 1.26.8; образ runtime выбран в backend/Dockerfile. Базовые образы frontend и ML описаны в соответствующих Dockerfiles. Исходники: [Docker Official Images](https://github.com/docker-library), [Distroless](https://github.com/GoogleContainerTools/distroless) и [NGINX unprivileged images](https://github.com/nginxinc/docker-nginx-unprivileged); перед распространением проверьте точные tags и слои. +## Манифест выпуска + +Манифест выпуска фиксирует, из чего состоит проверенный локальный выпуск: коммит, версии toolchain, хеши lockfiles, образ каждого сервиса с фактическим digest и компоненты, на которых проверка действительно выполнялась. Плавающие теги `latest` и `alpine` по договоренности остаются в Compose и Dockerfile; манифест закрепляет, во что они разрешились в момент выпуска. Интерфейс - `make -C deploy release-manifest`; остальные цели `release-*` готовят его входные данные и проверяют результат: + + 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 + +- `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/`. + +Тег выпуска - первые 12 символов коммита, с суффиксом `-dirty`, если рабочее дерево отличается от коммита. Отпечаток рабочего дерева - Git tree ID, записанный из временного индекса (заполняется из HEAD, затем `git add -A`) с закрепленными настройками переводов строк, режима файлов, symlink и fsmonitor. Он учитывает измененные, удаленные и неотслеживаемые файлы, не зависит от настроек diff и не меняет настоящий индекс. Все файлы пишутся в `deploy/release//`, который игнорируют Git и корневой `.dockerignore`. Манифесты не коммитятся: image ID собранных образов зависят от машины, платформы и времени сборки, а манифест описывает то, что собрала и проверила эта машина. Прикладывайте манифест к выпуску. + +### Формат + +Манифест - JSON с отсортированными ключами и схемой `lincodex.release-manifest/v1`: + +| Ключ | Содержимое | +| --- | --- | +| `schema`, `generated_at` | Версия схемы и время генерации в UTC | +| `release` | `tag`, `status` (`verified` или `unverified`), `scope` (`core`), `required_checks` (`smoke`, `e2e`) и `reasons`, по которым выпуск не проверен | +| `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` | + +`verification.status` принимает значения: + +- `verified`: хотя бы один принятый smoke или E2E записал именно этот image ID сервиса. Какие именно, перечисляет `verification.checks`. Проверенными могут быть только core-сервисы. +- `not_verified`: образа нет локально, он не участвовал в принятом успешном прогоне или относится к группе, которую не запускает ни одна проверка выпуска. ML собирается, но проверки его не запускают, и модели у него нет; образы monitoring записываются, только если есть локально. +- `missing`: компонент запланирован, но в репозитории нет его сервиса или образа: GPU inference, Judge0 и Qdrant. + +Выпуск получает `verified`, только если выполнены все условия ниже; иначе `release.reasons` называет каждое невыполненное: + +- рабочее дерево чистое, запись сборки корректна и соответствует текущим исходникам; +- каждый core-образ собран `release-build`, у каждого скачанного core-образа есть registry digest; +- evidence и smoke, и E2E для текущих исходников прошел на текущем image ID каждого core-компонента; +- все lockfiles и Dockerfile сервисов существуют; +- Go pin согласован, и бинарник backend сообщает версию Go из go.mod; +- Node в образе сборки frontend совпадает с `frontend/.node-version`. + +Версия 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` повторяет проверку. + +### Go pin + +go.mod объявляет `go 1.26.8` без отдельной строки `toolchain`, `GO_IMAGE` по умолчанию - `golang:1.26.8-alpine`, а этап сборки задает `GOTOOLCHAIN=local`, поэтому go.mod с требованием более новой Go роняет сборку вместо скачивания другого toolchain. `make -C deploy check` падает, если эти значения расходятся или Dockerfile использует базовый образ не через закрепляемый build-аргумент. Манифест также записывает версию из build information бинарника backend; для этого генератор создает контейнер из образа без запуска, копирует бинарник и удаляет контейнер. + +### Что не покрыто + +- Манифест не является SBOM, перечнем лицензий, подписью или provenance attestation и не публикуется в registry. +- Файлы в `deploy/release/` локальны и не защищены от подмены; evidence не подписан и подтверждает только то, что записала эта машина. +- Файлы, которые игнорирует Git, не входят в отпечаток. В контекст сборки они все равно попадают, если их не исключает `.dockerignore`. +- Образы собираются только для локальной платформы. Версии без переменной образа или label, например Kafka, определяются только digest. +- `verified` означает, что образ прошел записанные технические проверки. Публикация в Kafka, продуктовые сценарии, ML, мониторинг, резервное копирование и production-хосты не проверяются. +- CI запускает `check-release` в составе `make -C deploy check`, но не сборку выпуска, прогоны на образах выпуска и цели манифеста. + ## Observability configuration Prometheus опрашивает backend /metrics на порту 9090, PostgreSQL exporter, Redis exporter на порту 9121, SeaweedFS на порту 9327, node exporter, себя и необязательный ML target. Loki использует файловое хранилище в single-binary режиме с хранением 168 часов. Grafana загружает datasource Prometheus и Loki из observability/grafana/provisioning/. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 3ceb376..953b40c 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -25,7 +25,7 @@ make test запускает backend, frontend и ML тесты. make check та | make -C ml check | Ruff, mypy, pytest и сборку wheel | | make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов | | make -C deploy config | Рендер Compose конфигураций без запуска | -| make -C deploy check | Рендер Compose конфигураций и `check-workflows`, который падает, если job `aggregate` в workflow не зависит от всех остальных jobs или не имеет `if: always()` | +| make -C deploy check | Рендер Compose конфигураций, `check-workflows`, который падает, если job `aggregate` в workflow не зависит от всех остальных jobs или не имеет `if: always()`, и `check-release`; см. [Тесты манифеста выпуска](#тесты-манифеста-выпуска) | | make -C deploy smoke | Изолированный технический smoke по service health routes | | make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке | | make -C observability check | Проверку Prometheus, Loki, Alloy и dashboard JSON | @@ -60,6 +60,20 @@ Deployment smoke проверяет инфраструктурные маршр Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. +## Тесты манифеста выпуска + +`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что: + +- манифест не копирует значения окружения, labels и локальные пути, а две генерации различаются только `generated_at`; +- evidence засчитывается только для того же тега, коммита и отпечатка рабочего дерева, а evidence и записи сборки с неверной структурой не используются; +- компонент получает `verified` только при evidence для его точного image ID, ML, monitoring и отсутствующие компоненты никогда не проверены, а выпуск остается непроверенным без smoke и E2E на текущих образах, на грязном дереве, при скачанном core-образе без registry digest, отсутствующем lockfile или Dockerfile, другой версии Go в бинарнике или другой версии Node в образе сборки; +- `release-build` не пишет запись сборки, если коммит или рабочее дерево изменились во время сборки; +- отпечаток рабочего дерева временного Git-репозитория не зависит от настроек diff и переводов строк, учитывает неотслеживаемые файлы, пропускает игнорируемые и не меняет настоящий индекс; +- поиск секретов находит блоки ключей, токены, учетные данные в URL, локальные пути, имена пользователя и хоста и значения переменных, похожих на секреты, в том числе как подстроки и в base64, не печатая их; +- сравнение с запущенными контейнерами сообщает о другом digest, незапущенном и неизвестном сервисе. + +Тест не собирает образы и не запускает контейнеры. Полный путь: `release-build`, `release-smoke` и `release-e2e`, `release-manifest`, `release-up`, `release-manifest-verify` и `release-manifest-check`; см. [DEPLOY.md](DEPLOY.md#манифест-выпуска). + ## Bootstrap интеграционных тестов Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов. diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 58cca39..a099769 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,4 +1,9 @@ -FROM node:alpine AS build +# Base images are build arguments so that make -C deploy release-build can pin +# each one to the digest it resolved; the defaults keep the agreed tags. +ARG NODE_IMAGE=node:alpine +ARG NGINX_IMAGE=nginxinc/nginx-unprivileged:alpine + +FROM ${NODE_IMAGE} AS build WORKDIR /workspace/frontend RUN npm install --global pnpm@12.9.1 @@ -9,7 +14,7 @@ RUN pnpm install --frozen-lockfile COPY frontend/ ./ RUN pnpm run build -FROM nginxinc/nginx-unprivileged:alpine +FROM ${NGINX_IMAGE} COPY --from=build /workspace/frontend/dist/ /usr/share/nginx/html/ COPY deploy/nginx/nginx.conf /etc/nginx/nginx.conf diff --git a/ml/Dockerfile b/ml/Dockerfile index 1369231..16cdd6f 100644 --- a/ml/Dockerfile +++ b/ml/Dockerfile @@ -1,4 +1,8 @@ -FROM python:alpine AS base +# The base image is a build argument so that make -C deploy release-build can +# pin it to the digest it resolved; the default keeps the agreed tag. +ARG PYTHON_IMAGE=python:alpine + +FROM ${PYTHON_IMAGE} AS base RUN apk upgrade --no-cache