Compare commits

..
Author SHA1 Message Date
Codex 1b984de10a feat(map-gateway): support authenticated delegated cache-miss routing 2026-11-17 17:18:12 +03:00
58 changed files with 235 additions and 7960 deletions
-120
View File
@@ -1,120 +0,0 @@
# CMS Git CI: operating contract and next-repository onboarding
Ops source of truth: https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-78. Canon: DCPLATFORM-21; shared CI: DCPLATFORM-37.
## Начать здесь: назначение и источники
Рабочий маршрут подключения следующего приложения к Git CI на Synology, основанный на принятом DC CMS и опыте Device Core. Нормативный канон — https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-21 и его DEPLOY CANON ANCHOR 17.07.2026 (comment f99b03bd-5d6d-419f-b4ab-3e4601cfd0bf). Общая CI-архитектура и первый эталон Device Core — https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-37. Продукт CMS — https://ops.nodedc.ru/nodedc/browse/DC-9; сайт — DC-6; Device Core — DCPLATFORM-76.
Эта карта описывает текущий контракт, порядок действий и установленные причины отказов. Она не разрешает повторять исторические bootstrap/reconciliation-пакеты или переносить их exact predecessor на другой продукт. Перед новым проектом заполнить отдельный паспорт и сравнить его с двумя эталонами. Отличия сначала проектируются и проверяются; существующие guards не ослабляются.
## Подтверждённое состояние CMS
SILVER/DC_CMS, repositoryId=33, master, production https://cms.dcserve.ru/. Принятый source 5ea737318bc49d23cf90121224e5e4296ab579a5, Gitea run55, canonical release r55. Предыдущие обычные r52/r54 и r55 доставлены автоматически без NAS-команд оператора. Точный коммит master подтверждён повторным Git read.
Pipeline: push master → qualification точного SHA → Gitea artifact → исходящий контроллер с отдельной постоянной очередью → canonical plan/apply → cms-app → отдельная UI/API-приёмка. Это обновление приложения CMS. Сохранение контента сайта → render → SFTP на McHost — другой механизм, с собственной очередью и ограничениями. Site Registry, workspace, uploads и секреты сайтов не входят в application artifact.
Bootstrap dc-cms-autodeploy-v1-20261104-002 принят; повторная регистрация не требуется. Source инфраструктуры: NODEDC_PLATFORM 896b90e888ac2e6a77f64fca0e8fd1c3b6d747f5, ветка fix/device-r46-dns-reconciliation; CMS-ядро политики введено 6cf7a911471af5446f96879cb3616adc0aea21ca. Последняя подтверждённая оператором установка root runner: SHA256 52831367c42f991367f40170b5d9400e7fca34d906d15b19b1c549ef91846e88, Python3.8.15. Это зафиксированное доказательство установки, не гарантия неизменности сервера в будущем.
## Паспорт CMS: точные привязки
Source: https://git.dcserve.ru/SILVER/DC_CMS.git; master; event=push; workflow=ci.yml@refs/heads/master; один job qualify; label=nodedc-node22-build. Ровно два шага: Check the exact pushed commit; Retain the qualified release in this Gitea run. workflow_dispatch может квалифицировать, но текущий admission принимает только push.
Build runner: synology-cms-build, repo-scoped, observed ID=2. ID читается из проверенной root-private регистрации data/.runner и сопоставляется с run/job/name/repo/labels; 2 не является универсальной константой. Device Core имеет другую регистрацию (repo38/main, observed ID=1).
Runtime: /volume1/docker/dc-cms/source; фиксированные Compose/env/project dc-cms; service=cms-app. Bootstrap root /volume1/docker/nodedc-cms-autodeploy; private queue /var/lib/nodedc-cms-autodeploy. Units nodedc-cms-autodeploy.service и .timer в /usr/local/lib/systemd/system; root oneshot, OnBootSec=120s, OnUnitInactiveSec=30s; опубликованных портов нет. Приложение и его jobs не получают deploy authority.
Artifact: component=dc-cms-release; id=dc-cms-release-v1-r<runId>-<40-char-SHA>; descriptor server/cms-release.json; wrapper receipt release.json. runId, runNumber, attempt и source SHA — разные поля, их нельзя подменять друг другом.
## Три уровня доверия и секреты
CI job проверяет код и создаёт данные. У job нет production-реквизитов, произвольных volume mounts, privileged режима или Docker socket. Build-runner daemon имеет свой отдельно зарегистрированный доступ к Docker для запуска изолированных job-контейнеров; read-only bind socket сам по себе не делает Docker API безопасным, поэтому граница обеспечивается доверенным daemon и запретом передачи socket в jobs.
Admission controller только через закреплённый HTTPS origin/repo читает runs/artifacts. CMS использует существующую root-private read identity Device Core без копирования; доступ к repo33 проверен. Это выбор текущего внедрения, а не требование делить токен между будущими продуктами. Enrollment token, read token и секреты приложения имеют разные назначения. Enrollment передаётся отдельным приватным handoff, импортируется root-owned и удаляется из staging, не входит в TGZ/Git/логи/карточку.
Production исполняет только /usr/local/sbin/nodedc-deploy. Исходники контроллера/очереди детерминированно встроены в reviewed runner; runtime не импортирует Python с SMB. Private paths проверяются на owner/mode/type/symlink. Нельзя печатать Authorization, signed URL, raw inspect/Env, содержимое .runner и секретных JSON. В доказательствах допустимы хэши, имена полей и очищенные статусы.
## До разработки: снять факты и заполнить паспорт нового продукта
1. Прочитать DCPLATFORM-21, DCPLATFORM-37 и эту карту. Сверить код эталона с текущей веткой и deployed bytes. Снять исходный application/foundation/runtime baseline, accepted ledger и backup, health/auth и список сохраняемых данных/сервисов. Не включать CI поверх неизвестного predecessor.
2. Записать repo URL/numeric ID, production branch/event/workflow/job/steps, владельца, правило production intent, dependency commits, runtime/toolchain, точные build/Compose roots/env/project/services, health, rollback, queue namespace и activation floor. Все различия с CMS/Device Core выписать до реализации.
3. Проверить global и repository Actions, daemon RPC и регистрацию. REST endpoint регистрации не доказывает включённые Actions. На существующей Synology не переустанавливать Gitea и не повторять принятую регистрацию.
4. Проверить реальные kernel/Docker/cgroups capabilities, образы и resource budget. Принятый хост: Docker24.0.2, cgroupv1, CPUSet/CPUShares/memory/swap доступны, CFS quota/period и PIDs limit отсутствуют. CMS daemon: CPU7/shares64/512MiB; job: CPU7/shares128/2GiB, capacity1. Это проверенный профиль этого хоста, не значения для слепого копирования.
5. Сверить NAS POSIX inventory, включая невидимые по SMB @eaDir; base image RootFS и inherited config; поведение реального Compose, а не только direct docker build. Проверить runtime Node24 отдельно от CI Node22. Не считать healthy HTTP доказательством полного соответствия runtime.
## Квалификация точного коммита и воспроизводимость
Workflow создаёт пустой временный checkout и забирает точный gitea.sha. infra/ci/release.py требует HEAD=SHA и чистые tracked files; frozen npm ci --ignore-scripts для runtime и ui; node ui/build.mjs --check; синтаксис всех JS/MJS; multisite/publication/backup tests и Python release-contract tests. Сборка UI должна совпадать с committed admin assets. @nodedc-пакеты закреплены source SHA и archive hashes; компоненты не копируются в consumer как fork.
Артефакт содержит только allowlisted flat admin/server файлы и два точных package-файла, descriptor с hashes и foundationSha256. TGZ детерминирован: manifest.env + files.txt + payload; стабильный порядок, gzip mtime0. Снаружи Gitea ZIP содержит ровно TGZ + release.json. qualification/deployed=false означает только подготовку, не публикацию.
Не включать .env, credentials, runtime/site workspaces, медиа сайтов, ZIP-бэкапы, БД, node_modules, .git, symlinks/hardlinks, hooks или команды. Перед первым выпуском проверить tar/ZIP members, повторяемость SHA, denylist и полный путь скачивания через настоящий Gitea API. Зависимости из других реп должны быть опубликованы до квалификации.
## Admission: почему зелёного CI недостаточно
Проверяются фиксированные API origin/repo identity, pagination/discovery consistency, runId/runNumber/attempt/SHA/event/branch/workflow, единственный ожидаемый job и оба успешных шага, фактическая runner identity и labels. Неподходящие/красные/pending runs не получают deploy authority.
Artifact должен принадлежать этому repo/run/SHA, быть не истёкшим и иметь допустимый размер/receipt/digest. Допускается только точный same-origin signed artifact route; постоянный Authorization не передаётся в signed redirect. ZIP и внутренний TGZ проходят независимые проверки путей, типов, размеров и authority.
По parent graph доказывается installed → candidate → current master. Force push и расходящаяся история отклоняются. После скачивания и длительного plan run/source/ancestry проверяются повторно перед reservation/apply. Branch protection — отдельная политика репозитория; ancestry check не доказывает, что protection настроен. Изменение workflow/job/steps/runner является изменением доверенного контракта, а не косметической YAML-правкой.
## Постоянная очередь и восстановление после перезапуска
Отдельная SQLite WAL/synchronous FULL queue CMS хранит immutable repo/floor policy, run identity и deployment phase. Более ранний незавершённый run не обгоняется; duplicate не запускается повторно. Controller после crash сначала сверяет canonical applied/failed receipts и только потом принимает следующий release. Неоднозначный исход и failed rollback блокируют дальнейшее применение.
Очереди CMS и Device Core раздельны, production mutation сериализует общий canonical deploy lock. Timer исходящий, новых ingress/webhook endpoints нет. Исправление очереди не делается ручным SQL/reset: recovery допускается только зарегистрированным точным переходом после доказанного receipt. Не менять activation floor после включения для пропуска неудобной истории.
FirstRunNumber=1 и baseline 4c6f133 относятся только к исходной установке CMS. Для нового проекта floor вычисляется из его принятого baseline и фактической run history. На текущем сервере bootstrap002 terminal; повтор запрещён.
## Детерминированная база Docker до первого application apply
Mutable FROM node:24-alpine привёл к inherited Env drift при неизменных Dockerfile/Compose. Теперь resolver доказывает точный accepted image ancestor: полный strict RootFS prefix, platform и inherited Env/config; scoped Parent-chain с ограниченным Node-only cache fallback, без общего Docker inventory.
Если cache не содержит доказанную базу, допускается только source-registered Node24.18.0-alpine linux/amd64: manifest SHA256 4ba75f835bb8802193e4c114572113d4b26f95f6f094f4b5229d2a77773e0afc, config SHA256 91d56b2d4e1cf23103d90b0b024c1f489c288f9c3aba1042dd7279503b367de6. Plan читает/проверяет, но не pull. Только apply после exact proof может восстановить этот pinned digest при точном missing-image ответе. Permission/daemon/registry error не разрешает другой образ. Classic image ID=config digest и containerd ID=manifest digest проверяются относительно одной зарегистрированной пары.
Clean build имеет пустой projects, source Dockerfile не меняется. Во временном контексте FROM заменяется только на доказанный local image ID; DOCKER_BUILDKIT=0, --pull=false. Реальный BuildKit трактовал FROM sha256:<imageID> как repository и пытался сеть; legacy builder использует localID. После build до recreation сравниваются полный Env/Labels/config.
Compose добавляет ровно разрешённые project/service/version labels; builder воспроизводит принятые значения, а не текущую версию локального Compose. Другие/частичные/wrong labels отклоняются. Формат WorkingDir=/ и пустые User/Variant OCI/API обработаны только в проверенных границах. Рецепт CMS переносится на другой runtime только через его собственный registered base contract.
## Область application release и приёмка
dc-cms-release меняет только зарегистрированный source /volume1/docker/dc-cms/source и пересоздаёт cms-app с фиксированными Compose/env/project и --no-deps/--pull never. Runtime dependencies/Dockerfile/Compose не разрешено произвольно менять обычным release; initial foundation закрепляет adm-zip0.6.1. UI build dependencies отделены от runtime foundation.
Acceptance внутри apply проверяет auth health, exact application bytes в running image, новую generation/image, inherited configuration, env/mounts/network/ports, неизменность других Compose services, site/project content/config/secrets и сохранность runtime/данных. Rollback возвращает точные source и прежний image без rebuild. БД/тома не выбираются только потому, что приложение ими пользуется.
Initial install, installed update, rollback и migration — разные state-aware transitions. Новая dependency/schema/topology требует отдельного additive contract и tests. Manifest не выбирает roots/build commands/services/health/Compose/секреты; files.txt выбирает действие только внутри зарегистрированной политики.
## Порядок первого подключения нового репозитория
1. Завершить паспорт и read-only baseline. Если существующая инфраструктура уже подходит, переиспользовать её; не откатывать runner/Gitea к версиям из старых инструкций.
2. Добавить qualification и deterministic artifact builder; доказать clean Linux checkout, реальные downloads, negative payload/source tests.
3. Добавить отдельный recurring release domain и собственные allowlists, foundation, build/health/rollback. Проверить соседние компоненты и Python3.8 совместимость standalone runner. Incident recovery не копировать вместо normal update.
4. Разработать repo-specific admission и независимую queue/scheduler policy, registration/read credential import и activation floor. CMS показывает вариант отдельного bootstrap build-runner+timer; он может сначала ждать accepted baseline, но application mutation не начинается до полной регистрации и source proof.
5. Если нужен новый runner: отдельная reviewed SHA-pinned promotion, свежий verify-install, затем новый plan. Promotion ждёт свободное окно и повторно проверяет процессы после атомарного lock; чужой lock не удаляется. Пользователь не выполняет диагностические Docker/Python heredoc-команды.
6. Только data artifact скопировать в SMB inbox, сверить SHA, проверить lifecycle. Fresh plan → review точных scope/predecessor/SHA → один apply. Для автоконтроллера эти зарегистрированные проверки выполняются им штатно; routine push не требует ручного plan/apply.
7. Подтвердить installed baseline по ledger/archive/backup и отдельному UI/API сценарию. Проверить два последовательных реальных push, порядок, сохранность соседей, duplicate/outage/restart/failed-rollback tests. Не завершать на зелёном workflow.
8. Заполнить новую Ops-карту текущими версиями, точными доказательствами, ограничениями и ежедневным маршрутом; добавить только новые общие правила в DCPLATFORM-37.
## Ежедневный маршрут и ручные границы
Обычная работа: изменения кода → локальные необходимые проверки → commit → push production branch → qualification → canonical receipt → UI/API проверка. Для CMS branch=master. Увидеть success Actions и убедиться в успешном application receipt — два отдельных шага. Изменения контента через CMS не коммитятся обратно в Git автоматически.
При отдельном административном изменении runner допустим reviewed promotion и затем sudo /usr/local/sbin/nodedc-deploy verify-install. Для application artifact пользовательские NAS-команды только sudo /usr/local/sbin/nodedc-deploy plan <полный .tgz> и, после review, apply того же точного файла. Старый plan недействителен после runner/artifact/live-state изменения.
После deploy-ok runner сам завершил acceptance, архивирование и ledger. Inbox закономерно пуст. Не restage/reapply, не просить ручные post-apply Docker/health команды. Агент читает canonical lifecycle и выполняет отдельно продуктовую приёмку. No apply-latest, live-edit, SMB executable, compose down -v, volume prune, broad restart или прямой Docker API для обхода канона.
## Карта ошибок: симптом → доказательство → действие
«Installed application differs»: сначала exact files и NAS POSIX inventory. В bootstrap001 только flat @eaDir stream существующего allowlisted файла оказался невидим SMB; 10 app/foundation SHA совпали. Bootstrap002 отделил regular metadata, сохранив bytes; symlink/orphan/unknown paths остаются ошибкой. Не игнорировать все @eaDir/скрытые файлы.
«Qualification job mismatch»: сверить фактическую private registration. CMS получила ID2, скопированная Device policy ждала ID1. Правило исправлено на проверенную зарегистрированную identity; bootstrap/registration/queue не пересоздавались.
Runtime drift / failed rollback: наличие исходников и HTTP200 не доказывает rollback. CMS r39 — exact legacy SHA восстановлен только перестановкой двух Binds и пустыми DNS null/[] на трёх стабильных samples (16 кандидатов); Device r46 — только пустые DNS. Отдельные marker-only reconciliation приняты, затем новые releases. CMS fingerprintv2 сортирует только уникальные валидные bind-строки и нормализует пустые DNS; Device v3 добавляет пустые DNS к прежнему v2. Непустые значения и остальные поля не нормализуются.
Env drift нового image: сравнить inherited base/config до recreation. r40 штатно откатился; mutable Node tag заменён exact ancestry/config proof. Нельзя разрешать Env drift ради успешной сборки.
«Local base inventory invalid/outside bounds»: старый guard объединял разные причины; конкретный подслучай не доказан. Перейти на scoped ancestry/Node lookup с ограничениями и очищенными кодами, не увеличивать общий лимит вслепую.
«cms-base-missing»: проверить категории отдельно. Реальный Compose-label дефект воспроизведён и исправлен; затем NAS отклонил все пять кандидатов по layers. Один баг не доказывает единственную причину. Только registered immutable base с полным proof закрыл mismatch.
Node24 ERR_FS_CP_EEXIST при создании сайта: root уже зарезервирован; копирование детей в собственный root сохраняет no-overwrite/cleanup/symlink guards. Node22 CI сам по себе это не воспроизводил; нужен тест точной runtime-версии.
Promotion «Canonical runner is active»: ждать свободное окно и повторно проверять lock/processes, не убивать runner и не удалять чужой lock. Пустой/NUL-хвост SMB сразу после receipt: свежий bounded read/F_NOCACHE + lifecycle; не править журнал.
Доступ после смены Wi-Fi/VPN: отдельно DNS/route/current IFA/HTTPS/auth. Проблема доступа Mac не равна отказу NAS scheduler. Узкий route repair только в разрешённом контуре, без отключения TLS/VPN или смены токенов.
## Если выпуск не принят: обязательный порядок диагностики
Сначала записать exact commit/artifact SHA, установленный runner SHA, component/state transition, expected/actual field hashes, journal, backup, image/generation и rollback result. Raw Env и credentials не выводятся. Разделить qualification failure, preflight без mutation, healthy rollback, uncertain rollback и networking.
Если artifact ещё staged без terminal receipt, устранение причины и fresh plan может продолжить тот же кандидат, как r41. Если есть terminal failed/apply receipt, идентичный artifact не повторяется. После source correction — новый commit/run/patch/digest. При failed rollback или reconciliation-required — STOP mutation, read-only аудит; восстановление только новым точным registered transition после proof. Не reset queue и не переименовывать архив для обхода history.
Диагностика должна воспроизвести именно реальный путь (Compose vs direct build, Node24 vs Node22, NAS vs Docker Desktop). Unit success не доказывает live acceptance. Если причина неизвестна, она остаётся неизвестной: r9 Device runtime field и Gitea FinalizeArtifact r15 не объясняются последующими успешными runs.
## Принятые доказательства и регрессионные условия
CMS r55: source 5ea737318bc49d23cf90121224e5e4296ab579a5 → infra/ci/release.py → https://git.dcserve.ru/SILVER/DC_CMS/actions/runs/55 → nodedc-dc-cms-release-v1-r55-5ea737318bc49d23cf90121224e5e4296ab579a5.tgz, SHA256 c099a5dbd8c4d23b3ea4dd141948428277a2f06c11d66c274ff9f1b643db096d → applied 2026-11-05T19:45:01Z → backup dc-cms-release-dc-cms-release-v1-r55-5ea737318bc49d23cf90121224e5e4296ab579a5-20261105-224253. terminal_success, 10/10 runtime files exact. 25 Node +3 Python tests; UI build deterministic. Production: Authentik вход, два независимых сайта, Save→SFTP текста/SEO/knowledge/изображения, скачивание двух ZIP и CRC. Restore проверен в изолированном workspace; production restore не проводился.
Device r48: source fc2e9c8bc165f5f304690ecbf96efe33cbff2543 → run48 → nodedc-device-core-release-v1-r48-fc2e9c8bc165f5f304690ecbf96efe33cbff2543.tgz, SHA256 b43933fdd8c08185ef15d96023a6de2120b7b8c6df3e5327ccafc722d8c20898; applied 2026-11-05T11:36:53Z; 78/78 files exact, preserved Postgres/gateway/backhaul. Product header/settings checked. Exact backups в DCPLATFORM-76.
CMS r39 recovery: nodedc-dc-cms-r39-runtime-reconciliation-v2-20261104-001.tgz, SHA28fe141601d412e470aa8f6284dc93dee22c3d3dd60cafc4f7bcd7ef1c62a651, applied2026-11-04T20:28:35Z. Device r46 recovery: nodedc-device-core-release-r46-reconciliation-v1-20261105-001.tgz, SHA3ea603aad4bca9b313ee30dc8160a2168ddaca8df479194c35533687c6dd1a7d, applied2026-11-05T11:31:55Z. Оба services/build/runtime-mutation=none; original failed evidence сохранено. Не являются пакетами для повторного применения.
Методные доказательства и ограничения: R39_RUNTIME_RECONCILIATION.md, R40_BUILD_BASE.md, R41_BASE_DISCOVERY.md, R41_COMPOSE_LABELS.md, R41_NODE_BASE_ACQUISITION.md, R46_DNS_RECONCILIATION.md в pinned Platform source. Реальная local Compose/BuildKit integration проверяла config/labels/layers, но NAS совпадение базы доказано отдельно только успешным canonical r41 apply.
## Открытые границы, которые нельзя выдавать за готовность
Нет универсального self-service подключения любой репы: CMS и Device Core имеют отдельные policies/controllers/queues. Dockerfile/dependency/Compose/schema migrations не входят автоматически в ordinary release. Общая throughput/capacity при росте количества реп, retention/GC, credential rotation, pause/resume и disaster recovery требуют своих проверок.
Gitea artifact retention30дней; controller имеет bounded pagination/ancestry/download. Очередь не гарантирует доставку уже удалённого artifact. Source-overlay строится на NAS; это не image-release из Container Registry. Не утверждать отсутствие риска или гарантированную первую попытку: паспорт и предварительные тесты устраняют уже известные классы ошибок, новые различия требуют proof.
Отдельная SFTP-очередь сайтов пока in-process, без durable restart recovery, remote prune, atomic swap и remote rollback; эта граница не относится к durable Git-release queue CMS. Site-scoped RBAC/generic adapter/CMS→Git autosync не реализованы.
## Исходники, запуск проверок и правило актуализации
CMS: .gitea/workflows/ci.yml; infra/ci/release.py и test_release.py; ui/design-system.lock.json; docs/multisite.md. Platform: infra/cms-deploy/{README.md,CI_RUNBOOK.md,autodeploy-v1.json,autodeploy_runtime.py,controller.py,deployment_queue.py,gitea_source.py,release_runtime.py,embed_runtime.py,build_autodeploy.py,test_*.py}; infra/device-core-deploy/{controller.py,deployment_queue.py,R46_DNS_RECONCILIATION.md}; infra/deploy-runner standalone runner.
Локальная проверка изменений политики: python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'; регрессии Device Core deploy; Python3.8 grammar; deterministic embed/build; negative authority/denylists/rollback; затем реальные Compose/runtime probes только в разрешённой изоляции. Команды app qualification задаёт infra/ci/release.py. Повторять production bootstrap ради проверки запрещено.
После изменения обновлять текущие версии/контракт/ограничения и результат проверки. Не добавлять хронологический дневник каждой попытки. Значимые эксперименты сводить к условию → наблюдению → выводу/ограничению → evidence. Новые общие правила переносить также в DCPLATFORM-37, канонические authority изменения — DCPLATFORM-21. Локальные сырые traces и копии карточек находятся в outputs/review/closure и профильных review-каталогах этого чата; в Ops не помещать секреты.
@@ -1,72 +0,0 @@
# CMS r39: runtime representation and exact recovery
The first qualified CMS application release failed runtime acceptance and rollback
verification. The original failed journal, archive and six backup files remain
immutable. Availability alone was not treated as proof of recovery.
The installed plan-only diagnostic reported stable samples, the original image,
unchanged source, foundation, NAS metadata, project/site data, other containers,
running image source and healthy authenticated CMS. Its limited bind-order search
did not recover the original fingerprint because three DNS fields also differed.
## Exact evidence
The current runtime was reconstructed locally from the diagnostic's per-field
hashes, unchanged Compose source and unchanged environment file. Environment
values were retained only in memory. The complete reconstructed current digest
matched the NAS diagnostic, not merely selected field hashes. Changing exactly
these four representations then reproduced the complete saved predecessor digest:
| Field | Saved predecessor | Current |
| --- | --- | --- |
| `HostConfig.Binds` | projects, website | website, projects |
| `HostConfig.Dns` | `[]` | `null` |
| `HostConfig.DnsOptions` | `[]` | `null` |
| `HostConfig.DnsSearch` | `[]` | `null` |
Both bind strings, including source, destination and `rw`, are unchanged.
All environment values, ports, network names, mount options, resource settings
and security flags are included in the complete digest proof.
- Legacy predecessor: `e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f`.
- Current legacy digest: `00d5d3aa50519a923cc6cd2a6478c313e2c8433b4d089b214192da201fc599fd`.
- Shared version-2 digest: `5d656cf19d63800ca3c9d6f797dd5f71f86be0dfe55899ccb80a8935a937bbce`.
Docker 24.0.2 checks `len(...) > 0` for these three DNS settings in
[`daemon/container_operations.go`](https://github.com/moby/moby/blob/v24.0.2/daemon/container_operations.go).
Empty lists and null therefore select the same DNS fallback. Nonempty DNS lists
and their ordering are never discarded by the version-2 fingerprint.
## Registered transition
Component `dc-cms-runtime-reconciliation` has fixed root
`/volume1/docker/dc-cms/source`, no service/build/Compose selection, and only
`deployment/dc-cms-r39-runtime-reconciliation-v2.json` as payload. Its immutable
identity is `dc-cms-r39-runtime-reconciliation-v2-20261104-001`.
The descriptor pins the failed release, original backup hashes and legacy digest.
Fresh plan and apply recheck the exact original failed row/archive/backup. Three
identical live samples must have the original image and produce the saved digest
by enumerating only two observed bind strings and empty DNS representations
(at most 16 candidates). Existing source, data, metadata, foundation, dependency
and health acceptance then runs against the proven version-2 baseline.
Apply copies only the descriptor and rechecks the proof after the copy. Failure
removes only that new marker; no application service, secret, database, volume,
queue or failed historical receipt is changed by this metadata transition.
The automatic controller acknowledges r39 only after matching the successful
canonical recovery receipt, archived artifact and installed marker while retaining
the original incident evidence. Its separate exact `blocked -> failed` queue
transition is pinned to run 39, number 1, source/artifact digest and prior receipt.
The old release never becomes ready again; only a new qualified run may proceed.
New CMS releases record `runtimeFingerprintVersion=2` and per-field hashes for
future diagnostics. Version 1 remains strict for old evidence and the original
audit. Version 2 sorts only complete, unambiguous bind strings and normalizes
only null/empty DNS lists; real changes still fail acceptance. Device Core and
the accepted CMS bootstrap remain unchanged.
Build the data artifact with `build_runtime_reconciliation.py` only after the
reviewed root runner has been promoted and verified. A prepared candidate or
successful local proof does not establish production reconciliation.
-58
View File
@@ -1,58 +0,0 @@
# CMS r40: preserve the accepted Node base before recreation
Run 40 qualified commit `02318ab6689298244a2ac8b4e7521ed1945600ee`.
Its artifact SHA-256 is `68b36de85f56ad5c003e89f8f4dfe9e0a70b8d01e65846111b18106f677a30e9`.
Canonical apply failed at `2026-11-04T20:37:58Z`, reporting only `config.Env`.
Rollback `ok:dc-cms-release` restored and verified the original image, source,
configuration, other services and project/site data. Backup:
`dc-cms-release-dc-cms-release-v1-r40-02318ab6689298244a2ac8b4e7521ed1945600ee-20261104-233622`.
The failed archive/receipt stay immutable. No reconciliation is required and
this artifact is never retried.
The application builder used mutable `FROM node:24-alpine`. The source
Dockerfile, Compose and env-file were unchanged; rollback recreated the old
image with the same Compose and passed exact Env comparison. This locates the
drift in the new image's inherited environment. The discarded new container's
individual differing Env values were not recorded, so no exact Node version
transition is claimed. An application release must preserve its accepted base,
not silently update the Node image selected by a mutable local tag.
The initial correction inspected the accepted image by immutable ID and a
bounded global local-image inventory. That lookup was rejected by the NAS in
r41 preflight; it is superseded by the [scoped base discovery](R41_BASE_DISCOVERY.md).
The current read-only preflight selects a Node 24 base whose
complete root filesystem layers form a strict prefix of the accepted image,
and whose environment plus the registered HOST/PORT instructions exactly equals
the accepted image environment. Entrypoint, user, shell, labels, stop signal and
healthcheck must match. Base CMD is node, working directory is empty, and there
are no volumes, exposed ports or ONBUILD instructions. Duplicate Env keys,
missing or ambiguous ancestors and architecture changes fail before apply.
Proof stores image IDs and hashes only, never environment values.
Build rechecks that proof and the registered source Dockerfile hash. In the
clean temporary context it replaces only FROM with the proved local image ID.
Docker 24 legacy builder is selected explicitly with DOCKER_BUILDKIT=0 and
--pull=false. BuildKit's FROM sha256:<image-id> was tested locally and attempted
registry resolution; legacy builder resolved the local ID and completed.
This explicit selection avoids a backend-dependent pull or fallback.
The base contains no prior application/project layers. projects is empty in
the build context, while the live registry, secrets, site workspaces and NAS
metadata stay outside it. The new image's full inherited configuration and
environment are compared before any service recreation. A difference reports
field/key names only and stops there. Runtime acceptance and rollback remain
unchanged and strict. There is no relaxed Env comparison, image pull, queue
reset, dependency change, production file edit or broader service selection.
Validation: 87 CMS deployment tests, 95 Device Core regression tests, Python
3.8 AST and diff check. A separate local Docker integration creates isolated
fixture images without launching workload containers, invokes the actual
base resolver and builder, verifies exact environment/base ancestry, checks
all exported layers for the excluded private-project fixture and removes its
own image tags. It verifies the build mechanism, not NAS cache availability;
the production preflight remains authoritative for that.
Promotion is the separate root-owned runner gate. r41 is the new CMS commit
released after this correction; it remains staged, before application apply.
The discovery correction resumes that queued run after runner promotion;
no bootstrap, reconciliation replay or manual container command is needed.
-63
View File
@@ -1,63 +0,0 @@
# CMS r41: scoped, immutable base discovery
On 2026-11-05 the operator verified installed runner SHA
`73938104fcd004f028a52f5c4f46bf68af0712e25a828f014cb141af93745d26`.
Canonical plan for r41 stopped with
`CMS local base image inventory is invalid or outside bounds`.
The old guard combined empty inventory, more than 2048 unique IDs and invalid
ID formatting into that message. The actual NAS inventory was not captured;
there is no claim that a particular count or malformed line caused the failure.
The prior controller status also recorded TimeoutExpired, without its source.
r41 source is `4369f0a0cb813075e10ac917da62529420559f69`, Gitea run 41/number 3.
Artifact `nodedc-dc-cms-release-v1-r41-4369f0a0cb813075e10ac917da62529420559f69.tgz`
is 99102 bytes, SHA-256
`576fd0c07fb35a1803a56e665b25b06628ce41137bc2ac954a0c801179f57a77`.
Qualification passed and all payload bytes match the committed source.
The lifecycle inspector still reports staged, no applied/failed record or
backup, matching SHA, no warnings. r41 has not entered application apply.
The global inventory is removed. The new resolver first follows immutable
Parent IDs from the accepted CMS image, including untagged legacy ancestors.
Every edge must retain platform and a root-filesystem layer prefix; metadata
steps with equal layers are allowed. Invalid IDs, cycles, inconsistent layers
or platform, and depth beyond 128 edges stop safely. The nearest proven Node
base must pass all existing configuration and filesystem checks; a Parent
pointer alone is insufficient.
For images without a usable Parent chain, the fallback lists only local Node
repository references (`node:*`, `docker.io/library/node:*`), using explicit
`{{json .ID}}` formatting and full IDs. At most 256 rows are admitted. Each
candidate is inspected by immutable ID and re-proved against the accepted CMS
image; exactly one match is required. Tags are discovery hints, not authority.
A base absent from both paths fails before mutation. No global inventory,
prune, pull, base reconstruction or use of the old full application as a base.
CMS base-discovery reads have 30-second subprocess timeouts and an 8 MiB output
ceiling. Failures expose only allowlisted `cms-base-*` reason codes in the
public controller projection. Docker stderr, environment values, command
arguments and arbitrary DeployError messages are not copied into that status.
Runtime comparison, service scope, release identity, rollback, queue ordering,
source qualification, Device Core and the build recipe remain unchanged.
Validation: 93 CMS tests and 95 Device Core regression tests passed. Tests
cover untagged parent ancestry without listing, metadata steps, cycles, depth,
platform/layer mismatch, mutable tag drift, absent/ambiguous fallback, invalid
IDs, inventory bounds, timeouts and redacted status. A real local Docker
integration exercised the Parent chain and explicit JSON Node-only filter
(an inspect fixture cleared Parent to model that path), then built from the
same proved base. Exact inherited configuration and clean exported layers
passed. Only isolated local test tags were created and removed; no NAS or
workload containers were used. This does not prove NAS base availability.
After atomic root runner promotion and verify-install, the existing controller
performs a fresh canonical plan and apply for the queued r41. The corrected
runner is a relevant external-state change; no application artifact is changed
or restaged. r39/r40 and bootstrap/reconciliation remain terminal and must not
be replayed. An actual canonical application receipt is still required before
multisite migration and public-site publication.
Post-promotion evidence: the operator verified aa507dc and the controller reached
`cms-base-missing` at 06:29:54 UTC. The lookup worked but no candidate passed the
predicate. A reproducible Compose-label ownership error and the corrected
build model are documented in [the follow-up](R41_COMPOSE_LABELS.md).
-59
View File
@@ -1,59 +0,0 @@
# CMS r41: preserve Compose-owned image labels
The operator installed and verified runner SHA
`aa507dc77acdead0d3cd76db0f0254dca1b2f707638361b6e5e8cac1b5d6448b`
on 2026-11-05. At 06:29:54 UTC its automatic preflight reported
`CmsBuildBaseError`, reason `cms-base-missing`. r41 remained staged, with no
application receipt or backup. This means no discovered candidate passed the
predicate, not that Docker necessarily lacks the filesystem base.
The predicate had a reproducible ownership error: it required base-image Labels
to equal application-image Labels. Compose's BuildKit path adds its own project,
service and version labels to the application image. These are build metadata,
not inherited Node configuration. The behavior is explicit in
[Compose 2.20.3 getImageBuildLabels](https://github.com/docker/compose/blob/v2.20.3/pkg/compose/build.go#L502-L513).
The old direct-docker fixture omitted that production build path, so its passing
result did not test this case. Whether this is the sole NAS mismatch is still
unproven; do not claim the production base has already been accepted.
The corrected model permits exactly three Compose-owned additions: project must
be dc-cms, service must be cms-app, and version must be a bounded-format numeric
version with an optional release suffix. Partial, unknown or malformed Compose
labels fail. All other labels must still match the base exactly. The builder
passes those same three accepted values through explicit --label arguments;
it does not choose the local Compose version or delete any metadata. The full
post-build Labels comparison remains exact, as do Env, layers, platform and
all existing runtime/rollback guards. No change to the registered Dockerfile,
payload, service set, dependencies, sites, authentication or release queue.
Missing/ambiguous-base errors now carry a bounded diagnostic containing only
parent/node candidate counts and fixed rejection-category counts (layers,
platform, base shape, inherited config, labels, environment, Node version).
The public status validates this shape again; raw image fields, arbitrary keys,
label values, environment values and external stderr are never exported.
Validation: 95 CMS tests and 95 Device Core tests. New cases cover exact Compose
additions, inherited-label drift, wrong project/service, partial/unknown labels,
malformed version, exact builder flags, final Env/Labels mismatch before runtime
recreation and diagnostic redaction. Python 3.8 AST and diff checks pass.
A separate real local integration builds an isolated fixture with actual Docker
Compose/BuildKit (local Compose 5.0.0), without mocked image inspection. The
installed aa507dc predicate rejects that known base; the corrected predicate
accepts it through the real Node-only lookup. The canonical builder then builds
from the same immutable base using legacy Docker, retaining the exact full Env
and Compose labels. All exported layers exclude the private-project fixture,
and the registered source Dockerfile stays unchanged. Test tags are removed;
no NAS or workload containers are involved. Local evidence is not proof of NAS
cache availability.
The candidate is promoted through the same tested SHA-pinned root gate, with
aa507dc as predecessor. The existing automatic controller then replans queued
r41; no manual Docker action, image pull, failed-run replay or new application
commit is required. A successful canonical application receipt remains required
before the multisite migration and public Mission Core publication.
Post-promotion: 4dce749 was installed and verified. At 06:41:31 UTC the scoped
lookup reported parentCount 0, nodeCount 5, all rejected on layers. The label
fix therefore did not resolve the missing matching base. The next bounded
policy is [registered exact-base acquisition](R41_NODE_BASE_ACQUISITION.md).
@@ -1,86 +0,0 @@
# CMS r41: exact registered Node base acquisition
Installed runner `4dce7493d61efe67b49337fa7eab3fc441988b22b625181f1547fa72d6fce75b`
was verified by the operator. Its status at 2026-11-05 06:41:31 UTC was
`cms-base-missing`, parentCount 0, nodeCount 5, rejected.layers 5. All five local
Node references failed the filesystem-prefix check, before label comparison.
r41 is still staged, with matching SHA and no applied/failed record or backup.
The Compose-label defect was real but did not by itself resolve NAS base lookup.
The original runtime reconstruction proved Node 24.18.0 and Yarn 1.22.22.
Neither the preserved env-file nor Compose overrides those variables. The
official public `node:24.18.0-alpine` metadata for linux/amd64 was retrieved and
verified locally. The mutable tag was used for discovery only; the policy pins:
- Manifest: `sha256:4ba75f835bb8802193e4c114572113d4b26f95f6f094f4b5229d2a77773e0afc`.
- OCI config: `sha256:91d56b2d4e1cf23103d90b0b024c1f489c288f9c3aba1042dd7279503b367de6`.
- Four filesystem layers; compressed size 57633665 bytes; created 2026-06-24.
Exact public bytes are committed as node24-base-manifest.json and
node24-base-config.json and embedded as data in the reviewed root runner. They
contain no application/private data or executable artifact hook. Hash checks
bind the manifest to the config and its immutable image identity.
This is an additive, source-registered base-acquisition policy within
dc-cms-release. Application manifests cannot select images, platforms, network
policy, commands or roots. Read-only preflight first tries the existing cache.
If none match, it checks the registered public metadata against the accepted
CMS image: complete strict RootFS prefix, platform, Node 24, exact inherited Env
and configuration, and the already-defined Compose label additions. A matching
version alone never suffices. The official image has WorkingDir `/`; the
predicate now admits that default root as well as empty/default values, before
the fixed Dockerfile sets `/app`. Only known absent-vs-empty OCI User/Variant
defaults are projected when comparing public metadata with Docker 24's API;
runtime fingerprints and full post-build comparison are not normalized.
Preflight performs no pull or registry request. On an exact match its proof
names registeredBase=node24-alpine-amd64-v1 and the fixed digest/config pair.
Canonical apply re-proves the full record against the accepted image. Only an
exact missing-image error for that reference permits:
`docker pull --platform linux/amd64 docker.io/library/node@sha256:4ba75f835bb8802193e4c114572113d4b26f95f6f094f4b5229d2a77773e0afc`
An already cached registered image needs no network. Pull is bounded to 300s;
permission, daemon, registry or timeout failures never select another image.
After acquisition the actual RepoDigest, pinned image identity, full layers and
inherited config are checked again before build. Classic Docker image identity
is the registered OCI config digest; containerd image stores use the registered
manifest digest. Both must still have the exact pinned repository digest and
filesystem/config proof. No arbitrary identity is admitted.
The existing clean temporary Dockerfile uses that proved local ID with
DOCKER_BUILDKIT=0 and --pull=false. The source Dockerfile is unchanged. Full
post-build configuration and runtime acceptance remain exact. Compose itself
still uses --no-build --pull never --no-deps and selects only cms-app. Source,
sites/projects, authentication, other services, databases, mounts, ports and
secrets retain the same checks and rollback. A downloaded immutable base may
remain in Docker cache after rollback; it is never pruned or used as authority
to bypass application acceptance. No old application image/layers are reused
as a build base.
When registered metadata fails, public status gives only a fixed rejection
category and the first four accepted layer digests, alongside candidate counts.
It never exports Env values, label values, file contents or arbitrary stderr.
This supports an exact follow-up if the NAS base differs from this public
candidate. NAS matching remains unproven until its own preflight succeeds.
Validation: 104 CMS tests, 95 Device Core tests, Python 3.8 AST and diff checks.
Focused tests cover no pull in preflight, source-byte integrity, exact proof,
wrong source/reference/config/layers/repository, cached/missing image behavior,
both store identities, missing-image aliases, timeouts and redacted diagnostics.
Existing canonical failed-build tests retain the automatic rollback path.
A real local integration builds original CMS source 4c6f133 with actual Compose
and this official base, removes only its newly acquired digest reference, then
invokes the actual resolver and builder on candidate source 4369f0a. Preflight
does not restore the image; apply acquires only the pinned digest. Candidate
build passes exact inherited configuration/Compose labels, unchanged source
Dockerfile, identical base layers, exported-layer exclusion of old/new private
project fixtures, adm-zip 0.6.1 and Node syntax checks. Local Docker Desktop uses
containerd identities; NAS classic-store identity is covered by focused tests.
Only isolated test tags and ephemeral network-disabled verification containers
are used. This test does not prove NAS layer equality or NAS registry access.
After root runner promotion the existing controller replans queued r41. No new
CMS artifact, bootstrap or failed-release replay is required. A canonical
application receipt is still required before migrating/publishing the two sites.
-93
View File
@@ -1,93 +0,0 @@
# CMS Git deployment domain
The accepted CMS pipeline is live: `SILVER/DC_CMS`, repository 33, `master` → exact
qualification → Gitea artifact → outbound durable queue → canonical installer.
The accepted application release is r55, source
`5ea737318bc49d23cf90121224e5e4296ab579a5`. Bootstrap 002 and the incident-specific
reconciliation transitions are terminal; do not replay them.
Read [CI_RUNBOOK.md](CI_RUNBOOK.md) before modifying this domain or onboarding
another repository. The living operational card is
[DCPLATFORM-78 — CMS Git CI](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-78).
[DCPLATFORM-21](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-21) remains the
mandatory deployment canon; [DCPLATFORM-37](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-37)
is the shared CI and Device Core reference.
## Authority and isolation
CMS has its own repository-scoped `synology-cms-build` registration, controller,
SQLite queue and systemd service/timer. Registration identity is read from the
verified root-private record; it is not copied from Device Core. Its read client
uses the existing private read identity with access to repository 33. Enrollment,
application secrets and site workspaces never enter Git or release artifacts.
The daemon has the reviewed Synology CPUSet/memory isolation profile; job containers
have no Docker socket, production credentials or arbitrary host volumes.
Only the installed root-owned `/usr/local/sbin/nodedc-deploy` executes production
transitions. Source/controller modules are embedded deterministically, never
imported from writable SMB at runtime. A new application cannot choose roots,
services, Compose context, build commands or acceptance through its manifest.
## Application release contract
`dc-cms-release` accepts only registered flat `admin`/`server` application files,
the exact two dependency files and `server/cms-release.json`. Runtime dependencies,
Dockerfile and Compose changes require a separate reviewed foundation transition.
The initial foundation pins `adm-zip` 0.6.1. UI build dependencies are separate;
qualification verifies the committed UI assets against the frozen package build.
The clean temporary build context has an empty `projects` directory. The inherited
Node base must match accepted image ancestry and full configuration. A registered
immutable base can be restored only after exact proof; plan never pulls. Build
uses a proved local image ID and preserves Compose-owned labels. See
[R41_NODE_BASE_ACQUISITION.md](R41_NODE_BASE_ACQUISITION.md) for exact digests and limits.
The source Dockerfile is not rewritten. Application recreation selects only
`cms-app`, with fixed Compose/env/project, `--no-deps` and no implicit pull.
Rollback restores the prior image without rebuilding it.
Acceptance checks authentication/health, exact running application bytes,
image/generation, env/mounts/network/ports, other services and site/project data.
CMS fingerprint v2 normalizes only validated bind ordering and explicitly empty
DNS representations. Synology metadata is classified narrowly and preserved;
unknown paths, orphan streams and symlinks are rejected.
## Qualification and verification
CMS owns `.gitea/workflows/ci.yml` and `infra/ci/release.py`. Only successful exact
`push` runs on `master` are admitted; workflow dispatch is not a production trigger.
The controller checks repository/run/attempt/source/job/steps/registered runner,
artifact ownership/digest and installed → candidate → current-branch ancestry.
Its durable queue reconciles canonical receipts after interruption and blocks on
uncertain rollback. No manual NAS command is needed for an ordinary qualified push.
For changes to deployment policy:
```sh
python3 infra/cms-deploy/embed_runtime.py
python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'
python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'
```
Embedding is needed only after source changes to the embedded modules. Also check
Python 3.8 grammar, deterministic artifact bytes, negative authority/rollback cases
and the real Compose/runtime path. Documentation-only updates do not promote or
install a runner. Existing source commits, artifacts and acceptance evidence are
listed in the runbook; a green CI run alone is not production deployment evidence.
## Failure contracts
- [R39 runtime proof](R39_RUNTIME_RECONCILIATION.md): exact bind/DNS reconciliation,
no runtime mutation, immutable failed receipt.
- [R40 base drift](R40_BUILD_BASE.md): mutable tag changed inherited image state;
strict rollback remained intact.
- [R41 scoped discovery](R41_BASE_DISCOVERY.md): bounded ancestry/cache lookup,
no broad Docker inventory assumptions.
- [R41 Compose labels](R41_COMPOSE_LABELS.md): reproduced Compose additions are
preserved; this alone did not prove a matching NAS filesystem base.
- [R41 registered acquisition](R41_NODE_BASE_ACQUISITION.md): one exact public base,
full ancestry/config proof, then successful application installation.
These documents preserve the conditions and limitations of the investigated cases.
Their intermediate pending states are not current operational status. Use the
runbook and fresh canonical receipts for current state. CMS content publication
and portable site backups are separate product flows documented in DC-9.
-138
View File
@@ -1,138 +0,0 @@
# Registered read-only diagnosis. Never normalizes or reconciles production.
CMS_AUDIT_ID = 'dc-cms-r39-runtime-audit-v1-20261104-001'
CMS_AUDIT_ENTRY = 'deployment/dc-cms-r39-runtime-audit-v1.json'
CMS_AUDIT_FAILED_ID = 'dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a'
CMS_AUDIT_FAILED_SHA = '3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029'
CMS_AUDIT_BACKUP = 'dc-cms-release-'+CMS_AUDIT_FAILED_ID+'-20261104-223125'
CMS_AUDIT_BACKUP_SHA = {
'cms-runtime-before.json':'e14634fc1ef03da8b8a7751d9418b74c52da65dfe6dea82ad9c14ef04634263b',
'source-before.tgz':'cd35cb27dd4875e13cdf7202ab57c24e7db0a43c473454675fe122ebf23090b1',
'manifest.env':'ce246952d0ef6cee1f4b22b770108d5c92d671cc7984dc83e136d61f2e607f22',
'files.txt':'4a696155703c6aa15daf777331847a37cd5e8345e2bb0a6b1fc98515e27988d8',
'existing-files.txt':'46fa370124d7ed95362666e84372188bdf9d0c2b4c2e0e3d9dbeed42ad571762',
'missing-files.txt':'c31852f6da115fed68880fcf0aa8a7b4c0d2a7a9cfdae095907e95863bdb2409',
}
def cms_audit_descriptor():
return {'schemaVersion':'nodedc.dc-cms.runtime-audit.v1','auditId':CMS_AUDIT_ID,
'failedReleaseId':CMS_AUDIT_FAILED_ID,'failedSha256':CMS_AUDIT_FAILED_SHA,
'backupId':CMS_AUDIT_BACKUP,'backupSha256':CMS_AUDIT_BACKUP_SHA,
'allowedOperation':'canonical-plan-only','mutation':False}
def validate_cms_audit_payload(payload, entries, identity):
if identity!=CMS_AUDIT_ID or tuple(entries)!=(CMS_AUDIT_ENTRY,):
die('CMS runtime audit requires its exact registered identity and descriptor')
expected=(json.dumps(cms_audit_descriptor(),sort_keys=True,indent=2)+'\n').encode()
if (payload/CMS_AUDIT_ENTRY).read_bytes()!=expected:
die('CMS runtime audit descriptor mismatch')
def cms_audit_evidence():
if any(row.get('id')==CMS_AUDIT_FAILED_ID for row in load_state(STATE_FILE)):
die('CMS runtime audit found an unexpected successful receipt')
rows=[row for row in load_state(FAILED_STATE_FILE) if row.get('id')==CMS_AUDIT_FAILED_ID]
if len(rows)!=1:die('CMS runtime audit requires one exact failed receipt')
row=rows[0]
expected={'id':CMS_AUDIT_FAILED_ID,'sha256':CMS_AUDIT_FAILED_SHA,'backup_id':CMS_AUDIT_BACKUP,
'component':'dc-cms-release','status':'failed','started_apply':True,
'rollback_status':'failed:DeployError',
'message':'CMS environment, mounts, ports or network topology changed',
'artifact':'nodedc-'+CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125'}
if any(row.get(k)!=v for k,v in expected.items()):die('CMS runtime audit incident receipt differs')
archive=FAILED_DIR/expected['artifact'];backup=BACKUPS_DIR/CMS_AUDIT_BACKUP
for path in (archive,backup):
if any(p.is_symlink() for p in (path,*path.parents)):die('CMS runtime audit evidence path is unsafe')
if not archive.is_file() or sha256_file(archive)!=CMS_AUDIT_FAILED_SHA:
die('CMS runtime audit failed archive mismatch')
if collect_exact_files(backup,sorted(CMS_AUDIT_BACKUP_SHA),'CMS runtime audit backup')!=CMS_AUDIT_BACKUP_SHA:
die('CMS runtime audit backup differs')
return read_strict_json(backup/'cms-runtime-before.json','CMS runtime audit predecessor',max_bytes=512*1024)
def cms_audit_fields(info):
# Exact preimage of cms_runtime_snapshot; this does not change acceptance.
host=json.loads(json.dumps(info.get('HostConfig') or {}))
for field in ('Mounts','Ulimits'):
if isinstance(host.get(field),list):host[field].sort(key=lambda x:json.dumps(x,sort_keys=True))
config=info.get('Config') or {}
fields={'host':host,'config':{k:config.get(k) for k in ('Env','User','Cmd','Entrypoint','WorkingDir','ExposedPorts')},
'mounts':sorted(info.get('Mounts') or [],key=lambda x:json.dumps(x,sort_keys=True)),
'networks':sorted((info.get('NetworkSettings') or {}).get('Networks') or {})}
if isinstance(fields['config']['Env'],list):fields['config']['Env'].sort()
return fields
def cms_audit_digest(value):
return hashlib.sha256(json.dumps(value,sort_keys=True).encode()).hexdigest()
def cms_audit_sample():
runtime=cms_runtime_snapshot();info=inspect_container(runtime['id'])
fields=cms_audit_fields(info)
if info.get('Image')!=runtime['imageId'] or cms_audit_digest(fields)!=runtime['configSha256']:
die('CMS runtime changed during audit sampling')
return {'runtime':runtime,'fields':fields}
def cms_audit_probe(fields, expected, budget=20000):
"""Find a saved SHA preimage using observed values only; NEVER accept it."""
if not isinstance(expected,str) or not re.fullmatch('[a-f0-9]{64}',expected):die('CMS audit expected digest invalid')
current=cms_audit_digest(fields)
result={'expectedSha256':expected,'actualSha256':current,'exactCurrentMatch':current==expected,
'exactPreimageFound':current==expected,'changedFields':[],'candidatesChecked':1,'searchTruncated':False}
if current==expected:return result
original=json.loads(json.dumps(fields));work=json.loads(json.dumps(fields));lists=[]
for name in ('Binds','Mounts'):
value=original['host'].get(name)
if value is not None:
if not isinstance(value,list) or len(value)>8:
result.update(searchTruncated=True,reason='mount-list-bound');return result
if len({json.dumps(v,sort_keys=True) for v in value})!=len(value):
result.update(searchTruncated=True,reason='duplicate-mounts');return result
lists.append((name,value))
mode=original['host'].get('NetworkMode')
for alternative in [mode]+[n for n in original['networks'] if n!=mode]:
if alternative!=mode or 'NetworkMode' in original['host']:work['host']['NetworkMode']=alternative
for left in ([None] if lists[0][1] is None else itertools.permutations(lists[0][1])):
if left is not None:work['host'][lists[0][0]]=list(left)
for right in ([None] if lists[1][1] is None else itertools.permutations(lists[1][1])):
if right is not None:work['host'][lists[1][0]]=list(right)
if result['candidatesChecked']>=budget:
result['searchTruncated']=True;return result
result['candidatesChecked']+=1
if cms_audit_digest(work)==expected:
result['exactPreimageFound']=True
result['changedFields']=['HostConfig.'+k for k in ('Binds','Mounts','NetworkMode') if work['host'].get(k)!=original['host'].get(k)]
if alternative!=mode:result.update(currentNetworkMode=mode,matchingSavedNetworkMode=alternative)
return result
return result
def cms_runtime_audit(payload, entries, identity):
require_root();validate_cms_audit_payload(payload,entries,identity);before=cms_audit_evidence()
report={'schemaVersion':'nodedc.dc-cms.runtime-audit-report.v1','mutation':False,'applyAllowed':False,
'failedReleaseId':CMS_AUDIT_FAILED_ID,'incidentEvidenceExact':True,'checks':{}}
def check(name, fn):
try:report['checks'][name]={'ok':fn() is not False}
except Exception as error:report['checks'][name]={'ok':False,'errorType':type(error).__name__}
check('source',lambda:cms_application_inventory()[0]==before['installedFiles'])
check('metadata',lambda:cms_application_inventory()[1]==before['installedMetadata'])
check('foundation',lambda:cms_foundation()==before['foundation'])
check('siteAndProjectData',lambda:cms_preserved_data()==before['data'])
check('otherServices',lambda:cms_other_services()==before['otherServices'])
check('health',cms_healthchecks)
samples=[cms_audit_sample() for _ in range(3)];sample=samples[0];runtime=sample['runtime'];fields=sample['fields']
proof=cms_audit_probe(fields,before['runtime']['configSha256'])
proof.update(expectedImageId=before['runtime']['imageId'],actualImageId=runtime['imageId'],
imageMatches=runtime['imageId']==before['runtime']['imageId'],
imageRefMatches=runtime['imageRef']==before['runtime']['imageRef'],
sampleCount=len(samples),samplesStable=all(s==sample for s in samples),
mountCounts={k:len(fields['host'].get(k) or []) for k in ('Binds','Mounts')},
fieldSha256={section:{k:cms_audit_digest(v) for k,v in fields[section].items()} for section in ('host','config')})
check('runningImageSource',lambda:cms_image_files(runtime['id'])=={k:v for k,v in before['installedFiles'].items() if k not in CMS_DEPENDENCY_FILES})
report['runtime']=proof
print('cms_runtime_audit='+json.dumps(report,sort_keys=True,separators=(',',':')))
print('cms_runtime_audit_result=diagnostic-only;apply=forbidden;acceptance-barriers=unchanged')
return report
-21
View File
@@ -1,21 +0,0 @@
{
"baselineSourceCommit": "4c6f133ff1dba5975e45b3c7ab332c40eaf96ab8",
"branch": "master",
"buildRunner": "synology-cms-build",
"buildRunnerRepositoryId": 33,
"firstRunNumber": 1,
"installer": "/usr/local/sbin/nodedc-deploy",
"intervalAfterCompletionSeconds": 30,
"publishedPorts": [],
"releaseComponent": "dc-cms-release",
"releaseId": "dc-cms-autodeploy-v1-20261104-002",
"repository": "SILVER/DC_CMS",
"repositoryId": 33,
"scheduler": "native-systemd-timer",
"schemaVersion": "nodedc.dc-cms.autodeploy.v1",
"services": [
"cms-app"
],
"transport": "outbound-https",
"workflow": "ci.yml@refs/heads/master"
}
-362
View File
@@ -1,362 +0,0 @@
# DC CMS outbound automatic deployment. All authority stays in this file.
CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-002'
CMS_AUTODEPLOY_ENTRY = 'deployment/dc-cms-autodeploy-v1.json'
CMS_AUTODEPLOY_ENTRIES = CMS_CI_V4_ENTRIES
CMS_AUTODEPLOY_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy')
CMS_AUTODEPLOY_PRIVATE = Path('/var/lib/nodedc-cms-autodeploy')
CMS_AUTODEPLOY_PENDING = RUNTIME_DIR / 'dc-cms-autodeploy' / 'enrollment.pending.json'
CMS_AUTODEPLOY_UNIT_DIR = Path('/usr/local/lib/systemd/system')
CMS_AUTODEPLOY_SERVICE = 'nodedc-cms-autodeploy.service'
CMS_AUTODEPLOY_TIMER = 'nodedc-cms-autodeploy.timer'
CMS_AUTODEPLOY_BASELINE = CMS_BASELINE['sourceCommit']
CMS_AUTODEPLOY_DESCRIPTOR = {
'schemaVersion': 'nodedc.dc-cms.autodeploy.v1', 'releaseId': CMS_AUTODEPLOY_ID,
'repository': 'SILVER/DC_CMS', 'repositoryId': 33, 'branch': 'master',
'workflow': 'ci.yml@refs/heads/master', 'firstRunNumber': 1,
'baselineSourceCommit': CMS_AUTODEPLOY_BASELINE,
'transport': 'outbound-https', 'publishedPorts': [], 'scheduler': 'native-systemd-timer',
'intervalAfterCompletionSeconds': 30, 'installer': '/usr/local/sbin/nodedc-deploy',
'releaseComponent': 'dc-cms-release', 'services': ['cms-app'], 'buildRunner': 'synology-cms-build', 'buildRunnerRepositoryId': 33,
}
def cms_autodeploy_units():
return {
CMS_AUTODEPLOY_SERVICE: (
'[Unit]\nDescription=NODE.DC DC CMS canonical deployment controller\n'
'After=network-online.target\nWants=network-online.target\n\n'
'[Service]\nType=oneshot\nUser=root\nGroup=root\nUMask=0077\n'
'Environment=PATH=/usr/local/bin:/usr/bin:/bin\n'
'ExecStart=/usr/bin/python3 /usr/local/sbin/nodedc-deploy --dc-cms-autodeploy-tick\n'
'TimeoutStartSec=0\nTimeoutStopSec=300\nNice=10\n'
'StandardOutput=journal\nStandardError=journal\n'),
CMS_AUTODEPLOY_TIMER: (
'[Unit]\nDescription=Poll qualified DC CMS releases without inbound ports\n\n'
'[Timer]\nOnBootSec=120s\nOnUnitInactiveSec=30s\nAccuracySec=1s\n'
'Unit=nodedc-cms-autodeploy.service\n\n[Install]\nWantedBy=timers.target\n'),
}
def validate_cms_autodeploy_payload(payload, entries, identity):
if tuple(entries or ()) != CMS_AUTODEPLOY_ENTRIES or identity != CMS_AUTODEPLOY_ID:
die('DC CMS autodeploy requires its exact bootstrap descriptor')
try:
# Canonical byte representation prevents duplicate-key ambiguity.
data = (payload / CMS_AUTODEPLOY_ENTRY).read_bytes()
expected = (json.dumps(CMS_AUTODEPLOY_DESCRIPTOR, indent=2, sort_keys=True) + '\n').encode()
if data != expected:
die('DC CMS autodeploy descriptor differs from the registered contract')
except (OSError, ValueError):
die('DC CMS autodeploy descriptor is unreadable')
for rel,digest in CMS_CI_SOURCE_SHA256.items():
if sha256_file(payload/rel)!=digest:die('CMS CI immutable source mismatch')
return CMS_AUTODEPLOY_DESCRIPTOR
def cms_autodeploy_root_path(path, directory=False):
"""No runtime executable/state authority through a writable ancestor."""
for candidate in [path] + list(path.parents):
info = candidate.lstat()
if (stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022
or (candidate != path and not stat.S_ISDIR(info.st_mode))):
die('DC CMS autodeploy root path metadata rejected: ' + str(candidate))
info = path.lstat()
if not (stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)):
die('DC CMS autodeploy root path type rejected: ' + str(path))
return info
def cms_autodeploy_systemctl():
if Path('/proc/1/comm').read_text().strip() != 'systemd' or not Path('/run/systemd/system').is_dir():
die('DC CMS autodeploy requires the native systemd manager')
cms_autodeploy_root_path(CMS_AUTODEPLOY_UNIT_DIR, directory=True)
python = Path('/usr/bin/python3').resolve(strict=True)
cms_autodeploy_root_path(python)
candidates = []
for name in ('/bin/systemctl', '/usr/bin/systemctl'):
p = Path(name)
if p.exists():
resolved = p.resolve(strict=True)
cms_autodeploy_root_path(resolved)
if not os.access(str(resolved), os.X_OK):
die('DC CMS autodeploy systemctl is not executable')
if resolved not in candidates:
candidates.append(resolved)
if len(candidates) != 1:
die('DC CMS autodeploy native systemctl identity is ambiguous or missing')
return candidates[0]
def cms_autodeploy_ctl(*args, check=True):
return subprocess.run([str(cms_autodeploy_systemctl()), *args], text=True,
capture_output=True, check=check, timeout=35)
def cms_autodeploy_read_token(private=False):
# Reuse the existing read-only identity inside the root runner, never export
# or duplicate its secret. Source policy remains pinned to CMS repository 33.
return device_autodeploy_read_token(private=True)
def cms_autodeploy_enrollment():
return cms_autodeploy_read_token(private=True)[0]
def cms_autodeploy_import_token():
cms_autodeploy_read_token(private=True)
if not CMS_AUTODEPLOY_PRIVATE.exists():
cms_autodeploy_root_path(CMS_AUTODEPLOY_PRIVATE.parent,directory=True)
CMS_AUTODEPLOY_PRIVATE.mkdir(mode=0o700)
cms_autodeploy_root_path(CMS_AUTODEPLOY_PRIVATE,directory=True)
if stat.S_IMODE(CMS_AUTODEPLOY_PRIVATE.stat().st_mode)!=0o700:
die('CMS private queue directory must be 0700')
def cms_autodeploy_installed_source():
return cms_installed_release()['sourceCommit']
def preflight_cms_autodeploy(payload, entries, identity):
require_root()
validate_cms_autodeploy_payload(payload,entries,identity)
ctl=cms_autodeploy_systemctl()
preflight_cms_ci()
if cms_autodeploy_installed_source()!=CMS_AUTODEPLOY_BASELINE:
die('CMS bootstrap requires the registered initial predecessor')
if any(r.get('component')=='dc-cms-autodeploy' for r in load_state(STATE_FILE)):
die('CMS bootstrap is already applied')
for name in cms_autodeploy_units():
path=CMS_AUTODEPLOY_UNIT_DIR/name
if path.exists() or path.is_symlink():die('CMS controller unit already exists')
if cms_autodeploy_ctl('show',name,'--property=LoadState',check=False).stdout.strip()!='LoadState=not-found':
die('CMS controller unit name is already managed')
if not device_autodeploy_activated():die('CMS requires the established Gitea read identity')
_,Source,_,_=cms_autodeploy_library()
source=Source(cms_autodeploy_enrollment())
source.discover() # Fail before mutation unless the identity can read repo 33 Actions.
if not source.ancestor(CMS_AUTODEPLOY_BASELINE,source.main_commit()):die('CMS master diverged from installed baseline')
cms_healthchecks()
return {'systemctl':str(ctl),'inventory':cms_ci_inventory(),'runtime':cms_runtime_snapshot(),'data':cms_preserved_data(),'baseline':CMS_AUTODEPLOY_BASELINE}
def apply_cms_autodeploy(before):
apply_cms_ci()
cms_autodeploy_import_token()
for name, content in cms_autodeploy_units().items():
path = CMS_AUTODEPLOY_UNIT_DIR / name
fd, temporary = tempfile.mkstemp(prefix='.' + name + '.', dir=str(CMS_AUTODEPLOY_UNIT_DIR))
try:
with os.fdopen(fd, 'w') as stream:
os.fchmod(stream.fileno(), 0o644)
stream.write(content);stream.flush();os.fsync(stream.fileno())
os.link(temporary, str(path))
finally:
os.unlink(temporary)
fsync_directory(CMS_AUTODEPLOY_UNIT_DIR)
cms_autodeploy_ctl('daemon-reload')
cms_autodeploy_ctl('enable', CMS_AUTODEPLOY_TIMER)
cms_autodeploy_ctl('start', CMS_AUTODEPLOY_TIMER)
# The timer may fire immediately if boot was more than two minutes ago.
# Its worker refuses deployment until the canonical bootstrap receipt exists.
accept_cms_autodeploy(before)
def accept_cms_autodeploy(before):
accept_cms_ci(CMS_CI_V4_ENTRIES)
for name, content in cms_autodeploy_units().items():
path = CMS_AUTODEPLOY_UNIT_DIR / name
cms_autodeploy_root_path(path)
if path.read_text() != content:
die('DC CMS autodeploy installed unit differs')
result = cms_autodeploy_ctl('show', name, '--property=FragmentPath')
if result.stdout.strip() != 'FragmentPath=' + str(path):
die('DC CMS autodeploy effective unit origin mismatch')
if cms_autodeploy_ctl('show', name, '--property=DropInPaths').stdout.strip() != 'DropInPaths=':
die('DC CMS autodeploy unit has an undeclared drop-in')
if cms_autodeploy_ctl('is-enabled', CMS_AUTODEPLOY_TIMER).stdout.strip() != 'enabled':
die('DC CMS autodeploy timer is not enabled')
if cms_autodeploy_ctl('is-active', CMS_AUTODEPLOY_TIMER).stdout.strip() != 'active':
die('DC CMS autodeploy timer is not active')
cms_autodeploy_read_token(private=True)
if not cms_ci_inventory_preserved(before['inventory']) or cms_runtime_snapshot() != before['runtime'] or cms_preserved_data() != before['data'] or cms_autodeploy_installed_source() != before['baseline']:
die('DC CMS autodeploy bootstrap changed existing applications')
print('cms_autodeploy_accept=outbound-timer;ports=none;baseline=4c6f133;first-run=1;deploy-authority=canonical-runner')
def rollback_cms_autodeploy(root, backup_dir, entries, current_stamp, before):
# This domain owns only two previously absent units and the descriptor.
cms_autodeploy_ctl('stop', CMS_AUTODEPLOY_TIMER, check=False)
cms_autodeploy_ctl('stop', CMS_AUTODEPLOY_SERVICE, check=False)
cms_autodeploy_ctl('disable', CMS_AUTODEPLOY_TIMER, check=False)
for name, content in cms_autodeploy_units().items():
path = CMS_AUTODEPLOY_UNIT_DIR / name
if path.exists():
cms_autodeploy_root_path(path)
if path.read_text() != content:
die('DC CMS autodeploy rollback unit ownership mismatch')
path.unlink()
cms_autodeploy_ctl('daemon-reload')
capture_cms_ci_diagnostics(backup_dir)
stop_and_remove_compose_services('dc-cms-autodeploy', ('build-runner',))
restore_platform_overlay(root, backup_dir, entries, current_stamp)
if cms_ci_container_ids(own=True):die('CMS CI rollback left a runner')
for name in cms_autodeploy_units():
if (CMS_AUTODEPLOY_UNIT_DIR / name).exists():
die('DC CMS autodeploy rollback retained a unit')
if not cms_ci_inventory_preserved(before['inventory']) or cms_runtime_snapshot() != before['runtime'] or cms_preserved_data() != before['data']:
die('DC CMS autodeploy rollback application preservation failed')
# Credentials/queue are deliberately retained, never erased by rollback.
def cms_autodeploy_activated():
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'dc-cms-autodeploy']
if not rows:
return False
if len(rows) != 1 or rows[0].get('id') != CMS_AUTODEPLOY_ID or rows[0].get('status') != 'ok':
die('DC CMS autodeploy activation receipt mismatch')
row = rows[0]
with tempfile.TemporaryDirectory(prefix='autodeploy-activation-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest['component'] != 'dc-cms-autodeploy':
die('DC CMS autodeploy activation component mismatch')
validate_cms_autodeploy_payload(payload, entries, row['id'])
if (CMS_AUTODEPLOY_ROOT / CMS_AUTODEPLOY_ENTRY).read_bytes() != (payload / CMS_AUTODEPLOY_ENTRY).read_bytes():
die('DC CMS autodeploy activation descriptor drift')
return True
class CmsAutodeployInstaller:
def installed_source(self):
return cms_autodeploy_installed_source()
def stage(self, row, receipt, data):
expected = 'nodedc-dc-cms-release-v1-r' + str(row['id']) + '-' + row['sha'] + '.tgz'
if receipt['artifact'] != expected or hashlib.sha256(data).hexdigest() != receipt['sha256']:
die('DC CMS autodeploy staging identity mismatch')
identity = expected[len('nodedc-'):-4]
if any(r.get('id') == identity for r in load_state(STATE_FILE) + load_state(FAILED_STATE_FILE)):
die('DC CMS autodeploy artifact already has a terminal journal record')
with tempfile.TemporaryDirectory(prefix='autodeploy-stage-', dir=TMP_DIR) as tmp:
candidate = Path(tmp) / expected;candidate.write_bytes(data)
unpack = Path(tmp) / 'unpack';unpack.mkdir()
manifest, entries, payload = load_artifact(candidate, unpack)
if manifest['component'] != 'dc-cms-release' or manifest['id'] != identity:
die('DC CMS autodeploy canonical component scope mismatch')
d = validate_cms_release_payload(payload, entries, identity)
if (d['runId'],d['runNumber'],d['sourceCommit']) != (row['id'],row['number'],row['sha']):
die('DC CMS autodeploy payload run mismatch')
target = INBOX / expected
if target.exists() or target.is_symlink():
info = target.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or sha256_file(target) != receipt['sha256']:
die('DC CMS autodeploy inbox conflict')
else:
# Link a complete, fsynced file into the inbox without overwrite.
candidate.chmod(0o600)
with candidate.open('rb') as stream:os.fsync(stream.fileno())
os.link(str(candidate),str(target));candidate.unlink();fsync_directory(INBOX)
def plan(self, artifact):
plan_artifact(INBOX / artifact)
def apply(self, artifact):
apply_artifact(INBOX / artifact)
def receipt(self, row):
identity = row['artifact'][len('nodedc-'):-4]
applied = [r for r in load_state(STATE_FILE) if r.get('id') == identity]
failed = [r for r in load_state(FAILED_STATE_FILE) if r.get('id') == identity]
if len(applied) + len(failed) != 1:
return 'ambiguous', 'canonical-receipt-missing-or-conflicting'
record = (applied or failed)[0]
if record.get('component') != 'dc-cms-release' or record.get('sha256') != row['digest']:
return 'ambiguous', 'canonical-receipt-identity-mismatch'
archive = (APPLIED_DIR if applied else FAILED_DIR) / str(record.get('artifact',''))
backup = BACKUPS_DIR / str(record.get('backup_id',''))
if (archive.parent not in (APPLIED_DIR,FAILED_DIR) or archive.is_symlink() or not archive.is_file()
or sha256_file(archive) != row['digest'] or backup.parent != BACKUPS_DIR
or backup.is_symlink() or not backup.is_dir()):
return 'ambiguous', 'canonical-archive-or-backup-mismatch'
if applied and record.get('status') == 'ok':
outcome = 'deployed'
elif failed and cms_r39_reconciled(record):
return 'rolled-back', 'canonical-reconciled:' + CMS_RECON_ID
elif failed and record.get('rollback_status') == 'ok:dc-cms-release':
outcome = 'rolled-back'
else:
return 'ambiguous', 'canonical-rollback-unconfirmed'
return outcome, 'canonical:' + str(record['backup_id'])
def cms_autodeploy_publish_status(result):
# Public projection contains no credentials, API bodies or raw exceptions.
# It is an observation aid; only canonical journals authorize deployment.
result = dict(result, updatedAt=utc_now())
data = (json.dumps(result, sort_keys=True) + '\n').encode()
atomic_write_root_file(CMS_AUTODEPLOY_PRIVATE / 'status.json', data)
if CMS_AUTODEPLOY_ROOT.is_symlink() or not CMS_AUTODEPLOY_ROOT.is_dir():
die('DC CMS autodeploy status destination is not its descriptor root')
fd, temporary = tempfile.mkstemp(prefix='.status-', dir=str(CMS_AUTODEPLOY_ROOT))
try:
with os.fdopen(fd, 'wb') as stream:
os.fchmod(stream.fileno(), 0o644);stream.write(data);stream.flush();os.fsync(stream.fileno())
os.replace(temporary, str(CMS_AUTODEPLOY_ROOT / 'runtime-status.json'))
fsync_directory(CMS_AUTODEPLOY_ROOT)
finally:
if os.path.exists(temporary):os.unlink(temporary)
print('cms_autodeploy_tick=' + json.dumps(result, sort_keys=True))
def cms_autodeploy_error_status(error, policy_errors):
result={'status':'attention','errorType':type(error).__name__}
if isinstance(error,policy_errors):result['reason']=str(error)[:200]
# Only fixed CMS codes are added. External stderr/raw exception text stays
# private, even if a caller mutates the exception's message or code.
if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES:
result['reason']=error.code
diagnostic=cms_base_public_diagnostic(error.diagnostic)
if diagnostic is not None:result['baseLookup']=diagnostic
return result
def cms_autodeploy_tick():
require_root()
ensure_layout()
if not cms_autodeploy_activated():
return 0
cms_autodeploy_root_path(CMS_AUTODEPLOY_PRIVATE,directory=True)
os.umask(0o077)
lock_path = CMS_AUTODEPLOY_PRIVATE / 'controller.lock'
fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(fd,fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return 0
if LOCK_DIR.exists():
cms_autodeploy_publish_status({'status':'waiting','reason':'canonical-deploy-lock'})
return 0 # Another canonical installation owns the runtime.
Queue, Source, Controller, errors = cms_autodeploy_library()
token = cms_autodeploy_read_token(private=True)[0]
queue_path = CMS_AUTODEPLOY_PRIVATE / 'queue.sqlite3'
for path in (queue_path,Path(str(queue_path)+'-wal'),Path(str(queue_path)+'-shm')):
if path.exists() or path.is_symlink():
cms_autodeploy_root_path(path)
queue = Queue(queue_path,first_run_number=1)
try:
result = Controller(queue,Source(token,runner_id=cms_ci_registered_runner_id()),CmsAutodeployInstaller()).tick()
except Exception as error:
result = cms_autodeploy_error_status(error,errors)
finally:
queue.close()
cms_autodeploy_publish_status(result)
return 0 if result['status'] != 'attention' else 1
finally:
os.close(fd)
-17
View File
@@ -1,17 +0,0 @@
{
"filesSha256": {
"admin/admin.css": "1aa723320a3920c9bba41bb7b16c077eadbd464908f9a539259ac15d00fffc7c",
"admin/admin.js": "149212254c93c31da1df914a6d8049be982c40a8661180c4c2b6291e76244297",
"admin/index.html": "a4d24b78a71a6d3bbd3c9aac8f900ddab1ff1dd10f324e30a37b2363fbcdae26",
"admin/nodedc-logo.svg": "b8a2c9bc1342819883e67c1b8fcde4b60175c0f4bdeafd2d08b3cb87873478e0",
"server/admin-server.mjs": "a1f7db4a03b831cfd94474bdd8e272f35bf5826d15441f9203c38955a8f8a3e2"
},
"foundationSha256": {
"Dockerfile": "ccb783bd76b1588cbe0157bd317f6da06888d79f8a199fd0c5515000948acd42",
"infra/docker-compose.yml": "abb3a9d4e4e2ce15eb2ca52b335289dcd00808d85c78da6d1bc583a8b3517f48",
"infra/reverse-proxy/Caddyfile": "4d30188eb1f11b52a0eaf2d9476e0b0adda93a63e66938e8028cc11de4c2038f",
"package-lock.json": "73e0f87dafe7c54539af30be0f4797ea02b4715ba306c5d69e150edb2d679794",
"package.json": "96cfd6cb47317d9f45ef9fcc7ad7f5ed2cfa0efbf83fe031d66acdd84a217a62"
},
"sourceCommit": "4c6f133ff1dba5975e45b3c7ab332c40eaf96ab8"
}
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env python3
"""Deterministic data-only controller bootstrap; executable policy is in the root runner."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT=Path(__file__).resolve().parent
ENTRY='deployment/dc-cms-autodeploy-v1.json'
def bundle():
data=(ROOT/'autodeploy-v1.json').read_bytes()
identity=json.loads(data)['releaseId']
members={'manifest.env':('id='+identity+'\ncomponent=dc-cms-autodeploy\ntype=app-overlay\n').encode(),
'files.txt':('\n'.join((ENTRY,'docker-compose.cms-ci.yml','runner.yaml'))+'\n').encode(),'payload/'+ENTRY:data}
members.update({'payload/'+name:(ROOT/name).read_bytes() for name in ('docker-compose.cms-ci.yml','runner.yaml')})
output=io.BytesIO()
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed:
with tarfile.open(fileobj=compressed,mode='w') as archive:
for name,value in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value)
archive.addfile(info,io.BytesIO(value))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',required=True,type=Path)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps(dict(artifact=str(path),sha256=hashlib.sha256(data).hexdigest(),id=identity)))
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env python3
"""Build the fixed, data-only CMS r39 plan-only audit descriptor."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT=Path(__file__).resolve().parent
ENTRY='deployment/dc-cms-r39-runtime-audit-v1.json'
def bundle():
descriptor=(ROOT/'runtime-audit-v1.json').read_bytes()
identity=json.loads(descriptor)['auditId']
members={'manifest.env':f'id={identity}\ncomponent=dc-cms-runtime-audit\ntype=app-overlay\n'.encode(),
'files.txt':(ENTRY+'\n').encode(),'payload/'+ENTRY:descriptor}
output=io.BytesIO()
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed:
with tarfile.open(fileobj=compressed,mode='w') as archive:
for name,value in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value)
archive.addfile(info,io.BytesIO(value))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',type=Path,required=True)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity}))
@@ -1,33 +0,0 @@
#!/usr/bin/env python3
"""Build the fixed, data-only CMS r39 runtime reconciliation descriptor."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT=Path(__file__).resolve().parent
ENTRY='deployment/dc-cms-r39-runtime-reconciliation-v2.json'
def bundle():
descriptor=(ROOT/'runtime-reconciliation-v2.json').read_bytes()
identity=json.loads(descriptor)['releaseId']
members={'manifest.env':f'id={identity}\ncomponent=dc-cms-runtime-reconciliation\ntype=app-overlay\n'.encode(),
'files.txt':(ENTRY+'\n').encode(),'payload/'+ENTRY:descriptor}
output=io.BytesIO()
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed:
with tarfile.open(fileobj=compressed,mode='w') as archive:
for name,value in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value)
archive.addfile(info,io.BytesIO(value))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',type=Path,required=True)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity}))
-4
View File
@@ -1,4 +0,0 @@
{
"docker-compose.cms-ci.yml": "9c6b6bf2a9da2f7d5097b8d110882da1587b4d49018aba5ccf258a0218b351c2",
"runner.yaml": "94d8e4d8345b2b5bc7c8923bff7c31ff59083ec7115d633af10152b93bcd9da6"
}
-342
View File
@@ -1,342 +0,0 @@
# CMS owns one separately registered, repository-scoped build runner.
CMS_CI_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy')
CMS_CI_ENROLLMENT = DEPLOY_ROOT / 'runner-install' / 'cms-ci-enrollment.pending.json'
CMS_CI_IMAGE = GITEA_CI_IMAGE
CMS_CI_JOB_IMAGE = GITEA_CI_JOB_IMAGE
CMS_CI_ENTRIES = CMS_CI_V2_ENTRIES = CMS_CI_V3_ENTRIES = CMS_CI_V4_ENTRIES = ('deployment/dc-cms-autodeploy-v1.json','docker-compose.cms-ci.yml','runner.yaml')
CMS_CI_SOURCE_SHA256 = __CMS_CI_HASHES__
def read_cms_ci_v2_input(runtime=False):
"""Read a bounded operator handoff or the private NAS copy, never SMB modes."""
path = (CMS_CI_ROOT / "secrets" / "registration-token"
if runtime else CMS_CI_ENROLLMENT)
for parent in path.parents:
if parent.is_symlink():
die("CMS CI enrollment path contains a symlink")
try:
operator_uid = pwd.getpwnam("dctouch").pw_uid
except KeyError:
die("CMS CI staging account dctouch is missing")
try:
fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
except OSError:
die("CMS CI enrollment input cannot be opened safely")
with os.fdopen(fd, "rb") as stream:
info = os.fstat(stream.fileno())
if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1
or not 1 <= info.st_size <= 2048
or info.st_uid not in ((0,) if runtime else (0, operator_uid))
or (runtime and stat.S_IMODE(info.st_mode) != 0o600)):
die("CMS CI enrollment metadata rejected: "
f"runtime={runtime};mode={stat.S_IMODE(info.st_mode):04o};"
f"uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}")
raw = stream.read(2049)
after = os.fstat(stream.fileno())
if (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != (
after.st_size, after.st_mtime_ns, after.st_ctime_ns):
die("CMS CI enrollment changed while reading")
try:
if runtime:
token = raw.decode("ascii").strip()
else:
value = json.loads(raw)
if (not isinstance(value, dict) or set(value) != {"repository", "token"}
or value["repository"] != "SILVER/DC_CMS"):
raise ValueError()
token = value["token"]
if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{20,256}", token):
raise ValueError()
except (ValueError, UnicodeError):
die("CMS CI enrollment format is invalid")
return token, info
def preflight_cms_ci_v2_enrollment():
private = CMS_CI_ROOT / "secrets" / "registration-token"
if CMS_CI_ENROLLMENT.exists() or CMS_CI_ENROLLMENT.is_symlink():
token, info = read_cms_ci_v2_input()
if private.exists() or private.is_symlink():
if read_cms_ci_v2_input(runtime=True)[0] != token:
die("CMS CI existing runtime enrollment differs")
return f"import-staging;mode={stat.S_IMODE(info.st_mode):04o};uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}"
read_cms_ci_v2_input(runtime=True)
return "reuse-root-private-runtime"
def import_cms_ci_v2_enrollment():
"""The v2 apply transition owns private creation; plan never changes rights."""
preflight_cms_ci_v2_enrollment()
pending = CMS_CI_ENROLLMENT.exists()
token, source_info = read_cms_ci_v2_input(runtime=not pending)
directory = CMS_CI_ROOT / "secrets"
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if directory.is_symlink():
die("CMS CI private directory cannot be a symlink")
os.chown(str(directory), 0, 0)
directory.chmod(0o700)
target = directory / "registration-token"
if not target.exists():
fd, temporary = tempfile.mkstemp(prefix=".enrollment-", dir=str(directory))
try:
with os.fdopen(fd, "w") as stream:
os.fchown(stream.fileno(), 0, 0)
os.fchmod(stream.fileno(), 0o600)
stream.write(token + "\n")
stream.flush()
os.fsync(stream.fileno())
# Atomic publication without replacing an existing identity.
os.link(temporary, str(target))
finally:
os.unlink(temporary)
if read_cms_ci_v2_input(runtime=True)[0] != token:
die("CMS CI private enrollment import verification failed")
for path in (directory, CMS_CI_ROOT):
fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
if pending:
current = CMS_CI_ENROLLMENT.lstat()
if (current.st_dev, current.st_ino, current.st_mtime_ns, current.st_size) != (
source_info.st_dev, source_info.st_ino, source_info.st_mtime_ns, source_info.st_size):
die("CMS CI enrollment staging changed before cleanup")
CMS_CI_ENROLLMENT.unlink()
print("ci_enrollment=root-owned-private-runtime;staging=removed")
return token
def cms_ci_container_ids(own=False):
command = [str(DOCKER), "ps", "-aq", "--no-trunc"]
if own:
command += ["--filter", "label=com.docker.compose.project=nodedc-cms-ci"]
result = subprocess.run(command, capture_output=True, text=True, check=True)
ids = result.stdout.split()
if any(not re.fullmatch(r"[a-f0-9]{64}", value) for value in ids):
die("CMS CI Docker container identity is invalid")
return ids
def cms_ci_inventory():
result = {}
for container_id in cms_ci_container_ids():
info = inspect_container(container_id)
if info.get("Config", {}).get("Labels", {}).get("com.docker.compose.project") == "nodedc-cms-ci":
continue
result[container_id] = {
"image": info.get("Image"),
"startedAt": info.get("State", {}).get("StartedAt"),
"running": info.get("State", {}).get("Running"),
}
return result
def cms_ci_check_affinity(pid, exact=False):
if type(pid) is not int or pid < 0 or (exact and pid == 0):
die("CMS CI CPU affinity process identity is invalid")
try:
available = os.sched_getaffinity(pid)
except (AttributeError, OSError):
die("CMS CI CPU affinity cannot be verified")
valid = available == {7} if exact else 7 in available
if not valid:
die("CMS CI requires logical CPU7 affinity")
def cms_ci_host_capabilities(entries):
result = subprocess.run([str(DOCKER), "info", "--format", "{{json .}}"],
capture_output=True, text=True, check=True, timeout=30)
try:
raw = json.loads(result.stdout)
if not isinstance(raw, dict):
raise ValueError()
except ValueError:
die("CMS CI Docker capability report is invalid")
# Do not print registry/proxy configuration, host identity or Docker credentials.
fields = ("ServerVersion", "KernelVersion", "OSType", "Architecture", "NCPU",
"MemTotal", "MemoryLimit", "SwapLimit", "CpuCfsPeriod", "CpuCfsQuota",
"CPUShares", "CPUSet", "PidsLimit", "CgroupVersion")
report = {key: raw.get(key) for key in fields}
print("ci_host=" + json.dumps(report, sort_keys=True, separators=(",", ":")))
required = ["MemoryLimit"]
if tuple(entries) == CMS_CI_V4_ENTRIES:
required += ["CPUShares", "CPUSet", "SwapLimit"]
elif tuple(entries) == CMS_CI_V3_ENTRIES:
required.append("PidsLimit")
required.append("CPUShares")
else:
required += ["PidsLimit", "CpuCfsPeriod", "CpuCfsQuota", "SwapLimit"]
missing = [name for name in required if raw.get(name) is not True]
if missing:
die("CMS CI host lacks required resource controls: " + ",".join(missing))
if raw.get("OSType") != "linux" or raw.get("Architecture") not in ("amd64", "x86_64"):
die("CMS CI pinned worker requires Linux amd64")
if tuple(entries) == CMS_CI_V4_ENTRIES:
if type(raw.get("NCPU")) is not int or raw["NCPU"] < 8:
die("CMS CI CPU7 profile requires at least eight logical CPUs")
cms_ci_check_affinity(0)
return report
def accept_cms_ci_container(info, entries=CMS_CI_ENTRIES):
host = info.get("HostConfig", {})
config = info.get("Config", {})
if config.get("Image") != CMS_CI_IMAGE or not info.get("State", {}).get("Running"):
die("CMS CI runner image or running state mismatch")
labels = config.get("Labels", {})
if (labels.get("com.docker.compose.project") != "nodedc-cms-ci"
or labels.get("com.docker.compose.service") != "build-runner"):
die("CMS CI runner Compose identity mismatch")
if (host.get("PortBindings") or host.get("PublishAllPorts")
or host.get("NetworkMode") in ("host", "none")
or any(info.get("NetworkSettings", {}).get("Ports", {}).values())):
die("CMS CI host network or published port rejected")
if (host.get("Privileged") or host.get("CapAdd") or host.get("Devices")
or not host.get("ReadonlyRootfs") or host.get("PidMode")
or host.get("IpcMode") == "host" or host.get("CapDrop") != ["ALL"]
or "no-new-privileges:true" not in host.get("SecurityOpt", [])):
die("CMS CI runner host isolation mismatch")
if any(value.startswith("GITEA_RUNNER_REGISTRATION_TOKEN=") for value in config.get("Env", [])):
die("CMS CI registration token must remain file-backed")
v4 = tuple(entries) == CMS_CI_V4_ENTRIES
if v4 or tuple(entries) == CMS_CI_V3_ENTRIES:
valid_cpu = (host.get("CpuShares") == 64 and not host.get("NanoCpus")
and not host.get("CpuQuota") and not host.get("CpuPeriod"))
else:
valid_cpu = host.get("NanoCpus") == 500000000
valid_pids = host.get("PidsLimit") in (None, 0, -1) if v4 else host.get("PidsLimit") == 128
if v4:
valid_cpu = valid_cpu and host.get("CpusetCpus") == "7"
if host.get("MemorySwap") != 512 * 1024 ** 2:
die("CMS CI daemon memory/swap limit mismatch")
if (host.get("Memory") != 512 * 1024 ** 2
or not valid_cpu or not valid_pids):
die("CMS CI daemon resource limit mismatch")
if v4:
cms_ci_check_affinity(info.get("State", {}).get("Pid"), exact=True)
expected_mounts = {
"/config/runner.yaml": (str(CMS_CI_ROOT / "runner.yaml"), False),
"/data": (str(CMS_CI_ROOT / "data"), True),
"/run/secrets/registration-token": (str(CMS_CI_ROOT / "secrets/registration-token"), False),
"/var/run/docker.sock": ("/var/run/docker.sock", False),
}
actual = {
mount.get("Destination"): (mount.get("Source"), mount.get("RW"))
for mount in info.get("Mounts", []) if mount.get("Type") != "tmpfs"
}
if actual != expected_mounts:
die("CMS CI daemon mount boundary mismatch")
def accept_cms_ci(entries=CMS_CI_ENTRIES):
deadline = time.monotonic() + 60
registration = CMS_CI_ROOT / "data" / ".runner"
expected_image = inspect_local_image(CMS_CI_IMAGE, "CMS CI running image")
registered_since = None
while True:
ids = cms_ci_container_ids(own=True)
if len(ids) != 1:
die("CMS CI requires exactly one build-runner container")
info = inspect_container(ids[0])
accept_cms_ci_container(info, entries)
if info.get("Image") != expected_image or info.get("RestartCount", 0) != 0:
die("CMS CI image identity or restart count mismatch")
if registration.is_file() and not registration.is_symlink():
try:
value = json.loads(registration.read_text())
valid = (value.get("name") == "synology-cms-build"
and value.get("address", "").rstrip("/") == "https://git.dcserve.ru"
and value.get("id") and value.get("uuid") and value.get("token"))
except (ValueError, UnicodeError):
valid = False
if valid:
registration.chmod(0o600)
if registered_since is None:
registered_since = time.monotonic()
if time.monotonic() - registered_since >= 10:
print("ci_accept=registered-daemon;published_ports=none;production_deploy=false")
return
else:
registered_since = None
if time.monotonic() >= deadline:
die("CMS CI runner registration did not complete")
time.sleep(2)
def capture_cms_ci_diagnostics(backup_dir):
# Logs can contain tokens. Retain only fixed categories and counts, never raw text.
report = {"containers": [], "rawLogsSaved": False}
try:
for container_id in cms_ci_container_ids(own=True):
result = subprocess.run([str(DOCKER), "logs", "--tail", "60", container_id],
capture_output=True, text=True, timeout=10)
text = (result.stdout + result.stderr).lower()
signatures = {"dns": ("no such host", "server misbehaving"),
"tls": ("x509", "tls handshake"),
"network": ("connection refused", "i/o timeout", "no route to host"),
"actions-disabled-or-route": ("404", "not found"),
"token-rejected": ("registration token", "unauthenticated"),
"filesystem": ("permission denied", "read-only file system"),
"configuration": ("unmarshal", "yaml:", "invalid config"),
"registered": ("runner registered successfully",)}
reasons = [key for key, patterns in signatures.items() if any(p in text for p in patterns)]
report["containers"].append({"id": container_id, "categories": reasons or ["unclassified"],
"logLines": len(text.splitlines())})
except Exception:
report["diagnosticStatus"] = "unavailable"
(backup_dir / "ci-startup-diagnostics.json").write_text(json.dumps(report, sort_keys=True) + "\n")
print("ci_startup_diagnostics=" + json.dumps(report, sort_keys=True))
def preflight_cms_ci():
for path in (CMS_CI_ROOT,*CMS_CI_ROOT.parents):
if path.is_symlink():die('CMS CI root contains a symlink')
if any((CMS_CI_ROOT/rel).exists() for rel in CMS_CI_ENTRIES):die('CMS CI requires an uninstalled source partition')
if cms_ci_container_ids(own=True):die('CMS CI already has a runner')
cms_ci_host_capabilities(CMS_CI_V4_ENTRIES)
require_gitea_actions_ping()
preflight_cms_ci_v2_enrollment()
# Existing Device Core CI already acquired these exact digests. No new pull.
for image in (CMS_CI_IMAGE,CMS_CI_JOB_IMAGE):inspect_local_image(image,'CMS CI pinned image')
if shutil.disk_usage(CMS_CI_ROOT.parent).free < 8*1024**3:die('CMS CI requires 8 GiB free disk')
memory={line.split(':')[0]:int(line.split()[1]) for line in Path('/proc/meminfo').read_text().splitlines() if len(line.split())>=2}
if memory.get('MemAvailable',0)<3*1024**2:die('CMS CI requires 3 GiB available memory')
def apply_cms_ci():
import_cms_ci_v2_enrollment()
data=CMS_CI_ROOT/'data'
if data.is_symlink():die('CMS CI data cannot be a symlink')
data.mkdir(mode=0o700,exist_ok=True);os.chown(str(data),0,0);data.chmod(0o700)
subprocess.run(compose_base_cmd('dc-cms-autodeploy')+['up','-d','--no-build','--pull','never','--no-deps','build-runner'],cwd=str(CMS_CI_ROOT),check=True)
accept_cms_ci(CMS_CI_V4_ENTRIES)
def cms_ci_inventory_preserved(before):
current=cms_ci_inventory()
# A registered worker can create ephemeral CI job containers immediately.
# Every preexisting container must retain its exact image and generation.
return all(current.get(identity)==row for identity,row in before.items())
def cms_ci_registered_runner_id():
"""Bind qualification to this registered daemon, not Device Core's ID 1."""
path = CMS_CI_ROOT / 'data' / '.runner'
for parent in path.parents:
if parent.is_symlink():die('CMS CI registration path contains a symlink')
directory = path.parent.lstat()
if (not stat.S_ISDIR(directory.st_mode) or directory.st_uid != 0
or stat.S_IMODE(directory.st_mode) != 0o700):
die('CMS CI registration directory must remain root-private')
fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(fd, 'rb') as stream:
info = os.fstat(stream.fileno())
if (not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_nlink != 1
or stat.S_IMODE(info.st_mode) != 0o600 or not 1 <= info.st_size <= 16384):
die('CMS CI registered identity metadata rejected')
raw = stream.read(16385)
after = os.fstat(stream.fileno())
if (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns):
die('CMS CI registered identity changed while reading')
try:
value = json.loads(raw)
identity = value.get('id')
valid = (type(identity) is int and 0 < identity < 2**53
and value.get('name') == 'synology-cms-build'
and value.get('address', '').rstrip('/') == 'https://git.dcserve.ru'
and isinstance(value.get('uuid'), str) and value['uuid']
and isinstance(value.get('token'), str) and value['token'])
except (ValueError, UnicodeError, AttributeError, TypeError):
valid = False
if not valid:die('CMS CI registered identity content rejected')
return identity
-61
View File
@@ -1,61 +0,0 @@
"""One polling cycle with an injected canonical installer, no shell authority."""
from deployment_queue import REPOSITORY, REPOSITORY_ID, QueueError
class Controller:
def __init__(self, queue, source, installer):
self.queue, self.source, self.installer = queue, source, installer
def reconcile(self):
for row in self.queue.snapshot():
if row['phase'] == 'blocked':
outcome, receipt = self.installer.receipt(row)
if outcome == 'rolled-back':
self.queue.reconcile_r39(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt)
elif outcome != 'ambiguous':
raise QueueError('blocked_run_requires_exact_recovery')
continue
if row['phase'] != 'deploying':
continue
outcome, receipt = self.installer.receipt(row)
self.queue.reconcile(row['id'], digest=row['digest'], artifact=row['artifact'],
outcome=outcome, receipt=receipt)
def observe(self):
runs = self.source.discover()
# A disappeared pending run cannot be silently skipped. Keep its local
# reservation/order; a source error is actionable, never an expiry.
ids = {r['id'] for r in runs}
for row in self.queue.snapshot():
if row['phase'] in ('pending', 'ready') and row['id'] not in ids:
raise QueueError('observed_run_disappeared:' + str(row['id']))
self.queue.observe(runs, repository=REPOSITORY, repository_id=REPOSITORY_ID)
def tick(self):
self.reconcile()
self.observe()
row = self.queue.next_ready()
if row is None:
return {'status': 'waiting'}
run = self.source.successful_run(row)
baseline = self.installer.installed_source()
self.source.prove_lineage(baseline, row['sha'])
receipt, data = self.source.artifact(run)
# Staging validates the canonical payload and its relation to this run.
self.installer.stage(row, receipt, data)
self.installer.plan(receipt['artifact'])
# Recheck after potentially slow download/plan; a rerun/pending run may
# have appeared. Reserve still enforces the durable ordering atomically.
self.observe()
self.source.successful_run(row)
self.source.prove_lineage(baseline, row['sha'])
reserved = self.queue.reserve(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'])
try:
self.installer.apply(receipt['artifact'])
finally:
# Even a clean rollback is terminal for this exact artifact. Missing
# or conflicting evidence blocks subsequent installs after restart.
outcome, canonical_receipt = self.installer.receipt(reserved)
self.queue.reconcile(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'],
outcome=outcome, receipt=canonical_receipt)
return {'status': outcome, 'run': row['id'], 'source': row['sha']}
-202
View File
@@ -1,202 +0,0 @@
"""Durable release ordering. Pure state policy; no network or runtime authority.
The canonical installer remains the only production executor. A controller may
reserve a verified artifact here, then must reconcile its canonical receipt
after any crash before admitting another deployment.
"""
import re
import sqlite3
REPOSITORY = "SILVER/DC_CMS"
REPOSITORY_ID = 33
WORKFLOW = "ci.yml@refs/heads/master"
TERMINAL = {"deployed", "failed", "superseded", "blocked"}
SHA = re.compile(r"[0-9a-f]{40}")
DIGEST = re.compile(r"[0-9a-f]{64}")
class QueueError(ValueError):
pass
def positive(value):
return type(value) is int and 0 < value < 2**53
def normalize_run(run):
if not isinstance(run, dict):
raise QueueError("invalid_run")
if not all(positive(run.get(key)) for key in ("id", "run_number", "run_attempt")):
raise QueueError("invalid_run_identity")
if not isinstance(run.get("head_sha"), str) or not SHA.fullmatch(run["head_sha"]):
raise QueueError("invalid_source_sha")
status = run.get("status")
if status not in ("queued", "waiting", "in_progress", "completed"):
raise QueueError("unknown_run_status")
conclusion = run.get("conclusion")
if status == "completed" and conclusion not in (
"success", "failure", "cancelled", "skipped", "timed_out", "action_required", "neutral", "stale",
):
raise QueueError("unknown_run_conclusion")
relevant = (run.get("event") == "push" and run.get("head_branch") == "master"
and run.get("path") == WORKFLOW)
phase = "pending" if status != "completed" else "ready" if conclusion == "success" else "unqualified"
if not relevant:
phase = "ignored"
return (run["id"], run["run_number"], run["head_sha"], str(run.get("event", "")),
str(run.get("head_branch", "")), str(run.get("path", "")), run["run_attempt"], phase)
class DeploymentQueue:
def __init__(self, path, *, first_run_number):
if not positive(first_run_number):
raise QueueError("invalid_activation_floor")
self.db = sqlite3.connect(str(path), timeout=10, isolation_level=None)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS policy (
id INTEGER PRIMARY KEY CHECK(id=1),
repository TEXT NOT NULL, repository_id INTEGER NOT NULL,
first_run INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY, number INTEGER NOT NULL UNIQUE,
sha TEXT NOT NULL, event TEXT NOT NULL, branch TEXT NOT NULL,
workflow TEXT NOT NULL, attempt INTEGER NOT NULL, phase TEXT NOT NULL,
artifact TEXT, digest TEXT, receipt TEXT
);
CREATE INDEX IF NOT EXISTS runs_phase_number ON runs(phase,number);
CREATE INDEX IF NOT EXISTS runs_sha_phase ON runs(sha,phase);
""")
self.db.execute("INSERT OR IGNORE INTO policy VALUES(1,?,?,?)", (REPOSITORY, REPOSITORY_ID, first_run_number))
policy = self.db.execute("SELECT * FROM policy WHERE id=1").fetchone()
if (policy["repository"], policy["repository_id"], policy["first_run"]) != (REPOSITORY, REPOSITORY_ID, first_run_number):
self.db.close()
raise QueueError("queue_policy_changed")
self.first_run = first_run_number
def close(self):
self.db.close()
def transaction(self, operation):
self.db.execute("BEGIN IMMEDIATE")
try:
value = operation()
self.db.execute("COMMIT")
return value
except BaseException:
self.db.execute("ROLLBACK")
raise
def observe(self, runs, *, repository, repository_id):
if repository != REPOSITORY or type(repository_id) is not int or repository_id != REPOSITORY_ID:
raise QueueError("repository_identity_mismatch")
values = [normalize_run(run) for run in runs]
def apply():
for value in values:
identity, number, sha, event, branch, workflow, attempt, phase = value
if number < self.first_run:
continue
existing = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone()
if existing is None:
self.db.execute("INSERT INTO runs(id,number,sha,event,branch,workflow,attempt,phase) VALUES(?,?,?,?,?,?,?,?)", value)
continue
if tuple(existing[k] for k in ("number", "sha", "event", "branch", "workflow")) != (number, sha, event, branch, workflow):
raise QueueError("run_identity_changed")
if attempt < existing["attempt"]:
continue # A stale API page cannot rewind a rerun.
if existing["phase"] in TERMINAL or existing["phase"] == "deploying":
continue
if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase == "pending":
continue
if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase != existing["phase"]:
raise QueueError("terminal_run_outcome_changed")
self.db.execute("UPDATE runs SET phase=?,attempt=? WHERE id=?", (phase, attempt, identity))
self.transaction(apply)
def _next(self):
blocked = self.db.execute("SELECT id,phase FROM runs WHERE phase IN ('deploying','blocked') ORDER BY number LIMIT 1").fetchone()
if blocked:
raise QueueError("canonical_reconciliation_required:" + str(blocked["id"]))
while True:
row = self.db.execute("SELECT * FROM runs WHERE phase IN ('pending','ready') ORDER BY number LIMIT 1").fetchone()
if row is None or row["phase"] != "ready":
return None
newer = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND number>=? LIMIT 1", (row["number"],)).fetchone()
duplicate = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND sha=? LIMIT 1", (row["sha"],)).fetchone()
if newer or duplicate:
self.db.execute("UPDATE runs SET phase='superseded' WHERE id=?", (row["id"],))
continue
return dict(row)
def next_ready(self):
return self.transaction(self._next)
def reserve(self, identity, *, digest, artifact):
if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
raise QueueError("invalid_artifact_digest")
def apply():
row = self._next()
if row is None or row["id"] != identity:
raise QueueError("deployment_order_mismatch")
expected = "nodedc-dc-cms-release-v1-r" + str(identity) + "-" + row["sha"] + ".tgz"
if artifact != expected:
raise QueueError("artifact_identity_mismatch")
self.db.execute("UPDATE runs SET phase='deploying',digest=?,artifact=? WHERE id=?", (digest, artifact, identity))
return {**row, "phase": "deploying", "digest": digest, "artifact": artifact}
return self.transaction(apply)
def reconcile(self, identity, *, digest, artifact, outcome, receipt):
"""Caller must prove the canonical applied/failed journal and archive.
No receipt or uncertain/failed rollback => blocked, never automatic retry.
A clean rollback may be followed by a new release, never this artifact.
"""
if outcome not in ("deployed", "rolled-back", "ambiguous"):
raise QueueError("invalid_canonical_outcome")
if not isinstance(receipt, str) or not receipt or len(receipt) > 240:
raise QueueError("canonical_receipt_required")
phase = {"deployed": "deployed", "rolled-back": "failed", "ambiguous": "blocked"}[outcome]
def apply():
row = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone()
if row is None or (row["digest"], row["artifact"]) != (digest, artifact):
raise QueueError("canonical_artifact_mismatch")
if row["phase"] == phase and row["receipt"] == receipt:
return
if row["phase"] != "deploying":
raise QueueError("canonical_outcome_conflict")
self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity))
self.transaction(apply)
def reconcile_r39(self, identity, *, digest, artifact, receipt):
"""Exact terminal blocked -> failed recovery after canonical proof.
This never makes the failed artifact ready again. The caller verifies
the immutable failed evidence and the separate successful recovery.
"""
sha = 'c9d8f0ae59211ce3443300acfea311907508261a'
expected_receipt = 'canonical-reconciled:dc-cms-r39-runtime-reconciliation-v2-20261104-001'
if (type(identity) is not int or identity != 39
or digest != '3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029'
or artifact != 'nodedc-dc-cms-release-v1-r39-'+sha+'.tgz'
or receipt != expected_receipt):
raise QueueError('r39_reconciliation_identity_mismatch')
def apply():
row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone()
if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (1,sha,'push','master',WORKFLOW,digest,artifact):
raise QueueError('r39_reconciliation_row_mismatch')
if row['phase'] == 'failed' and row['receipt'] == receipt:
return
if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed':
raise QueueError('r39_reconciliation_predecessor_mismatch')
self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity))
self.transaction(apply)
def snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
@@ -1,42 +0,0 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpu_shares: 64
cpuset: "7"
mem_limit: 512m
memswap_limit: 512m
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-cms-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-cms-autodeploy/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-cms-autodeploy/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-cms-autodeploy/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
-25
View File
@@ -1,25 +0,0 @@
"""Refresh the reviewed standalone section; runtime never imports from SMB."""
import json
from pathlib import Path
ROOT=Path(__file__).resolve().parent
RUNNER=ROOT.parent/'deploy-runner/nodedc-deploy'
START='# BEGIN GENERATED CMS DEPLOYMENT\n'
END='# END GENERATED CMS DEPLOYMENT\n'
def section():
release=(ROOT/'release_runtime.py').read_text().replace('__CMS_BASELINE__',repr(json.loads((ROOT/'baseline.json').read_text()))).replace('__CMS_FOUNDATION__',repr(json.loads((ROOT/'foundation.json').read_text())))
release=release.replace('__CMS_NODE_BASE_CONFIG__',repr((ROOT/'node24-base-config.json').read_text())).replace('__CMS_NODE_BASE_MANIFEST__',repr((ROOT/'node24-base-manifest.json').read_text()))
ci=(ROOT/'ci_runtime.py').read_text().replace('__CMS_CI_HASHES__',repr(json.loads((ROOT/'ci-source-sha256.json').read_text())))
auto=(ROOT/'autodeploy_runtime.py').read_text()
library='def cms_autodeploy_library():\n'
for file in ('deployment_queue.py','gitea_source.py','controller.py'):
lines=[line for line in (ROOT/file).read_text().splitlines() if not line.startswith('from deployment_queue import ')]
library+='\n'.join(' '+line if line else '' for line in lines)+'\n\n'
library+=' return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)\n'
audit=(ROOT/'audit_runtime.py').read_text()
reconciliation=(ROOT/'reconciliation_runtime.py').read_text()
return START+release+'\n'+ci+'\n'+auto+'\n'+audit+'\n'+reconciliation+'\n'+library+END
if __name__=='__main__':
before,rest=RUNNER.read_text().split(START,1);_,after=rest.split(END,1)
RUNNER.write_text(before+section()+after)
-211
View File
@@ -1,211 +0,0 @@
{
"name": "dc-cms",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dc-cms",
"version": "0.1.0",
"dependencies": {
"adm-zip": "0.6.1",
"jose": "^6.2.3",
"ssh2-sftp-client": "^12.1.1"
}
},
"node_modules/adm-zip": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz",
"integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==",
"license": "MIT",
"engines": {
"node": ">=14.0"
}
},
"node_modules/asn1": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": "~2.1.0"
}
},
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
"license": "BSD-3-Clause",
"dependencies": {
"tweetnacl": "^0.14.3"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/buildcheck": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
"optional": true,
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/cpu-features": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
"hasInstallScript": true,
"optional": true,
"dependencies": {
"buildcheck": "~0.0.6",
"nan": "^2.19.0"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/jose": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",
"integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/nan": {
"version": "2.28.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.28.0.tgz",
"integrity": "sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ==",
"license": "MIT",
"optional": true
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/ssh2": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
"hasInstallScript": true,
"dependencies": {
"asn1": "^0.2.6",
"bcrypt-pbkdf": "^1.0.2"
},
"engines": {
"node": ">=10.16.0"
},
"optionalDependencies": {
"cpu-features": "~0.0.10",
"nan": "^2.23.0"
}
},
"node_modules/ssh2-sftp-client": {
"version": "12.1.1",
"resolved": "https://registry.npmjs.org/ssh2-sftp-client/-/ssh2-sftp-client-12.1.1.tgz",
"integrity": "sha512-wYVDgwkpcKG2iPGQQ+QR33xkWqLFIaVrYvA+uON4pmxTPaPuB81f1aooUEPN75e/9DCK6rrKYXb6zR6zP3+EtA==",
"license": "Apache-2.0",
"dependencies": {
"concat-stream": "^2.0.0",
"ssh2": "^1.16.0"
},
"engines": {
"node": ">=18.20.4"
},
"funding": {
"type": "individual",
"url": "https://square.link/u/4g7sPflL"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
}
}
}
-15
View File
@@ -1,15 +0,0 @@
{
"name": "dc-cms",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"admin": "node server/admin-server.mjs",
"start": "node server/admin-server.mjs"
},
"dependencies": {
"adm-zip": "0.6.1",
"jose": "^6.2.3",
"ssh2-sftp-client": "^12.1.1"
}
}
-7
View File
@@ -1,7 +0,0 @@
{
"Dockerfile": "ccb783bd76b1588cbe0157bd317f6da06888d79f8a199fd0c5515000948acd42",
"infra/docker-compose.yml": "abb3a9d4e4e2ce15eb2ca52b335289dcd00808d85c78da6d1bc583a8b3517f48",
"infra/reverse-proxy/Caddyfile": "4d30188eb1f11b52a0eaf2d9476e0b0adda93a63e66938e8028cc11de4c2038f",
"package-lock.json": "aca65991c748c6e39b6cbc50405ab5a2bc7bb0d5d1b56a5a4c68bce5f645e47c",
"package.json": "40ee5bc4cf6b634612efa1fc293f6ab1955ee4520701a5dee7c8990fb5ad5fa2"
}
-263
View File
@@ -1,263 +0,0 @@
"""Read-only, bounded Gitea source verification. No production execution authority.
The privileged installer must independently validate the returned TGZ with its
canonical loader and reconcile its own journal. Nothing here accepts commands,
paths, origins, or credentials from a workflow artifact.
"""
import hashlib
import io
import json
import re
import stat
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW, SHA, normalize_run, positive
ORIGIN = "https://git.dcserve.ru"
PREFIX = "/api/v1/repos/" + REPOSITORY
PAGE_SIZE = 50
MAX_PAGES = 200
MAX_JSON = 8 * 1024 * 1024
MAX_ARCHIVE = 64 * 1024 * 1024
class SourceError(ValueError):
pass
def require(condition, code):
if not condition:
raise SourceError(code)
def strict_json(data):
def unique(pairs):
result = {}
for key, value in pairs:
require(key not in result, "duplicate_json_key")
result[key] = value
return result
try:
return json.loads(data, object_pairs_hook=unique)
except (UnicodeError, ValueError):
raise SourceError("invalid_json") from None
def signed_artifact_redirect(original, target):
origin, dest = urllib.parse.urlsplit(original), urllib.parse.urlsplit(target)
if (origin.scheme + "://" + origin.netloc != ORIGIN
or dest.scheme + "://" + dest.netloc != ORIGIN or origin.query or dest.fragment
or not re.fullmatch(re.escape(PREFIX) + r"/actions/artifacts/[1-9][0-9]*/zip", origin.path)
or dest.path != origin.path + "/raw"):
return False
pairs = urllib.parse.parse_qsl(dest.query, keep_blank_values=True)
params = dict(pairs)
return (len(pairs) == 2 and set(params) == {"sig", "expires"}
and re.fullmatch(r"[A-Za-z0-9_-]{32,128}", params["sig"]) is not None
and re.fullmatch(r"[0-9]{10,13}", params["expires"]) is not None)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Gitea 1.27 signs a same-origin /zip/raw URL. Only this exact route is
# allowed and the persistent token is deliberately NOT forwarded.
if (req is not None and req.get_method() == "GET" and code in (302, 303)
and signed_artifact_redirect(req.full_url, newurl)):
return urllib.request.Request(newurl, headers={"Accept": "application/octet-stream"})
raise SourceError("api_redirect_refused")
class GiteaSource:
def __init__(self, token, *, runner_id=None):
require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token")
require(runner_id is None or positive(runner_id), "invalid_registered_runner_id")
self._token = token
self._runner_id = runner_id
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
def request(self, suffix, *, archive=False):
require(isinstance(suffix, str) and (suffix == "" or suffix.startswith("/")), "invalid_api_path")
require(not any(value in suffix for value in ("..", "\\", "#", "@", "\r", "\n", "%")), "invalid_api_path")
# Only methods below construct suffixes; this additional allowlist keeps
# even accidental future callers from reading other API resources.
require(re.fullmatch(
r"(?:|/branches/master|/git/commits/[a-f0-9]{40}"
r"|/actions/runs(?:/[1-9][0-9]*(?:/jobs|/artifacts)?)?"
r"|/actions/artifacts/[1-9][0-9]*/zip)(?:\?page=[1-9][0-9]*&limit=50)?", suffix),
"api_route_not_allowed")
require(archive == suffix.endswith("/zip"), "api_response_type_mismatch")
maximum = MAX_ARCHIVE if archive else MAX_JSON
request = urllib.request.Request(ORIGIN + PREFIX + suffix,
headers={"Authorization": "token " + self._token,
"Accept": "application/octet-stream" if archive else "application/json"})
try:
with self._opener.open(request, timeout=25) as response:
require(response.status == 200 and (response.geturl() == request.full_url or (archive and signed_artifact_redirect(request.full_url, response.geturl()))), "api_response_identity")
data = response.read(maximum + 1)
except urllib.error.HTTPError as error:
raise SourceError("api_http_" + str(error.code)) from None
except (OSError, urllib.error.URLError):
raise SourceError("api_unavailable") from None
require(len(data) <= maximum, "api_response_too_large")
return data if archive else strict_json(data)
def repository(self):
repo = self.request("")
require(isinstance(repo, dict) and type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
and repo.get("full_name") == REPOSITORY and repo.get("default_branch") == "master"
and repo.get("archived") is False and repo.get("mirror") is False,
"repository_identity_mismatch")
return repo
def pages(self, suffix, key):
rows, identities, total = [], set(), None
for page in range(1, MAX_PAGES + 1):
data = self.request(suffix + "?page=" + str(page) + "&limit=50")
require(isinstance(data, dict) and type(data.get("total_count")) is int
and 0 <= data["total_count"] <= PAGE_SIZE * MAX_PAGES, "pagination_total_invalid")
require(total is None or total == data["total_count"], "pagination_changed")
total = data["total_count"]
batch = data.get(key)
require(isinstance(batch, list) and len(batch) <= PAGE_SIZE, "pagination_batch_invalid")
for item in batch:
require(isinstance(item, dict) and positive(item.get("id")) and item["id"] not in identities,
"pagination_duplicate_or_invalid_id")
identities.add(item["id"])
rows.extend(batch)
require(len(rows) <= total, "pagination_overflow")
if len(rows) == total:
return rows
require(len(batch) == PAGE_SIZE, "pagination_incomplete")
raise SourceError("pagination_limit")
def run(self, identity):
require(positive(identity), "invalid_run_id")
run = self.request("/actions/runs/" + str(identity))
self.validate_run(run)
require(run["id"] == identity, "run_identity_mismatch")
return run
@staticmethod
def validate_run(run):
normalize_run(run)
# Gitea 1.27.2 leaves top-level repository_id=0. The nested repository
# and fixed repository endpoint carry the actual identity instead.
repo = run.get("repository") or {}
require(type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
and repo.get("full_name") == REPOSITORY, "run_repository_mismatch")
def discover(self):
self.repository()
runs = self.pages("/actions/runs", "workflow_runs")
for run in runs:
self.validate_run(run)
require(len({run["run_number"] for run in runs}) == len(runs), "duplicate_run_number")
# A push/deletion while pages were read must not silently hide an older
# pending run. Recheck identity/count, without requiring phases to stop.
check = self.pages("/actions/runs", "workflow_runs")
identity = lambda values: sorted((r["id"], r["run_number"], r["head_sha"], r["event"], r["head_branch"], r["path"]) for r in values)
for run in check:
self.validate_run(run)
require(identity(runs) == identity(check), "discovery_changed")
return check
def successful_run(self, row):
require(positive(self._runner_id), "registered_runner_identity_required")
run = self.run(row["id"])
require((run["run_number"], run["head_sha"], run["run_attempt"]) ==
(row["number"], row["sha"], row["attempt"]), "qualified_run_changed")
require(run["path"] == WORKFLOW and run["event"] == "push" and run["head_branch"] == "master"
and run["status"] == "completed" and run["conclusion"] == "success", "run_not_qualified")
jobs = self.pages("/actions/runs/" + str(run["id"]) + "/jobs", "jobs")
require(len(jobs) == 1, "qualification_job_count")
job = jobs[0]
require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"]
and job.get("head_branch") == "master" and job.get("run_attempt") == run["run_attempt"]
and job.get("name") == "qualify" and job.get("labels") == ["nodedc-node22-build"]
and type(job.get("runner_id")) is int and job["runner_id"] == self._runner_id
and job.get("runner_name") == "synology-cms-build" and job.get("status") == "completed"
and job.get("conclusion") == "success", "qualification_job_mismatch")
steps = job.get("steps")
require(isinstance(steps, list) and all(isinstance(s, dict) for s in steps) and [s.get("name") for s in steps] ==
["Check the exact pushed commit", "Retain the qualified release in this Gitea run"]
and all(s.get("status") == "completed" and s.get("conclusion") == "success" for s in steps),
"qualification_steps_mismatch")
return run
def main_commit(self):
branch = self.request("/branches/master")
require(isinstance(branch, dict) and branch.get("name") == "master", "main_branch_mismatch")
sha = (branch.get("commit") or {}).get("id")
require(isinstance(sha, str) and SHA.fullmatch(sha), "main_commit_invalid")
return sha
def ancestor(self, ancestor, descendant, *, limit=1024):
require(all(isinstance(s, str) and SHA.fullmatch(s) for s in (ancestor, descendant)), "ancestry_sha_invalid")
pending, seen = [descendant], set()
while pending:
sha = pending.pop()
if sha == ancestor:
return True
if sha in seen:
continue
require(len(seen) < limit, "ancestry_limit")
seen.add(sha)
commit = self.request("/git/commits/" + sha)
require(isinstance(commit, dict) and commit.get("sha") == sha, "commit_identity_mismatch")
parents = commit.get("parents")
require(isinstance(parents, list) and len(parents) <= 32, "commit_parents_invalid")
for parent in parents:
value = parent.get("sha") if isinstance(parent, dict) else None
require(isinstance(value, str) and SHA.fullmatch(value), "commit_parent_invalid")
pending.append(value)
return False
def prove_lineage(self, installed, candidate):
main = self.main_commit()
require(candidate != installed and self.ancestor(installed, candidate)
and self.ancestor(candidate, main), "non_forward_main_release")
require(self.main_commit() == main, "main_changed_during_proof")
return main
def artifact(self, run):
artifacts = self.pages("/actions/runs/" + str(run["id"]) + "/artifacts", "artifacts")
candidates = [a for a in artifacts if a.get("name") == "dc-cms-release"]
require(len(candidates) == 1, "qualified_artifact_count")
artifact = candidates[0]
owner = artifact.get("workflow_run") or {}
require(owner.get("id") == run["id"] and owner.get("repository_id") == REPOSITORY_ID
and owner.get("head_sha") == run["head_sha"] and artifact.get("expired") is False
and type(artifact.get("size_in_bytes")) is int and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE,
"artifact_owner_or_size_mismatch")
blob = self.request("/actions/artifacts/" + str(artifact["id"]) + "/zip", archive=True)
require(len(blob) == artifact["size_in_bytes"], "artifact_download_size_mismatch")
return unpack_artifact(blob, run)
def unpack_artifact(blob, run):
identity = "nodedc-dc-cms-release-v1-r" + str(run["id"]) + "-" + run["head_sha"] + ".tgz"
require(len(blob) <= MAX_ARCHIVE, "archive_too_large")
try:
with zipfile.ZipFile(io.BytesIO(blob)) as archive:
members = archive.infolist()
require(len(members) == 2 and set(archive.namelist()) == {identity, "release.json"}, "zip_entry_mismatch")
for member in members:
require(not member.is_dir() and stat.S_IFMT(member.external_attr >> 16) in (0, stat.S_IFREG)
and not member.flag_bits & 1 and 0 < member.file_size <= MAX_ARCHIVE,
"zip_member_invalid")
if member.filename == "release.json":
require(member.file_size <= 4096, "zip_receipt_too_large")
data = archive.read(identity)
receipt = strict_json(archive.read("release.json"))
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError):
raise SourceError("archive_invalid") from None
expected = {"artifact": identity, "sourceCommit": run["head_sha"], "runId": run["id"],
"runNumber": run["run_number"], "deployed": False,
"sha256": hashlib.sha256(data).hexdigest()}
require(receipt == expected and type(receipt.get("runId")) is int
and type(receipt.get("runNumber")) is int and receipt.get("deployed") is False, "release_receipt_mismatch")
return receipt, data
File diff suppressed because one or more lines are too long
@@ -1,41 +0,0 @@
{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
"mediaType": "application/vnd.oci.image.config.v1+json",
"digest": "sha256:91d56b2d4e1cf23103d90b0b024c1f489c288f9c3aba1042dd7279503b367de6",
"size": 6522
},
"layers": [
{
"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
"digest": "sha256:55afa1ecc21d2bb5e5045f32dafee56272ffd89860bac26f6c32123439af26a4",
"size": 3846391
},
{
"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
"digest": "sha256:7e2a5e2761f53b694faaee16c5ad1e400cb41224f693337aac52e74bee3b2f65",
"size": 52524717
},
{
"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
"digest": "sha256:57eb903fc7a4b0006b1253f877823b15c51433ccd41a20392812682211c46a6c",
"size": 1262109
},
{
"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
"digest": "sha256:21af007bacf625b557dda6dbce062088808612be54a955980b3d8efb8ea7d082",
"size": 448
}
],
"annotations": {
"com.docker.official-images.bashbrew.arch": "amd64",
"org.opencontainers.image.base.digest": "sha256:79ff19e9084a00eece421b2523fb93e22d730e2c0e525905de047e848e56d95f",
"org.opencontainers.image.base.name": "alpine:3.24",
"org.opencontainers.image.created": "2026-06-24T18:11:03Z",
"org.opencontainers.image.revision": "303e6c3be0be8010403376712d3018fb99809f86",
"org.opencontainers.image.source": "https://github.com/nodejs/docker-node.git#303e6c3be0be8010403376712d3018fb99809f86:24/alpine3.24",
"org.opencontainers.image.url": "https://hub.docker.com/_/node",
"org.opencontainers.image.version": "24-alpine"
}
}
-141
View File
@@ -1,141 +0,0 @@
# Exact r39 reconciliation; this code is embedded in the root-owned runner.
CMS_RECON_ID = 'dc-cms-r39-runtime-reconciliation-v2-20261104-001'
CMS_RECON_ENTRY = 'deployment/dc-cms-r39-runtime-reconciliation-v2.json'
CMS_RECON_LEGACY_SHA = 'e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f'
CMS_DNS_FIELDS = ('Dns','DnsOptions','DnsSearch')
def cms_reconciliation_descriptor():
return {'schemaVersion':'nodedc.dc-cms.runtime-reconciliation.v2','releaseId':CMS_RECON_ID,
'failedReleaseId':CMS_AUDIT_FAILED_ID,'failedSha256':CMS_AUDIT_FAILED_SHA,
'backupId':CMS_AUDIT_BACKUP,'backupSha256':CMS_AUDIT_BACKUP_SHA,
'legacyRuntimeSha256':CMS_RECON_LEGACY_SHA,'runtimeFingerprintVersion':2,
'mode':'prove-restored-baseline-bind-order-empty-dns-only'}
def validate_cms_reconciliation_payload(payload, entries, identity):
if tuple(entries or ())!=(CMS_RECON_ENTRY,) or identity!=CMS_RECON_ID:
die('CMS reconciliation identity/entry mismatch')
marker=payload/CMS_RECON_ENTRY
if marker.is_symlink() or not marker.is_file():die('CMS reconciliation marker is unsafe')
expected=(json.dumps(cms_reconciliation_descriptor(),sort_keys=True,indent=2)+'\n').encode()
if marker.read_bytes()!=expected:die('CMS reconciliation descriptor mismatch')
def cms_runtime_fields_v2(fields):
result=json.loads(json.dumps(fields));host=result['host']
binds=host.get('Binds')
if not isinstance(binds,list) or not 1<=len(binds)<=8:
die('CMS v2 bind list is missing or outside bounds')
targets=[]
for bind in binds:
if not isinstance(bind,str) or '\0' in bind:die('CMS v2 bind is malformed')
parts=bind.split(':')
if len(parts) not in (2,3):die('CMS v2 bind is ambiguous')
for path in parts[:2]:
if not path.startswith('/') or str(PurePosixPath(path))!=path or '..' in PurePosixPath(path).parts:
die('CMS v2 bind path is not canonical')
if len(parts)==3 and not parts[2]:die('CMS v2 bind options are ambiguous')
targets.append(parts[1])
if len(set(targets))!=len(targets):die('CMS v2 duplicate bind target')
host['Binds']=sorted(binds)
# Docker 24 uses len(...) > 0 for these three settings. Nonempty lists and
# their order are untouched; every other HostConfig field remains exact.
for key in CMS_DNS_FIELDS:
if key not in host:die('CMS v2 DNS field is missing')
value=host[key]
if value is None:host[key]=[]
elif not isinstance(value,list) or any(not isinstance(v,str) for v in value):
die('CMS v2 DNS field is malformed')
return result
def cms_runtime_v2_from_sample(sample):
fields=cms_runtime_fields_v2(sample['fields'])
digests={section+'.'+key:cms_audit_digest(value) for section in ('host','config')
for key,value in fields[section].items()}
digests.update({key:cms_audit_digest(fields[key]) for key in ('mounts','networks')})
return {**sample['runtime'],'configSha256':cms_audit_digest(fields),'fieldSha256':digests}
def cms_runtime_snapshot_v2():
return cms_runtime_v2_from_sample(cms_audit_sample())
def cms_r39_representation_proof(fields, expected):
cms_runtime_fields_v2(fields) # Validate paths and types before enumeration.
if not isinstance(expected,str) or not re.fullmatch('[a-f0-9]{64}',expected):
die('CMS reconciliation predecessor digest is invalid')
if len(fields['host']['Binds'])!=2 or any(fields['host'][k] not in (None,[]) for k in CMS_DNS_FIELDS):
die('CMS r39 proof requires exactly two binds and empty DNS settings')
work=json.loads(json.dumps(fields));checked=0
for binds in itertools.permutations(fields['host']['Binds']):
work['host']['Binds']=list(binds)
for dns in itertools.product((None,[]),repeat=3):
for key,value in zip(CMS_DNS_FIELDS,dns):work['host'][key]=value
checked+=1
if cms_audit_digest(work)==expected:return checked
die('CMS runtime differs beyond bind order and empty DNS representation')
def cms_r39_failed_row():
return {'artifact':'nodedc-'+CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125',
'backup_id':CMS_AUDIT_BACKUP,'component':'dc-cms-release',
'failed_at':'2026-11-04T19:34:46+00:00','id':CMS_AUDIT_FAILED_ID,
'message':'CMS environment, mounts, ports or network topology changed',
'rollback_status':'failed:DeployError','sha256':CMS_AUDIT_FAILED_SHA,
'started_apply':True,'status':'failed'}
def cms_r39_evidence():
rows=[r for r in load_state(FAILED_STATE_FILE) if r.get('id')==CMS_AUDIT_FAILED_ID or r.get('sha256')==CMS_AUDIT_FAILED_SHA]
if rows!=[cms_r39_failed_row()]:die('CMS reconciliation failed receipt mismatch')
before=cms_audit_evidence()
if before['runtime']['configSha256']!=CMS_RECON_LEGACY_SHA:
die('CMS reconciliation saved runtime digest differs')
return before
def cms_r39_restored_baseline(before):
samples=[cms_audit_sample() for _ in range(3)]
if any(sample!=samples[0] for sample in samples):die('CMS runtime changed during reconciliation')
sample=samples[0];old=before['runtime'];runtime=sample['runtime']
if runtime['imageId']!=old['imageId'] or runtime['imageRef']!=old['imageRef']:
die('CMS reconciliation original image mismatch')
checked=cms_r39_representation_proof(sample['fields'],old['configSha256'])
result=json.loads(json.dumps(before));result['runtimeFingerprintVersion']=2
result['runtime']=cms_runtime_v2_from_sample(sample)
print('cms_reconciliation_proof=exact-legacy-sha;changed-representation=bind-order,empty-dns;'
'samples=3;candidates='+str(checked)+';fingerprint=v2')
return result
def preflight_cms_reconciliation(payload, entries, identity, *, marker_installed=False):
require_root();validate_cms_reconciliation_payload(payload,entries,identity)
marker=CMS_ROOT/CMS_RECON_ENTRY
if not marker_installed and (marker.exists() or marker.is_symlink()):
die('CMS reconciliation marker already exists')
before=cms_r39_restored_baseline(cms_r39_evidence())
accept_cms_release(before,rollback=True)
print('cms_reconciliation_accept=restored-baseline-proven;services=none;build=none;runtime-mutation=none')
return before
def cms_r39_reconciled(row):
if row!=cms_r39_failed_row():return False
marker=CMS_ROOT/CMS_RECON_ENTRY
records=[r for r in load_state(STATE_FILE) if r.get('id')==CMS_RECON_ID]
if not records:
# During canonical apply the marker may precede its success receipt.
# Neither marker presence nor an in-progress apply grants queue release.
return False
if len(records)!=1 or records[0].get('component')!='dc-cms-runtime-reconciliation' or records[0].get('status')!='ok':
die('CMS reconciliation applied receipt mismatch')
validate_cms_reconciliation_payload(CMS_ROOT,(CMS_RECON_ENTRY,),CMS_RECON_ID)
with tempfile.TemporaryDirectory(prefix='cms-r39-marker-',dir=TMP_DIR) as tmp:
manifest,entries,payload=load_artifact(device_release_applied_archive(records[0]),Path(tmp))
if manifest.get('component')!='dc-cms-runtime-reconciliation' or manifest.get('id')!=CMS_RECON_ID:
die('CMS reconciliation applied archive identity mismatch')
if sha256_file(payload/CMS_RECON_ENTRY)!=sha256_file(marker):die('CMS reconciliation marker drift')
cms_r39_evidence()
return True
-555
View File
@@ -1,555 +0,0 @@
# Embedded into the reviewed root runner. This file is never imported from SMB.
CMS_ROOT = Path('/volume1/docker/dc-cms/source')
CMS_RELEASE_ENTRY = 'server/cms-release.json'
CMS_RELEASE_SERVICES = ('cms-app',)
CMS_BASELINE = __CMS_BASELINE__
CMS_FOUNDATION = __CMS_FOUNDATION__
CMS_DEPENDENCY_FILES = ('package.json', 'package-lock.json')
CMS_NODE_BASE_MANIFEST = 'sha256:4ba75f835bb8802193e4c114572113d4b26f95f6f094f4b5229d2a77773e0afc'
CMS_NODE_BASE_CONFIG = 'sha256:91d56b2d4e1cf23103d90b0b024c1f489c288f9c3aba1042dd7279503b367de6'
CMS_NODE_BASE_REF = 'docker.io/library/node@'+CMS_NODE_BASE_MANIFEST
CMS_NODE_BASE_CONFIG_JSON = __CMS_NODE_BASE_CONFIG__
CMS_NODE_BASE_MANIFEST_JSON = __CMS_NODE_BASE_MANIFEST__
def cms_release_path(rel, *, directory=False):
validate_posix_path(rel)
if directory and rel in ('admin', 'server'):
return True
if rel == CMS_RELEASE_ENTRY or rel in CMS_DEPENDENCY_FILES:
return True
parts = PurePosixPath(rel).parts
if (len(parts) == 2 and parts[0] in ('admin', 'server')
and re.fullmatch(r'[a-zA-Z0-9_-]+\.(?:mjs|js|css|html|svg)', parts[1])):
return True
die('CMS release path outside application scope: ' + rel)
def cms_release_entries(entries):
if not entries or len(set(entries)) != len(entries) or list(entries) != sorted(entries):
die('CMS release requires sorted unique application files')
required = {'admin/index.html', 'admin/admin.js', 'admin/admin.css', 'server/admin-server.mjs', CMS_RELEASE_ENTRY, *CMS_DEPENDENCY_FILES}
if not required <= set(entries):
die('CMS release is missing application entrypoints')
for rel in entries:
cms_release_path(rel)
def validate_cms_release_payload(payload, entries, identity):
cms_release_entries(entries)
d = read_strict_json(payload / CMS_RELEASE_ENTRY, 'CMS release', max_bytes=256*1024)
if (set(d) != {'schemaVersion','releaseId','repository','repositoryId','branch','sourceCommit','runId','runNumber','qualification','filesSha256','foundationSha256'}
or d.get('schemaVersion') != 'nodedc.dc-cms.release.v1'
or d.get('repository') != 'SILVER/DC_CMS' or type(d.get('repositoryId')) is not int or d['repositoryId'] != 33
or d.get('branch') != 'master' or not re.fullmatch('[a-f0-9]{40}', str(d.get('sourceCommit')))
or any(type(d.get(k)) is not int or not 0 < d[k] < 2**53 for k in ('runId','runNumber'))
or d.get('releaseId') != identity or identity != 'dc-cms-release-v1-r'+str(d['runId'])+'-'+d['sourceCommit']):
die('CMS release identity mismatch')
actual = collect_exact_files(payload, [p for p in entries if p != CMS_RELEASE_ENTRY], 'CMS release')
if d.get('filesSha256') != actual:
die('CMS release application digest mismatch')
if d.get('foundationSha256') != {p: CMS_FOUNDATION[p] for p in ('Dockerfile','package.json','package-lock.json','infra/docker-compose.yml')} or any(actual.get(p) != CMS_FOUNDATION[p] for p in CMS_DEPENDENCY_FILES):
die('CMS release cannot change dependencies, Dockerfile or Compose foundation')
if d.get('qualification') != {'status':'qualified','steps':['frozen-install','syntax','multisite-tests'],'deployed':False}:
die('CMS release qualification mismatch')
return d
def cms_foundation():
expected = CMS_FOUNDATION if (CMS_ROOT / CMS_RELEASE_ENTRY).exists() else CMS_BASELINE['foundationSha256']
if collect_exact_files(CMS_ROOT, sorted(expected), 'CMS foundation') != expected:
die('CMS foundation differs from the registered predecessor')
# Include env-file identity without disclosing any values.
env = CMS_ROOT / 'infra/.env.synology'
if env.is_symlink() or not env.is_file():
die('CMS environment file is missing or unsafe')
return {**expected, 'infra/.env.synology':sha256_file(env)}
def cms_without_synology_metadata(files, label):
"""Partition only NAS EA streams attached to a present application file.
Synology exposes these files to POSIX but hides them from SMB. They are
never application payload or build input. Unknown paths remain rejected.
"""
application = {}
metadata = {}
for rel, digest in files.items():
parts = PurePosixPath(rel).parts
if '@eaDir' not in parts:
application[rel] = digest
continue
if (len(parts) != 3 or parts[0] not in ('admin', 'server')
or parts[1] != '@eaDir' or not parts[2].endswith('@SynoEAStream')):
die(label + ' has an unrecognized Synology metadata path: ' + rel)
sibling = parts[0] + '/' + parts[2][:-len('@SynoEAStream')]
cms_release_path(sibling)
if sibling not in files:
die(label + ' has orphaned Synology metadata: ' + rel)
metadata[rel] = digest
return application, metadata
def cms_application_inventory():
files = collect_exact_files(CMS_ROOT, ('admin', 'server', *CMS_DEPENDENCY_FILES), 'CMS installed app')
return cms_without_synology_metadata(files, 'CMS installed app')
def cms_installed_release():
for row in load_state(FAILED_STATE_FILE):
if (row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply')
and not str(row.get('rollback_status','')).startswith('ok:') and not cms_r39_reconciled(row)):
die('CMS deployment requires failed-rollback reconciliation')
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'dc-cms-release']
if rows:
row = rows[-1]
with tempfile.TemporaryDirectory(prefix='cms-baseline-',dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row),Path(tmp))
if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']:
die('CMS predecessor receipt mismatch')
descriptor = validate_cms_release_payload(payload, entries, row['id'])
expected = collect_exact_files(payload, entries, 'CMS predecessor')
else:
# Initial transition is independently anchored in the exact live CMS source.
descriptor = {'sourceCommit':CMS_BASELINE['sourceCommit'],'runNumber':0,'releaseId':'dc-cms-4c6f133'}
expected = {**CMS_BASELINE['filesSha256'], **{p:CMS_BASELINE['foundationSha256'][p] for p in CMS_DEPENDENCY_FILES}}
actual, _ = cms_application_inventory()
if actual != expected:
delta = {'missing':sorted(set(expected)-set(actual)), 'unexpected':sorted(set(actual)-set(expected)),
'changed':sorted(p for p in set(actual)&set(expected) if actual[p]!=expected[p])}
die('CMS installed application differs from its canonical predecessor: ' + json.dumps(delta, sort_keys=True))
cms_foundation()
return descriptor
def cms_runtime_snapshot():
identity = compose_service_container_id('dc-cms-release','cms-app')
info = inspect_container(identity)
config = info.get('Config') or {}
labels = config.get('Labels') or {}
state = info.get('State') or {}
if labels.get('com.docker.compose.project') != 'dc-cms' or labels.get('com.docker.compose.service') != 'cms-app' or not state.get('Running'):
die('CMS application runtime identity or readiness mismatch')
host = json.loads(json.dumps(info.get('HostConfig') or {}))
for field in ('Mounts','Ulimits'):
if isinstance(host.get(field),list):host[field].sort(key=lambda x:json.dumps(x,sort_keys=True))
fields = {'host':host,'config':{k:config.get(k) for k in ('Env','User','Cmd','Entrypoint','WorkingDir','ExposedPorts')},
'mounts':sorted(info.get('Mounts') or [],key=lambda x:json.dumps(x,sort_keys=True)),
'networks':sorted((info.get('NetworkSettings') or {}).get('Networks') or {})}
if isinstance(fields['config']['Env'],list):fields['config']['Env'].sort()
image_ref = config.get('Image','')
if not re.fullmatch(r'[a-z0-9][a-z0-9_./:-]+',image_ref) or '@' in image_ref:
die('CMS existing image tag cannot be safely restored')
return {'id':identity,'imageId':info['Image'],'imageRef':image_ref,'configSha256':hashlib.sha256(json.dumps(fields,sort_keys=True).encode()).hexdigest()}
def cms_other_services():
result = {}
proc = subprocess.run([str(DOCKER),'ps','-aq','--no-trunc','--filter','label=com.docker.compose.project'],capture_output=True,text=True,check=True)
for identity in proc.stdout.split():
if not re.fullmatch('[a-f0-9]{64}',identity):die('CMS preserved container identity mismatch')
info = inspect_container(identity);labels=(info.get('Config') or {}).get('Labels') or {}
if labels.get('com.docker.compose.project') == 'dc-cms' and labels.get('com.docker.compose.service') == 'cms-app':continue
if str(labels.get('com.docker.compose.oneoff','False')).lower() == 'true':continue
result[identity]={'fingerprint':gitea_actions_fingerprint_v2(info),'running':(info.get('State') or {}).get('Running'),'startedAt':(info.get('State') or {}).get('StartedAt')}
return result
def cms_preserved_data():
# Hash configuration and content; runtime data never enters the build context.
return {'projects':collect_exact_files(CMS_ROOT,('projects',),'CMS projects'),
'sites':collect_exact_files(Path('/volume1/docker/dc-cms'),('sites',),'CMS sites')}
def cms_healthchecks():
healthcheck_url({'url':'http://172.22.0.222:9918/healthz','headers':{'Host':'cms.dcserve.ru'},
'expected_json':{'ok':True,'service':'dc-cms','authEnabled':True}})
for check in COMPONENTS['dc-cms']['healthchecks']:healthcheck_url(check)
def cms_image_env(config):
# Values remain in process memory. Reject ambiguous duplicate keys.
values=config.get('Env')
if not isinstance(values,list):die('CMS image environment is missing')
result={}
for value in values:
if not isinstance(value,str) or '=' not in value or '\0' in value:
die('CMS image environment is malformed')
key,data=value.split('=',1)
if not re.fullmatch('[A-Za-z_][A-Za-z0-9_]*',key) or key in result:
die('CMS image environment has ambiguous keys')
result[key]=data
return result
CMS_BUILD_BASE_ERROR_CODES = frozenset((
'cms-base-docker-timeout','cms-base-docker-unavailable','cms-base-docker-failed',
'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch',
'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth',
'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format',
'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous','cms-base-build-labels',
'cms-base-image-not-found','cms-base-registered-mismatch','cms-base-registered-proof',
'cms-base-registered-image','cms-base-fetch-failed','cms-base-fetch-timeout',
))
CMS_BASE_REJECTION_CODES = frozenset(('layers','platform','base-shape','inherited-config','labels','environment','node-version'))
def cms_base_public_diagnostic(value):
# Public counts only, never arbitrary keys/values from image inspection.
if not isinstance(value,dict) or set(value) not in ({'parentCount','nodeCount','rejected'},{'parentCount','nodeCount','rejected','registeredRejection','acceptedPrefix'}):return None
if any(type(value[k]) is not int or not 0<=value[k]<=384 for k in ('parentCount','nodeCount')):return None
rejected=value['rejected']
if not isinstance(rejected,dict) or not set(rejected)<=CMS_BASE_REJECTION_CODES:return None
if any(type(v) is not int or not 0<=v<=384 for v in rejected.values()):return None
result={'parentCount':value['parentCount'],'nodeCount':value['nodeCount'],'rejected':dict(rejected)}
if 'registeredRejection' in value:
prefix=value['acceptedPrefix']
if (not isinstance(value['registeredRejection'],str) or value['registeredRejection'] not in CMS_BASE_REJECTION_CODES or not isinstance(prefix,list) or len(prefix)>4
or any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in prefix)):return None
result.update(registeredRejection=value['registeredRejection'],acceptedPrefix=list(prefix))
return result
class CmsBuildBaseError(DeployError):
def __init__(self, code, diagnostic=None):
if code not in CMS_BUILD_BASE_ERROR_CODES:
raise ValueError('Unknown CMS base error code')
self.code=code
self.diagnostic=cms_base_public_diagnostic(diagnostic)
super().__init__(code)
def cms_base_docker_json(args, *, lines=False):
# CMS-only bounded read. Neither Docker stderr nor image Env is public.
try:
proc=subprocess.run([str(DOCKER),*args],capture_output=True,text=True,check=True,timeout=30)
except subprocess.TimeoutExpired:
raise CmsBuildBaseError('cms-base-docker-timeout') from None
except subprocess.CalledProcessError as error:
missing_names=([args[2]] if len(args)==3 else [])
if len(args)==3 and args[2]==CMS_NODE_BASE_REF:
missing_names += [prefix+'@'+CMS_NODE_BASE_MANIFEST for prefix in ('node','library/node')]
if (len(args)==3 and args[:2]==['image','inspect']
and (re.fullmatch('sha256:[a-f0-9]{64}',args[2]) or args[2]==CMS_NODE_BASE_REF)
and error.returncode==1 and (error.stdout or '').strip()=='[]'
and (error.stderr or '').strip() in [prefix+name for prefix in ('Error response from daemon: No such image: ','Error: No such image: ') for name in missing_names]):
raise CmsBuildBaseError('cms-base-image-not-found') from None
raise CmsBuildBaseError('cms-base-docker-failed') from None
except (OSError,UnicodeError):
raise CmsBuildBaseError('cms-base-docker-unavailable') from None
if len(proc.stdout)>8*1024*1024:
raise CmsBuildBaseError('cms-base-output-limit')
try:
return [json.loads(line) for line in proc.stdout.splitlines()] if lines else json.loads(proc.stdout)
except (ValueError,TypeError):
raise CmsBuildBaseError('cms-base-json-invalid') from None
def cms_inspect_image(identity):
if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)):
die('CMS immutable image identity is invalid')
rows=cms_base_docker_json(['image','inspect',identity])
if not isinstance(rows,list) or len(rows)!=1 or not isinstance(rows[0],dict) or rows[0].get('Id')!=identity:
raise CmsBuildBaseError('cms-base-image-mismatch')
return rows[0]
def cms_image_build_labels(config):
labels=config.get('Labels')
if labels is None:return {}
if not isinstance(labels,dict) or any(not isinstance(k,str) or not isinstance(v,str) for k,v in labels.items()):
raise CmsBuildBaseError('cms-base-build-labels')
owned={k:v for k,v in labels.items() if k.startswith('com.docker.compose.')}
if not owned:return {}
prefix='com.docker.compose.'
if (set(owned)!={prefix+'project',prefix+'service',prefix+'version'}
or owned[prefix+'project']!='dc-cms' or owned[prefix+'service']!='cms-app'
or len(owned[prefix+'version'])>80
or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?',owned[prefix+'version'])):
raise CmsBuildBaseError('cms-base-build-labels')
return owned
def cms_base_labels_match(config, accepted):
# Compose's BuildKit path adds exactly project/service/version to the app
# image, not its Node base. Reproduce these labels; never ignore drift.
try:build_labels=cms_image_build_labels(accepted)
except CmsBuildBaseError:return False
base=config.get('Labels');old=accepted.get('Labels')
if base==old:return True
if not build_labels or (base is not None and not isinstance(base,dict)):return False
base=base or {}
return not set(base)&set(build_labels) and {**base,**build_labels}==old
def cms_node_base_rejection(image, accepted):
# Prove filesystem ancestry AND the exact config inherited by the fixed
# Dockerfile. Neither a mutable tag nor a matching NODE_VERSION is proof.
layers=(image.get('RootFS') or {}).get('Layers')
original=(accepted.get('RootFS') or {}).get('Layers')
if ((image.get('RootFS') or {}).get('Type')!='layers'
or (accepted.get('RootFS') or {}).get('Type')!='layers'
or not isinstance(layers,list) or not isinstance(original,list) or not layers
or len(layers)>=len(original) or original[:len(layers)]!=layers
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in layers)):
return 'layers'
if any(image.get(key)!=accepted.get(key) for key in ('Os','Architecture','Variant')):
return 'platform'
config=image.get('Config') or {};old=accepted.get('Config') or {}
if (image.get('Os')!='linux' or config.get('Cmd')!=['node']
or config.get('WorkingDir') not in ('',None,'/')
or config.get('OnBuild') not in (None,[]) or config.get('Volumes') not in (None,{})
or config.get('ExposedPorts') not in (None,{})):
return 'base-shape'
for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck'):
if config.get(key)!=old.get(key):return 'inherited-config'
if not cms_base_labels_match(config,old):return 'labels'
try:
env=cms_image_env(config);old_env=cms_image_env(old)
except DeployError:
return 'environment'
if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return 'node-version'
if {**env,'HOST':'0.0.0.0','PORT':'8090'}!=old_env:return 'environment'
return None
def cms_node_base_matches(image, accepted):
return cms_node_base_rejection(image,accepted) is None
def cms_registered_node_image(accepted):
# Source-registered public OCI bytes, never supplied by an app artifact.
if ('sha256:'+hashlib.sha256(CMS_NODE_BASE_CONFIG_JSON.encode()).hexdigest()!=CMS_NODE_BASE_CONFIG
or 'sha256:'+hashlib.sha256(CMS_NODE_BASE_MANIFEST_JSON.encode()).hexdigest()!=CMS_NODE_BASE_MANIFEST):
raise CmsBuildBaseError('cms-base-registered-proof')
manifest=json.loads(CMS_NODE_BASE_MANIFEST_JSON);config=json.loads(CMS_NODE_BASE_CONFIG_JSON)
if (manifest['config']['digest']!=CMS_NODE_BASE_CONFIG or config['os']!='linux' or config['architecture']!='amd64'
or len(config['rootfs']['diff_ids'])!=4 or len(manifest['layers'])!=4):
raise CmsBuildBaseError('cms-base-registered-proof')
image={'Id':CMS_NODE_BASE_CONFIG,'Os':'linux','Architecture':'amd64',
'Config':config['config'],'RootFS':{'Type':'layers','Layers':config['rootfs']['diff_ids']}}
# Docker 24 serializes the default User/Variant as empty strings; newer
# image APIs omit them. Project only these known OCI defaults for comparison.
old=accepted.get('Config') or {}
if 'User' not in image['Config'] and old.get('User')=='':image['Config']['User']=''
if accepted.get('Variant')=='':image['Variant']=''
return image
def cms_registered_node_proof(accepted):
image=cms_registered_node_image(accepted)
return {'registeredBase':'node24-alpine-amd64-v1','registryReference':CMS_NODE_BASE_REF,
'configDigest':CMS_NODE_BASE_CONFIG,'acceptedImageId':accepted['Id'],
'layersSha256':cms_audit_digest(image['RootFS']['Layers'])}
def cms_materialize_registered_node(proof, accepted):
# The read-only preflight has already proved this exact source base. Reprove
# before the sole allowed pull, then verify actual local bytes before build.
if proof!=cms_registered_node_proof(accepted) or not cms_node_base_matches(cms_registered_node_image(accepted),accepted):
raise CmsBuildBaseError('cms-base-registered-proof')
try:rows=cms_base_docker_json(['image','inspect',CMS_NODE_BASE_REF])
except CmsBuildBaseError as error:
if error.code!='cms-base-image-not-found':raise
print('cms_build_base_acquire=registered-digest;reference='+CMS_NODE_BASE_REF+';platform=linux/amd64')
try:
subprocess.run([str(DOCKER),'pull','--platform','linux/amd64',CMS_NODE_BASE_REF],
capture_output=True,text=True,check=True,timeout=300)
except subprocess.TimeoutExpired:raise CmsBuildBaseError('cms-base-fetch-timeout') from None
except (subprocess.CalledProcessError,OSError):raise CmsBuildBaseError('cms-base-fetch-failed') from None
rows=cms_base_docker_json(['image','inspect',CMS_NODE_BASE_REF])
if not isinstance(rows,list) or len(rows)!=1 or not isinstance(rows[0],dict):
raise CmsBuildBaseError('cms-base-registered-image')
image=rows[0]
# Classic Docker uses the OCI config ID, containerd stores the manifest ID.
# Both identities are pinned to the exact registered manifest/config pair.
aliases={prefix+'@'+CMS_NODE_BASE_MANIFEST for prefix in ('node','library/node','docker.io/library/node')}
if (image.get('Id') not in (CMS_NODE_BASE_CONFIG,CMS_NODE_BASE_MANIFEST)
or not aliases.intersection(image.get('RepoDigests') or [])
or (image.get('RootFS') or {}).get('Layers')!=cms_registered_node_image(accepted)['RootFS']['Layers']
or not cms_node_base_matches(image,accepted)):
raise CmsBuildBaseError('cms-base-registered-image')
return image
def cms_resolve_build_base(runtime):
accepted=cms_inspect_image(runtime['imageId'])
diagnostic={'parentCount':0,'nodeCount':0,'rejected':{}}
def matches(image,kind):
diagnostic[kind]+=1
reason=cms_node_base_rejection(image,accepted)
if reason is not None:diagnostic['rejected'][reason]=diagnostic['rejected'].get(reason,0)+1
return reason is None
# Legacy builds retain immutable Parent edges, including untagged bases.
# Follow this app's ancestry, never enumerate another component's cache.
current=accepted;seen={accepted['Id']};base=None
for depth in range(128):
parent=current.get('Parent')
if parent in ('',None):break
if not re.fullmatch('sha256:[a-f0-9]{64}',str(parent)):
raise CmsBuildBaseError('cms-base-parent-invalid')
if parent in seen:raise CmsBuildBaseError('cms-base-parent-cycle')
seen.add(parent);image=cms_inspect_image(parent)
layers=(image.get('RootFS') or {}).get('Layers')
child=(current.get('RootFS') or {}).get('Layers')
if ((image.get('RootFS') or {}).get('Type')!='layers'
or (current.get('RootFS') or {}).get('Type')!='layers'
or not isinstance(layers,list) or not isinstance(child,list)
or len(layers)>len(child) or child[:len(layers)]!=layers
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in child)):
raise CmsBuildBaseError('cms-base-parent-layers')
if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')):
raise CmsBuildBaseError('cms-base-parent-platform')
if matches(image,'parentCount'):
base=image;break
current=image
else:
raise CmsBuildBaseError('cms-base-parent-depth')
method='parent-chain'
if base is None:
# BuildKit/pulled images may have no Parent. Only inspect local official
# Node repository candidates; a tag never substitutes for ancestry proof.
rows=cms_base_docker_json(['image','ls','--all','--no-trunc',
'--filter','reference=node:*','--filter','reference=docker.io/library/node:*',
'--format','{{json .ID}}'],lines=True)
if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit')
if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows):
raise CmsBuildBaseError('cms-base-inventory-format')
found=[]
for identity in sorted(set(rows)):
image=cms_inspect_image(identity)
if matches(image,'nodeCount'):found.append(image)
if not found:
registered=cms_registered_node_image(accepted)
reason=cms_node_base_rejection(registered,accepted)
if reason is not None:
diagnostic.update(registeredRejection=reason,acceptedPrefix=((accepted.get('RootFS') or {}).get('Layers') or [])[:4])
raise CmsBuildBaseError('cms-base-registered-mismatch',diagnostic)
print('cms_build_base=registered-node24-base-v1;reference='+CMS_NODE_BASE_REF+';acquire=apply-only')
return cms_registered_node_proof(accepted)
if len(found)!=1:raise CmsBuildBaseError('cms-base-ambiguous',diagnostic)
base=found[0];method='node-cache'
proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'],
'layersSha256':cms_audit_digest(base['RootFS']['Layers']),
'configSha256':cms_audit_digest(base['Config'])}
print('cms_build_base=accepted-image-ancestor;lookup='+method+';immutable-id='+base['Id']+';pull=never')
return proof
def preflight_cms_release(payload, entries, identity):
require_root()
d = validate_cms_release_payload(payload,entries,identity)
previous = cms_installed_release()
if d['runNumber'] <= previous['runNumber'] or d['sourceCommit'] == previous['sourceCommit']:
die('CMS release is stale or already installed')
installed, metadata = cms_application_inventory()
# v1 is additive: deleting an application file requires a reviewed transition.
if not set(installed) <= set(entries):die('CMS v1 release cannot remove existing application files')
cms_healthchecks()
runtime=cms_runtime_snapshot_v2()
base=cms_resolve_build_base(runtime)
return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'],
'runtimeFingerprintVersion':2,'runtime':runtime,'buildBase':base,'otherServices':cms_other_services(),
'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata}
def build_cms_release(before):
proof=before['buildBase']
if proof.get('acceptedImageId')!=before['runtime']['imageId']:
die('CMS build base predecessor changed')
registered=proof.get('registeredBase') is not None
if registered:
accepted=cms_inspect_image(proof['acceptedImageId']);base=cms_materialize_registered_node(proof,accepted)
else:
base=cms_inspect_image(proof['imageId']);accepted=cms_inspect_image(proof['acceptedImageId'])
if (not cms_node_base_matches(base,accepted)
or cms_audit_digest(base['RootFS']['Layers'])!=proof['layersSha256']
or (not registered and cms_audit_digest(base['Config'])!=proof['configSha256'])):
die('CMS build base differs from its preflight proof')
dockerfile=(CMS_ROOT/'Dockerfile').read_bytes()
if hashlib.sha256(dockerfile).hexdigest()!=CMS_FOUNDATION['Dockerfile'] or not dockerfile.startswith(b'FROM node:24-alpine\n'):
die('CMS build recipe differs from the registered foundation')
# Legacy Dockerfile COPYs projects. Supply an empty directory, never the NAS
# project registry, encrypted passwords, uploaded ZIPs or site workspaces.
with tempfile.TemporaryDirectory(prefix='cms-build-',dir=TMP_DIR) as temp:
context=Path(temp)
(context/'projects').mkdir()
for rel in ('Dockerfile','package.json','package-lock.json',*before['entries']):
target=context/rel;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(CMS_ROOT/rel,target)
# Pin only the temporary recipe. The registered source Dockerfile is
# unchanged; no previous application/project layers enter this image.
(context/'Dockerfile').write_bytes(('FROM '+base['Id']+'\n').encode()+dockerfile.split(b'\n',1)[1])
# Docker 24's legacy builder accepts a local image ID in FROM. BuildKit
# interprets sha256:<id> as a registry repository and must not be used.
labels=cms_image_build_labels(accepted.get('Config') or {})
label_args=[item for key,value in sorted(labels.items()) for item in ('--label',key+'='+value)]
subprocess.run([str(DOCKER),'build','--pull=false',*label_args,'--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)],
check=True,env={**os.environ,'DOCKER_BUILDKIT':'0'})
image=docker_json(['image','inspect',before['runtime']['imageRef']],'CMS built image')
if not isinstance(image,list) or len(image)!=1:die('CMS built image is ambiguous')
before['builtImageId']=image[0]['Id']
expected=accepted.get('Config') or {};actual=image[0].get('Config') or {}
changed=[key for key in ('User','Cmd','Entrypoint','WorkingDir','ExposedPorts','Shell','StopSignal','Healthcheck','Labels','Volumes','OnBuild')
if actual.get(key)!=expected.get(key)]
actual_env=cms_image_env(actual);expected_env=cms_image_env(expected)
if actual_env!=expected_env:
names=sorted(k for k in set(actual_env)|set(expected_env) if actual_env.get(k)!=expected_env.get(k))
changed.append('Env['+','.join(names)+']')
if changed:die('CMS built image changes inherited configuration before recreation: '+','.join(changed))
print('cms_build_accept=inherited-config-exact;runtime-not-recreated')
def run_cms_release_compose():
cmd=compose_base_cmd('dc-cms-release')+['up','-d','--force-recreate','--no-build','--pull','never','--no-deps','cms-app']
subprocess.run(cmd,cwd=str(CMS_ROOT/'infra'),check=True)
def cms_image_files(identity):
script="""const fs=require('fs'),c=require('crypto'),r={};
for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){
const rel=d+'/'+n,f='/app/'+rel,s=fs.lstatSync(f);
if(s.isFile())r[rel]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
else if(n==='@eaDir'&&s.isDirectory())for(const m of fs.readdirSync(f)){
const q=f+'/'+m;if(!fs.lstatSync(q).isFile())throw Error('unexpected runtime metadata path');
r[rel+'/'+m]=c.createHash('sha256').update(fs.readFileSync(q)).digest('hex');
}else throw Error('unexpected runtime path');
}process.stdout.write(JSON.stringify(r))"""
proc=subprocess.run([str(DOCKER),'exec',identity,'node','-e',script],capture_output=True,text=True,check=True,timeout=30)
return cms_without_synology_metadata(json.loads(proc.stdout), 'CMS running image')[0]
def accept_cms_release(before, *, rollback=False):
cms_healthchecks()
version=before.get('runtimeFingerprintVersion',1)
if type(version) is not int or version not in (1,2):die('CMS runtime fingerprint version mismatch')
current=cms_runtime_snapshot_v2() if version==2 else cms_runtime_snapshot();old=before['runtime']
if current['configSha256'] != old['configSha256'] or current['imageRef'] != old['imageRef']:
detail=''
if version==2:
previous=old.get('fieldSha256') or {};actual=current.get('fieldSha256') or {}
changed=sorted(k for k in set(previous)|set(actual) if previous.get(k)!=actual.get(k))
detail='; fields='+','.join(changed)
die('CMS environment, mounts, ports or network topology changed'+detail)
expected_image=old['imageId'] if rollback else before['builtImageId']
if current['imageId'] != expected_image or (not rollback and current['id']==old['id']):
die('CMS selected service image/generation mismatch')
expected_foundation=before['foundation'] if rollback else {**CMS_FOUNDATION,'infra/.env.synology':before['foundation']['infra/.env.synology']}
if cms_other_services()!=before['otherServices'] or cms_foundation()!=expected_foundation or cms_preserved_data()!=before['data']:
die('CMS release changed preserved applications or project data')
actual, metadata=cms_application_inventory()
if metadata != before['installedMetadata']:die('CMS release changed preserved Synology metadata')
if rollback:
if actual!=before['installedFiles']:die('CMS rollback source mismatch')
else:
validate_cms_release_payload(CMS_ROOT,before['entries'],before['descriptor']['releaseId'])
version=subprocess.run([str(DOCKER),'exec',current['id'],'node','-p',"require('adm-zip/package.json').version"],capture_output=True,text=True,check=True,timeout=30).stdout.strip()
if version != '0.6.1':die('CMS running ZIP dependency differs from the qualified version')
if cms_image_files(current['id']) != {k:v for k,v in actual.items() if k not in CMS_DEPENDENCY_FILES}:die('CMS running image differs from accepted source')
print('cms_release_accept='+('rollback' if rollback else before['descriptor']['sourceCommit'])+';services=cms-app;sites-auth-databases-secrets=preserved')
def rollback_cms_release(root, backup_dir, entries, current_stamp, before, runtime_started):
restore_platform_overlay(root,backup_dir,entries,current_stamp)
subprocess.run([str(DOCKER),'image','tag',before['runtime']['imageId'],before['runtime']['imageRef']],check=True)
if runtime_started:run_cms_release_compose()
accept_cms_release(before,rollback=True)
-26
View File
@@ -1,26 +0,0 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpuset-cpus=7 --cpu-shares=128 --memory=2g --memory-swap=2g --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
-17
View File
@@ -1,17 +0,0 @@
{
"allowedOperation": "canonical-plan-only",
"auditId": "dc-cms-r39-runtime-audit-v1-20261104-001",
"backupId": "dc-cms-release-dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a-20261104-223125",
"backupSha256": {
"cms-runtime-before.json": "e14634fc1ef03da8b8a7751d9418b74c52da65dfe6dea82ad9c14ef04634263b",
"existing-files.txt": "46fa370124d7ed95362666e84372188bdf9d0c2b4c2e0e3d9dbeed42ad571762",
"files.txt": "4a696155703c6aa15daf777331847a37cd5e8345e2bb0a6b1fc98515e27988d8",
"manifest.env": "ce246952d0ef6cee1f4b22b770108d5c92d671cc7984dc83e136d61f2e607f22",
"missing-files.txt": "c31852f6da115fed68880fcf0aa8a7b4c0d2a7a9cfdae095907e95863bdb2409",
"source-before.tgz": "cd35cb27dd4875e13cdf7202ab57c24e7db0a43c473454675fe122ebf23090b1"
},
"failedReleaseId": "dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a",
"failedSha256": "3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029",
"mutation": false,
"schemaVersion": "nodedc.dc-cms.runtime-audit.v1"
}
@@ -1,18 +0,0 @@
{
"backupId": "dc-cms-release-dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a-20261104-223125",
"backupSha256": {
"cms-runtime-before.json": "e14634fc1ef03da8b8a7751d9418b74c52da65dfe6dea82ad9c14ef04634263b",
"existing-files.txt": "46fa370124d7ed95362666e84372188bdf9d0c2b4c2e0e3d9dbeed42ad571762",
"files.txt": "4a696155703c6aa15daf777331847a37cd5e8345e2bb0a6b1fc98515e27988d8",
"manifest.env": "ce246952d0ef6cee1f4b22b770108d5c92d671cc7984dc83e136d61f2e607f22",
"missing-files.txt": "c31852f6da115fed68880fcf0aa8a7b4c0d2a7a9cfdae095907e95863bdb2409",
"source-before.tgz": "cd35cb27dd4875e13cdf7202ab57c24e7db0a43c473454675fe122ebf23090b1"
},
"failedReleaseId": "dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a",
"failedSha256": "3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029",
"legacyRuntimeSha256": "e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f",
"mode": "prove-restored-baseline-bind-order-empty-dns-only",
"releaseId": "dc-cms-r39-runtime-reconciliation-v2-20261104-001",
"runtimeFingerprintVersion": 2,
"schemaVersion": "nodedc.dc-cms.runtime-reconciliation.v2"
}
-109
View File
@@ -1,109 +0,0 @@
import copy
from contextlib import redirect_stdout
import io
import unittest
from unittest.mock import patch
from test_runner import r
from test_build_base import compose_labels
def registered_images():
base=r.cms_registered_node_image({'Config':{'User':''}})
base['RepoDigests']=['node@'+r.CMS_NODE_BASE_MANIFEST]
accepted=copy.deepcopy(base);accepted['Id']='sha256:'+'b'*64
accepted['RootFS']['Layers'].append('sha256:'+'e'*64)
accepted['Config'].update(Cmd=['npm','run','admin'],WorkingDir='/app',ExposedPorts={'8090/tcp':{}},Labels=compose_labels())
accepted['Config']['Env']+=['HOST=0.0.0.0','PORT=8090']
return base,accepted
class CmsBaseAcquisitionTests(unittest.TestCase):
def test_registered_public_bytes_and_docker24_default_projection(self):
base,accepted=registered_images()
self.assertEqual(base['Config']['WorkingDir'],'/')
self.assertEqual(base['Config']['User'],'')
self.assertTrue(r.cms_node_base_matches(base,accepted))
newer=copy.deepcopy(accepted);newer['Config'].pop('User')
self.assertNotIn('User',r.cms_registered_node_image(newer)['Config'])
self.assertTrue(r.cms_node_base_matches(r.cms_registered_node_image(newer),newer))
with patch.object(r,'CMS_NODE_BASE_CONFIG_JSON',r.CMS_NODE_BASE_CONFIG_JSON+' '):
with self.assertRaisesRegex(r.CmsBuildBaseError,'registered-proof'):r.cms_registered_node_image(accepted)
def test_preflight_proves_registered_base_without_pull_or_image_mutation(self):
base,accepted=registered_images()
with patch.object(r,'cms_inspect_image',return_value=accepted),patch.object(r,'cms_base_docker_json',return_value=[]),patch.object(r.subprocess,'run') as run,redirect_stdout(io.StringIO()):
proof=r.cms_resolve_build_base({'imageId':accepted['Id']})
self.assertEqual(proof,r.cms_registered_node_proof(accepted));run.assert_not_called()
self.assertEqual(proof['registryReference'],r.CMS_NODE_BASE_REF)
def test_registered_mismatch_reports_only_fixed_reason_and_base_layer_prefix(self):
for field in ('layers','environment'):
base,accepted=registered_images()
if field=='layers':accepted['RootFS']['Layers'][0]='sha256:'+'f'*64
else:accepted['Config']['Env'].append('SECRET=private-fixture')
with patch.object(r,'cms_inspect_image',return_value=accepted),patch.object(r,'cms_base_docker_json',return_value=[]),patch.object(r.subprocess,'run') as run:
with self.assertRaises(r.CmsBuildBaseError) as error:r.cms_resolve_build_base({'imageId':accepted['Id']})
run.assert_not_called();status=r.cms_autodeploy_error_status(error.exception,())
self.assertEqual(status['reason'],'cms-base-registered-mismatch')
self.assertEqual(status['baseLookup']['registeredRejection'],field)
self.assertNotIn('private-fixture',str(status));self.assertNotIn('SECRET',str(status))
def test_only_exact_missing_image_response_can_trigger_acquisition(self):
args=['image','inspect',r.CMS_NODE_BASE_REF]
for stderr,expected in [('Error response from daemon: No such image: '+r.CMS_NODE_BASE_REF,'cms-base-image-not-found'),
('Error: No such image: '+r.CMS_NODE_BASE_REF,'cms-base-image-not-found'),
('Error response from daemon: No such image: node@'+r.CMS_NODE_BASE_MANIFEST,'cms-base-image-not-found'),
('permission denied private-fixture','cms-base-docker-failed')]:
error=r.subprocess.CalledProcessError(1,['docker'],output='[]\n',stderr=stderr)
with patch.object(r.subprocess,'run',side_effect=error):
with self.assertRaisesRegex(r.CmsBuildBaseError,expected):r.cms_base_docker_json(args)
def test_cached_registered_image_uses_no_network_for_both_image_store_identities(self):
for identity in (r.CMS_NODE_BASE_CONFIG,r.CMS_NODE_BASE_MANIFEST):
base,accepted=registered_images();base['Id']=identity
with patch.object(r,'cms_base_docker_json',return_value=[base]),patch.object(r.subprocess,'run') as run:
self.assertEqual(r.cms_materialize_registered_node(r.cms_registered_node_proof(accepted),accepted),base)
run.assert_not_called()
def test_missing_registered_base_pulls_only_fixed_digest_then_reproves_local_image(self):
base,accepted=registered_images()
with patch.object(r,'cms_base_docker_json',side_effect=[r.CmsBuildBaseError('cms-base-image-not-found'),[base]]) as inspect,patch.object(r.subprocess,'run') as run,redirect_stdout(io.StringIO()):
self.assertEqual(r.cms_materialize_registered_node(r.cms_registered_node_proof(accepted),accepted),base)
self.assertEqual(inspect.call_count,2)
run.assert_called_once_with([str(r.DOCKER),'pull','--platform','linux/amd64',r.CMS_NODE_BASE_REF],capture_output=True,text=True,check=True,timeout=300)
def test_forged_proof_or_changed_accepted_base_stops_before_docker(self):
base,accepted=registered_images();proof=r.cms_registered_node_proof(accepted)
for key in proof:
with patch.object(r,'cms_base_docker_json') as inspect,patch.object(r.subprocess,'run') as run:
with self.assertRaisesRegex(r.CmsBuildBaseError,'registered-proof'):r.cms_materialize_registered_node({**proof,key:'private-fixture'},accepted)
inspect.assert_not_called();run.assert_not_called()
accepted['RootFS']['Layers'][0]='sha256:'+'0'*64
with patch.object(r,'cms_base_docker_json') as inspect:
with self.assertRaisesRegex(r.CmsBuildBaseError,'registered-proof'):r.cms_materialize_registered_node(proof,accepted)
inspect.assert_not_called()
def test_local_image_identity_layers_environment_and_repository_are_not_substitutable(self):
for field in ('Id','RepoDigests','Layers','Env'):
base,accepted=registered_images();proof=r.cms_registered_node_proof(accepted)
if field=='Id':base['Id']='sha256:'+'f'*64
elif field=='RepoDigests':base['RepoDigests']=['other@'+r.CMS_NODE_BASE_MANIFEST]
elif field=='Layers':base['RootFS']['Layers'][0]='sha256:'+'f'*64
else:base['Config']['Env'].append('SECRET=private-fixture')
with patch.object(r,'cms_base_docker_json',return_value=[base]),patch.object(r.subprocess,'run') as run:
with self.assertRaisesRegex(r.CmsBuildBaseError,'registered-image'):r.cms_materialize_registered_node(proof,accepted)
run.assert_not_called()
def test_unavailable_docker_and_registry_errors_never_choose_another_base(self):
base,accepted=registered_images();proof=r.cms_registered_node_proof(accepted)
with patch.object(r,'cms_base_docker_json',side_effect=r.CmsBuildBaseError('cms-base-docker-failed')),patch.object(r.subprocess,'run') as run:
with self.assertRaisesRegex(r.CmsBuildBaseError,'docker-failed'):r.cms_materialize_registered_node(proof,accepted)
run.assert_not_called()
for error,code in [(r.subprocess.TimeoutExpired(['private-fixture'],300),'fetch-timeout'),
(r.subprocess.CalledProcessError(1,['private-fixture'],stderr='private-fixture'),'fetch-failed')]:
with patch.object(r,'cms_base_docker_json',side_effect=r.CmsBuildBaseError('cms-base-image-not-found')),patch.object(r.subprocess,'run',side_effect=error),redirect_stdout(io.StringIO()):
with self.assertRaisesRegex(r.CmsBuildBaseError,code) as caught:r.cms_materialize_registered_node(proof,accepted)
self.assertNotIn('private-fixture',str(caught.exception))
if __name__=='__main__':unittest.main()
-218
View File
@@ -1,218 +0,0 @@
import copy
from contextlib import redirect_stdout
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from test_runner import r, fixture
def images():
base={'Id':'sha256:'+'a'*64,'Os':'linux','Architecture':'amd64',
'RootFS':{'Type':'layers','Layers':['sha256:'+'1'*64,'sha256:'+'2'*64]},
'Config':{'Env':['PATH=/bin','NODE_VERSION=24.18.0','YARN_VERSION=1.22.22'],
'Cmd':['node'],'Entrypoint':['docker-entrypoint.sh'],'WorkingDir':'','User':''}}
old=copy.deepcopy(base);old['Id']='sha256:'+'b'*64
old['RootFS']['Layers']+=['sha256:'+'3'*64]
old['Config'].update(Cmd=['npm','run','admin'],WorkingDir='/app',ExposedPorts={'8090/tcp':{}})
old['Config']['Env']+=['HOST=0.0.0.0','PORT=8090']
return base,old
def proof(base,old):
return {'imageId':base['Id'],'acceptedImageId':old['Id'],
'layersSha256':r.cms_audit_digest(base['RootFS']['Layers']),
'configSha256':r.cms_audit_digest(base['Config'])}
def compose_labels():
return {'com.docker.compose.project':'dc-cms','com.docker.compose.service':'cms-app','com.docker.compose.version':'2.20.3'}
class CmsBuildBaseTests(unittest.TestCase):
def test_proves_actual_ancestry_and_inherited_environment(self):
base,old=images();saved=copy.deepcopy(base)
self.assertTrue(r.cms_node_base_matches(base,old))
self.assertEqual(base,saved)
# A mutable tag's new image must fail even if it has the same version.
for field,value in [('Env',['PATH=/bin','NODE_VERSION=24.19.0','YARN_VERSION=1.22.22']),
('OnBuild',['RUN unauthorized']),('Volumes',{'/private':{}}),
('Labels',{'extra':'value'}),('User','1000'),('Entrypoint',['other']),
('WorkingDir','/app'),('Cmd',['npm','run','admin']),('ExposedPorts',{'80/tcp':{}})]:
changed=copy.deepcopy(base);changed['Config'][field]=value
self.assertFalse(r.cms_node_base_matches(changed,old),field)
for field,value in [('Architecture','arm64'),('Os','windows')]:
changed=copy.deepcopy(base);changed[field]=value
self.assertFalse(r.cms_node_base_matches(changed,old),field)
changed=copy.deepcopy(base);changed['RootFS']['Layers'][0]='sha256:'+'9'*64
self.assertFalse(r.cms_node_base_matches(changed,old))
self.assertFalse(r.cms_node_base_matches(old,old))
def test_duplicate_environment_and_secret_values_never_appear_in_errors(self):
for env in [None,{},['TOKEN=private-fixture','TOKEN=other'],['NO_SEPARATOR'],['=bad'],['A=bad\0']]:
with self.assertRaises(r.DeployError) as error:r.cms_image_env({'Env':env})
self.assertNotIn('private-fixture',str(error.exception))
def test_compose_build_labels_are_owned_additions_not_inherited_base_config(self):
base,old=images();old['Config']['Labels']=compose_labels()
original=copy.deepcopy((base,old))
self.assertTrue(r.cms_node_base_matches(base,old))
self.assertEqual(r.cms_image_build_labels(old['Config']),compose_labels())
self.assertEqual((base,old),original)
# Extra inherited labels still have to match exactly.
base['Config']['Labels']={'vendor':'original'}
self.assertFalse(r.cms_node_base_matches(base,old))
old['Config']['Labels']['vendor']='original'
self.assertTrue(r.cms_node_base_matches(base,old))
for labels in [{'arbitrary':'private-fixture'}, {**compose_labels(),'com.docker.compose.extra':'private-fixture'},
{**compose_labels(),'com.docker.compose.project':'other'},
{**compose_labels(),'com.docker.compose.service':'other'},
{**compose_labels(),'com.docker.compose.version':'bad\nprivate-fixture'},
{**compose_labels(),'com.docker.compose.version':'2.20.3+'+'a'*81},
{'com.docker.compose.project':'dc-cms'},['private-fixture']]:
b,o=images();o['Config']['Labels']=labels
self.assertFalse(r.cms_node_base_matches(b,o))
for labels in [{**compose_labels(),'com.docker.compose.extra':'private-fixture'},['private-fixture']]:
with self.assertRaises(r.CmsBuildBaseError) as error:r.cms_image_build_labels({'Labels':labels})
self.assertNotIn('private-fixture',str(error.exception))
def test_parent_chain_finds_untagged_base_without_global_inventory(self):
base,old=images();middle=copy.deepcopy(old);middle['Id']='sha256:'+'c'*64
old['Parent']=middle['Id'];middle['Parent']=base['Id']
inventory={i['Id']:i for i in (base,old,middle)}
with patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__) as inspect,patch.object(r,'cms_base_docker_json') as listing,redirect_stdout(io.StringIO()) as output:
self.assertEqual(r.cms_resolve_build_base({'imageId':old['Id']}),proof(base,old))
self.assertEqual(inspect.call_count,3);listing.assert_not_called()
self.assertIn('lookup=parent-chain',output.getvalue())
self.assertNotIn('PATH=',output.getvalue())
def test_parent_chain_rejects_cycles_invalid_edges_and_depth(self):
base,old=images()
for code,alter in [
('parent-invalid',lambda b,o:o.update(Parent='latest')),
('parent-cycle',lambda b,o:o.update(Parent=o['Id'])),
('parent-layers',lambda b,o:b['RootFS']['Layers'].reverse()),
('parent-platform',lambda b,o:b.update(Architecture='arm64')),
]:
b,o=copy.deepcopy(base),copy.deepcopy(old);o['Parent']=b['Id'];alter(b,o)
inventory={i['Id']:i for i in (b,o)}
with self.subTest(code=code),patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__),patch.object(r,'cms_base_docker_json') as listing:
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code):r.cms_resolve_build_base({'imageId':o['Id']})
listing.assert_not_called()
chain=[]
for i in range(130):
item=copy.deepcopy(old);item['Id']='sha256:'+format(i,'064x');item['Parent']='sha256:'+format(i+1,'064x');chain.append(item)
with patch.object(r,'cms_inspect_image',side_effect={i['Id']:i for i in chain}.__getitem__):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-parent-depth'):r.cms_resolve_build_base({'imageId':chain[0]['Id']})
def test_node_cache_fallback_ignores_mutable_tag_and_rejects_missing_or_ambiguous_base(self):
base,old=images();latest=copy.deepcopy(base);latest['Id']='sha256:'+'c'*64
latest['Config']['Env'][1]='NODE_VERSION=24.19.0'
latest['RootFS']['Layers'][1]='sha256:'+'4'*64
latest['RepoTags']=['node:24-alpine']
for inventory,success in [([latest,base,old],True),([latest,old],False),([latest,base,old,{**base,'Id':'sha256:'+'d'*64}],False)]:
by_id={i['Id']:i for i in inventory}
with patch.object(r,'cms_inspect_image',side_effect=by_id.__getitem__),patch.object(r,'cms_base_docker_json',return_value=list(by_id)) as run,redirect_stdout(io.StringIO()) as output:
if success:self.assertEqual(r.cms_resolve_build_base({'imageId':old['Id']}),proof(base,old))
else:
with self.assertRaises(r.DeployError):r.cms_resolve_build_base({'imageId':old['Id']})
self.assertEqual(run.call_args.args[0],['image','ls','--all','--no-trunc','--filter','reference=node:*','--filter','reference=docker.io/library/node:*','--format','{{json .ID}}'])
self.assertEqual(run.call_args.kwargs,{'lines':True})
self.assertNotIn('PATH=',output.getvalue())
def test_inventory_rejects_short_ids_malformed_values_and_excess_before_inspect(self):
base,old=images()
for rows,code in [(['abcdef123456'],'format'),([{}],'format'),([None],'format'),([base['Id']]*257,'limit')]:
with self.subTest(code=code,rows=len(rows)),patch.object(r,'cms_inspect_image',return_value=old) as inspect,patch.object(r,'cms_base_docker_json',return_value=rows):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-inventory-'+code):r.cms_resolve_build_base({'imageId':old['Id']})
inspect.assert_called_once_with(old['Id'])
def test_docker_reads_are_bounded_and_external_errors_are_redacted(self):
for error,code in [
(r.subprocess.TimeoutExpired(['docker','private-fixture'],30,stderr='secret-fixture'),'docker-timeout'),
(r.subprocess.CalledProcessError(1,['docker'],stderr='secret-fixture'),'docker-failed'),
(OSError('secret-fixture'),'docker-unavailable'),
]:
with patch.object(r.subprocess,'run',side_effect=error) as run:
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code) as caught:r.cms_base_docker_json(['image','inspect','fixture'])
self.assertNotIn('secret-fixture',str(caught.exception));self.assertEqual(run.call_args.kwargs['timeout'],30)
for value,lines,expected in [('[]',False,[]),('"sha256:abc"\n',True,['sha256:abc']),('',True,[])]:
with patch.object(r.subprocess,'run',return_value=type('Result',(),{'stdout':value})()):
self.assertEqual(r.cms_base_docker_json(['fixture'],lines=lines),expected)
for value,code in [('secret-fixture','json-invalid'),('x'*(8*1024*1024+1),'output-limit')]:
with patch.object(r.subprocess,'run',return_value=type('Result',(),{'stdout':value})()):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code):r.cms_base_docker_json(['fixture'])
def test_image_inspection_requires_exact_immutable_identity(self):
base,old=images()
for rows in [[old],[],[base,base],[None],{}]:
with patch.object(r,'cms_base_docker_json',return_value=rows):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-image-mismatch'):r.cms_inspect_image(base['Id'])
with patch.object(r,'cms_base_docker_json',return_value=[base]):self.assertEqual(r.cms_inspect_image(base['Id']),base)
def test_public_status_contains_only_allowlisted_base_codes(self):
error=r.CmsBuildBaseError('cms-base-missing');error.args=('secret-fixture',)
self.assertEqual(r.cms_autodeploy_error_status(error,())['reason'],'cms-base-missing')
error.code='secret-fixture'
self.assertNotIn('reason',r.cms_autodeploy_error_status(error,()))
for error in [r.DeployError('secret-fixture'),r.subprocess.TimeoutExpired(['private-fixture'],30)]:
result=r.cms_autodeploy_error_status(error,())
self.assertNotIn('reason',result);self.assertNotIn('fixture',json.dumps(result))
with self.assertRaises(ValueError):r.CmsBuildBaseError('secret-fixture')
def test_missing_base_diagnostic_has_only_bounded_rejection_counts(self):
base,old=images();old['Config']['Labels']={'private-fixture':'never-export'}
inventory={i['Id']:i for i in (base,old)}
with patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__),patch.object(r,'cms_base_docker_json',return_value=[base['Id']]):
with self.assertRaises(r.CmsBuildBaseError) as error:r.cms_resolve_build_base({'imageId':old['Id']})
status=r.cms_autodeploy_error_status(error.exception,())
self.assertEqual(status['baseLookup'],{'parentCount':0,'nodeCount':1,'rejected':{'labels':1},'registeredRejection':'layers','acceptedPrefix':old['RootFS']['Layers']})
self.assertNotIn('private-fixture',json.dumps(status));self.assertNotIn('never-export',json.dumps(status))
for value in [None,{}, {'parentCount':0,'nodeCount':1,'rejected':{'private-fixture':1}},
{'parentCount':0,'nodeCount':1,'rejected':{'labels':'private-fixture'}},
{'parentCount':True,'nodeCount':1,'rejected':{}},
{'parentCount':0,'nodeCount':99999,'rejected':{}},
{'parentCount':0,'nodeCount':1,'rejected':{},'extra':'private-fixture'}]:
error.exception.diagnostic=value
self.assertNotIn('baseLookup',r.cms_autodeploy_error_status(error.exception,()))
def test_build_pins_only_clean_temporary_recipe_and_rejects_drift_before_recreation(self):
for drift,with_labels in [(d,l) for d in ('none','env','labels') for l in (False,True)]:
base,old=images()
if with_labels:old['Config']['Labels']=compose_labels()
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);entries,_=fixture(root)
recipe=b'FROM node:24-alpine\nWORKDIR /app\n'
(root/'Dockerfile').write_bytes(recipe)
(root/'projects').mkdir();(root/'projects/password.json').write_text('private-fixture')
before={'entries':entries,'runtime':{'imageRef':'dc-cms-cms-app','imageId':old['Id']},'buildBase':proof(base,old)}
built=copy.deepcopy(old);built['Id']='sha256:'+'e'*64
if drift=='env':built['Config']['Env'].append('TOKEN=private-fixture')
if drift=='labels':built['Config']['Labels']={**(built['Config'].get('Labels') or {}),'private':'private-fixture'}
def build(cmd,**kwargs):
self.assertIn('--pull=false',cmd)
self.assertEqual(kwargs['env']['DOCKER_BUILDKIT'],'0')
actual_labels=[cmd[i+1] for i,value in enumerate(cmd) if value=='--label']
self.assertEqual(actual_labels,[k+'='+v for k,v in sorted(compose_labels().items())] if with_labels else [])
context=Path(cmd[-1]);self.assertEqual(list((context/'projects').iterdir()),[])
self.assertEqual((context/'Dockerfile').read_bytes(),('FROM '+base['Id']+'\nWORKDIR /app\n').encode())
self.assertEqual(set(p.relative_to(context).as_posix() for p in context.rglob('*') if p.is_file()),set(entries)|{'Dockerfile'})
self.assertNotIn('private-fixture',str(cmd))
with patch.object(r,'CMS_ROOT',root),patch.object(r,'TMP_DIR',root),patch.dict(r.CMS_FOUNDATION,{'Dockerfile':r.hashlib.sha256(recipe).hexdigest()}),patch.object(r,'cms_inspect_image',side_effect=[base,old]),patch.object(r.subprocess,'run',side_effect=build),patch.object(r,'docker_json',return_value=[built]),redirect_stdout(io.StringIO()):
if drift!='none':
with self.assertRaisesRegex(r.DeployError,'before recreation: '+('Env' if drift=='env' else 'Labels')) as error:r.build_cms_release(before)
self.assertNotIn('private-fixture',str(error.exception))
else:r.build_cms_release(before)
self.assertEqual((root/'Dockerfile').read_bytes(),recipe)
def test_changed_base_proof_rejected_before_build(self):
base,old=images();bad=proof(base,old);bad['configSha256']='0'*64
before={'runtime':{'imageId':old['Id']},'buildBase':bad}
with patch.object(r,'cms_inspect_image',side_effect=[base,old]),patch.object(r.subprocess,'run') as run:
with self.assertRaisesRegex(r.DeployError,'preflight proof'):r.build_cms_release(before)
run.assert_not_called()
if __name__=='__main__':unittest.main()
-74
View File
@@ -1,74 +0,0 @@
import hashlib
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from deployment_queue import DeploymentQueue, QueueError
from controller import Controller
from test_gitea_source import run,A,B,C
class ControllerTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.path=Path(self.tmp.name)/'queue.db'
self.q=DeploymentQueue(self.path,first_run_number=8);self.addCleanup(self.q.close)
self.s=mock.Mock();self.i=mock.Mock()
self.i.installed_source.return_value=A
self.r=run();self.s.discover.return_value=[self.r];self.s.successful_run.return_value=self.r
self.data=b'archive';self.artifact='nodedc-dc-cms-release-v1-r8-'+B+'.tgz'
self.receipt={'artifact':self.artifact,'sha256':hashlib.sha256(self.data).hexdigest()}
self.s.artifact.return_value=(self.receipt,self.data)
self.i.receipt.return_value=('deployed','canonical:line1')
self.c=Controller(self.q,self.s,self.i)
def test_success_is_reserved_before_apply_and_never_repeated(self):
def apply(a):self.assertEqual(self.q.snapshot()[0]['phase'],'deploying')
self.i.apply.side_effect=apply
self.assertEqual(self.c.tick()['status'],'deployed')
self.assertEqual(self.c.tick()['status'],'waiting')
self.i.apply.assert_called_once_with(self.artifact)
def test_earlier_pending_blocks_newer_ready_but_failed_ci_does_not(self):
pending=run();pending.update(status='in_progress',conclusion=None)
self.s.discover.return_value=[run(9,C),pending]
self.assertEqual(self.c.tick()['status'],'waiting');self.i.apply.assert_not_called()
pending.update(status='completed',conclusion='failure');self.c.observe()
self.assertEqual(self.q.next_ready()['id'],9)
def test_failure_with_clean_rollback_is_terminal(self):
self.i.apply.side_effect=RuntimeError('failure');self.i.receipt.return_value=('rolled-back','failed:line1')
with self.assertRaises(RuntimeError):self.c.tick()
self.assertEqual(self.q.snapshot()[0]['phase'],'failed')
self.assertEqual(self.c.tick()['status'],'waiting');self.assertEqual(self.i.apply.call_count,1)
def test_missing_receipt_blocks_restart(self):
self.i.apply.side_effect=RuntimeError('crash');self.i.receipt.return_value=('ambiguous','missing-receipt')
with self.assertRaises(RuntimeError):self.c.tick()
with self.assertRaises(QueueError):self.c.tick()
self.assertEqual(self.i.apply.call_count,1)
def test_restart_reconciles_success_without_second_apply(self):
self.c.observe();self.q.reserve(8,digest=self.receipt['sha256'],artifact=self.artifact)
self.assertEqual(self.c.tick()['status'],'waiting')
self.i.apply.assert_not_called();self.assertEqual(self.q.snapshot()[0]['phase'],'deployed')
def test_network_or_plan_error_before_reservation_preserves_ready_queue(self):
self.i.plan.side_effect=RuntimeError('network')
with self.assertRaises(RuntimeError):self.c.tick()
self.assertEqual(self.q.snapshot()[0]['phase'],'ready');self.i.apply.assert_not_called()
def test_new_rerun_before_reservation_prevents_apply(self):
pending=run();pending.update(run_attempt=2,status='in_progress',conclusion=None)
self.s.discover.side_effect=[[run()],[pending]]
with self.assertRaises(QueueError):self.c.tick()
self.i.apply.assert_not_called()
def test_disappeared_pending_run_never_skipped(self):
pending=run();pending.update(status='in_progress',conclusion=None)
self.s.discover.return_value=[pending];self.c.observe()
self.s.discover.return_value=[run(9,C)]
with self.assertRaisesRegex(QueueError,'disappeared'):self.c.tick()
self.i.apply.assert_not_called()
if __name__=='__main__':unittest.main()
-138
View File
@@ -1,138 +0,0 @@
import tempfile
from pathlib import Path
import unittest
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID
def run(number, *, status="completed", conclusion="success", **updates):
return {"id": number + 100, "run_number": number, "run_attempt": 1,
"head_sha": format(number, "040x"), "event": "push", "head_branch": "master",
"path": "ci.yml@refs/heads/master", "status": status, "conclusion": conclusion, **updates}
class QueueTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / "queue.db"
self.q = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(lambda: self.q.close())
def observe(self, *values):
self.q.observe(list(values), repository=REPOSITORY, repository_id=REPOSITORY_ID)
def reserve(self, number):
r = self.q.next_ready()
self.assertEqual(r["number"], number)
return self.q.reserve(r["id"], digest="a"*64,
artifact="nodedc-dc-cms-release-v1-r"+str(r["id"])+"-"+r["sha"]+".tgz")
def finish(self, row, outcome="deployed"):
self.q.reconcile(row["id"], digest=row["digest"], artifact=row["artifact"],
outcome=outcome, receipt="canonical-test-receipt-"+str(row["id"]))
def test_overlapping_pushes_wait_for_older_qualification(self):
self.observe(run(2), run(1, status="in_progress", conclusion=None))
self.assertIsNone(self.q.next_ready())
self.observe(run(1))
self.finish(self.reserve(1))
self.finish(self.reserve(2))
self.assertIsNone(self.q.next_ready())
def test_failed_tests_do_not_deploy_and_next_push_can_proceed(self):
self.observe(run(2), run(1, conclusion="failure"))
self.finish(self.reserve(2))
self.assertEqual(self.q.snapshot()[0]["phase"], "unqualified")
def test_duplicate_observations_and_receipts_are_idempotent(self):
self.observe(run(1), run(1))
row = self.reserve(1)
self.finish(row)
self.finish(row)
self.observe(run(1))
self.assertEqual(len(self.q.snapshot()), 1)
self.assertIsNone(self.q.next_ready())
def test_wrong_branch_event_and_workflow_never_deploy(self):
self.observe(run(1, head_branch="feature"), run(2, event="workflow_dispatch"), run(3, path="other.yml@refs/heads/master"))
self.assertIsNone(self.q.next_ready())
self.assertEqual({r["phase"] for r in self.q.snapshot()}, {"ignored"})
def test_wrong_repository_and_malformed_sha_rejected(self):
for repo, identity in [("other/Device", 38), (REPOSITORY, 39), (REPOSITORY, 33.0)]:
with self.assertRaises(QueueError): self.q.observe([run(1)], repository=repo, repository_id=identity)
with self.assertRaises(QueueError): self.observe(run(1, head_sha="main; execute"))
self.assertEqual(self.q.snapshot(), [])
def test_identity_conflict_rolls_back_entire_observation(self):
self.observe(run(1))
with self.assertRaises(QueueError): self.observe(run(2), run(1, head_sha="b"*40))
self.assertEqual(len(self.q.snapshot()), 1)
def test_restart_preserves_pending_and_requires_reconciliation_for_reserved(self):
self.observe(run(1), run(2))
row = self.reserve(1)
self.q.close()
self.q = DeploymentQueue(self.path, first_run_number=1)
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
self.finish(row)
self.assertEqual(self.q.next_ready()["number"], 2)
def test_ambiguous_or_failed_rollback_halts_following_deploys(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "ambiguous")
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
def test_clean_rollback_never_retries_same_artifact_but_allows_forward_fix(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "rolled-back")
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 2)
def test_late_old_run_and_same_source_cannot_downgrade_installed_revision(self):
self.observe(run(5))
self.finish(self.reserve(5))
self.observe(run(4), run(6, head_sha=run(5)["head_sha"]))
self.assertIsNone(self.q.next_ready())
self.assertEqual([r["phase"] for r in self.q.snapshot()], ["superseded", "deployed", "superseded"])
def test_second_controller_cannot_reserve_another_deploy(self):
self.observe(run(1), run(2))
second = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(second.close)
self.reserve(1)
with self.assertRaises(QueueError): second.next_ready()
def test_wrong_receipt_cannot_close_crashed_deployment(self):
self.observe(run(1))
row = self.reserve(1)
with self.assertRaisesRegex(QueueError, "artifact_mismatch"):
self.q.reconcile(row["id"], digest="b"*64, artifact=row["artifact"], outcome="deployed", receipt="wrong")
with self.assertRaises(QueueError): self.q.next_ready()
def test_activation_floor_is_persistent_and_old_history_is_not_deployed(self):
self.q.close()
self.path = Path(self.temp.name) / "second.db"
self.q = DeploymentQueue(self.path, first_run_number=3)
self.observe(run(1), run(2), run(3))
self.assertEqual(self.q.next_ready()["number"], 3)
with self.assertRaisesRegex(QueueError, "policy_changed"):
DeploymentQueue(self.path, first_run_number=1)
def test_terminal_api_outcome_cannot_change_without_a_new_attempt(self):
self.observe(run(1, conclusion="failure"))
with self.assertRaisesRegex(QueueError, "outcome_changed"): self.observe(run(1))
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 1)
def test_large_backlog_of_duplicate_sources_is_iterative(self):
self.observe(run(1))
self.finish(self.reserve(1))
self.observe(*(run(n, head_sha=run(1)["head_sha"]) for n in range(2, 1200)))
self.assertIsNone(self.q.next_ready())
self.assertEqual(len(self.q.snapshot()), 1199)
if __name__ == "__main__":
unittest.main()
-108
View File
@@ -1,108 +0,0 @@
from contextlib import ExitStack,redirect_stdout,redirect_stderr
import hashlib
import io
import tarfile
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from test_runner import r,ROOT,fixture
from build_autodeploy import bundle
from embed_runtime import section,START,END
class CmsBootstrapDispatchTests(unittest.TestCase):
def test_exact_embedded_policy(self):
source=Path(r.__file__).read_text()
self.assertEqual(START+source.split(START,1)[1].split(END,1)[0]+END,section())
q,s,c,e=r.cms_autodeploy_library()
with tempfile.TemporaryDirectory() as d:
queue=q(Path(d)/'queue',first_run_number=1);self.assertIsNone(queue.next_ready());queue.close()
def test_archive_and_scope(self):
identity,data=bundle();self.assertEqual(data,bundle()[1])
with tempfile.TemporaryDirectory() as d:
root=Path(d);a=root/'a.tgz';a.write_bytes(data);work=root/'work';work.mkdir()
m,e,p=r.load_artifact(a,work)
self.assertEqual(m['id'],identity);self.assertEqual(tuple(e),r.CMS_AUTODEPLOY_ENTRIES)
self.assertEqual(r.component_services(m['component'],e),('build-runner',))
self.assertEqual(r.component_builds(m['component'],e),())
def test_unactivated_worker_never_reads_secret(self):
with patch.object(r,'require_root'),patch.object(r,'ensure_layout'),patch.object(r,'cms_autodeploy_activated',return_value=False),patch.object(r,'cms_autodeploy_read_token') as read:
self.assertEqual(r.cms_autodeploy_tick(),0);read.assert_not_called()
def execute(self,fail=False):
with tempfile.TemporaryDirectory() as d,ExitStack() as stack:
root=Path(d);live=root/'live';identity,data=bundle();events=[]
for name in ('inbox','applied','failed','backups','state','tmp'):(root/name).mkdir()
artifact=root/'inbox/bootstrap.tgz';artifact.write_bytes(data)
for name,value in [('INBOX',root/'inbox'),('APPLIED_DIR',root/'applied'),('FAILED_DIR',root/'failed'),('BACKUPS_DIR',root/'backups'),('STATE_DIR',root/'state'),('TMP_DIR',root/'tmp'),('STATE_FILE',root/'state/applied.jsonl'),('FAILED_STATE_FILE',root/'state/failed.jsonl'),('LOCK_DIR',root/'lock')]:stack.enter_context(patch.object(r,name,value))
stack.enter_context(patch.dict(r.COMPONENTS,{'dc-cms-autodeploy':{**r.COMPONENTS['dc-cms-autodeploy'],'payload_root':live,'compose_root':live,'compose_files':(live/'docker-compose.cms-ci.yml',)}}))
for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name))
stack.enter_context(patch.object(r,'preflight_cms_autodeploy',return_value={'baseline':'test'}))
stack.enter_context(patch.object(r,'apply_cms_autodeploy',side_effect=lambda b:events.append('install')))
def accept(before):
events.append('accept')
if fail:raise r.DeployError('injected')
def rollback(target,backup,entries,stamp,before):
events.append('rollback');r.restore_platform_overlay(target,backup,entries,stamp)
stack.enter_context(patch.object(r,'accept_cms_autodeploy',side_effect=accept))
stack.enter_context(patch.object(r,'rollback_cms_autodeploy',side_effect=rollback))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail:
with self.assertRaises(r.DeployError):r.apply_artifact(artifact)
else:r.apply_artifact(artifact)
return events,r.load_state(r.STATE_FILE),r.load_state(r.FAILED_STATE_FILE)
def test_canonical_success_receipt_follows_acceptance(self):
events,applied,failed=self.execute()
self.assertEqual(events,['install','accept']);self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['sha256'],hashlib.sha256(bundle()[1]).hexdigest())
def test_canonical_failure_uses_cms_rollback(self):
events,applied,failed=self.execute(True)
self.assertEqual(events,['install','accept','rollback']);self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'],'ok:dc-cms-autodeploy-bootstrap')
def test_application_dispatch_success_and_failed_build_or_acceptance(self):
for failure in (None,'build','accept'):
with self.subTest(failure=failure),tempfile.TemporaryDirectory() as d,ExitStack() as stack:
root=Path(d);payload=root/'payload';payload.mkdir();entries,descriptor=fixture(payload)
live=root/'live';live.mkdir();fixture(live)
(live/'server/admin-server.mjs').write_bytes(b'// predecessor')
installed=r.collect_exact_files(live,entries,'test')
before={'runtime':{'imageId':'old-id','imageRef':'dc-cms-cms-app'},'descriptor':descriptor,'entries':entries,'installedFiles':installed}
for name in ('inbox','applied','failed','backups','state','tmp'):(root/name).mkdir()
artifact=root/'inbox/app.tgz'
members={'manifest.env':f"id={descriptor['releaseId']}\ncomponent=dc-cms-release\ntype=app-overlay\n".encode(),'files.txt':('\n'.join(entries)+'\n').encode(),**{'payload/'+p:(payload/p).read_bytes() for p in entries}}
with tarfile.open(artifact,'w:gz') as archive:
for name,value in members.items():
info=tarfile.TarInfo(name);info.size=len(value);info.mode=0o644;archive.addfile(info,io.BytesIO(value))
compose=live/'compose.yml';compose.write_text('fixture');events=[]
for name,value in [('INBOX',root/'inbox'),('APPLIED_DIR',root/'applied'),('FAILED_DIR',root/'failed'),('BACKUPS_DIR',root/'backups'),('STATE_DIR',root/'state'),('TMP_DIR',root/'tmp'),('STATE_FILE',root/'state/applied.jsonl'),('FAILED_STATE_FILE',root/'state/failed.jsonl'),('LOCK_DIR',root/'lock')]:stack.enter_context(patch.object(r,name,value))
stack.enter_context(patch.dict(r.COMPONENTS,{'dc-cms-release':{**r.COMPONENTS['dc-cms-release'],'payload_root':live,'compose_root':live,'compose_files':(compose,),'compose_env_file':None}}))
for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name))
stack.enter_context(patch.object(r,'preflight_cms_release',return_value=before))
def operation(name):
def call(*args,**kwargs):
events.append(name)
if name==failure:raise r.DeployError('injected '+name)
return call
stack.enter_context(patch.object(r,'build_cms_release',side_effect=operation('build')))
stack.enter_context(patch.object(r,'run_cms_release_compose',side_effect=operation('compose')))
stack.enter_context(patch.object(r,'run_healthchecks',side_effect=operation('health')))
def accept(b,rollback=False):
if rollback:
events.append('rollback-accept');self.assertEqual(r.collect_exact_files(live,entries,'restored'),installed)
else:operation('accept')()
stack.enter_context(patch.object(r,'accept_cms_release',side_effect=accept))
stack.enter_context(patch.object(r.subprocess,'run',side_effect=operation('tag')))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if failure:
with self.assertRaises(r.DeployError):r.apply_artifact(artifact)
self.assertEqual(r.load_state(r.FAILED_STATE_FILE)[0]['rollback_status'],'ok:dc-cms-release')
self.assertFalse(r.load_state(r.STATE_FILE));self.assertEqual(events[-1],'rollback-accept')
else:
r.apply_artifact(artifact);self.assertEqual(events,['build','compose','health','accept']);self.assertEqual(len(r.load_state(r.STATE_FILE)),1)
if __name__=='__main__':unittest.main()
-146
View File
@@ -1,146 +0,0 @@
"""Untrusted API/ZIP boundaries and complete source lineage."""
import copy
import hashlib
import io
import json
import stat
import unittest
from unittest import mock
import zipfile
import urllib.request
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW
from gitea_source import GiteaSource, SourceError, NoRedirect, strict_json, unpack_artifact
A, B, C = 'a'*40, 'b'*40, 'c'*40
def run(number=8, sha=B):
return dict(id=number, run_number=number, run_attempt=1, head_sha=sha,
event='push', head_branch='master', path=WORKFLOW, status='completed', conclusion='success',
repository={'id':33, 'full_name':REPOSITORY})
def job(r):
return dict(id=8, run_id=r['id'], head_sha=r['head_sha'], head_branch='master', run_attempt=1,
name='qualify', labels=['nodedc-node22-build'], runner_id=2, runner_name='synology-cms-build', status='completed', conclusion='success',
steps=[dict(name=n,status='completed',conclusion='success') for n in
('Check the exact pushed commit','Retain the qualified release in this Gitea run')])
def packed(r, mutate=None, names=None):
name='nodedc-dc-cms-release-v1-r'+str(r['id'])+'-'+r['head_sha']+'.tgz'
data=b'qualified tgz fixture'
receipt=dict(artifact=name,sourceCommit=r['head_sha'],runId=r['id'],runNumber=r['run_number'],
deployed=False,sha256=hashlib.sha256(data).hexdigest())
if mutate:mutate(receipt)
out=io.BytesIO()
with zipfile.ZipFile(out,'w') as z:
z.writestr(name,data)
z.writestr('release.json',json.dumps(receipt))
for n in names or []:z.writestr(n,b'extra')
return out.getvalue()
class SourceTests(unittest.TestCase):
def setUp(self):self.s=GiteaSource('a'*40,runner_id=2)
def test_no_redirects_or_unapproved_routes(self):
with self.assertRaises(SourceError):NoRedirect().redirect_request(None,None,302,'',{},'https://other/')
for path in ['/../../user','/actions/runs?token=a','//user','/branches/other','/actions/artifacts/1/zip%3f']:
with self.subTest(path=path),self.assertRaises(SourceError):self.s.request(path)
def test_observed_signed_download_redirect_strips_persistent_token(self):
url='https://git.dcserve.ru/api/v1/repos/SILVER/DC_CMS/actions/artifacts/6/zip'
target=url+'/raw?sig='+'a'*43+'&expires=1790708000'
req=urllib.request.Request(url,headers={'Authorization':'token '+'b'*40})
redirected=NoRedirect().redirect_request(req,None,302,'',{},target)
self.assertIsNone(redirected.get_header('Authorization'))
self.assertEqual(redirected.full_url,target)
for bad in [target.replace('git.dcserve.ru','example.com'),target.replace('/6/','/7/'),
target+'&extra=1',target+'&sig='+'c'*43,target.replace('https:','http:')]:
with self.subTest(url=bad),self.assertRaises(SourceError):NoRedirect().redirect_request(req,None,302,'',{},bad)
with self.assertRaises(SourceError):NoRedirect().redirect_request(redirected,None,302,'',{},target)
def test_duplicate_json_keys_and_token_format(self):
for value in [b'{"id":1,"id":2}',b'invalid',b'\xff']:
with self.assertRaises(SourceError):strict_json(value)
for token in ['', 'A'*40,'a'*40+'\n','secret']:
with self.assertRaises(SourceError):GiteaSource(token)
def test_paginated_complete_unique(self):
with mock.patch.object(self.s,'request',side_effect=[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=51,items=[dict(id=51)])]) as get:
self.assertEqual(len(self.s.pages('/actions/runs','items')),51)
self.assertEqual(get.call_args.args[0],'/actions/runs?page=2&limit=50')
def test_partial_changed_and_duplicate_pages_fail(self):
scenarios=[
[dict(total_count=2,items=[dict(id=1)])],
[dict(total_count=2,items=[dict(id=1),dict(id=1)])],
[dict(total_count=True,items=[])],
[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=50,items=[])],
]
for pages in scenarios:
with self.subTest(pages=len(pages)),mock.patch.object(self.s,'request',side_effect=pages),self.assertRaises(SourceError):self.s.pages('/actions/runs','items')
def test_run_nested_repository_identity_not_broken_top_level_field(self):
r=run();r['repository_id']=0;self.s.validate_run(r)
r['repository']['id']=39
with self.assertRaises(SourceError):self.s.validate_run(r)
def test_discovery_rejects_change_between_complete_scans(self):
with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[run()],[run(),run(9,C)]]),self.assertRaises(SourceError):self.s.discover()
def test_discovery_allows_status_progress_without_loss(self):
pending=run();pending.update(status='in_progress',conclusion=None)
with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[pending],[run()]]):self.assertEqual(self.s.discover(),[run()])
def test_success_must_have_exact_job_and_steps(self):
r=run();row=dict(id=8,number=8,sha=B,attempt=1)
with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[job(r)]):self.assertEqual(self.s.successful_run(row),r)
for field,value in [('runner_id',1),('runner_id',True),('runner_name','synology-device-core-build'),('labels',['ubuntu-latest']),('steps',[]),('head_sha',A),('conclusion','failure')]:
j=job(r);j[field]=value
with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[j]),self.assertRaises(SourceError):self.s.successful_run(row)
def test_qualification_requires_explicit_registered_runner(self):
for invalid in (0, True, -1, '2', 2**53):
with self.assertRaises(SourceError):GiteaSource('a'*40,runner_id=invalid)
with self.assertRaisesRegex(SourceError, 'registered_runner_identity_required'):
GiteaSource('a'*40).successful_run(dict(id=8,number=8,sha=B,attempt=1))
# Registration numbers are allocated by Gitea, never fixed at 1 or 2.
source=GiteaSource('a'*40,runner_id=17);j=job(run());j['runner_id']=17
with mock.patch.object(source,'run',return_value=run()),mock.patch.object(source,'pages',return_value=[j]):
self.assertEqual(source.successful_run(dict(id=8,number=8,sha=B,attempt=1)),run())
def test_ancestry_proves_both_edges_and_stable_main(self):
graph={C:[B],B:[A],A:[]}
def get(path):
sha=path.rsplit('/',1)[1]
return dict(sha=sha,parents=[dict(sha=p) for p in graph[sha]])
with mock.patch.object(self.s,'request',side_effect=get),mock.patch.object(self.s,'main_commit',return_value=C):
self.assertEqual(self.s.prove_lineage(A,B),C)
with self.assertRaises(SourceError):self.s.prove_lineage(B,A)
with self.assertRaises(SourceError):self.s.prove_lineage(B,B)
with mock.patch.object(self.s,'ancestor',return_value=True),mock.patch.object(self.s,'main_commit',side_effect=[B,C]),self.assertRaises(SourceError):self.s.prove_lineage(A,B)
def test_ancestry_malformed_and_bound(self):
with mock.patch.object(self.s,'request',return_value=dict(sha=B,parents=[dict(sha=C)])),self.assertRaisesRegex(SourceError,'ancestry_limit'):self.s.ancestor(A,B,limit=1)
with mock.patch.object(self.s,'request',return_value=dict(sha=C,parents=[])),self.assertRaisesRegex(SourceError,'commit_identity'):self.s.ancestor(A,B)
def test_zip_requires_exact_receipt_and_only_two_files(self):
r=run();receipt,data=unpack_artifact(packed(r),r)
self.assertEqual(receipt['sha256'],hashlib.sha256(data).hexdigest())
for change in [lambda d:d.update(sourceCommit=A),lambda d:d.update(deployed=True),lambda d:d.update(sha256='f'*64),lambda d:d.update(extra='value')]:
with self.assertRaises(SourceError):unpack_artifact(packed(r,change),r)
for name in ['../../script','runtime/token','.DS_Store']:
with self.assertRaises(SourceError):unpack_artifact(packed(r,names=[name]),r)
with self.assertRaises(SourceError):unpack_artifact(b'bad zip',r)
def test_artifact_owner_download_digest_bound_to_run(self):
r=run();blob=packed(r)
a=dict(id=8,name='dc-cms-release',workflow_run=dict(id=8,repository_id=33,head_sha=B),expired=False,size_in_bytes=len(blob))
with mock.patch.object(self.s,'pages',return_value=[a]),mock.patch.object(self.s,'request',return_value=blob):self.assertEqual(self.s.artifact(r)[0]['sourceCommit'],B)
a['workflow_run']['repository_id']=39
with mock.patch.object(self.s,'pages',return_value=[a]),self.assertRaises(SourceError):self.s.artifact(r)
if __name__=='__main__':unittest.main()
-247
View File
@@ -1,247 +0,0 @@
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
from test_runner import r
from build_runtime_reconciliation import bundle
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID, WORKFLOW
from controller import Controller
def old_fields():
return {'host':{'Binds':['/source/a:/a:rw','/source/b:/b:rw'],
'Dns':[],'DnsOptions':[],'DnsSearch':[], 'NetworkMode':'cms-edge',
'ReadonlyRootfs':False,'PortBindings':{}},
'config':{'Env':['TOKEN=fixture-never-print'],'Cmd':['npm','run','admin']},
'mounts':[{'Source':'/source/a','Destination':'/a','RW':True}], 'networks':['cms-edge']}
def sample(fields=None, identity='new'):
fields=copy.deepcopy(fields or old_fields())
return {'fields':fields,'runtime':{'id':identity,'imageId':'old-image','imageRef':'dc-cms-cms-app',
'configSha256':r.cms_audit_digest(fields)}}
def incident():
return {'runtime':sample(identity='old')['runtime'],'installedFiles':{'server/app.mjs':'sha'},
'installedMetadata':{},'foundation':{},'data':{},'otherServices':{}}
def changed_sample():
fields=old_fields();fields['host']['Binds'].reverse()
for key in r.CMS_DNS_FIELDS:fields['host'][key]=None
return sample(fields)
class ReconciliationTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.root=Path(self.tmp.name)
self.artifact=self.root/'candidate.tgz';self.artifact.write_bytes(bundle()[1])
unpack=self.root/'unpack';unpack.mkdir()
self.manifest,self.entries,self.payload=r.load_artifact(self.artifact,unpack)
def acceptance(self,stack):
before=incident()
for name,value in [('cms_healthchecks',None),('cms_foundation',{}),('cms_preserved_data',{}),
('cms_other_services',{}),('cms_application_inventory',(before['installedFiles'],{})),
('cms_image_files',before['installedFiles']),('cms_r39_evidence',before),
('cms_audit_sample',changed_sample())]:
stack.enter_context(patch.object(r,name,return_value=value))
return before
def test_fixed_data_only_artifact_and_no_service_or_build_authority(self):
self.assertEqual(self.artifact.read_bytes(),bundle()[1])
self.assertEqual(self.entries,[r.CMS_RECON_ENTRY])
self.assertEqual(self.manifest['id'],r.CMS_RECON_ID)
self.assertEqual(r.component_services(self.manifest['component'],self.entries),())
self.assertEqual(r.component_builds(self.manifest['component'],self.entries),())
self.assertEqual(r.component_compose_files(self.manifest['component']),())
for path in ['server/app.mjs','deployment/other.json','.env','projects/nodedc.json']:
with self.assertRaises(r.DeployError):r.allowed_payload_path(self.manifest['component'],path)
for key,value in [('runtimeFingerprintVersion',1),('mode','restart'),('failedSha256','a'*64),('extra',True)]:
descriptor=r.cms_reconciliation_descriptor();descriptor[key]=value
(self.payload/r.CMS_RECON_ENTRY).write_text(json.dumps(descriptor))
with self.assertRaises(r.DeployError):r.validate_cms_reconciliation_payload(self.payload,self.entries,r.CMS_RECON_ID)
def test_only_evidenced_representation_changes_are_equal(self):
old=old_fields();new=changed_sample()['fields'];saved=copy.deepcopy(new)
self.assertNotEqual(r.cms_audit_digest(old),r.cms_audit_digest(new))
self.assertEqual(r.cms_runtime_fields_v2(old),r.cms_runtime_fields_v2(new))
self.assertLessEqual(r.cms_r39_representation_proof(new,r.cms_audit_digest(old)),16)
self.assertEqual(new,saved)
def test_real_dns_env_mount_port_network_and_security_drift_remain_rejected(self):
old=old_fields();variants=[]
for section,key,value in [('config','Env',['TOKEN=changed']),('config','Cmd',['other']),
('host','Dns',['1.1.1.1']),('host','DnsOptions',['ndots:2']),
('host','DnsSearch',['internal']),('host','NetworkMode','other'),
('host','ReadonlyRootfs',True),('host','PortBindings',{'80/tcp':[]}),
('host','Binds',['/different:/a:rw','/source/b:/b:rw'])]:
fields=changed_sample()['fields'];fields[section][key]=value;variants.append(fields)
fields=changed_sample()['fields'];fields['mounts'][0]['RW']=False;variants.append(fields)
fields=changed_sample()['fields'];fields['networks'].append('other');variants.append(fields)
for fields in variants:
self.assertNotEqual(r.cms_runtime_fields_v2(old),r.cms_runtime_fields_v2(fields))
with self.assertRaises(r.DeployError):r.cms_r39_representation_proof(fields,r.cms_audit_digest(old))
fields=old_fields();fields['host']['Dns']=['1.1.1.1','8.8.8.8']
reversed_fields=copy.deepcopy(fields);reversed_fields['host']['Dns'].reverse()
self.assertNotEqual(r.cms_runtime_fields_v2(fields),r.cms_runtime_fields_v2(reversed_fields))
def test_ambiguous_binds_and_missing_or_malformed_dns_fail_closed(self):
for binds in [[],None,['a:/a:rw'],['/a:/a:'],['/a:/a:rw','/b:/a:rw'],['/a:/a/../b:rw'],['/a:/a:rw\0']]:
fields=old_fields();fields['host']['Binds']=binds
with self.assertRaises(r.DeployError):r.cms_runtime_fields_v2(fields)
for value in ['',{},False,0,['valid',1]]:
fields=old_fields();fields['host']['Dns']=value
with self.assertRaises(r.DeployError):r.cms_runtime_fields_v2(fields)
fields=old_fields();del fields['host']['Dns']
with self.assertRaises(r.DeployError):r.cms_runtime_fields_v2(fields)
def test_three_stable_samples_prove_old_image_and_preserve_original_evidence(self):
before=incident();saved=copy.deepcopy(before)
with patch.object(r,'cms_audit_sample',return_value=changed_sample()),redirect_stdout(io.StringIO()) as output:
result=r.cms_r39_restored_baseline(before)
self.assertEqual(before,saved);self.assertEqual(result['runtimeFingerprintVersion'],2)
self.assertEqual(result['runtime']['configSha256'],r.cms_audit_digest(r.cms_runtime_fields_v2(old_fields())))
self.assertIn('config.Env',result['runtime']['fieldSha256'])
self.assertNotIn('fixture-never-print',output.getvalue()+json.dumps(result['runtime']))
for key,value in [('imageId','wrong-image'),('imageRef','wrong-ref')]:
changed=changed_sample();changed['runtime'][key]=value
with patch.object(r,'cms_audit_sample',return_value=changed),self.assertRaises(r.DeployError):r.cms_r39_restored_baseline(before)
other=changed_sample();other['runtime']['id']='another-generation'
with patch.object(r,'cms_audit_sample',side_effect=[changed_sample(),other,changed_sample()]),self.assertRaisesRegex(r.DeployError,'changed during'):
r.cms_r39_restored_baseline(before)
def test_legacy_acceptance_stays_strict_new_acceptance_uses_version_two(self):
with ExitStack() as stack:
before=self.acceptance(stack)
stack.enter_context(patch.object(r,'cms_runtime_snapshot',return_value=changed_sample()['runtime']))
with self.assertRaisesRegex(r.DeployError,'environment'):r.accept_cms_release(before,rollback=True)
stack.enter_context(redirect_stdout(io.StringIO()))
restored=r.cms_r39_restored_baseline(before)
r.accept_cms_release(restored,rollback=True)
for version in [True,0,3,'2']:
with self.assertRaisesRegex(r.DeployError,'version mismatch'):r.accept_cms_release({**restored,'runtimeFingerprintVersion':version},rollback=True)
newer=changed_sample();newer['fields']['config']['Env']=['TOKEN=changed']
with patch.object(r,'cms_audit_sample',return_value=newer),self.assertRaisesRegex(r.DeployError,'config.Env') as error:
r.accept_cms_release(restored,rollback=True)
self.assertNotIn('TOKEN',str(error.exception))
def test_preflight_for_new_release_captures_versioned_field_hashes(self):
with ExitStack() as stack:
for name,value in [('require_root',None),('validate_cms_release_payload',{'sourceCommit':'new','runNumber':2}),
('cms_installed_release',{'sourceCommit':'old','runNumber':0}),
('cms_application_inventory',({'app':'sha'},{})),('cms_healthchecks',None),
('cms_foundation',{}),('cms_preserved_data',{}),('cms_other_services',{}),
('cms_runtime_snapshot_v2',{'fieldSha256':{'config.Env':'sha'}}),
('cms_resolve_build_base',{'imageId':'fixture-base'})]:
stack.enter_context(patch.object(r,name,return_value=value))
legacy=stack.enter_context(patch.object(r,'cms_runtime_snapshot'))
result=r.preflight_cms_release(self.payload,['app'],'new')
self.assertEqual(result['runtimeFingerprintVersion'],2);legacy.assert_not_called()
self.assertEqual(result['runtime']['fieldSha256'],{'config.Env':'sha'})
def test_failed_receipt_is_exact_and_cannot_be_relabelled(self):
row=r.cms_r39_failed_row()
with patch.object(r,'load_state',return_value=[row]),patch.object(r,'cms_audit_evidence',return_value={'runtime':{'configSha256':r.CMS_RECON_LEGACY_SHA}}):
self.assertEqual(r.cms_r39_evidence()['runtime']['configSha256'],r.CMS_RECON_LEGACY_SHA)
row['rollback_status']='ok:dc-cms-release'
with self.assertRaises(r.DeployError):r.cms_r39_evidence()
with patch.object(r,'load_state',return_value=[]),patch.object(r,'CMS_ROOT',self.payload):
self.assertFalse(r.cms_r39_reconciled(r.cms_r39_failed_row()))
self.assertFalse(r.cms_r39_reconciled({**r.cms_r39_failed_row(),'id':'other'}))
def test_source_barrier_requires_separate_canonical_reconciliation(self):
expected={**r.CMS_BASELINE['filesSha256'],**{p:r.CMS_BASELINE['foundationSha256'][p] for p in r.CMS_DEPENDENCY_FILES}}
with ExitStack() as stack:
stack.enter_context(patch.object(r,'load_state',side_effect=lambda path:[r.cms_r39_failed_row()] if path==r.FAILED_STATE_FILE else []))
stack.enter_context(patch.object(r,'cms_application_inventory',return_value=(expected,{})))
stack.enter_context(patch.object(r,'cms_foundation'))
proof=stack.enter_context(patch.object(r,'cms_r39_reconciled',return_value=False))
with self.assertRaisesRegex(r.DeployError,'reconciliation'):r.cms_installed_release()
proof.return_value=True
self.assertEqual(r.cms_installed_release()['sourceCommit'],r.CMS_BASELINE['sourceCommit'])
proof.assert_called_with(r.cms_r39_failed_row())
def execute_apply(self, fail=False):
live=self.root/'live';live.mkdir()
for name in ('inbox','applied','failed','backups','state','tmp'):(self.root/name).mkdir()
with ExitStack() as stack:
self.acceptance(stack)
for name,value in [('CMS_ROOT',live),('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),
('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),
('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),
('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),
('LOCK_DIR',self.root/'state/deploy.lock')]:stack.enter_context(patch.object(r,name,value))
stack.enter_context(patch.dict(r.COMPONENTS,{self.manifest['component']:{**r.COMPONENTS[self.manifest['component']],'payload_root':live}}))
for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name))
def health():
if fail and (live/r.CMS_RECON_ENTRY).exists():raise r.DeployError('injected post-copy health failure')
stack.enter_context(patch.object(r,'cms_healthchecks',side_effect=health))
command=stack.enter_context(patch.object(r.subprocess,'run'))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail:
with self.assertRaises(r.DeployError):r.apply_artifact(self.artifact)
self.assertFalse((live/r.CMS_RECON_ENTRY).exists())
self.assertFalse(r.load_state(r.STATE_FILE))
self.assertEqual(r.load_state(r.FAILED_STATE_FILE)[0]['rollback_status'],'ok:dc-cms-runtime-reconciliation-marker-only')
else:
r.apply_artifact(self.artifact)
self.assertTrue(r.cms_r39_reconciled(r.cms_r39_failed_row()))
row=r.load_state(r.STATE_FILE)[0];archive=r.APPLIED_DIR/row['artifact']
archive.write_bytes(archive.read_bytes()+b'changed')
with self.assertRaises(r.DeployError):r.cms_r39_reconciled(r.cms_r39_failed_row())
command.assert_not_called()
def test_full_apply_proves_restoration_and_requires_archive_receipt_marker(self):self.execute_apply()
def test_failed_apply_rolls_back_marker_without_runtime_mutation(self):self.execute_apply(fail=True)
class ReconciledQueueTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.q=DeploymentQueue(Path(self.tmp.name)/'queue.db',first_run_number=1);self.addCleanup(self.q.close)
self.sha='c9d8f0ae59211ce3443300acfea311907508261a'
self.run={'id':39,'run_number':1,'head_sha':self.sha,'run_attempt':1,'status':'completed','conclusion':'success','event':'push','head_branch':'master','path':WORKFLOW}
self.q.observe([self.run],repository=REPOSITORY,repository_id=REPOSITORY_ID)
self.artifact='nodedc-'+r.CMS_AUDIT_FAILED_ID+'.tgz'
self.q.reserve(39,digest=r.CMS_AUDIT_FAILED_SHA,artifact=self.artifact)
self.q.reconcile(39,digest=r.CMS_AUDIT_FAILED_SHA,artifact=self.artifact,outcome='ambiguous',receipt='canonical-rollback-unconfirmed')
self.kw={'digest':r.CMS_AUDIT_FAILED_SHA,'artifact':self.artifact,'receipt':'canonical-reconciled:'+r.CMS_RECON_ID}
def test_exact_recovery_is_terminal_idempotent_and_not_replayed_on_observe(self):
self.q.reconcile_r39(39,**self.kw);self.q.reconcile_r39(39,**self.kw)
self.assertEqual(self.q.snapshot()[0]['phase'],'failed')
self.q.observe([self.run],repository=REPOSITORY,repository_id=REPOSITORY_ID)
self.assertIsNone(self.q.next_ready())
with self.assertRaises(QueueError):self.q.reserve(39,digest=r.CMS_AUDIT_FAILED_SHA,artifact=self.artifact)
following={**self.run,'id':40,'run_number':2,'head_sha':'a'*40}
self.q.observe([self.run,following],repository=REPOSITORY,repository_id=REPOSITORY_ID)
self.assertEqual(self.q.next_ready()['id'],40)
self.assertEqual(self.q.snapshot()[0]['phase'],'failed')
def test_missing_or_wrong_proof_cannot_release_blocked_row(self):
for key,value in [('receipt','canonical-reconciled:other'),('digest','a'*64),('artifact','other.tgz')]:
with self.assertRaises(QueueError):self.q.reconcile_r39(39,**{**self.kw,key:value})
self.assertEqual(self.q.snapshot()[0]['phase'],'blocked')
with self.assertRaises(QueueError):self.q.reconcile_r39(40,**self.kw)
self.q.db.execute("UPDATE runs SET receipt='different' WHERE id=39")
with self.assertRaises(QueueError):self.q.reconcile_r39(39,**self.kw)
def test_controller_waits_for_canonical_receipt_then_never_applies_old_release(self):
source=Mock();source.discover.return_value=[self.run]
installer=Mock();installer.receipt.return_value=('ambiguous','canonical-rollback-unconfirmed')
controller=Controller(self.q,source,installer)
with self.assertRaisesRegex(QueueError,'reconciliation_required'):controller.tick()
installer.receipt.return_value=('rolled-back',self.kw['receipt'])
self.assertEqual(controller.tick(),{'status':'waiting'})
self.assertEqual(self.q.snapshot()[0]['phase'],'failed')
installer.apply.assert_not_called();installer.stage.assert_not_called()
if __name__=='__main__':unittest.main()
@@ -1,76 +0,0 @@
"""The qualification runner is allocated at registration, never Device Core's ID."""
from contextlib import ExitStack
import json
import os
from pathlib import Path
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
from test_runner import r
class RegisteredRunnerTests(unittest.TestCase):
def fixture(self, root):
data=root/'data';data.mkdir(mode=0o700)
registration=data/'.runner'
value={'id':2,'name':'synology-cms-build','address':'https://git.dcserve.ru',
'uuid':'fixture-uuid','token':'fixture-private-token'}
registration.write_text(json.dumps(value));registration.chmod(0o600)
return registration,value
def read(self, root, *, file_owner=0, directory_owner=0, links=None):
# Local tests run without root. Only ownership is emulated; modes, file
# descriptors, symlink protection and content reads use real temp files.
original_lstat=Path.lstat;original_fstat=os.fstat
def fields(value, **changes):
result={name:getattr(value,name) for name in ('st_mode','st_uid','st_nlink','st_size','st_mtime_ns','st_ctime_ns')}
return SimpleNamespace(**{**result,**changes})
def lstat(path, *args, **kwargs):
value=original_lstat(path,*args,**kwargs)
return fields(value,st_uid=directory_owner) if path==root/'data' else value
def fstat(fd):
value=original_fstat(fd)
return fields(value,st_uid=file_owner,st_nlink=value.st_nlink if links is None else links)
with patch.object(r,'CMS_CI_ROOT',root),patch.object(Path,'lstat',lstat),patch.object(r.os,'fstat',fstat):
return r.cms_ci_registered_runner_id()
def test_allocated_id_is_read_from_registered_private_identity(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d).resolve();p,value=self.fixture(root)
for identity in (2,17,293):
value['id']=identity;p.write_text(json.dumps(value))
self.assertEqual(self.read(root),identity)
def test_identity_metadata_must_remain_private_and_single_link(self):
for kwargs in ({'file_owner':501},{'directory_owner':501},{'links':2}):
with self.subTest(kwargs=kwargs),tempfile.TemporaryDirectory() as d:
root=Path(d).resolve();self.fixture(root)
with self.assertRaises(r.DeployError):self.read(root,**kwargs)
for rel,mode in (('data',0o755),('data/.runner',0o644)):
with self.subTest(path=rel),tempfile.TemporaryDirectory() as d:
root=Path(d).resolve();self.fixture(root);(root/rel).chmod(mode)
with self.assertRaises(r.DeployError):self.read(root)
def test_other_daemon_or_origin_and_invalid_id_are_rejected(self):
for key,value in (('id',True),('id',0),('id','2'),('id',2**53),('name','synology-device-core-build'),
('address','https://other.example'),('uuid',''),('token','')):
with self.subTest(key=key,value=value),tempfile.TemporaryDirectory() as d:
root=Path(d).resolve();p,identity=self.fixture(root)
identity[key]=value;p.write_text(json.dumps(identity))
with self.assertRaises(r.DeployError):self.read(root)
def test_registration_symlink_is_rejected_without_reading_target(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d).resolve();p,_=self.fixture(root)
target=root/'other';p.rename(target);p.symlink_to(target)
with self.assertRaises(OSError):self.read(root)
def test_registration_input_is_bounded_and_malformed_data_is_rejected(self):
for data in ('x'*16385,'not JSON','[]'):
with self.subTest(length=len(data)),tempfile.TemporaryDirectory() as d:
root=Path(d).resolve();p,_=self.fixture(root);p.write_text(data)
with self.assertRaises(r.DeployError):self.read(root)
if __name__=='__main__':unittest.main()
-95
View File
@@ -1,95 +0,0 @@
import ast
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
RUNNER=ROOT/'infra/deploy-runner/nodedc-deploy'
loader=importlib.machinery.SourceFileLoader('cms_runner',str(RUNNER))
spec=importlib.util.spec_from_loader(loader.name,loader)
r=importlib.util.module_from_spec(spec);loader.exec_module(r)
def fixture(root):
files={p:b'// fixture' for p in ('admin/index.html','admin/admin.js','admin/admin.css','admin/nodedc-logo.svg','server/admin-server.mjs','server/site-app.mjs','server/multisite-server.mjs')}
for p in r.CMS_DEPENDENCY_FILES:files[p]=(ROOT/'infra/cms-deploy/fixtures'/p).read_bytes()
d={'schemaVersion':'nodedc.dc-cms.release.v1','releaseId':'dc-cms-release-v1-r1-'+'a'*40,'repository':'SILVER/DC_CMS','repositoryId':33,'branch':'master','sourceCommit':'a'*40,'runId':1,'runNumber':1,'qualification':{'status':'qualified','steps':['frozen-install','syntax','multisite-tests'],'deployed':False},'foundationSha256':{k:v for k,v in r.CMS_FOUNDATION.items() if k!='infra/reverse-proxy/Caddyfile'},'filesSha256':{p:r.hashlib.sha256(v).hexdigest() for p,v in files.items()}}
files[r.CMS_RELEASE_ENTRY]=(json.dumps(d)+'\n').encode()
for p,data in files.items():
(root/p).parent.mkdir(parents=True,exist_ok=True);(root/p).write_bytes(data)
return sorted(files),d
class CmsRunnerTests(unittest.TestCase):
def test_fixed_scope(self):
with tempfile.TemporaryDirectory() as tmp:
entries,d=fixture(Path(tmp))
self.assertEqual(r.component_services('dc-cms-release',entries),('cms-app',))
self.assertEqual(r.validate_cms_release_payload(Path(tmp),entries,d['releaseId']),d)
for path in ('projects/nodedc.json','server/data/a.js','server/.env','admin/uploads/a.js','admin/../server/a.js','Dockerfile','infra/docker-compose.yml','server/cms-release.json/extra'):
with self.subTest(path=path),self.assertRaises(r.DeployError):r.allowed_payload_path('dc-cms-release',path)
self.assertEqual(r.component_services('dc-cms-autodeploy',r.CMS_AUTODEPLOY_ENTRIES),('build-runner',))
def test_descriptor_identity_foundation_and_digest(self):
for key,value in [('repositoryId',38),('branch','main'),('runId',True),('sourceCommit','short'),('filesSha256',{}),('foundationSha256',{}),('qualification',{'status':'qualified'})]:
with self.subTest(key=key),tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);entries,d=fixture(root);identity=d['releaseId'];d[key]=value
(root/r.CMS_RELEASE_ENTRY).write_text(json.dumps(d))
with self.assertRaises(r.DeployError):r.validate_cms_release_payload(root,entries,identity)
def test_bootstrap_descriptor_exact_bytes(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);p=root/r.CMS_AUTODEPLOY_ENTRY;p.parent.mkdir()
for name in r.CMS_CI_SOURCE_SHA256:(root/name).write_bytes((ROOT/'infra/cms-deploy'/name).read_bytes())
p.write_text(json.dumps(r.CMS_AUTODEPLOY_DESCRIPTOR,indent=2,sort_keys=True)+'\n')
r.validate_cms_autodeploy_payload(root,r.CMS_AUTODEPLOY_ENTRIES,r.CMS_AUTODEPLOY_ID)
p.write_text(p.read_text()+' ')
with self.assertRaises(r.DeployError):r.validate_cms_autodeploy_payload(root,r.CMS_AUTODEPLOY_ENTRIES,r.CMS_AUTODEPLOY_ID)
self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['repositoryId'],33)
self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['branch'],'master')
self.assertIn('--dc-cms-autodeploy-tick',r.cms_autodeploy_units()[r.CMS_AUTODEPLOY_SERVICE])
self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['publishedPorts'],[])
def test_no_dependency_recreation_or_rollback_rebuild(self):
with patch.object(r.subprocess,'run') as run:
r.run_cms_release_compose()
cmd=run.call_args.args[0]
self.assertEqual(cmd[-8:],['up','-d','--force-recreate','--no-build','--pull','never','--no-deps','cms-app'])
before={'runtime':{'imageId':'old-id','imageRef':'dc-cms-cms-app'}}
with patch.object(r,'restore_platform_overlay') as restore,patch.object(r.subprocess,'run') as run,patch.object(r,'run_cms_release_compose') as compose,patch.object(r,'accept_cms_release') as accept:
r.rollback_cms_release('root','backup',[], 'stamp',before,True)
restore.assert_called_once();compose.assert_called_once();accept.assert_called_once_with(before,rollback=True)
self.assertEqual(run.call_args.args[0],[str(r.DOCKER),'image','tag','old-id','dc-cms-cms-app'])
def test_unrelated_domains_unchanged_except_reviewed_r46_extension(self):
old=subprocess.check_output(['git','show','27c155276a703dd4fd39385011fc5e3f86afcae4:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True)
current=RUNNER.read_text()
allowed={'allowed_payload_path','load_artifact','component_services','plan_artifact','apply_artifact','run_healthchecks','main'}
# The separately reviewed r46 recovery now changes these Device entry
# points. Its exact identity, v1/v2 compatibility and queue transitions
# are tested in device-core-deploy/test_r46_reconciliation.py.
allowed.update({'device_release_predecessor','validate_device_release_reconciliation_payload',
'preflight_device_release_reconciliation','device_release_capture_field_digests',
'device_release_runtime_drift_message','preflight_device_release','accept_device_release',
'DeviceAutodeployInstaller','device_autodeploy_library'})
old_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(old).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
current_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(current).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
for name,node in old_functions.items():
if name not in allowed:self.assertEqual(current_functions[name],node,name)
def methods(source):
cls=next(n for n in ast.parse(source).body if isinstance(n,ast.ClassDef) and n.name=='DeviceAutodeployInstaller')
return {n.name:ast.dump(n,include_attributes=False) for n in cls.body if isinstance(n,ast.FunctionDef)}
before,after=methods(old),methods(current)
for name,node in before.items():
if name!='receipt':self.assertEqual(after[name],node,name)
# None of the CMS runtime changes as part of Device recovery.
baseline=subprocess.check_output(['git','show','6cf7a91:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True)
def cms(source):return source.split('# BEGIN GENERATED CMS DEPLOYMENT\n',1)[1].split('# END GENERATED CMS DEPLOYMENT\n',1)[0]
self.assertEqual(cms(baseline),cms(current))
if __name__=='__main__':unittest.main()
-116
View File
@@ -1,116 +0,0 @@
from contextlib import ExitStack,redirect_stdout,redirect_stderr
import copy
import hashlib
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from test_runner import r
from build_runtime_audit import bundle
def fields():
return {'host':{'Binds':['/host/a:/a:ro','/host/b:/b:rw'],'Mounts':None,'NetworkMode':'cms-edge',
'PortBindings':{},'ReadonlyRootfs':False},
'config':{'Env':['PRIVATE_TOKEN=fixture-never-print'],'Cmd':['npm','run','admin']},
'mounts':[],'networks':['cms-edge','other-attached']}
class CmsAuditTests(unittest.TestCase):
def test_deterministic_data_only_archive_and_exact_scope(self):
identity,data=bundle();self.assertEqual(data,bundle()[1])
with tempfile.TemporaryDirectory() as d:
root=Path(d);artifact=root/'audit.tgz';artifact.write_bytes(data);unpack=root/'unpack';unpack.mkdir()
m,e,p=r.load_artifact(artifact,unpack)
self.assertEqual(m['id'],r.CMS_AUDIT_ID);self.assertEqual(tuple(e),(r.CMS_AUDIT_ENTRY,))
self.assertEqual(r.component_services(m['component'],e),())
self.assertEqual(r.component_builds(m['component'],e),())
(p/r.CMS_AUDIT_ENTRY).write_text('{}')
with self.assertRaises(r.DeployError):r.validate_cms_audit_payload(p,e,identity)
for name in ('server/admin-server.mjs','deployment/other.json','.env','deployment/'+r.CMS_AUDIT_ENTRY):
with self.assertRaises(r.DeployError):r.allowed_payload_path('dc-cms-runtime-audit',name)
def test_apply_refuses_audit_before_any_application_mutation(self):
with tempfile.TemporaryDirectory() as d,ExitStack() as stack:
root=Path(d)
for name in ('inbox','applied','failed','backups','state','tmp'):(root/name).mkdir()
artifact=root/'inbox/audit.tgz';artifact.write_bytes(bundle()[1])
for key,value in [('INBOX',root/'inbox'),('APPLIED_DIR',root/'applied'),('FAILED_DIR',root/'failed'),('BACKUPS_DIR',root/'backups'),('STATE_DIR',root/'state'),('TMP_DIR',root/'tmp'),('STATE_FILE',root/'state/applied.jsonl'),('FAILED_STATE_FILE',root/'state/failed.jsonl'),('LOCK_DIR',root/'lock')]:stack.enter_context(patch.object(r,key,value))
for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name))
changed=stack.enter_context(patch.object(r,'copy_payload_path'))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
with self.assertRaisesRegex(r.DeployError,'plan-only'):r.apply_artifact(artifact)
changed.assert_not_called()
def test_probe_identifies_order_but_does_not_change_or_accept_it(self):
previous=fields();current=copy.deepcopy(previous);current['host']['Binds'].reverse()
original=copy.deepcopy(current);proof=r.cms_audit_probe(current,r.cms_audit_digest(previous))
self.assertFalse(proof['exactCurrentMatch']);self.assertTrue(proof['exactPreimageFound'])
self.assertEqual(proof['changedFields'],['HostConfig.Binds']);self.assertEqual(current,original)
def test_probe_reports_attached_network_difference_without_authorizing_it(self):
previous=fields();current=copy.deepcopy(previous);current['host']['NetworkMode']='other-attached'
proof=r.cms_audit_probe(current,r.cms_audit_digest(previous))
self.assertFalse(proof['exactCurrentMatch']);self.assertTrue(proof['exactPreimageFound'])
self.assertEqual(proof['changedFields'],['HostConfig.NetworkMode'])
def test_probe_does_not_mask_real_configuration_changes(self):
original=fields()
for section,key,value in [('config','Env',['CHANGED=1']),('config','Cmd',['other']),('host','ReadonlyRootfs',True),('host','PortBindings',{'80/tcp':[{'HostPort':'80'}]})]:
current=copy.deepcopy(original);current[section][key]=value
self.assertFalse(r.cms_audit_probe(current,r.cms_audit_digest(original))['exactPreimageFound'])
def test_probe_is_bounded(self):
current=fields();current['host']['Binds']=['duplicate','duplicate']
self.assertTrue(r.cms_audit_probe(current,'a'*64)['searchTruncated'])
current['host']['Binds']=[str(i) for i in range(9)]
self.assertTrue(r.cms_audit_probe(current,'a'*64)['searchTruncated'])
self.assertTrue(r.cms_audit_probe(fields(),'a'*64,budget=1)['searchTruncated'])
def test_audit_preimage_matches_unchanged_acceptance_fingerprint(self):
info={'Id':'a'*64,'Image':'sha256:old','State':{'Running':True},'HostConfig':{'Binds':['b','a'],'Mounts':[{'Target':'z'},{'Target':'a'}],'Ulimits':[{'Name':'z'},{'Name':'a'}]},
'Config':{'Image':'dc-cms-cms-app','Env':['Z=1','A=1'],'Labels':{'com.docker.compose.project':'dc-cms','com.docker.compose.service':'cms-app'}},
'Mounts':[],'NetworkSettings':{'Networks':{'cms-edge':{}}}}
with patch.object(r,'compose_service_container_id',return_value=info['Id']),patch.object(r,'inspect_container',return_value=info):
self.assertEqual(r.cms_runtime_snapshot()['configSha256'],r.cms_audit_digest(r.cms_audit_fields(info)))
def test_report_is_read_only_and_does_not_print_environment_values(self):
runtime={'id':'container','imageId':'old-image','imageRef':'dc-cms-cms-app','configSha256':r.cms_audit_digest(fields())}
sample={'runtime':runtime,'fields':fields()}
before={'runtime':runtime,'installedFiles':{'server/app.mjs':'a'},'installedMetadata':{},'foundation':{},'data':{},'otherServices':{}}
output=io.StringIO()
with ExitStack() as stack:
for name,value in [('require_root',None),('validate_cms_audit_payload',None),('cms_audit_evidence',before),('cms_application_inventory',(before['installedFiles'],{})),('cms_foundation',{}),('cms_preserved_data',{}),('cms_other_services',{}),('cms_healthchecks',None),('cms_audit_sample',sample),('cms_image_files',before['installedFiles'])]:stack.enter_context(patch.object(r,name,return_value=value))
apply=stack.enter_context(patch.object(r,'copy_payload_path'));run=stack.enter_context(patch.object(r.subprocess,'run'))
stack.enter_context(redirect_stdout(output));report=r.cms_runtime_audit(Path('/unused'),[],r.CMS_AUDIT_ID)
apply.assert_not_called();run.assert_not_called()
self.assertFalse(report['mutation']);self.assertFalse(report['applyAllowed'])
self.assertTrue(all(v['ok'] for v in report['checks'].values()))
self.assertNotIn('fixture-never-print',output.getvalue())
def test_incident_evidence_requires_exact_journal_archive_and_backup(self):
with tempfile.TemporaryDirectory() as d,ExitStack() as stack:
root=Path(d).resolve();failed=root/'failed';failed.mkdir();backups=root/'backups';backups.mkdir()
archive=failed/('nodedc-'+r.CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125');archive.write_bytes(b'fixture archive')
digest=hashlib.sha256(archive.read_bytes()).hexdigest();backup=backups/r.CMS_AUDIT_BACKUP;backup.mkdir()
for name in r.CMS_AUDIT_BACKUP_SHA:(backup/name).write_bytes(b'fixture backup')
(backup/'cms-runtime-before.json').write_text('{"fixture": true}')
hashes={name:hashlib.sha256((backup/name).read_bytes()).hexdigest() for name in r.CMS_AUDIT_BACKUP_SHA}
row={'id':r.CMS_AUDIT_FAILED_ID,'sha256':digest,'backup_id':r.CMS_AUDIT_BACKUP,'component':'dc-cms-release',
'status':'failed','started_apply':True,'rollback_status':'failed:DeployError','artifact':archive.name,
'message':'CMS environment, mounts, ports or network topology changed'}
for name,value in [('FAILED_DIR',failed),('BACKUPS_DIR',backups),('CMS_AUDIT_FAILED_SHA',digest),('CMS_AUDIT_BACKUP_SHA',hashes)]:stack.enter_context(patch.object(r,name,value))
stack.enter_context(patch.object(r,'load_state',side_effect=lambda path:[row] if path==r.FAILED_STATE_FILE else []))
self.assertEqual(r.cms_audit_evidence(),{'fixture':True})
row['rollback_status']='ok:dc-cms-release'
with self.assertRaisesRegex(r.DeployError,'receipt differs'):r.cms_audit_evidence()
row['rollback_status']='failed:DeployError'
archive.write_bytes(b'changed')
with self.assertRaisesRegex(r.DeployError,'archive mismatch'):r.cms_audit_evidence()
archive.write_bytes(b'fixture archive');(backup/'source-before.tgz').write_bytes(b'changed')
with self.assertRaisesRegex(r.DeployError,'backup differs'):r.cms_audit_evidence()
if __name__=='__main__':unittest.main()
-112
View File
@@ -1,112 +0,0 @@
"""Regression for POSIX-only @eaDir files observed on the production NAS."""
from contextlib import ExitStack
import hashlib
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from unittest.mock import patch
from test_runner import r
class SynologyMetadataTests(unittest.TestCase):
def initial(self, root):
for rel in r.CMS_BASELINE['filesSha256']:
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text('predecessor: ' + rel)
for rel in r.CMS_BASELINE['foundationSha256']:
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text('foundation: ' + rel)
(root / 'infra/.env.synology').write_text('TEST_ONLY=1\n')
baseline = {'sourceCommit':r.CMS_BASELINE['sourceCommit']}
for key in ('filesSha256', 'foundationSha256'):
baseline[key] = {rel:hashlib.sha256((root/rel).read_bytes()).hexdigest()
for rel in r.CMS_BASELINE[key]}
stream = root / 'server/@eaDir/admin-server.mjs@SynoEAStream'
stream.parent.mkdir(mode=0o777)
stream.write_bytes(b'NAS extended attribute fixture')
stream.chmod(0o777)
return baseline, stream
def initial_check(self, root, baseline):
with patch.object(r, 'CMS_ROOT', root), patch.object(r, 'CMS_BASELINE', baseline), patch.object(r, 'load_state', return_value=[]):
return r.cms_installed_release()
def test_initial_predecessor_with_posix_only_metadata(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
baseline, stream = self.initial(root)
self.assertEqual(self.initial_check(root, baseline)['sourceCommit'], baseline['sourceCommit'])
with patch.object(r, 'CMS_ROOT', root):
app, metadata = r.cms_application_inventory()
self.assertNotIn(stream.relative_to(root).as_posix(), app)
self.assertEqual(metadata, {stream.relative_to(root).as_posix():hashlib.sha256(stream.read_bytes()).hexdigest()})
def test_actual_source_drift_still_fails_with_actionable_paths(self):
for mutation, expected in [('change','changed'), ('extra','unexpected'), ('remove','missing')]:
with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as d:
root = Path(d)
baseline, _ = self.initial(root)
if mutation == 'change': (root/'admin/admin.js').write_text('unauthorized')
elif mutation == 'extra': (root/'server/unexpected.mjs').write_text('unauthorized')
else: (root/'admin/index.html').unlink()
with self.assertRaisesRegex(r.DeployError, expected):
self.initial_check(root, baseline)
def test_unknown_or_orphaned_metadata_is_rejected(self):
for rel in ('server/@eaDir/code.mjs', 'server/@eaDir/missing.mjs@SynoEAStream',
'server/@eaDir/nested/admin-server.mjs@SynoEAStream', 'admin/@eaDir/.env@SynoEAStream'):
with self.subTest(rel=rel), tempfile.TemporaryDirectory() as d:
root = Path(d)
baseline, _ = self.initial(root)
extra = root/rel
extra.parent.mkdir(parents=True, exist_ok=True)
extra.write_text('unexpected')
with self.assertRaises(r.DeployError): self.initial_check(root, baseline)
def test_metadata_symlinks_still_fail(self):
for whole_directory in (False, True):
with self.subTest(directory=whole_directory), tempfile.TemporaryDirectory() as d:
root = Path(d)
baseline, stream = self.initial(root)
stream.unlink()
if whole_directory:
stream.parent.rmdir()
stream.parent.symlink_to(root/'admin', target_is_directory=True)
else:
stream.symlink_to(root/'server/admin-server.mjs')
with self.assertRaisesRegex(r.DeployError, 'unsafe'):
self.initial_check(root, baseline)
def test_runtime_inventory_executes_with_and_without_old_metadata(self):
node = shutil.which('node')
self.assertIsNotNone(node, 'node is required to verify the in-container inventory program')
run = subprocess.run
for with_metadata in (False, True):
with self.subTest(metadata=with_metadata), tempfile.TemporaryDirectory() as d:
root = Path(d)
baseline, stream = self.initial(root)
if not with_metadata:
stream.unlink();stream.parent.rmdir()
def execute(cmd, **kwargs):
self.assertEqual(cmd[:5], [str(r.DOCKER),'exec','fixture-container','node','-e'])
return run([node,'-e',cmd[5].replace('/app/', str(root)+'/')], **kwargs)
with patch.object(r.subprocess, 'run', side_effect=execute):
self.assertEqual(r.cms_image_files('fixture-container'), baseline['filesSha256'])
def test_runtime_metadata_symlink_is_rejected(self):
node = shutil.which('node');run = subprocess.run
with tempfile.TemporaryDirectory() as d:
root = Path(d)
_, stream = self.initial(root)
stream.unlink();stream.symlink_to(root/'server/admin-server.mjs')
def execute(cmd, **kwargs):
return run([node,'-e',cmd[5].replace('/app/', str(root)+'/')], **kwargs)
with patch.object(r.subprocess, 'run', side_effect=execute), self.assertRaises(subprocess.CalledProcessError):
r.cms_image_files('fixture-container')
if __name__ == '__main__': unittest.main()
File diff suppressed because one or more lines are too long
@@ -152,21 +152,21 @@ class MountOrderTests(unittest.TestCase):
new['descriptor'] = {'releaseId':'fixture','sourceCommit':'a'*40}
stack.enter_context(mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':new['runtime'][args[-1].split('/')[1].split(':')[0]]['imageId']}]))
with redirect_stdout(io.StringIO()):R.accept_device_release(new)
for version in [True,0,4,'2']:
for version in [True,0,3,'2']:
with self.subTest(version=version),self.assertRaisesRegex(R.DeployError,'version mismatch'):R.accept_device_release({**before,'runtimeFingerprintVersion':version})
def test_preflight_records_v3_for_new_normal_release(self):
def test_preflight_records_v2_for_new_normal_release(self):
with ExitStack() as stack:
for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v3',runtime())]:
for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v2',runtime())]:
stack.enter_context(mock.patch.object(R,name,return_value=value))
for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']:
stack.enter_context(mock.patch.object(R,name))
legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot'))
detail = stack.enter_context(mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':{'Config.Env':'a'*64}}))
before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id')
self.assertEqual(before['runtimeFingerprintVersion'],3);legacy.assert_not_called()
self.assertEqual(before['runtimeFingerprintVersion'],2);legacy.assert_not_called()
self.assertEqual(before['runtimeFieldDigests'],{'device-manager':{'Config.Env':'a'*64}})
detail.assert_called_once_with(before['runtime'],3)
detail.assert_called_once_with(before['runtime'])
def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self):
old = samples_fixture();before = evidence_fixture(old);current = reorder(old)
@@ -1,115 +0,0 @@
"""r46 immutable evidence, v3 acceptance and marker-only runtime boundary."""
import copy
from contextlib import ExitStack
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from test_device_core_release import R, fixture, runtime
class R46EvidenceTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
def evidence(self, stack):
e = copy.deepcopy(R.DEVICE_R46_EVIDENCE)
failed, backups, source = (self.root / p for p in ('failed', 'backups', 'source'))
for p in (failed, backups, source):
p.mkdir()
fixture(source)
backup = backups / e['failedRow']['backup_id']
backup.mkdir()
entries = R.DEVICE_RELEASE_ENTRIES
before = {'runtimeFingerprintVersion': 2, 'predecessor': e['predecessor'],
'installedFiles': R.collect_exact_files(source, entries, 'fixture')}
(backup / 'device-release-before.json').write_text(json.dumps(before))
for name in ('existing-files.txt', 'files.txt'):
(backup / name).write_text('\n'.join(entries) + '\n')
(backup / 'missing-files.txt').write_text('')
(backup / 'manifest.env').write_text('fixture')
with tarfile.open(backup / 'source-before.tgz', 'w:gz') as tar:
for entry in entries:
tar.add(source / entry, arcname=entry)
archive = failed / e['failedRow']['artifact']
archive.write_bytes(b'exact failed archive')
e['failedRow']['sha256'] = R.sha256_file(archive)
e['backupHashes'] = {p.name: R.sha256_file(p) for p in backup.iterdir()}
for name, value in [('DEVICE_R46_EVIDENCE', e), ('TMP_DIR', self.root),
('FAILED_DIR', failed), ('BACKUPS_DIR', backups)]:
stack.enter_context(patch.object(R, name, value))
ledger = stack.enter_context(patch.object(R, 'load_state', side_effect=lambda p: [e['failedRow']] if p == R.FAILED_STATE_FILE else []))
return e, before, backup, archive, ledger
def test_exact_receipt_backup_and_source_evidence(self):
with ExitStack() as stack:
e, before, backup, archive, ledger = self.evidence(stack)
self.assertEqual(R.device_r46_evidence(), before)
for path in [archive, *backup.iterdir()]:
old = path.read_bytes()
path.write_bytes(old + b'changed')
with self.subTest(path=path.name), self.assertRaises(R.DeployError):
R.device_r46_evidence()
path.write_bytes(old)
ledger.side_effect = lambda p: [e['failedRow']]
with self.assertRaisesRegex(R.DeployError, 'receipt mismatch'):
R.device_r46_evidence()
def test_hash_consistent_but_conflicting_backup_is_rejected(self):
with ExitStack() as stack:
e, before, backup, _, _ = self.evidence(stack)
before['installedFiles']['package.json'] = 'f' * 64
target = backup / 'device-release-before.json'
target.write_text(json.dumps(before))
e['backupHashes'][target.name] = R.sha256_file(target)
with self.assertRaisesRegex(R.DeployError, 'source/runtime evidence conflict'):
R.device_r46_evidence()
def test_v3_acceptance_preserves_images_database_topology_and_source(self):
old = runtime()
before = {'runtimeFingerprintVersion': 3, 'runtime': old, 'compose': {},
'otherComposeServices': {}, 'installedFiles': {}}
with ExitStack() as stack:
stack.enter_context(patch.object(R, 'DEVICE_PLANE_ROOT', self.root / 'live'))
for name, value in [('component_compose_files', ()), ('collect_exact_files', {}),
('device_release_other_compose_services', {}),
('validate_device_manager_control_plane_runtime', None),
('validate_installed_device_b2', None)]:
stack.enter_context(patch.object(R, name, return_value=value))
current = stack.enter_context(patch.object(R, 'device_release_runtime_snapshot_v3', return_value=old))
R.accept_device_release(before, rollback=True)
for service, key, value in [('device-manager', 'imageId', 'wrong-image'),
('device-control-core', 'runtimeConfigSha256', 'wrong-config'),
('device-postgres', 'containerId', 'recreated'),
('device-gateway', 'restartCount', 1),
('device-backhaul-target', 'containerId', 'recreated')]:
changed = copy.deepcopy(old)
changed[service][key] = value
current.return_value = changed
with self.subTest(service=service, key=key), self.assertRaises(R.DeployError):
R.accept_device_release(before, rollback=True)
current.return_value = old
with patch.object(R, 'collect_exact_files', return_value={'unexpected.js': 'sha'}), self.assertRaisesRegex(R.DeployError, 'source mismatch'):
R.accept_device_release(before, rollback=True)
with patch.object(R, 'device_release_other_compose_services', return_value={'other': {}}), self.assertRaisesRegex(R.DeployError, 'unrelated Compose'):
R.accept_device_release(before, rollback=True)
def test_marker_runtime_dispatch_has_no_build_or_restart(self):
entries = (R.DEVICE_R46_RECON_ENTRY,)
component = 'device-core-release-reconciliation'
with patch.object(R, 'run_build') as build, patch.object(R, 'run_compose') as compose, patch.object(R, 'prepare_component_runtime') as prepare:
R.run_component_runtime(component, entries, ())
build.assert_not_called()
compose.assert_not_called()
prepare.assert_not_called()
with patch.object(R, 'preflight_device_r46_reconciliation') as preflight:
R.run_healthchecks(component, entries, ())
preflight.assert_called_once_with(R.DEVICE_PLANE_ROOT, entries, R.DEVICE_R46_RECON_ID, marker_installed=True)
if __name__ == '__main__':
unittest.main()
@@ -1,75 +0,0 @@
# Device Core r46: empty DNS representation
The r46 release (`e30a6dd2a1eae306d811977188f5d118aefed4ab`) failed
acceptance on 2026-11-05. Its rollback restored the accepted r38 source,
but failed the v2 configuration fingerprint. The recorded field evidence
identifies exactly `HostConfig.Dns`, `DnsOptions`, and `DnsSearch`: saved
`[]`, observed `null`. The failed artifact and original backups stay immutable.
An accessible UI and 79 matching source files alone do not prove runtime rollback.
## Registered transition
`device-core-release-reconciliation` gains one exact marker:
`deployment/device-core-release-r46-reconciliation-v1.json`, identity
`device-core-release-r46-reconciliation-v1-20261105-001`.
The live root remains `/volume1/docker/nodedc-device-plane`. The marker selects
no service, build, Compose operation, runtime mutation, database or secret.
The existing marker-only rollback removes only the newly installed marker.
The builder accepts no authority from command-line or payload metadata.
`r46-evidence.json` pins the exact failed receipt, archive, six backup files and
the successful CMS r47/r49/r50 receipts plus their immutable runtime backups.
`r46_runtime.py` is embedded in the standalone root-owned installer by
`embed_r46.py`; no code is loaded from SMB at runtime.
## Runtime proof
The recovery reads three stable observations of all five Device services.
It enumerates at most eight combinations of the three **empty** DNS fields
and must reproduce each saved whole v2 SHA exactly. No field hash substitutes
for this whole-configuration proof. Nonempty DNS settings, environment, mounts,
bind order, ports, security flags and networks cannot be changed by the proof.
Every image must equal the saved image ID. Preserved Postgres, gateway and
backhaul also retain their complete identity and state. Source, Compose,
B2 foundation, runtime boundaries and health are checked by existing acceptance.
Fingerprint v3 keeps the existing v2 mount normalization and converts only
explicit `null` values in the three DNS fields to `[]`. Missing fields and
malformed values fail closed. Nonempty lists retain every value and their
order. Historic v1/v2 fingerprints and their exact acceptance remain intact.
New normal Device releases record v3 and version-matched diagnostic hashes.
## Concurrent CMS releases
CMS legitimately replaced its container after the Device incident. Recovery
does not ignore CMS or arbitrary unrelated drift. It validates only the pinned
r47 → r49 → r50 chain, every canonical receipt/archive/backup, the current r50
source, running application bytes, configuration and health. The original CMS
container ID comes from the pinned r47 backup. Only that one old/new CMS entry
is substituted in the derived in-memory baseline. The other 61 Compose entries
must be unchanged. CMS's own preserved-service snapshot must also match.
A newer CMS successor or unexplained container change requires new review.
CMS source, sites, configuration, credentials and runtime are never written.
## Queue and operator gates
A marker alone, including an in-progress apply, grants nothing. Only a separate
successful canonical recovery receipt with the matching archived marker permits
the exact run46/run-number39/digest/source tuple to move from `blocked` to
terminal `failed`. It is never made `ready` and never retried. The next qualified
commit follows the ordinary outbound Git deployment route.
1. Review source/tests and promote the SHA-pinned root-owned installer, checking
the exact previous installer SHA and an idle deploy lock.
2. Run `verify-install` immediately from the installed path.
3. Stage the deterministic marker artifact, inspect its lifecycle, then obtain a
fresh canonical `plan`. The plan itself performs the read-only runtime proof.
4. Review the plan and apply once. `apply` repeats all proof before and after
marker installation; no application runtime changes are selected.
5. Observe the ordinary next release receipt, then check the resulting Device UI.
Tests cover integrity failures, real configuration drift, image and dependency
changes, unstable observations, unsupported versions, exact artifact scope,
CMS generation drift, historical v1/v2 compatibility, queue identity and
idempotency, marker-only runtime dispatch and Python 3.8 syntax.
@@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""Deterministic data-only marker for the exact r46 rollback reconciliation."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parent
ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json'
def bundle():
descriptor = (ROOT / 'r46-reconciliation-v1.json').read_bytes()
identity = json.loads(descriptor)['releaseId']
members = {
'manifest.env': ('id=' + identity + '\ncomponent=device-core-release-reconciliation\ntype=app-overlay\n').encode(),
'files.txt': (ENTRY + '\n').encode(),
'payload/' + ENTRY: descriptor,
}
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for name, data in sorted(members.items()):
info = tarfile.TarInfo(name)
info.mode, info.size = 0o644, len(data)
archive.addfile(info, io.BytesIO(data))
return identity, output.getvalue()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir', required=True, type=Path)
args = parser.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
identity, data = bundle()
path = args.output_dir / ('nodedc-' + identity + '.tgz')
with path.open('xb') as stream:
stream.write(data)
print(json.dumps({'artifact': str(path), 'id': identity, 'sha256': hashlib.sha256(data).hexdigest()}))
-7
View File
@@ -8,13 +8,6 @@ class Controller:
def reconcile(self):
for row in self.queue.snapshot():
if row['phase'] == 'blocked':
outcome, receipt = self.installer.receipt(row)
if outcome == 'rolled-back':
self.queue.reconcile_r46(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt)
elif outcome != 'ambiguous':
raise QueueError('blocked_run_requires_exact_recovery')
continue
if row['phase'] != 'deploying':
continue
outcome, receipt = self.installer.receipt(row)
@@ -174,29 +174,5 @@ class DeploymentQueue:
self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity))
self.transaction(apply)
def reconcile_r46(self, identity, *, digest, artifact, receipt):
"""Exact terminal blocked -> failed recovery after canonical proof.
This never makes the failed artifact ready again. The caller verifies
the immutable failed evidence and the separate successful recovery.
"""
sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab'
expected_receipt = 'canonical-reconciled:device-core-release-r46-reconciliation-v1-20261105-001'
if (type(identity) is not int or identity != 46
or digest != 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba'
or artifact != 'nodedc-device-core-release-v1-r46-'+sha+'.tgz'
or receipt != expected_receipt):
raise QueueError('r46_reconciliation_identity_mismatch')
def apply():
row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone()
if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (39,sha,'push','main',WORKFLOW,digest,artifact):
raise QueueError('r46_reconciliation_row_mismatch')
if row['phase'] == 'failed' and row['receipt'] == receipt:
return
if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed':
raise QueueError('r46_reconciliation_predecessor_mismatch')
self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity))
self.transaction(apply)
def snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
-24
View File
@@ -1,24 +0,0 @@
"""Embed the reviewed r46 recovery into the standalone root-owned runner."""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent
RUNNER = ROOT.parent / 'deploy-runner/nodedc-deploy'
START = '# BEGIN GENERATED DEVICE R46 RECOVERY\n'
END = '# END GENERATED DEVICE R46 RECOVERY\n'
def section():
source = (ROOT / 'r46_runtime.py').read_text()
evidence = json.loads((ROOT / 'r46-evidence.json').read_text())
return START + source.replace('__DEVICE_R46_EVIDENCE__', repr(evidence)) + '\n' + END
if __name__ == '__main__':
current = RUNNER.read_text()
if START in current:
before, rest = current.split(START, 1)
_, after = rest.split(END, 1)
current = before + section() + after
else:
current = current.replace('\ndef main(argv):', '\n' + section() + '\n\ndef main(argv):', 1)
RUNNER.write_text(current)
@@ -1,61 +0,0 @@
{
"backupHashes": {
"device-release-before.json": "52927379518030d1e979d897e5cb298481d81a78fb694c5ab68896bfeb8a64d4",
"existing-files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a",
"files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a",
"manifest.env": "c126a1df2b28d0474e80727e5716311ea6b9aa5702f6b76e9d4742205d87ba62",
"missing-files.txt": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"source-before.tgz": "dc40d86d52be8f7e02fb7ec0928da371e37f813676bba182fb883212cc7ec967"
},
"cms": [
{
"backupSha256": "1156f7bdc0313cb4ad8f2541cbe260e965784201b18baacb548480ee6add902d",
"row": {
"applied_at": "2026-11-05T10:32:58+00:00",
"artifact": "nodedc-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1.tgz",
"backup_id": "dc-cms-release-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1-20261105-133137",
"component": "dc-cms-release",
"id": "dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1",
"sha256": "dfd7bbc8753af8b6693253a5a7030995fc6745e541e5206ca1e708bf17555a5d",
"status": "ok"
}
},
{
"backupSha256": "6a800c80d6cd533bf7d31745baa20ab9912ac9c93f1e9febbe19a61006650547",
"row": {
"applied_at": "2026-11-05T10:35:39+00:00",
"artifact": "nodedc-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835.tgz",
"backup_id": "dc-cms-release-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835-20261105-133344",
"component": "dc-cms-release",
"id": "dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835",
"sha256": "d69852e99b251310bc96ec88dcc89d9d16ca704c49f35d8a168c2835440652b0",
"status": "ok"
}
},
{
"backupSha256": "2b96d060d5aee54998dabb1c432fe495469cebc92a59b859ff00a0c1183690ca",
"row": {
"applied_at": "2026-11-05T10:54:15+00:00",
"artifact": "nodedc-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3.tgz",
"backup_id": "dc-cms-release-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3-20261105-135303",
"component": "dc-cms-release",
"id": "dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3",
"sha256": "88a09153b860280c0a28c51e13bbe8d68cb39e7030ce2ba70bc9a0bf8a367c43",
"status": "ok"
}
}
],
"failedRow": {
"artifact": "nodedc-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab.tgz.20261105-132438",
"backup_id": "device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438",
"component": "device-core-release",
"failed_at": "2026-11-05T10:30:32+00:00",
"id": "device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab",
"message": "Device Core release runtime configuration drift: device-control-core; field_evidence={\"actualSha256\":\"103d405d730b8de86f1c83f4aa5b31f99e1cfc04de76e48bbb4dbab54149b018\",\"changedFields\":[{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.Dns\"},{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.DnsOptions\"},{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.DnsSearch\"}],\"evidence\":\"captured\",\"expectedSha256\":\"37c24299b8eeede7707905a435e99360de08eb2a852d1f4750db353efa17c7b2\",\"schema\":\"nodedc.device-core.runtime-drift-fields.v1\",\"service\":\"device-control-core\",\"truncated\":false}",
"rollback_status": "failed:DeployError",
"sha256": "b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba",
"started_apply": true,
"status": "failed"
},
"predecessor": "device-core-release-v1-r38-dcb0c76ac8e9403c05cc64e9cdde5ebf859f2766"
}
@@ -1,10 +0,0 @@
{
"backupId": "device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438",
"cmsSuccessor": "dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3",
"failedReleaseId": "device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab",
"failedSha256": "b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba",
"mode": "prove-restored-baseline-empty-dns-only",
"releaseId": "device-core-release-r46-reconciliation-v1-20261105-001",
"runtimeFingerprintVersion": 3,
"schemaVersion": "nodedc.device-core.r46-reconciliation.v1"
}
-221
View File
@@ -1,221 +0,0 @@
"""Versioned DNS representation fingerprint and exact r46 evidence-only recovery.
Embedded into the root-owned runner. No production code is imported from SMB.
Historical v1/v2 hashes are never reinterpreted without an exact preimage proof.
"""
DEVICE_R46_EVIDENCE = __DEVICE_R46_EVIDENCE__
DEVICE_R46_RECON_ID = 'device-core-release-r46-reconciliation-v1-20261105-001'
DEVICE_R46_RECON_ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json'
DEVICE_DNS_FIELDS = ('Dns', 'DnsOptions', 'DnsSearch')
def device_release_fields_v3(fields):
result = device_release_mounts_v2(fields)
host = result['HostConfig']
for key in DEVICE_DNS_FIELDS:
if key not in host:
die('Device Core v3 DNS field is missing')
value = host[key]
if value is None:
host[key] = []
elif not isinstance(value, list) or any(not isinstance(v, str) for v in value):
die('Device Core v3 DNS field is malformed')
return result
def device_release_runtime_snapshot_v3():
result = {}
for service, sample in device_release_drift_sample().items():
row = dict(sample['runtime'])
if not row['running'] or row['health'] not in (None, 'healthy'):
die('Device Core predecessor service is not healthy: ' + service)
row['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(sample['fields']))
result[service] = row
return result
def device_r46_dns_proof(fields, expected):
device_release_fields_v3(fields) # Validate, without altering the v2 preimage.
candidate = device_release_mounts_v2(fields)
if not isinstance(expected, str) or not re.fullmatch('[a-f0-9]{64}', expected):
die('Device Core r46 saved digest is invalid')
if any(candidate['HostConfig'][k] not in (None, []) for k in DEVICE_DNS_FIELDS):
die('Device Core r46 proof requires empty DNS settings')
for checked, values in enumerate(itertools.product((None, []), repeat=3), 1):
for key, value in zip(DEVICE_DNS_FIELDS, values):
candidate['HostConfig'][key] = value
if device_release_drift_digest(candidate) == expected:
return checked
die('Device Core r46 runtime differs beyond empty DNS representation')
def device_r46_descriptor():
e = DEVICE_R46_EVIDENCE
return {'schemaVersion': 'nodedc.device-core.r46-reconciliation.v1',
'releaseId': DEVICE_R46_RECON_ID, 'failedReleaseId': e['failedRow']['id'],
'failedSha256': e['failedRow']['sha256'], 'backupId': e['failedRow']['backup_id'],
'runtimeFingerprintVersion': 3, 'mode': 'prove-restored-baseline-empty-dns-only',
'cmsSuccessor': e['cms'][-1]['row']['id']}
def validate_device_r46_payload(payload, entries, identity):
if tuple(entries or ()) != (DEVICE_R46_RECON_ENTRY,) or identity != DEVICE_R46_RECON_ID:
die('Device Core r46 reconciliation identity/entry mismatch')
marker = payload / DEVICE_R46_RECON_ENTRY
expected = (json.dumps(device_r46_descriptor(), sort_keys=True, indent=2) + '\n').encode()
if marker.is_symlink() or not marker.is_file() or marker.read_bytes() != expected:
die('Device Core r46 reconciliation descriptor mismatch')
def device_r46_evidence():
e = DEVICE_R46_EVIDENCE
row = e['failedRow']
records = [r for r in load_state(FAILED_STATE_FILE)
if r.get('id') == row['id'] or r.get('sha256') == row['sha256']]
if records != [row] or any(r.get('id') == row['id'] or r.get('sha256') == row['sha256']
for r in load_state(STATE_FILE)):
die('Device Core r46 failed receipt mismatch')
archive = FAILED_DIR / row['artifact']
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row['sha256']:
die('Device Core r46 failed archive mismatch')
backup = BACKUPS_DIR / row['backup_id']
if backup.is_symlink() or not backup.is_dir():
die('Device Core r46 backup is unsafe')
for name, digest in e['backupHashes'].items():
path = backup / name
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die('Device Core r46 backup digest mismatch: ' + name)
before = read_strict_json(backup / 'device-release-before.json', 'Device Core r46 backup', max_bytes=256*1024)
if before.get('runtimeFingerprintVersion') != 2 or before.get('predecessor') != e['predecessor']:
die('Device Core r46 predecessor/version mismatch')
existing = read_backup_path_list(backup / 'existing-files.txt')
missing = read_backup_path_list(backup / 'missing-files.txt')
validate_backup_partition(DEVICE_RELEASE_ENTRIES, existing, missing, 'Device Core r46 reconciliation')
if missing:
die('Device Core r46 backup partition mismatch')
with tempfile.TemporaryDirectory(prefix='device-r46-evidence-', dir=TMP_DIR) as tmp:
materialize_backup_tree(backup / 'source-before.tgz', Path(tmp), set(existing))
if collect_exact_files(Path(tmp), existing, 'Device Core r46 source backup') != before['installedFiles']:
die('Device Core r46 source/runtime evidence conflict')
return before
def device_r46_cms_evidence():
"""Read only the three exact accepted CMS successors, not arbitrary drift."""
evidence = DEVICE_R46_EVIDENCE['cms']
applied = load_state(STATE_FILE)
failed = load_state(FAILED_STATE_FILE)
backups = []
for item in evidence:
row = item['row']
if [r for r in applied if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] != [row]:
die('Device Core r46 CMS successor receipt mismatch')
if any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] for r in failed):
die('Device Core r46 CMS successor has conflicting receipt')
backup = BACKUPS_DIR / row['backup_id']
path = backup / 'cms-runtime-before.json'
if (backup.is_symlink() or not backup.is_dir() or path.is_symlink() or not path.is_file()
or sha256_file(path) != item['backupSha256']):
die('Device Core r46 CMS successor backup mismatch')
before = read_strict_json(path, 'Device Core r46 CMS backup', max_bytes=2*1024*1024)
with tempfile.TemporaryDirectory(prefix='device-r46-cms-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']:
die('Device Core r46 CMS archive identity mismatch')
descriptor = validate_cms_release_payload(payload, entries, row['id'])
if descriptor != before['descriptor']:
die('Device Core r46 CMS source/backup identity mismatch')
backups.append(before)
for previous, current in zip(backups, backups[1:]):
if (current['predecessor'] != previous['descriptor']['sourceCommit']
or current['otherServices'] != previous['otherServices']):
die('Device Core r46 CMS successor chain mismatch')
return backups
def device_r46_other_services(before, cms_backups):
# A new CMS container is permitted only after proving the exact r47/r49/r50
# chain and current r50 app bytes, health, config and all unrelated services.
latest = cms_backups[-1]
if cms_installed_release() != latest['descriptor']:
die('Device Core r46 requires the exact accepted CMS successor')
cms_healthchecks()
runtime = cms_runtime_snapshot_v2()
if (runtime['configSha256'] != latest['runtime']['configSha256']
or runtime['imageRef'] != latest['runtime']['imageRef']
or runtime['id'] == latest['runtime']['id']):
die('Device Core r46 CMS configuration/generation drift')
actual, metadata = cms_application_inventory()
if (metadata != latest['installedMetadata'] or cms_foundation() != latest['foundation']
or cms_image_files(runtime['id']) != {k: v for k, v in actual.items() if k not in CMS_DEPENDENCY_FILES}
or cms_other_services() != latest['otherServices']):
die('Device Core r46 CMS source or preserved services differ')
old_id = cms_backups[0]['runtime']['id']
saved = before['otherComposeServices']
current = device_release_other_compose_services()
if old_id not in saved or runtime['id'] not in current or old_id in current:
die('Device Core r46 CMS predecessor container identity mismatch')
unchanged = {k: v for k, v in saved.items() if k != old_id}
if (any(cms_backups[0]['otherServices'].get(k) != v for k, v in unchanged.items())
or {k: v for k, v in current.items() if k != runtime['id']} != unchanged):
die('Device Core r46 changed an unrelated Compose service')
return current
def device_r46_restored_baseline(before):
if before.get('runtimeFingerprintVersion') != 2 or set(before['runtime']) != set(DEVICE_RELEASE_INVENTORY):
die('Device Core r46 requires the exact v2 inventory')
samples = [device_release_drift_sample() for _ in range(3)]
if any(sample != samples[0] for sample in samples):
die('Device Core r46 runtime changed during reconciliation')
baseline = json.loads(json.dumps(before))
baseline['runtimeFingerprintVersion'] = 3
baseline.pop('runtimeFieldDigests', None) # Historical v2 diagnostics stay in the immutable backup.
for service in DEVICE_RELEASE_INVENTORY:
sample = samples[0][service]
row, fields, old = sample['runtime'], sample['fields'], before['runtime'][service]
if (not row['running'] or row['health'] not in (None, 'healthy') or row['imageId'] != old['imageId']
or row['runtimeConfigSha256'] != device_release_drift_digest(fields)):
die('Device Core r46 image/health/evidence mismatch: ' + service)
v2 = dict(row, runtimeConfigSha256=device_release_drift_digest(device_release_mounts_v2(fields)))
if service not in DEVICE_RELEASE_SERVICES and v2 != old:
die('Device Core r46 preserved service differs: ' + service)
device_r46_dns_proof(fields, old['runtimeConfigSha256'])
baseline['runtime'][service]['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(fields))
return baseline
def preflight_device_r46_reconciliation(payload, entries, identity, *, marker_installed=False):
require_root()
validate_device_r46_payload(payload, entries, identity)
marker = DEVICE_PLANE_ROOT / DEVICE_R46_RECON_ENTRY
if not marker_installed and (marker.exists() or marker.is_symlink()):
die('Device Core r46 marker already exists')
before = device_r46_evidence()
baseline = device_r46_restored_baseline(before)
baseline['otherComposeServices'] = device_r46_other_services(before, device_r46_cms_evidence())
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
accept_device_release(baseline, rollback=True)
print('device_r46_reconciliation=exact-v2-sha;dns-empty-only;samples=3;fingerprint=v3;'
'cms-successor=r50;services=none;build=none;runtime-mutation=none')
return baseline
def device_r46_reconciled(row):
if row != DEVICE_R46_EVIDENCE['failedRow']:
return False
records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_R46_RECON_ID]
if not records:
return False # Marker alone, including in-progress apply, grants nothing.
if (len(records) != 1 or records[0].get('component') != 'device-core-release-reconciliation'
or records[0].get('status') != 'ok'):
die('Device Core r46 reconciliation receipt mismatch')
validate_device_r46_payload(DEVICE_PLANE_ROOT, (DEVICE_R46_RECON_ENTRY,), DEVICE_R46_RECON_ID)
with tempfile.TemporaryDirectory(prefix='device-r46-marker-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp))
if manifest['component'] != 'device-core-release-reconciliation' or manifest['id'] != DEVICE_R46_RECON_ID:
die('Device Core r46 reconciliation archive identity mismatch')
validate_device_r46_payload(payload, entries, manifest['id'])
device_r46_evidence()
device_r46_cms_evidence()
return True
@@ -1,298 +0,0 @@
import ast
import copy
from contextlib import ExitStack, redirect_stdout
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
from build_r46_reconciliation import bundle
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID, WORKFLOW
from controller import Controller
from embed_r46 import section, START, END
ROOT = Path(__file__).resolve().parents[2]
RUNNER = ROOT / 'infra/deploy-runner/nodedc-deploy'
loader = importlib.machinery.SourceFileLoader('device_r46_runner', str(RUNNER))
spec = importlib.util.spec_from_loader(loader.name, loader)
r = importlib.util.module_from_spec(spec)
loader.exec_module(r)
def fields():
return {'HostConfig': {'Dns': [], 'DnsOptions': [], 'DnsSearch': [],
'Mounts': [{'Target': '/a', 'Source': '/source/a', 'Type': 'bind'},
{'Target': '/b', 'Source': '/source/b', 'Type': 'bind'}],
'Binds': ['/a:/a:ro', '/b:/b:ro'], 'NetworkMode': 'private-egress',
'ReadonlyRootfs': True, 'CapAdd': [], 'PortBindings': {}},
'Config': {'Env': ['TOKEN=fixture-do-not-log'], 'Cmd': ['node', 'server.js'], 'User': '123'},
'Mounts': [{'Source': '/source/a', 'Destination': '/a', 'RW': False}],
'networks': ['private-egress']}
def incident():
samples, runtime = {}, {}
for service in r.DEVICE_RELEASE_INVENTORY:
f = fields()
row = {'service': service, 'containerId': 'old-' + service, 'imageId': 'image-' + service,
'running': True, 'health': 'healthy', 'restartCount': 0, 'status': 'running',
'runtimeConfigSha256': r.device_release_drift_digest(r.device_release_mounts_v2(f))}
runtime[service] = copy.deepcopy(row)
if service in r.DEVICE_RELEASE_SERVICES:
row['containerId'] = 'restored-' + service
for key in r.DEVICE_DNS_FIELDS:
f['HostConfig'][key] = None
row['runtimeConfigSha256'] = r.device_release_drift_digest(f)
samples[service] = {'runtime': row, 'fields': f}
return {'runtimeFingerprintVersion': 2, 'runtime': runtime,
'installedFiles': {'app.js': 'sha'}, 'otherComposeServices': {}, 'compose': {}}, samples
class FingerprintTests(unittest.TestCase):
def test_v3_only_empty_dns_and_existing_v2_mount_order(self):
old = fields()
new = copy.deepcopy(old)
new['HostConfig']['Mounts'].reverse()
for key in r.DEVICE_DNS_FIELDS:
new['HostConfig'][key] = None
saved = copy.deepcopy(new)
self.assertNotEqual(r.device_release_mounts_v2(old), r.device_release_mounts_v2(new))
self.assertEqual(r.device_release_fields_v3(old), r.device_release_fields_v3(new))
self.assertEqual(r.device_r46_dns_proof(new, r.device_release_drift_digest(r.device_release_mounts_v2(old))), 8)
self.assertEqual(new, saved)
def test_nonempty_dns_order_is_preserved_not_reconciled(self):
old = fields()
for key in r.DEVICE_DNS_FIELDS:
new = copy.deepcopy(old)
new['HostConfig'][key] = ['one', 'two']
self.assertEqual(r.device_release_fields_v3(new)['HostConfig'][key], ['one', 'two'])
rev = copy.deepcopy(new)
rev['HostConfig'][key].reverse()
self.assertNotEqual(r.device_release_fields_v3(new), r.device_release_fields_v3(rev))
with self.assertRaises(r.DeployError):
r.device_r46_dns_proof(new, r.device_release_drift_digest(old))
def test_real_drift_remains_rejected(self):
old = fields()
mutations = [lambda f: f['Config'].update(Env=['TOKEN=changed']),
lambda f: f['Config'].update(Cmd=['wrong']),
lambda f: f['HostConfig'].update(NetworkMode='host'),
lambda f: f['HostConfig'].update(ReadonlyRootfs=False),
lambda f: f['HostConfig'].update(CapAdd=['SYS_ADMIN']),
lambda f: f['HostConfig'].update(PortBindings={'80/tcp': []}),
lambda f: f['HostConfig']['Binds'].reverse(),
lambda f: f['HostConfig']['Mounts'][0].update(Source='/different'),
lambda f: f['Mounts'][0].update(RW=True),
lambda f: f.update(networks=['other'])]
for mutate in mutations:
new = copy.deepcopy(old)
mutate(new)
with self.subTest(mutate=mutate), self.assertRaises(r.DeployError):
r.device_r46_dns_proof(new, r.device_release_drift_digest(r.device_release_mounts_v2(old)))
def test_malformed_dns_and_mounts_fail_closed(self):
for key in r.DEVICE_DNS_FIELDS:
for value in ('', False, 0, {}, [1], [None]):
f = fields()
f['HostConfig'][key] = value
with self.subTest(key=key, value=value), self.assertRaises(r.DeployError):
r.device_release_fields_v3(f)
f = fields()
del f['HostConfig'][key]
with self.assertRaises(r.DeployError):
r.device_release_fields_v3(f)
f = fields()
f['HostConfig']['Mounts'][1]['Target'] = '/a'
with self.assertRaises(r.DeployError):
r.device_release_fields_v3(f)
def test_stable_exact_old_images_and_preserved_services(self):
before, samples = incident()
saved = copy.deepcopy(before)
with patch.object(r, 'device_release_drift_sample', return_value=samples) as read:
baseline = r.device_r46_restored_baseline(before)
self.assertEqual(read.call_count, 3)
self.assertEqual(before, saved)
self.assertEqual(baseline['runtimeFingerprintVersion'], 3)
for service in r.DEVICE_RELEASE_INVENTORY:
self.assertEqual(baseline['runtime'][service]['imageId'], before['runtime'][service]['imageId'])
self.assertEqual(baseline['installedFiles'], before['installedFiles'])
def test_unstable_unhealthy_changed_images_and_preserved_identity_rejected(self):
before, samples = incident()
service = r.DEVICE_RELEASE_SERVICES[0]
for key, value in [('imageId', 'new'), ('running', False), ('health', 'unhealthy')]:
changed = copy.deepcopy(samples)
changed[service]['runtime'][key] = value
with patch.object(r, 'device_release_drift_sample', return_value=changed), self.assertRaises(r.DeployError):
r.device_r46_restored_baseline(before)
changed = copy.deepcopy(samples)
changed[service]['runtime']['containerId'] = 'unstable'
with patch.object(r, 'device_release_drift_sample', side_effect=[samples, changed, samples]), self.assertRaises(r.DeployError):
r.device_r46_restored_baseline(before)
preserved = next(s for s in r.DEVICE_RELEASE_INVENTORY if s not in r.DEVICE_RELEASE_SERVICES)
changed = copy.deepcopy(samples)
changed[preserved]['runtime']['containerId'] = 'recreated-db'
with patch.object(r, 'device_release_drift_sample', return_value=changed), self.assertRaises(r.DeployError):
r.device_r46_restored_baseline(before)
class ArtifactTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.artifact = self.root / 'candidate.tgz'
self.artifact.write_bytes(bundle()[1])
unpack = self.root / 'unpack'
unpack.mkdir()
self.manifest, self.entries, self.payload = r.load_artifact(self.artifact, unpack)
def test_exact_deterministic_data_only_scope(self):
self.assertEqual(self.artifact.read_bytes(), bundle()[1])
self.assertEqual(self.entries, [r.DEVICE_R46_RECON_ENTRY])
component = self.manifest['component']
self.assertEqual(r.component_services(component, self.entries), ())
self.assertEqual(r.component_builds(component, self.entries), ())
self.assertEqual(r.component_compose_files(component), ())
for path in ('services/device-manager/app.js', '.env', 'deployment/other.json', 'data/db'):
with self.assertRaises(r.DeployError):
r.allowed_payload_path(component, path)
for key, value in [('runtimeFingerprintVersion', 2), ('mode', 'restart'), ('cmsSuccessor', 'other')]:
d = r.device_r46_descriptor()
d[key] = value
(self.payload / r.DEVICE_R46_RECON_ENTRY).write_text(json.dumps(d))
with self.assertRaises(r.DeployError):
r.validate_device_r46_payload(self.payload, self.entries, r.DEVICE_R46_RECON_ID)
def test_preflight_owns_all_checks_and_no_runtime_mutation(self):
before, samples = incident()
with ExitStack() as stack:
for name, value in [('require_root', None), ('device_r46_evidence', before),
('device_release_drift_sample', samples), ('device_r46_cms_evidence', []),
('device_r46_other_services', {})]:
stack.enter_context(patch.object(r, name, return_value=value))
stack.enter_context(patch.object(r, 'DEVICE_PLANE_ROOT', self.root / 'live'))
health = stack.enter_context(patch.object(r, 'run_healthchecks'))
accept = stack.enter_context(patch.object(r, 'accept_device_release'))
mutation = stack.enter_context(patch.object(r.subprocess, 'run', side_effect=AssertionError('unexpected command')))
with redirect_stdout(io.StringIO()):
result = r.preflight_device_r46_reconciliation(self.payload, self.entries, r.DEVICE_R46_RECON_ID)
health.assert_called_once_with('device-core-release', r.DEVICE_RELEASE_ENTRIES, r.DEVICE_RELEASE_SERVICES)
accept.assert_called_once_with(result, rollback=True)
mutation.assert_not_called()
accept.side_effect = r.DeployError('guard rejection')
with self.assertRaises(r.DeployError):
r.preflight_device_r46_reconciliation(self.payload, self.entries, r.DEVICE_R46_RECON_ID)
def test_marker_without_success_receipt_never_releases_queue(self):
row = r.DEVICE_R46_EVIDENCE['failedRow']
with patch.object(r, 'load_state', return_value=[]):
self.assertFalse(r.device_r46_reconciled(row))
with patch.object(r, 'load_state', return_value=[{'id': r.DEVICE_R46_RECON_ID, 'status': 'failed'}]), self.assertRaises(r.DeployError):
r.device_r46_reconciled(row)
self.assertFalse(r.device_r46_reconciled({**row, 'sha256': 'a' * 64}))
def test_registered_routes_and_embedded_source_are_current(self):
source = RUNNER.read_text()
self.assertEqual(source.split(START, 1)[1].split(END, 1)[0], section().split(START, 1)[1].split(END, 1)[0])
ast.parse(source, feature_version=(3, 8))
self.assertIn('device_release_runtime_snapshot_v3()', source)
self.assertIn('not device_release_r5_reconciled(row) and not device_r46_reconciled(row)', source)
self.assertIn('ok:device-core-release-reconciliation-marker-only', source)
class CmsSuccessorTests(unittest.TestCase):
def fixture(self, stack):
preserved = {'stable': {'fingerprint': 'exact', 'running': True, 'startedAt': 'old'}}
old = {'old-cms': {'fingerprint': 'old'}, **preserved}
current = {'new-cms': {'fingerprint': 'new'}, **preserved}
latest = {'runtime': {'id': 'cms49', 'configSha256': 'config', 'imageRef': 'cms'},
'descriptor': {'releaseId': 'cms50'}, 'installedMetadata': {}, 'foundation': {'compose': 'sha'},
'otherServices': {**preserved, 'device': {'fingerprint': 'restored'}}}
backups = [{'runtime': {'id': 'old-cms'}, 'otherServices': latest['otherServices']}, latest]
values = {'cms_installed_release': latest['descriptor'], 'cms_healthchecks': None,
'cms_runtime_snapshot_v2': {'id': 'new-cms', 'configSha256': 'config', 'imageRef': 'cms'},
'cms_application_inventory': ({'admin/index.html': 'exact'}, {}),
'cms_foundation': latest['foundation'], 'cms_image_files': {'admin/index.html': 'exact'},
'cms_other_services': latest['otherServices'], 'device_release_other_compose_services': current}
mocks = {name: stack.enter_context(patch.object(r, name, return_value=value)) for name, value in values.items()}
return {'otherComposeServices': old}, backups, current, mocks
def test_only_exact_accepted_cms_generation_may_change(self):
with ExitStack() as stack:
before, backups, current, mocks = self.fixture(stack)
self.assertEqual(r.device_r46_other_services(before, backups), current)
self.assertIn('old-cms', before['otherComposeServices'])
mocks['device_release_other_compose_services'].return_value = {**current, 'foreign': {}}
with self.assertRaises(r.DeployError):
r.device_r46_other_services(before, backups)
def test_cms_drift_or_other_container_changes_not_ignored(self):
mutations = [('cms_installed_release', {'releaseId': 'unreviewed51'}),
('cms_image_files', {'admin/index.html': 'changed'}),
('cms_other_services', {}), ('cms_foundation', {}),
('cms_runtime_snapshot_v2', {'id': 'new-cms', 'configSha256': 'changed', 'imageRef': 'cms'}),
('cms_application_inventory', ({'admin/index.html': 'exact'}, {'unexpected': 'metadata'})),
('device_release_other_compose_services', {'new-cms': {}, 'stable': {'fingerprint': 'changed'}})]
for name, value in mutations:
with self.subTest(name=name), ExitStack() as stack:
before, backups, _, mocks = self.fixture(stack)
mocks[name].return_value = value
with self.assertRaises(r.DeployError):
r.device_r46_other_services(before, backups)
class QueueRecoveryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.q = DeploymentQueue(Path(self.tmp.name) / 'queue.db', first_run_number=1)
self.addCleanup(self.q.close)
self.sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab'
self.digest = r.DEVICE_R46_EVIDENCE['failedRow']['sha256']
self.artifact = 'nodedc-device-core-release-v1-r46-' + self.sha + '.tgz'
self.receipt = 'canonical-reconciled:' + r.DEVICE_R46_RECON_ID
run = {'id': 46, 'run_number': 39, 'run_attempt': 1, 'head_sha': self.sha,
'status': 'completed', 'conclusion': 'success', 'event': 'push', 'head_branch': 'main', 'path': WORKFLOW}
self.q.observe([run], repository=REPOSITORY, repository_id=REPOSITORY_ID)
self.q.reserve(46, digest=self.digest, artifact=self.artifact)
self.q.reconcile(46, digest=self.digest, artifact=self.artifact, outcome='ambiguous', receipt='canonical-rollback-unconfirmed')
def test_exact_blocked_to_failed_is_idempotent_never_ready(self):
for _ in range(2):
self.q.reconcile_r46(46, digest=self.digest, artifact=self.artifact, receipt=self.receipt)
self.assertEqual(self.q.snapshot()[0]['phase'], 'failed')
self.assertIsNone(self.q.next_ready())
def test_wrong_identity_digest_receipt_or_row_stays_blocked(self):
for values in [(47, self.digest, self.artifact, self.receipt),
(46, 'a' * 64, self.artifact, self.receipt),
(46, self.digest, self.artifact, 'canonical:unconfirmed')]:
with self.assertRaises(QueueError):
self.q.reconcile_r46(values[0], digest=values[1], artifact=values[2], receipt=values[3])
self.q.db.execute("UPDATE runs SET branch='other' WHERE id=46")
with self.assertRaises(QueueError):
self.q.reconcile_r46(46, digest=self.digest, artifact=self.artifact, receipt=self.receipt)
self.assertEqual(self.q.snapshot()[0]['phase'], 'blocked')
def test_controller_reconciles_only_canonical_receipt(self):
installer = Mock()
controller = Controller(self.q, Mock(), installer)
installer.receipt.return_value = ('ambiguous', 'canonical-rollback-unconfirmed')
controller.reconcile()
self.assertEqual(self.q.snapshot()[0]['phase'], 'blocked')
installer.receipt.return_value = ('rolled-back', self.receipt)
controller.reconcile()
self.assertEqual(self.q.snapshot()[0]['phase'], 'failed')
installer.apply.assert_not_called()
installer.plan.assert_not_called()
if __name__ == '__main__':
unittest.main()
+39
View File
@@ -0,0 +1,39 @@
# Optional delegated Core egress
Prepared 17 November 2026; **not deployed on NAS**. The legacy AMD path remains
active when no delegation is supplied. McHost's relay is installed, but Cesium
country-blocks its public egress IP; Mission Core has therefore not selected it.
`src/egress.mjs` admits a request-scoped `nodedc.map-egress/v1` binding only with a
separate HMAC signature over schema, method, path and payload. A browser or trusted
subject header alone cannot set the route. The key is derived from Gateway's
existing administrative secret with the domain `nodedc.map-egress.core/v1`; Core
would receive only the derived key in private `services/cesium-ion/egress-signing.key`
(64 hexadecimal characters). No key has been provisioned in this rollout. Keep
the key, binding and provider credentials out of logs, responses and Git.
The binding expires within 30 seconds and supplies a pinned relay endpoint,
credential and Cesium profile. TLS 1.3 certificate verification by exact fingerprint
precedes HTTP credentials. Destination checks forbid private addresses and arbitrary
provider hosts. The relay allows only GET/HEAD; range and conditional headers are
forwarded. Cancellation closes the stream. Concurrent relay requests are bounded
at 16; handshake and body idle timeouts are 8 and 30 seconds.
Cache lookup is unchanged and occurs before external fetch. Delegation affects
only a miss/refresh fetch: it does not change canonical URLs, object keys, index
format, credential scoping, atomic fills or the physical cache root. Warm hits
need neither AMD nor VPS. Do not rebuild, copy, clear or reindex tiles for this
transport change. The health contract advertises `egressContract` after deployment;
Core requires this contract and its signing key before admitting a cached route.
Three delegation tests passed, including real TLS pin/header/cancellation cases.
Existing smoke checks passed for no-browser-credentials, live-cache-fallback and
streaming-cache-fill (unchanged warm-hit writes, conditional responses, bounded
singleflight and partial-object privacy). These are local checks, not proof of a
deployed Gateway or live NAS-to-VPS acceptance.
Before activation: qualify a reachable provider exit; build and deploy only with
the canonical NODE.DC artifact/runner plan/apply workflow; provision the derived
private key; verify bounded warm hits, cold fills and NAS outage/recovery. Preserve
the existing AMD route as rollback. No NAS deployment artifact was staged during
the blocked McHost qualification.
+103
View File
@@ -0,0 +1,103 @@
// Delegated Core egress is authenticated separately from map-read admission.
// A browser/trusted-subject header alone cannot redirect provider credentials.
import {AsyncLocalStorage} from 'node:async_hooks';
import {createHash, createHmac, timingSafeEqual} from 'node:crypto';
import {lookup} from 'node:dns/promises';
import {Agent, request as httpRequest} from 'node:http';
import {isIP} from 'node:net';
import {Readable} from 'node:stream';
import {connect} from 'node:tls';
export const egressContext = new AsyncLocalStorage();
const contract = 'nodedc.map-egress/v1';
const hosts = new Set(['api.cesium.com', 'assets.ion.cesium.com', 'assets.cesium.com',
'dev.virtualearth.net', 'ecn.tiles.virtualearth.net',
...[0,1,2,3].map(n=>`ecn.t${n}.tiles.virtualearth.net`)]);
function denied(code='map_egress_request_rejected', statusCode=403) {
return Object.assign(new Error(code), {statusCode});
}
export function signingKey(adminSecret) {
return createHmac('sha256', adminSecret).update('nodedc.map-egress.core/v1').digest();
}
export function authorizeEgress(request, adminSecret, path, now=Date.now()) {
const payload=request.headers['x-nodedc-map-egress'];
const signature=request.headers['x-nodedc-map-egress-signature'];
if (!payload && !signature) return null;
if (!adminSecret || typeof payload!=='string' || payload.length>4096 || !/^[A-Za-z0-9_-]+$/.test(payload)
|| typeof signature!=='string' || !/^[a-f0-9]{64}$/.test(signature)) throw denied();
const expected=createHmac('sha256',signingKey(adminSecret))
.update(`${contract}\n${request.method}\n${path}\n${payload}`).digest();
if (!timingSafeEqual(expected,Buffer.from(signature,'hex'))) throw denied();
let value;
try {value=JSON.parse(Buffer.from(payload,'base64url'));} catch {throw denied();}
if (!value || Object.keys(value).sort().join(',')!=='endpoint,fingerprint,profile,schema,timestamp,token'
|| value.schema!==contract || value.profile!=='cesium' || !Number.isSafeInteger(value.timestamp)
|| Math.abs(now/1000-value.timestamp)>30 || !/^[a-f0-9]{64}$/.test(value.fingerprint)
|| !/^[A-Za-z0-9_-]{43}$/.test(value.token)) throw denied();
validateEndpoint(value.endpoint);
return value;
}
export function publicIPv4(address) {
if(isIP(address)!==4) return false;
const [a,b,c]=address.split('.').map(Number);
return !(a===0||a===10||a===127||a>=224||(a===100&&b>=64&&b<=127)
||(a===169&&b===254)||(a===172&&b>=16&&b<=31)||(a===192&&(b===168||b===0||b===2))
||(a===198&&(b===18||b===19||(b===51&&c===100)))||(a===203&&b===0&&c===113));
}
function validateEndpoint(endpoint) {
let url;
try {url=new URL(endpoint);} catch {throw denied();}
if(url.protocol!=='https:'||url.username||url.password||url.search||url.hash||url.pathname!=='/'
|| !url.port || Number(url.port)<1024 || Number(url.port)>65535) throw denied();
return url;
}
let active=0;
export async function relayFetch(binding,target,options={},dependencies={}) {
const provider=new URL(target);
if(provider.protocol!=='https:'||!hosts.has(provider.hostname)||provider.username||provider.password
||provider.hash||(provider.port&&provider.port!=='443')||!['GET','HEAD'].includes(options.method||'GET')) throw denied();
const endpoint=validateEndpoint(binding.endpoint);
if(active>=16) throw denied('map_egress_capacity_reached',503);
active++;
let socket,agent,released=false;
const release=()=>{if(!released){released=true;active--;agent?.destroy();socket?.destroy();}};
try {
const addresses=await (dependencies.lookup||lookup)(endpoint.hostname,{all:true,family:4});
if(!addresses.length||addresses.some(item=>!publicIPv4(item.address))) throw denied();
options.signal?.throwIfAborted();
socket=await new Promise((resolve,reject)=>{
const candidate=(dependencies.connect||connect)({host:addresses[0].address,port:Number(endpoint.port),servername:isIP(endpoint.hostname)?undefined:endpoint.hostname,
rejectUnauthorized:false,minVersion:'TLSv1.3'});
const timer=setTimeout(()=>candidate.destroy(new Error('relay_timeout')),8000);
const abort=()=>candidate.destroy(new Error('relay_cancelled'));
options.signal?.addEventListener('abort',abort,{once:true});
candidate.once('error',error=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);reject(error);});
candidate.once('secureConnect',()=>{
clearTimeout(timer);options.signal?.removeEventListener('abort',abort);
const actual=createHash('sha256').update(candidate.getPeerCertificate().raw||Buffer.alloc(0)).digest('hex');
if(actual!==binding.fingerprint){candidate.destroy();reject(denied('map_egress_identity_changed',502));}
else resolve(candidate); // No HTTP bytes/credentials sent before this point.
});
});
const input=new Headers(options.headers||{}), headers={Authorization:`Bearer ${binding.token}`};
for(const name of ['accept','range','if-none-match','if-modified-since']) if(input.has(name)) headers[name]=input.get(name);
if(input.has('authorization')) headers['X-Nodedc-Upstream-Authorization']=input.get('authorization');
if(input.has('referer')) headers['X-Nodedc-Upstream-Referer']=input.get('referer');
agent=new Agent({keepAlive:false});
agent.createConnection=()=>socket;
const response=await new Promise((resolve,reject)=>{
const req=httpRequest({host:endpoint.hostname,port:Number(endpoint.port),agent,method:options.method||'GET',
path:'/v1/fetch/cesium?'+new URLSearchParams({url:provider.href}),headers,signal:options.signal},resolve);
req.setTimeout(30000,()=>req.destroy(new Error('relay_timeout')));
req.once('error',reject);req.end();
});
response.once('close',release);
const responseHeaders=new Headers();
for(const [key,value] of Object.entries(response.headers)) if(value!==undefined&&!['transfer-encoding','connection','set-cookie'].includes(key))
responseHeaders.set(key,Array.isArray(value)?value.join(', '):value);
if(options.method==='HEAD'||[204,205,304].includes(response.statusCode)) {
response.resume();return new Response(null,{status:response.statusCode,headers:responseHeaders});
}
return new Response(Readable.toWeb(response),{status:response.statusCode,headers:responseHeaders});
} catch(error) {release();throw error?.statusCode?error:denied('map_egress_unavailable',502);}
}
+16 -6
View File
@@ -12,6 +12,7 @@ import {
TRANSPORT_STATION_PROFILE_ID,
createReferenceStationSource,
} from "./reference-station-source.mjs";
import {authorizeEgress, egressContext, relayFetch} from "./egress.mjs";
import { loadZoneSourceProfile } from "./zone-source-snapshot.mjs";
const canonicalCesiumAssetIds = ["1", "2", "96188"];
@@ -21,6 +22,8 @@ const cesiumVerificationTransportVersion = 4;
const canonicalCesiumEgressHosts = new Set([
"api.cesium.com",
"assets.ion.cesium.com",
"assets.cesium.com",
"ecn.tiles.virtualearth.net",
"dev.virtualearth.net",
"ecn.t0.tiles.virtualearth.net",
"ecn.t1.tiles.virtualearth.net",
@@ -63,7 +66,7 @@ let activeCesiumIonToken = (await readStoredCesiumIonToken()) || config.bootstra
let ionTokenWriteQueue = Promise.resolve();
let ionTokenGeneration = 0;
const server = createServer(async (request, response) => {
const server = createServer((request, response) => egressContext.run(null, async () => {
applyCors(request, response);
if (request.method === "OPTIONS") return response.writeHead(204).end();
let requestPath = "unknown";
@@ -82,6 +85,7 @@ const server = createServer(async (request, response) => {
return serveZoneSourceGeneration(request, response);
}
if (!isAllowedRequest(request)) return writeJson(response, 401, { ok: false, error: "map_gateway_auth_required" });
egressContext.enterWith(authorizeEgress(request, config.mapGatewayAdminSecret, requestUrl.pathname));
if (requestUrl.pathname === `/api/map/reference-sources/v1/profiles/${TRANSPORT_STATION_PROFILE_ID}/current`
&& ["GET", "HEAD"].includes(request.method || "")) {
@@ -96,6 +100,7 @@ const server = createServer(async (request, response) => {
return writeJson(response, 200, {
ok: true,
service: "nodedc-map-gateway",
egressContract: "nodedc.map-egress/v1",
cache: await cacheStats(liveCache),
offlineSnapshot: offlineSnapshot ? await cacheStats(offlineSnapshot) : null,
diagnostics: gatewayDiagnostics.status(),
@@ -144,7 +149,7 @@ const server = createServer(async (request, response) => {
error: errorCode,
});
}
});
}));
server.listen(config.port, "0.0.0.0", () => {
console.log(`NODE.DC Map Gateway listening on http://0.0.0.0:${config.port}`);
@@ -1356,16 +1361,20 @@ function throughCesiumEgress(target, options = {}) {
async function fetchWithTimeout(target, options = {}, diagnostic = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), config.upstreamTimeoutMs);
const viaEgress = shouldUseCesiumEgress(target);
const binding = egressContext.getStore();
const viaRelay = Boolean(binding && canonicalCesiumEgressHosts.has(new URL(String(target)).hostname));
const viaEgress = viaRelay || shouldUseCesiumEgress(target);
const provider = safeProviderName(target);
const operation = safeProviderOperation(diagnostic.operation);
const assetId = /^\d{1,20}$/.test(String(diagnostic.assetId || "")) ? String(diagnostic.assetId) : undefined;
const request = viaEgress
const request = viaEgress && !viaRelay
? throughCesiumEgress(target, options)
: { target, options };
const startedAt = Date.now();
try {
const response = await fetch(request.target, { ...request.options, signal: controller.signal, redirect: "follow" });
const response = viaRelay
? await relayFetch(binding, target, {...options, signal: controller.signal})
: await fetch(request.target, { ...request.options, signal: controller.signal, redirect: "follow" });
const egressError = safeEgressErrorCode(response.headers.get("x-nodedc-egress-error"));
// The restricted egress emits a short code instead of a target URL or a
// secret. Preserve it through Map Gateway so the operator can distinguish
@@ -1498,7 +1507,8 @@ function createGatewayDiagnostics(slowUpstreamMs) {
function safeEgressErrorCode(value) {
const code = String(value || "").trim();
return /^amd_[a-z0-9_.:-]{1,100}$/.test(code) ? code : "";
const relay = new Set(["upstream_region_denied", "upstream_unavailable", "capacity_reached", "access_rejected", "request_rejected"]);
return /^amd_[a-z0-9_.:-]{1,100}$/.test(code) || relay.has(code) ? code : "";
}
function safeDiagnosticCode(value) {
+60
View File
@@ -0,0 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash,createHmac,X509Certificate} from 'node:crypto';
import {createServer} from 'node:https';
import {connect} from 'node:tls';
import {execFileSync} from 'node:child_process';
import {mkdtemp,readFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {authorizeEgress,publicIPv4,relayFetch,signingKey} from '../src/egress.mjs';
const secret='a'.repeat(64);
function signed(overrides={}) {
const value={schema:'nodedc.map-egress/v1',timestamp:1000,profile:'cesium',
endpoint:'https://1.1.1.1:19446',fingerprint:'b'.repeat(64),token:'c'.repeat(43),...overrides};
const payload=Buffer.from(JSON.stringify(value)).toString('base64url');
const signature=createHmac('sha256',signingKey(secret)).update(`nodedc.map-egress/v1\nGET\n/api/map/cache\n${payload}`).digest('hex');
return {method:'GET',headers:{'x-nodedc-map-egress':payload,'x-nodedc-map-egress-signature':signature}};
}
test('signed admission rejects tampering, expiry and a subject without delegation',()=>{
assert.equal(authorizeEgress(signed(),secret,'/api/map/cache',1000000).profile,'cesium');
assert.throws(()=>authorizeEgress(signed(),secret,'/api/map/ion',1000000));
assert.throws(()=>authorizeEgress(signed(),secret,'/api/map/cache',1031000));
assert.throws(()=>authorizeEgress(signed(),'wrong','/api/map/cache',1000000));
assert.throws(()=>authorizeEgress(signed({profile:'arbitrary'}),secret,'/api/map/cache',1000000));
assert.equal(authorizeEgress({headers:{'x-nodedc-user-id':'operator'}},secret,'/api/map/cache'),null);
});
test('public relay destination excludes private and special address ranges',()=>{
for(const address of ['127.0.0.1','0.0.0.0','10.1.1.1','100.64.0.1','169.254.169.254','172.22.0.1','192.168.1.2','198.18.0.1','203.0.113.1','224.0.0.1','::1']) assert.equal(publicIPv4(address),false,address);
assert.equal(publicIPv4('1.1.1.1'),true);
});
test('TLS pin checked before secrets; range and cancellation preserve transport boundaries',async()=>{
const folder=await mkdtemp(join(tmpdir(),'egress-test-'));
let server;
try {
execFileSync('openssl',['req','-x509','-newkey','ed25519','-nodes','-days','1','-subj','/CN=test','-keyout',join(folder,'key'),'-out',join(folder,'cert')],{stdio:'ignore'});
const cert=await readFile(join(folder,'cert')),key=await readFile(join(folder,'key'));
const fingerprint=createHash('sha256').update(new X509Certificate(cert).raw).digest('hex');
const received=[];
server=createServer({cert,key,minVersion:'TLSv1.3'},(req,res)=>{
received.push({url:req.url,headers:req.headers});
res.writeHead(206,{'content-type':'application/octet-stream','content-range':'bytes 1-3/4','set-cookie':'secret'});res.end('abc');
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const dependencies={lookup:async()=>[{address:'1.1.1.1'}],connect:options=>connect({...options,host:'127.0.0.1',port:server.address().port})};
const binding={endpoint:'https://1.1.1.1:19446',token:'c'.repeat(43),fingerprint};
await assert.rejects(relayFetch({...binding,fingerprint:'0'.repeat(64)},'https://assets.ion.cesium.com/a',{},dependencies),/identity_changed/);
assert.equal(received.length,0);
const response=await relayFetch(binding,'https://assets.ion.cesium.com/a',{headers:{authorization:'Bearer provider-secret',range:'bytes=1-3',cookie:'no'}},dependencies);
assert.equal(response.status,206);assert.equal(await response.text(),'abc');
assert.equal(response.headers.get('content-range'),'bytes 1-3/4');assert.equal(response.headers.get('set-cookie'),null);
assert.equal(received[0].headers.authorization,'Bearer '+binding.token);
assert.equal(received[0].headers['x-nodedc-upstream-authorization'],'Bearer provider-secret');
assert.equal(received[0].headers.cookie,undefined);
const cancelled=new AbortController();cancelled.abort();
await assert.rejects(relayFetch(binding,'https://assets.ion.cesium.com/a',{signal:cancelled.signal},dependencies));
assert.equal(received.length,1,'A cancelled request must not send credentials');
await assert.rejects(relayFetch(binding,'https://private.example/',{},dependencies));
} finally {if(server)await new Promise(resolve=>server.close(resolve));await rm(folder,{recursive:true,force:true});}
});