From 88a31ba0d55478a667a43b4e04ad601a48d4ab50 Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Thu, 8 Oct 2026 17:47:06 +0300 Subject: [PATCH] fix(deploy): require verified release manifests --- deploy/Makefile | 2 +- deploy/scripts/release_manifest.py | 19 +++++++++++++++++++ deploy/scripts/test_release_manifest.py | 20 ++++++++++++++++++++ docs/en/DEPLOY.md | 4 ++-- docs/ru/DEPLOY.md | 4 ++-- 5 files changed, 44 insertions(+), 5 deletions(-) diff --git a/deploy/Makefile b/deploy/Makefile index d8a462c..054b204 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -151,7 +151,7 @@ release-smoke: ## Run the smoke against the release images and record passing ev release-e2e: ## Run the Playwright suite against the release images and record passing evidence @LINCODEX_RELEASE_TAG="$(LINCODEX_RELEASE_TAG)" bash scripts/e2e.sh -release-manifest: ## Publish an immutable deploy/release//manifest.json from local images and data versions +release-manifest: ## Publish a verified immutable manifest from local images and data versions @$(RELEASE) manifest $(if $(strip $(RELEASE_ID)),--release-id "$(RELEASE_ID)",) $(if $(strip $(RELEASE_DATA_MANIFEST)),--data-manifest "$(RELEASE_DATA_MANIFEST)",) release-manifest-verify: ## Compare running containers of RELEASE_VERIFY_PROJECT with the manifest (or RELEASE_MANIFEST) diff --git a/deploy/scripts/release_manifest.py b/deploy/scripts/release_manifest.py index adda759..ab9f5d1 100644 --- a/deploy/scripts/release_manifest.py +++ b/deploy/scripts/release_manifest.py @@ -1647,6 +1647,24 @@ def prepare_manifest_images(manifest: dict[str, Any], docker: Docker) -> None: manifest["restore"]["status"] = "blocked" +def require_verified_release(manifest: dict[str, Any]) -> None: + """Reject public publication unless the candidate passed every release check.""" + release = manifest.get("release") + if isinstance(release, dict) and release.get("status") == "verified": + return + + reasons = release.get("reasons") if isinstance(release, dict) else None + details = ( + "; ".join(reason for reason in reasons if isinstance(reason, str)) + if isinstance(reasons, list) + else "" + ) + message = "Refusing to publish an unverified release manifest; no manifest was written." + if details: + message += " " + details + raise ReleaseError(message) + + def manifest_file(path_text: str | None, root: Path = ROOT) -> Path: if not path_text: return default_manifest(root) @@ -1698,6 +1716,7 @@ def command_manifest(args: argparse.Namespace, docker: Docker | None = None, roo data_versions = read_data_versions(args.data_manifest, root) compose_files = {name: file_digest(root / name) for name in CORE_COMPOSE_FILES} manifest = build_manifest(inputs, utc_now(), release_id, data_versions, compose_files, root) + require_verified_release(manifest) path = release_artifact_dir(release_id, root) / "manifest.json" with immutable_release_lock(release_id, root): if path.exists(): diff --git a/deploy/scripts/test_release_manifest.py b/deploy/scripts/test_release_manifest.py index 108fbdf..acb4ac1 100644 --- a/deploy/scripts/test_release_manifest.py +++ b/deploy/scripts/test_release_manifest.py @@ -682,6 +682,26 @@ class ImmutableReleaseTest(unittest.TestCase): self.assertCountEqual(results, ["created", "collision"]) self.assertIn(json.loads(path.read_text(encoding="utf-8")), documents) + def test_command_refuses_unverified_release_without_creating_artifacts(self) -> None: + import tempfile + from argparse import Namespace + from unittest import mock + + candidates = (("dirty-stage", inputs(dirty=True)), ("unchecked-stage", inputs(checks=()))) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for release_id, candidate in candidates: + with self.subTest(release_id=release_id): + args = Namespace(release_id=release_id, data_manifest=None) + with mock.patch.object(release, "collect_inputs", return_value=candidate), mock.patch.object( + release, "prepare_manifest_images" + ) as prepare_images: + with self.assertRaisesRegex(release.ReleaseError, "unverified.*no manifest was written"): + release.command_manifest(args, object(), root) + prepare_images.assert_not_called() + self.assertFalse((root / "deploy/release" / release_id / "manifest.json").exists()) + self.assertFalse((root / "deploy/release" / release_id).exists()) + def test_command_reread_is_unchanged_and_changed_data_needs_a_new_id(self) -> None: import tempfile from argparse import Namespace diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 80cefb5..13a68f2 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -550,7 +550,7 @@ A release manifest records the source, toolchains, lockfile hashes, Compose file - `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 local images, the build record, evidence, and optionally a data descriptor. It pulls nothing. `RELEASE_DATA_MANIFEST=` selects a repository-relative JSON file using schema `lincodex.release-data/v1`; it describes `bank`, `policy`, and `seed` as either available with a version and artifact paths, or unavailable with a reason. Artifact paths must be normalized repository-relative paths without symlinks or environment files. The manifest stores their SHA-256 hashes and sizes; restore checks the files still match. Descriptors, artifact counts, and sizes have explicit limits. +- `release-manifest` reads local images, the build record, evidence, and optionally a data descriptor. It pulls nothing. It publishes only a `verified` candidate. A dirty tree, a build record that does not match the source, or missing or rejected required evidence makes the command exit before it creates `manifest.json` or retention tags for built images; the error lists the verification reasons. Fix the source or evidence and rerun the required checks. `RELEASE_DATA_MANIFEST=` selects a repository-relative JSON file using schema `lincodex.release-data/v1`; it describes `bank`, `policy`, and `seed` as either available with a version and artifact paths, or unavailable with a reason. Artifact paths must be normalized repository-relative paths without symlinks or environment files. The manifest stores their SHA-256 hashes and sizes; restore checks the files still match. Descriptors, artifact counts, and sizes have explicit limits. - Without a data descriptor, the manifest records bundled demo policy source version `1` and hashes `backend/internal/domain/policy_demo.go`. This identifies the shipped definition only; it does not report the policy row currently stored in PostgreSQL, because startup leaves an existing row unchanged. The assessment bank has no accepted release snapshot and the demo seed is not yet versioned, so both remain unavailable and `product_data_status` is `partial`. This is not a full MVP readiness result. - The manifest is published once at `deploy/release//manifest.json`. A release ID is a validated 1-64 character slug. A second run with identical content leaves the original bytes and modification time unchanged; changed data or stage under the same ID fails and requires a new ID. Publication is serialized per ID and creates the file atomically, without replacing an existing manifest. Build and evidence records remain under `deploy/release//`. - `release-manifest-check` checks the manifest location and structure and scans it for secrets and machine data. `RELEASE_MANIFEST=` selects an exact artifact for check, verify, restore, or down; otherwise `RELEASE_ID` selects it, falling back to the current commit-based ID. @@ -591,7 +591,7 @@ The release is `verified` only when all of the following hold; otherwise `releas - 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. +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 rejected by `release-manifest`; it reports the verification reasons and leaves no new manifest. Generating the manifest again for the same ID, source, images, evidence, and data leaves the submitted file unchanged. A new data snapshot or stage gets a new ID. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, `.env` content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and `release-manifest-check` repeats the scan. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index a51c3c3..a5883d1 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -552,7 +552,7 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen - `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 и необязательное описание данных; ничего не скачивает. `RELEASE_DATA_MANIFEST=` выбирает JSON внутри репозитория со схемой `lincodex.release-data/v1`. Он описывает `bank`, `policy` и `seed` как доступные с версией и путями к артефактам либо недоступные с причиной. Пути нормализованы, относительны к репозиторию, не проходят через symlink и env-файлы. Манифест записывает SHA-256 и размер каждого файла, а восстановление проверяет их; для данных заданы пределы количества и размера. +- `release-manifest` читает локальные образы, запись сборки, evidence и необязательное описание данных; ничего не скачивает. Он публикует только проверенный кандидат со статусом `verified`. Грязное дерево, несоответствие записи сборки исходникам или отсутствие либо отказ обязательных проверок завершают команду до создания `manifest.json` и ссылок удержания собранных образов; ошибка перечисляет причины. Исправьте исходники или evidence и повторите обязательные проверки. `RELEASE_DATA_MANIFEST=` выбирает JSON внутри репозитория со схемой `lincodex.release-data/v1`. Он описывает `bank`, `policy` и `seed` как доступные с версией и путями к артефактам либо недоступные с причиной. Пути нормализованы, относительны к репозиторию, не проходят через symlink и env-файлы. Манифест записывает SHA-256 и размер каждого файла, а восстановление проверяет их; для данных заданы пределы количества и размера. - Без описания данных манифест записывает версию `1` встроенного исходника демонстрационной политики и хеш `backend/internal/domain/policy_demo.go`. Это только определение из исходников; оно не сообщает версию строки политики в PostgreSQL, потому что старт не заменяет существующую строку. У банка оценивания нет принятого снимка, а демонстрационный seed пока не версионирован, поэтому оба недоступны и `product_data_status` равен `partial`. Это не означает готовность всего MVP. - Публикация выполняется один раз в `deploy/release//manifest.json`. ID - проверяемый slug длиной от 1 до 64 символов. Повтор с тем же содержимым сохраняет исходные байты и mtime. Изменение данных или этапа под тем же ID завершается ошибкой; используйте новый ID. Публикация сериализована для каждого ID и атомарно создает файл без замены существующего. Записи сборки и evidence остаются в `deploy/release//`. - `release-manifest-check` проверяет расположение и структуру манифеста, а также ищет секреты и данные машины. `RELEASE_MANIFEST=` выбирает точный артефакт для check, verify, restore или down; иначе его выбирает `RELEASE_ID`, по умолчанию равный текущему ID на основе коммита. @@ -593,7 +593,7 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen - Go pin согласован, и бинарник backend сообщает версию Go из go.mod; - Node в образе сборки frontend совпадает с `frontend/.node-version`. -Версия Python, отличная от `ml/.python-version`, отражается в `matches_version_file`, но не блокирует выпуск: ML вне проверяемого охвата. Поэтому плавающий тег `node:alpine` может сделать выпуск непроверенным, пока не обновлен `.node-version`. Грязное дерево не отклоняется: манифест пишется со статусом `unverified` и причиной, чтобы локального кандидата можно было проверить до коммита. +Версия Python, отличная от `ml/.python-version`, отражается в `matches_version_file`, но не блокирует выпуск: ML вне проверяемого охвата. Поэтому плавающий тег `node:alpine` может сделать выпуск непроверенным, пока не обновлен `.node-version`. `release-manifest` отклоняет грязное дерево, сообщает причины и не создает новый манифест. `source_kind` равен `bundled_source` для исходника демонстрационной политики и `snapshot` для входного снимка данных. `bundled_source` не доказывает, какая версия политики находится в runtime-базе. Bank и seed остаются недоступны, пока для них нет принятых снимков. Поля версий образа копируются только из разрешенных переменных и OCI labels. Манифест не содержит значения окружения, содержимое `.env`, labels контейнеров, mounts, локальные пути, имя пользователя или хоста. До публикации он проверяется на эти данные и секреты; `release-manifest-check` повторяет сканирование.