feat(deploy): add release manifest with pinned base image digests

This commit is contained in:
shira committed 2026-10-06 15:43:03 +03:00
1 parent ea0982a762
commit a0551a34b8
18 files changed
+2316 -21

No files matched your search

+4
View File
@@ -6,6 +6,10 @@
Thumbs.db Thumbs.db
.env .env
.env.example .env.example
**/.env
**/.env.*
# Release manifests, build records, and evidence stay out of build contexts.
deploy/release
**/node_modules **/node_modules
**/dist **/dist
**/coverage **/coverage
+11 -2
View File
@@ -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 WORKDIR /src/backend
COPY go.mod go.sum ./ COPY go.mod go.sum ./
@@ -7,7 +16,7 @@ RUN go mod download
COPY . ./ COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app 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 / WORKDIR /
COPY --from=build /out/app /app COPY --from=build /out/app /app
+1
View File
@@ -0,0 +1 @@
/release/
+51 -3
View File
@@ -12,12 +12,25 @@ CORE_FILE := $(ROOT)/deploy/docker/docker-compose.yml
ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml
MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml
E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.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") 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 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 config: ## Render all Compose files with safe example values
@test -f "$(ROOT)/backend/Dockerfile" || { printf 'Missing backend/Dockerfile.\n' >&2; exit 2; } @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 "$(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 "$(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)" $(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 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 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; } @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 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 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' 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 smoke: ## Start an isolated stack and check infrastructure health routes
@bash scripts/smoke.sh @bash scripts/smoke.sh
test-e2e: ## Run the Playwright suite against an isolated throwaway stack test-e2e: ## Run the Playwright suite against an isolated throwaway stack
@bash scripts/e2e.sh @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/<tag>/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
+4 -1
View File
@@ -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. - `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. - `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. - `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/<service>:<tag>` 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). 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/<tag>/`, 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). See the [deployment guide](../docs/en/DEPLOY.md).
+4 -1
View File
@@ -8,8 +8,11 @@
- `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами. - `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами.
- `nginx/` содержит конфигурацию раздачи frontend и проксирования API. - `nginx/` содержит конфигурацию раздачи frontend и проксирования API.
- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright. - `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/<service>:<tag>` без скачивания из 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-набор). 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/<tag>/` (игнорируется Git); `make -C deploy release-manifest-verify` сверяет запущенные контейнеры с манифестом, а `make -C deploy release-clean` удаляет образы выпуска. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска).
Подробнее: [развертывание](../docs/ru/DEPLOY.md). Подробнее: [развертывание](../docs/ru/DEPLOY.md).
@@ -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
+15
View File
@@ -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
+27 -4
View File
@@ -9,11 +9,25 @@
# Optional environment: # Optional environment:
# E2E_SPEC_DIR directory with specs to run instead of frontend/e2e, for # E2E_SPEC_DIR directory with specs to run instead of frontend/e2e, for
# example a scratch copy while debugging the suite. # 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 set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
compose_file="$root/deploy/docker/docker-compose.yml" compose_file="$root/deploy/docker/docker-compose.yml"
e2e_file="$root/deploy/docker/docker-compose.e2e.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" frontend_dir="$root/frontend"
artifacts_dir="$frontend_dir/test-results/e2e" artifacts_dir="$frontend_dir/test-results/e2e"
spec_dir="${E2E_SPEC_DIR:-$frontend_dir/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." fail "Installed @playwright/test $installed differs from $declared. Run make -C frontend install."
[[ -d "$spec_dir" ]] || fail "Spec directory $spec_dir does not exist." [[ -d "$spec_dir" ]] || fail "Spec directory $spec_dir does not exist."
spec_dir=$(cd "$spec_dir" && pwd) 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 for dockerfile in "$root/backend/Dockerfile" "$root/frontend/Dockerfile"; do
[[ -f "$dockerfile" ]] || fail "Missing required build file $dockerfile." [[ -f "$dockerfile" ]] || fail "Missing required build file $dockerfile."
done done
@@ -65,12 +82,11 @@ compose() {
APP_PROJECT="$project" APP_NETWORK="$network" APP_STORAGE_NETWORK="$storage_network" \ APP_PROJECT="$project" APP_NETWORK="$network" APP_STORAGE_NETWORK="$storage_network" \
PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \ PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \
E2E_UID="$(id -u)" E2E_GID="$(id -g)" \ 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 \ docker compose \
--env-file "$env_file" \ --env-file "$env_file" \
-p "$project" \ -p "$project" \
-f "$compose_file" \ "${compose_files[@]}" \
-f "$e2e_file" \
"$@" "$@"
} }
@@ -87,6 +103,9 @@ done
if [[ -n "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ]]; then if [[ -n "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ]]; then
fail "Refusing to use existing Compose project $project." fail "Refusing to use existing Compose project $project."
fi fi
if [[ -n "$release_tag" ]]; then
PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" require-images --tag "$release_tag"
fi
cleanup() { cleanup() {
local result=$? local result=$?
@@ -138,7 +157,7 @@ printf 'E2E project: %s (Playwright %s)\n' "$project" "$declared"
compose config --quiet compose config --quiet
compose --profile e2e config --quiet compose --profile e2e config --quiet
started=1 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, # The backend has no Compose health check; wait until it reports PostgreSQL,
# Redis, and SeaweedFS ready before the browser starts. # Redis, and SeaweedFS ready before the browser starts.
@@ -162,5 +181,9 @@ set -e
if ((status != 0)); then if ((status != 0)); then
printf 'Playwright failed with exit code %s; traces and screenshots are in %s/results.\n' \ printf 'Playwright failed with exit code %s; traces and screenshots are in %s/results.\n' \
"$status" "$artifacts_dir" >&2 "$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 fi
exit "$status" exit "$status"
File diff suppressed because it is too large. Load diff
+26 -3
View File
@@ -1,9 +1,25 @@
#!/usr/bin/env bash #!/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 set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
compose_file="$root/deploy/docker/docker-compose.yml" 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" 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 project=lincodex-smoke
app_network="${project}_default" app_network="${project}_default"
port=18080 port=18080
@@ -15,10 +31,10 @@ started=0
# .env.example and points mail links at its own loopback port. # .env.example and points mail links at its own loopback port.
compose() { compose() {
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \ 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" \ --env-file "$env_file" \
-p "$project" \ -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 printf 'Refusing to use existing Compose project %s.\n' "$project" >&2
exit 2 exit 2
fi fi
if [[ -n "$release_tag" ]]; then
PYTHONDONTWRITEBYTECODE=1 python3 "$release_script" require-images --tag "$release_tag"
fi
cleanup() { cleanup() {
local result=$? local result=$?
@@ -60,7 +79,7 @@ trap cleanup EXIT
compose config --quiet compose config --quiet
started=1 started=1
compose up --build -d --wait --wait-timeout 120 compose up "${up_args[@]}" -d --wait --wait-timeout 120
wait_for() { wait_for() {
local url=$1 local url=$1
@@ -165,4 +184,8 @@ fi
curl --fail --silent --show-error "http://127.0.0.1:$port/api/v1/healthz" >/dev/null curl --fail --silent --show-error "http://127.0.0.1:$port/api/v1/healthz" >/dev/null
compose up -d --wait --wait-timeout 90 seaweedfs compose up -d --wait --wait-timeout 90 seaweedfs
wait_for_readiness 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.' printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, storage authentication and network isolation, and the disabled mail transport.'
+613
View File
@@ -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()
+66 -1
View File
@@ -311,7 +311,7 @@ For remote ML scraping, set ML_METRICS_TARGET to hostname:port or IPv4:port and
## Services and images ## 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 | | 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. 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/<service>:<tag>`. 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 `<tag>@<digest>`. 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=<project>` compares every running container of that Compose project with the manifest of the current tag, or with `RELEASE_MANIFEST=<path>`, 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/<tag>/`, 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:<id>`, 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 ## 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/. 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/.
+15 -1
View File
@@ -25,7 +25,7 @@ Useful focused commands:
| make -C ml check | Ruff, mypy, pytest, and wheel build | | 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 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 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 smoke | Isolated technical smoke of service health routes |
| make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack | | make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack |
| make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON | | 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-<n>` 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. 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-<n>` 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 ## 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. 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.
+66 -1
View File
@@ -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 | | Компонент | Текущий источник образа | Основной 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 и слои. 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/<service>:<tag>`. Домен `.invalid` никогда не разрешается, а release-overlay задает `pull_policy: never`, поэтому отсутствующий образ выпуска не скачивается из registry. Каждый Dockerfile принимает базовые образы как build-аргументы `*_IMAGE`, по умолчанию равные согласованным тегам; цель разрешает каждый базовый образ в его repository digest из локального хранилища образов и собирает с `<tag>@<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=<project>` сравнивает каждый запущенный контейнер этого Compose-проекта по image ID с манифестом текущего тега или с `RELEASE_MANIFEST=<path>`. Цель печатает статус выпуска и завершается со статусом 1 при другом digest, незапущенном сервисе или сервисе, которого нет в манифесте.
- `release-clean` удаляет локальные образы `lincodex.invalid/*` и оставляет файлы в `deploy/release/`.
Тег выпуска - первые 12 символов коммита, с суффиксом `-dirty`, если рабочее дерево отличается от коммита. Отпечаток рабочего дерева - Git tree ID, записанный из временного индекса (заполняется из HEAD, затем `git add -A`) с закрепленными настройками переводов строк, режима файлов, symlink и fsmonitor. Он учитывает измененные, удаленные и неотслеживаемые файлы, не зависит от настроек diff и не меняет настоящий индекс. Все файлы пишутся в `deploy/release/<tag>/`, который игнорируют 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:<id>` или 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 ## 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/. 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/.
+15 -1
View File
@@ -25,7 +25,7 @@ make test запускает backend, frontend и ML тесты. make check та
| make -C ml check | Ruff, mypy, pytest и сборку wheel | | make -C ml check | Ruff, mypy, pytest и сборку wheel |
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов | | make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
| make -C deploy config | Рендер Compose конфигураций без запуска | | 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 smoke | Изолированный технический smoke по service health routes |
| make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке | | make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке |
| make -C observability check | Проверку Prometheus, Loki, Alloy и dashboard JSON | | 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-<n>` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет 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-<n>` с `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 интеграционных тестов ## Bootstrap интеграционных тестов
Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов. Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов.
+7 -2
View File
@@ -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 WORKDIR /workspace/frontend
RUN npm install --global pnpm@12.9.1 RUN npm install --global pnpm@12.9.1
@@ -9,7 +14,7 @@ RUN pnpm install --frozen-lockfile
COPY frontend/ ./ COPY frontend/ ./
RUN pnpm run build RUN pnpm run build
FROM nginxinc/nginx-unprivileged:alpine FROM ${NGINX_IMAGE}
COPY --from=build /workspace/frontend/dist/ /usr/share/nginx/html/ COPY --from=build /workspace/frontend/dist/ /usr/share/nginx/html/
COPY deploy/nginx/nginx.conf /etc/nginx/nginx.conf COPY deploy/nginx/nginx.conf /etc/nginx/nginx.conf
+5 -1
View File
@@ -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 RUN apk upgrade --no-cache