Compare commits
224
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cf7a91147 | ||
|
|
06b722160c | ||
|
|
dc95821766 | ||
|
|
bf3c2444ae | ||
|
|
0998d76428 | ||
|
|
3abfce339d | ||
|
|
e09f249f4c | ||
|
|
e629cf10bc | ||
|
|
f5cc50d29c | ||
|
|
aeaaae50c3 | ||
|
|
28d8466ef9 | ||
|
|
27c155276a | ||
|
|
39a2239563 | ||
|
|
1e191868be | ||
|
|
9dcd520503 | ||
|
|
7374ca57d7 | ||
|
|
50dc3b1a2c | ||
|
|
93b91a4b1e | ||
|
|
aba78dea98 | ||
|
|
feeb0766c0 | ||
|
|
d1c5401f52 | ||
|
|
f7416bc59a | ||
|
|
d46ecc4cb1 | ||
|
|
bc386ae504 | ||
|
|
ed500278a0 | ||
|
|
d161d7fb91 | ||
|
|
d87a0c48b4 | ||
|
|
ae5adfbd63 | ||
|
|
1adc0a66b3 | ||
|
|
1650c4f221 | ||
|
|
3321046c2a | ||
|
|
aa84e73bd8 | ||
|
|
f775929093 | ||
|
|
11b73e6468 | ||
|
|
6e2baf16fc | ||
|
|
dcf5304345 | ||
|
|
680ba0285e | ||
|
|
c3bd8023d6 | ||
|
|
853e423643 | ||
|
|
7b0e6d0bdf | ||
|
|
e642113124 | ||
|
|
bd715e9d71 | ||
|
|
8d501224b4 | ||
|
|
c5c4e69acb | ||
|
|
0438fbd80b | ||
|
|
e2ea7e177d | ||
|
|
209f4f439e | ||
|
|
a6771b2fbf | ||
|
|
502acd3771 | ||
|
|
87a1e64807 | ||
|
|
952290a49d | ||
|
|
6123a06527 | ||
|
|
12901e0e19 | ||
|
|
a6fb60d38f | ||
|
|
94e437e842 | ||
|
|
c1c9818e30 | ||
|
|
26dbcfd262 | ||
|
|
a9ea31f00a | ||
|
|
827bf0a58a | ||
|
|
40fbfcf351 | ||
|
|
185c54ced2 | ||
|
|
9c359111ea | ||
|
|
71fff82c99 | ||
|
|
fe1c8054be | ||
|
|
3ea2133bcd | ||
|
|
4b73a15765 | ||
|
|
bdb85cb4f7 | ||
|
|
66e0c62451 | ||
|
|
606872edcc | ||
|
|
6fd172ecc5 | ||
|
|
e21c188f85 | ||
|
|
b513ed973b | ||
|
|
20ef5894cc | ||
|
|
9fa74a1243 | ||
|
|
020d4dbad7 | ||
|
|
d8c0e9f3b1 | ||
|
|
c2d06bddc7 | ||
|
|
2eb6116880 | ||
|
|
6fa9164933 | ||
|
|
e85bb1448e | ||
|
|
3a13f0effc | ||
|
|
1e01161a83 | ||
|
|
d641744dca | ||
|
|
bb0724c52c | ||
|
|
094cf7143a | ||
|
|
f53759cb15 | ||
|
|
35c37de586 | ||
|
|
0f44cca27d | ||
|
|
724e745628 | ||
|
|
be964eccb7 | ||
|
|
6461e7fca8 | ||
|
|
1124c15216 | ||
|
|
50b9179fe4 | ||
|
|
393741f1bd | ||
|
|
227c7c26c1 | ||
|
|
c9d6068f36 | ||
|
|
42892cd43b | ||
|
|
5565486ac9 | ||
|
|
28371f67a5 | ||
|
|
6a8c1ce1ef | ||
|
|
9f12edd736 | ||
|
|
72b4846b32 | ||
|
|
1adbabefcf | ||
|
|
37bdbebb4e | ||
|
|
8defd55715 | ||
|
|
04ba3a9f99 | ||
|
|
4374a9b4e7 | ||
|
|
0679142561 | ||
|
|
29ba5de92e | ||
|
|
1d1e9a96b3 | ||
|
|
f5d7916338 | ||
|
|
43dc9b1f45 | ||
|
|
422ddb020f | ||
|
|
fceaca9546 | ||
|
|
72db23c0e9 | ||
|
|
9fdaed1c95 | ||
|
|
70bafdd028 | ||
|
|
336602c7ca | ||
|
|
bf0bc50abb | ||
|
|
07224c6f0d | ||
|
|
6352a26020 | ||
|
|
e868fd4bcf | ||
|
|
cd5bf2a6d9 | ||
|
|
4f75f57177 | ||
|
|
b48b6dbfc9 | ||
|
|
0688516003 | ||
|
|
96227461dd | ||
|
|
1eb6c462e3 | ||
|
|
3bb5e6dc27 | ||
|
|
b1a5a26b9a | ||
|
|
558940f691 | ||
|
|
9d8638b8d2 | ||
|
|
a3308c9b3d | ||
|
|
2b1795509b | ||
|
|
3c538ad98c | ||
|
|
aca47c6143 | ||
|
|
1102e25e6e | ||
|
|
e217723784 | ||
|
|
e9e03143cd | ||
|
|
951b884c4b | ||
|
|
fe274872e4 | ||
|
|
f0a4fb43c5 | ||
|
|
a9fe5f44e3 | ||
|
|
c19b0789c7 | ||
|
|
34769af350 | ||
|
|
659f98ad8f | ||
|
|
abebb9fac6 | ||
|
|
8cc917508e | ||
|
|
eab47bc1fa | ||
|
|
f02a1d4125 | ||
|
|
73364b4acb | ||
|
|
59f9fc2b26 | ||
|
|
25b12d77e4 | ||
|
|
4cf3a83ef1 | ||
|
|
a5a5644dbf | ||
|
|
6f9da1b677 | ||
|
|
f97a9d924d | ||
|
|
e4383b6162 | ||
|
|
50cba59bde | ||
|
|
ad3760e767 | ||
|
|
2a30e1e991 | ||
|
|
ec45d09509 | ||
|
|
9db0de540d | ||
|
|
6c764d0d28 | ||
|
|
93eb13219a | ||
|
|
23919e384e | ||
|
|
4cdc78d545 | ||
|
|
e843bbda66 | ||
|
|
2def90fa33 | ||
|
|
92070f21e8 | ||
|
|
fdda153595 | ||
|
|
4402c9ed25 | ||
|
|
a9b8d71968 | ||
|
|
45884cd4dc | ||
|
|
358b259aac | ||
|
|
bc23c550db | ||
|
|
77bf8036d2 | ||
|
|
9bebd2f504 | ||
|
|
92d292ce87 | ||
|
|
343812b90d | ||
|
|
3446f3edc2 | ||
|
|
8a7465cf0e | ||
|
|
def9a24e0d | ||
|
|
847a08da93 | ||
|
|
56b766b23b | ||
|
|
d85912b9d7 | ||
|
|
f67c49bc4d | ||
|
|
95446bdc24 | ||
|
|
0611a88971 | ||
|
|
3c5d8f6cef | ||
|
|
02816c4352 | ||
|
|
31e078d6e5 | ||
|
|
2dd6e33a54 | ||
|
|
a0a4d36fa2 | ||
|
|
3415674e76 | ||
|
|
567f1550ab | ||
|
|
fedaf24098 | ||
|
|
7b55d887bc | ||
|
|
59e9c92415 | ||
|
|
569b8762e6 | ||
|
|
e527812826 | ||
|
|
d196d4b0c7 | ||
|
|
7ef0ca8eab | ||
|
|
a31b679ab9 | ||
|
|
7460258228 | ||
|
|
099796a61d | ||
|
|
a7c6c34c82 | ||
|
|
1aceabee44 | ||
|
|
5953b1bd0e | ||
|
|
f35cd34167 | ||
|
|
e11f9bd7e7 | ||
|
|
7003efa75a | ||
|
|
79928d822e | ||
|
|
999fe4d906 | ||
|
|
92feff97e6 | ||
|
|
f8c19d712a | ||
|
|
1aaf53c378 | ||
|
|
25b4ce0f6d | ||
|
|
cfaed054d1 | ||
|
|
6258de83e3 | ||
|
|
3526351b1b | ||
|
|
2d5fef3948 | ||
|
|
83cca4224b | ||
|
|
390907cc9c |
@@ -16,6 +16,9 @@ build/
|
|||||||
.next/
|
.next/
|
||||||
coverage/
|
coverage/
|
||||||
|
|
||||||
|
# canonical deploy packages are transferred through the NAS inbox, not Git
|
||||||
|
infra/deploy-artifacts/
|
||||||
|
|
||||||
# logs
|
# logs
|
||||||
*.log
|
*.log
|
||||||
logs/
|
logs/
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ Git repo:
|
|||||||
- `services/notification-core/README.md`
|
- `services/notification-core/README.md`
|
||||||
- `services/ai-workspace-assistant/README.md`
|
- `services/ai-workspace-assistant/README.md`
|
||||||
- `services/ai-workspace-hub/README.md`
|
- `services/ai-workspace-hub/README.md`
|
||||||
|
- `services/ontology-core/README.md`
|
||||||
- `tasks/CODEX_PLATFORM_AUTH_TASK.md`
|
- `tasks/CODEX_PLATFORM_AUTH_TASK.md`
|
||||||
|
|
||||||
## Базовое правило
|
## Базовое правило
|
||||||
@@ -43,3 +44,9 @@ Plane не переносится внутрь Launcher. Launcher не стан
|
|||||||
Notification Core живёт в `services/notification-core` как отдельный платформенный сервис с собственным Postgres. Он не использует Authentik DB: Authentik отвечает за identity/session, Notification Core отвечает за events/deliveries/read-state.
|
Notification Core живёт в `services/notification-core` как отдельный платформенный сервис с собственным Postgres. Он не использует Authentik DB: Authentik отвечает за identity/session, Notification Core отвечает за events/deliveries/read-state.
|
||||||
|
|
||||||
AI Workspace Assistant живёт в `services/ai-workspace-assistant` как общий платформенный слой для пользовательских Codex executors, selected executor, shared conversations, surfaces и tool packs. AI Workspace Hub остаётся отдельным тонким транспортом для remote Codex workers и не хранит смысловое состояние ассистента.
|
AI Workspace Assistant живёт в `services/ai-workspace-assistant` как общий платформенный слой для пользовательских Codex executors, selected executor, shared conversations, surfaces и tool packs. AI Workspace Hub остаётся отдельным тонким транспортом для remote Codex workers и не хранит смысловое состояние ассистента.
|
||||||
|
|
||||||
|
Ontology Core живёт в `services/ontology-core` как docs-first семантический слой для canonical entities, relations, aliases, guardrails, evidence, первого resolver MVP между OPS и ENGINE и policy MVP для NDC Core Assistant access. Он не владеет доменными БД HUB/OPS/ENGINE и не заменяет Launcher/HUB roles или OPS Gateway enforcement.
|
||||||
|
|
||||||
|
Map Gateway живёт в `services/map-gateway` как общий platform boundary для provider credentials, безопасного asset endpoint exchange, tile/3D Tiles proxy и persistent offline TileCache. Runtime cache не является source artifact и хранится в named volume/object storage, а не в Git.
|
||||||
|
|
||||||
|
Внешние бизнес-поставщики подключаются по `packages/external-provider-contract`: adapter конкретного API принадлежит изолированному NDC L2 workflow, а Platform даёт один provider-neutral External Data Plane для raw retention, canonical facts, current/history projections и scoped read products. Connection instance несёт tenant scope, credential reference и collection profile, но не secret value. Provider/domain mapping, entity filtering и renderer logic не попадают в Platform Data Plane. Provider-issued credentials сохраняются в native NDC L2 Credentials; внутренний scoped publish grant генерируется и сохраняется generic control plane внутри native credential boundary, EDP получает только digest, а MCP видит только opaque reference/status. Legacy plaintext provisioning и managed digest-only ensure включаются независимо и по умолчанию закрыты. Подробный канон — `docs/ADR_L2_OWNED_EXTERNAL_CONNECTORS.md`.
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
{"schemaVersion":"nodedc.mission-core-map-access.v1","state":"enabled"}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# ADR: канон External Provider Data Plane
|
||||||
|
|
||||||
|
Статус: **superseded**.
|
||||||
|
Дата: 2026-07-13.
|
||||||
|
Владелец решения: NODE.DC Platform.
|
||||||
|
|
||||||
|
> Заменено 2026-07-14 документом
|
||||||
|
> [`ADR_L2_OWNED_EXTERNAL_CONNECTORS.md`](ADR_L2_OWNED_EXTERNAL_CONNECTORS.md).
|
||||||
|
> Этот черновик неверно помещал provider adapter, normalisation и collection
|
||||||
|
> policy в `services/<provider>-gateway`. Новое правило: adapter принадлежит
|
||||||
|
> изолированному L2 workflow; Platform Data Plane остаётся provider-neutral.
|
||||||
|
|
||||||
|
## Контекст
|
||||||
|
|
||||||
|
Клиент может подключить к NODE.DC любой внешний продукт: телеметрию, ERP,
|
||||||
|
роботов, энергетику, BIM-систему или иной источник данных. Gelios Pro для
|
||||||
|
Gelios — первый конкретный поставщик для проверки канона, а не исключительная
|
||||||
|
архитектурная ветка. Нельзя превращать Engine workflow, Ontology Core или общую БД Platform
|
||||||
|
в место, куда попадают токены, raw payloads и частная логика каждого API.
|
||||||
|
|
||||||
|
Нужна повторяемая форма, в которой новый provider добавляется как отдельный
|
||||||
|
adapter, но получает общие правила scope, секретов, collection, хранения,
|
||||||
|
read-model, аудита и безопасной публикации в NDC.
|
||||||
|
|
||||||
|
## Решение
|
||||||
|
|
||||||
|
1. В `platform/packages/external-provider-contract` живёт общий versioned
|
||||||
|
контракт интеграции. Это не runtime и не база данных. Он задаёт форму
|
||||||
|
`provider`, `connection`, `capability catalog`, `credential reference`,
|
||||||
|
`access scope`, `field policy`, `collection profile`, `retention policy`,
|
||||||
|
`read model` и красный command-domain.
|
||||||
|
2. Каждый provider получает самостоятельный app-owned adapter в
|
||||||
|
`platform/services/<provider>-gateway`. Первый экземпляр —
|
||||||
|
`platform/services/gelios-gateway`. Adapter владеет intake contract, rate
|
||||||
|
budget, normalisation, collection policy, storage и своим internal
|
||||||
|
read/realtime API. Сам provider secret остаётся в Engine Credentials и
|
||||||
|
доступен только назначенному защищённому execution workflow.
|
||||||
|
3. Один provider service может обслуживать много клиентов. Каждая строка,
|
||||||
|
cursor, audit-event и read-model обязана иметь `tenant_id` и
|
||||||
|
`connection_id`; видимость provider account сама по себе не является
|
||||||
|
продуктовым scope. Для клиента с отдельными требованиями изоляции допустим
|
||||||
|
отдельный deployment/database profile без изменения контракта.
|
||||||
|
4. База принадлежит adapter-сервису, а не Ontology Core, Engine, Tasker или
|
||||||
|
общему Platform Postgres. Для пространственно-временного Gelios-кейса
|
||||||
|
базой служит PostgreSQL 16 + TimescaleDB + PostGIS (`gelios-postgres`).
|
||||||
|
Другой provider может выбрать иной storage engine только через явный ADR,
|
||||||
|
сохранив внешний контракт.
|
||||||
|
5. Ontology Core хранит только provider-neutral и provider-specific смыслы,
|
||||||
|
связи, правила и контракты. Он не хранит credentials, runtime telemetry,
|
||||||
|
customer raw payloads или renderer objects. Enforcement остаётся в
|
||||||
|
gateway/adapters. Engine Credentials хранит provider secret в границе
|
||||||
|
специально назначенного execution workflow; значение не сериализуется в
|
||||||
|
граф, ontology, логи, read-model или UI.
|
||||||
|
6. Engine L2 Collector использует credential reference и получает разрешённые
|
||||||
|
данные поставщика. Он передаёт в adapter только аутентифицированный нормализованный
|
||||||
|
intake payload. Остальные L2 workflow получают исключительно scoped
|
||||||
|
internal API/event contract и не читают gateway DB напрямую.
|
||||||
|
|
||||||
|
## Каноническая форма нового подключения
|
||||||
|
|
||||||
|
```text
|
||||||
|
Client / tenant
|
||||||
|
-> Engine Credential + protected Collector workflow
|
||||||
|
-> provider connection instance
|
||||||
|
-> provider adapter (safe intake policy + normalizer)
|
||||||
|
-> provider-owned storage and projections
|
||||||
|
-> internal read/realtime contract
|
||||||
|
-> L2 workflow / approved interface binding
|
||||||
|
-> renderer adapter
|
||||||
|
```
|
||||||
|
|
||||||
|
Каждый новый provider добавляет только свой adapter package, capability
|
||||||
|
catalog, schema mappings, scrubbed fixtures и domain ontology package. Он не
|
||||||
|
добавляет отдельную схему доступа к Engine/Studio и не создаёт прямой путь из
|
||||||
|
browser в provider API.
|
||||||
|
|
||||||
|
## Полнота данных без неконтролируемого объёма
|
||||||
|
|
||||||
|
«Предусмотреть все данные» означает каталогизировать каждую provider
|
||||||
|
capability и поле, а не опрашивать весь account на максимальной частоте.
|
||||||
|
Collection profile явно решает, какие safe-read capabilities, поля, scope и
|
||||||
|
частота включены в конкретной connection instance.
|
||||||
|
|
||||||
|
| Слой | Что хранится | Режим |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Capability catalog | documented endpoint/read-field/command capability и его риск | versioned source + ontology |
|
||||||
|
| Inventory/configuration | units, devices, groups, sensors, custom definitions | медленный reconcile |
|
||||||
|
| Current projection | последняя разрешённая позиция, состояние и display fields | idempotent upsert |
|
||||||
|
| Event history | нормализованные события и approved measurements | append-only, partitioned |
|
||||||
|
| Raw envelope | полный safe-read ответ с provenance и hash | restricted cold layer, retention-bound |
|
||||||
|
| Aggregates/features | rollups и признаки для аналитики/предиктива | derived, replaceable |
|
||||||
|
|
||||||
|
Raw envelope не выдаётся UI и не становится таблицей «всё в JSON навсегда».
|
||||||
|
Вначале он может быть compressed/partitioned storage с метаданными в БД; при
|
||||||
|
реальном объёме переносится в object storage, а PostgreSQL хранит immutable
|
||||||
|
index, hash, policy и ссылку. Retention, raw depth и downsampling утверждаются
|
||||||
|
после замера сообщений/сек, размера payload, требуемой истории, RPO/RTO и
|
||||||
|
стоимости. Так инженер может запросить ранее не показанное поле из
|
||||||
|
каталога/архива, не раздувая горячую read-модель.
|
||||||
|
|
||||||
|
## Realtime и интерфейс
|
||||||
|
|
||||||
|
Частота provider collection, обновления `current projection` и выдачи в UI —
|
||||||
|
три разные настройки. Например, map consumer может получать выбранную
|
||||||
|
read-модель раз в 3 секунды, но это не даёт ему права опрашивать Gelios раз в
|
||||||
|
3 секунды или создавать отдельный polling loop на каждого зрителя.
|
||||||
|
|
||||||
|
Gateway сначала обновляет одну current projection и публикует change event.
|
||||||
|
L2/Map binding затем может sampling/throttle этот поток по утверждённой
|
||||||
|
настройке интерфейса. Источник истины для live state — gateway storage, не
|
||||||
|
долгоживущий workflow и не Cesium session.
|
||||||
|
|
||||||
|
## Commands: моделируются, но не подключаются
|
||||||
|
|
||||||
|
Command templates, параметры, delivery states и audit входят в capability
|
||||||
|
catalog и ontology полностью. Read adapter не содержит send route и не
|
||||||
|
использует command capability. В будущем command execution создаётся только
|
||||||
|
как отдельный `provider-command-gateway`/red-domain deployment с явным
|
||||||
|
человеческим подтверждением, role/scope check, idempotency, audit и отдельным
|
||||||
|
security review. До этого команда не может быть отправлена из collector, L2,
|
||||||
|
Map или AI Workspace.
|
||||||
|
|
||||||
|
## Обязательные артефакты каждого adapter
|
||||||
|
|
||||||
|
- `provider manifest`: provider id, adapter version, auth modes, rate limits;
|
||||||
|
- capability and field catalog: read/write classification, source evidence,
|
||||||
|
pagination and error semantics;
|
||||||
|
- connection profile: tenant, secret reference, approved scope, field policy,
|
||||||
|
collection and retention profile;
|
||||||
|
- normalised contract and migrations; scrubbed fixtures and contract tests;
|
||||||
|
- health/metrics/audit without secrets or raw personal data;
|
||||||
|
- ontology package with stable subjects, relations and guardrails;
|
||||||
|
- internal read/realtime API contract; no browser/provider bypass.
|
||||||
|
|
||||||
|
## Не решено этим ADR
|
||||||
|
|
||||||
|
- конкретный deployment topology и HA/PITR target для каждого volume;
|
||||||
|
- выбор object storage после real-volume measurement;
|
||||||
|
- L2 stream execution contract и Module Studio binding implementation;
|
||||||
|
- параметры first Gelios collection profile и owner-approved connection scope.
|
||||||
|
|
||||||
|
Gelios-specific применение этого решения описано в
|
||||||
|
`docs/ADR_GELIOS_DATA_PLANE.md`.
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
# ADR: Gelios adapter в External Provider Data Plane
|
||||||
|
|
||||||
|
Статус: **superseded**.
|
||||||
|
Дата: 2026-07-13.
|
||||||
|
Владелец решения: NODE.DC Platform.
|
||||||
|
|
||||||
|
> Заменено 2026-07-14 документом
|
||||||
|
> [`ADR_L2_OWNED_EXTERNAL_CONNECTORS.md`](ADR_L2_OWNED_EXTERNAL_CONNECTORS.md).
|
||||||
|
> Gelios остаётся domain/ontology примером, но не получает отдельный
|
||||||
|
> provider-owned gateway: fetch, mapping и collection policy живут в его L2
|
||||||
|
> connector instance; Platform предоставляет нейтральный Data Plane.
|
||||||
|
|
||||||
|
## Контекст
|
||||||
|
|
||||||
|
Gelios Pro поставляет непрерывную телеметрию, конфигурацию устройств и пространственные данные. В текущем доступе подтверждены 107 видимых units, из них 105 с `lastMsg`; окончательный connection scope должен быть зафиксирован allowlist-ом владельца. Это не данные Ontology Core и не данные Tasker. Они требуют отдельного контура для текущего состояния, истории, геозапросов, аналитики и будущих прогнозов.
|
||||||
|
|
||||||
|
Gelios является первым provider adapter, который подчиняется общему
|
||||||
|
`docs/ADR_EXTERNAL_PROVIDER_DATA_PLANE.md`: connection instance хранит
|
||||||
|
connection scope/policy, Engine Credentials владеет provider secret, gateway
|
||||||
|
владеет storage/read-моделью, а ontology описывает значения, но не runtime
|
||||||
|
data.
|
||||||
|
|
||||||
|
Физические trike-команды существуют в домене, но **не входят в ingestion или тестирование**. Для них позднее потребуется отдельный, ручной и аудируемый контур.
|
||||||
|
|
||||||
|
## Решение
|
||||||
|
|
||||||
|
1. Создать отдельный сервис `platform/services/gelios-gateway` как storage/read gateway:
|
||||||
|
- не хранит и не получает provider token;
|
||||||
|
- принимает только аутентифицированный safe-read intake от защищённого Engine L2 Collector workflow;
|
||||||
|
- применяет allowlist и field policy до записи;
|
||||||
|
- нормализует ответ в сущности пакета `gelios`;
|
||||||
|
- публикует read-модель для Engine L2 workflow и Map View.
|
||||||
|
2. В Engine появляется отдельный Gelios Credential и NDC Agent L2 collection profile:
|
||||||
|
- credential скрывает access/refresh pair и его lifecycle;
|
||||||
|
- credential привязан только к намеренно пошаренному Collector workflow;
|
||||||
|
- Collector содержит allowlist read-capabilities и не имеет command transport;
|
||||||
|
- ни секрет, ни provider response без нормализации не передаются в ontology, UI, Gateway или другие workflow.
|
||||||
|
3. Выделить сервису собственную БД `gelios-postgres`, не деля её с Tasker, Authentik, Notification Core или Ontology Core. В будущей multi-tenant форме эта БД обслуживает несколько Gelios connection instances, но все records разделены `tenant_id` и `connection_id`.
|
||||||
|
4. Базовый движок: PostgreSQL 16 с расширениями TimescaleDB и PostGIS.
|
||||||
|
- Timescale hypertable хранит временные ряды и автоматически делит их по времени.
|
||||||
|
- PostGIS хранит нормализованные точки и геометрии зон, а не renderer-объекты Cesium.
|
||||||
|
- Данный выбор покрывает транзакционную конфигурацию, realtime upsert, исторические запросы, SQL-аналитику и географию одним контуром.
|
||||||
|
5. **Не** использовать RabbitMQ Tasker как общую шину Gelios. Если измерения покажут, что прямой writer или число независимых потребителей не справляются, добавить в Gelios-контур NATS JetStream с durable pull consumers. Он даст replay, acknowledgement и контролируемое удержание сообщений.
|
||||||
|
6. Engine level-2 Collector — единственная точка provider access; остальные workflow являются потребителями read-модели. Ontology Core остаётся только словарём и контрактами.
|
||||||
|
|
||||||
|
## Целевой поток
|
||||||
|
|
||||||
|
```text
|
||||||
|
Gelios REST (safe read only)
|
||||||
|
-> NDC Agent L2 collection profile + protected credential
|
||||||
|
-> authenticated normalized intake
|
||||||
|
-> Gelios Gateway: scope -> field policy -> normalizer
|
||||||
|
-> gelios-postgres: current state + immutable telemetry history
|
||||||
|
-> [при необходимости] NATS JetStream
|
||||||
|
-> `fleet.positions.current.v1` read API / realtime subscription
|
||||||
|
-> NDC workflow level 2
|
||||||
|
-> Map View semantic binding
|
||||||
|
-> Cesium renderer adapter
|
||||||
|
```
|
||||||
|
|
||||||
|
Ни один шаг не получает права отправить команду устройству. Красный command-domain находится вне этого потока; metadata каталога команд сохраняется, но send transport не создаётся.
|
||||||
|
|
||||||
|
## Модель хранения v0
|
||||||
|
|
||||||
|
| Слой | Назначение | Минимальные записи |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Контроль | граница и повторяемость сбора | `access_scope`, `collection_run`, `ingestion_cursor`, endpoint/response metrics |
|
||||||
|
| Каталог | стабильные сущности и их конфигурация | `unit`, `unit_group`, `tracker_device`, sensor/maintenance/custom-field definitions |
|
||||||
|
| Current state | одна актуальная запись на unit для карты и интерфейса | `unit_current`, `position_fix`, approved operational status |
|
||||||
|
| History | неизменяемые события с временем наблюдения и получения | `telemetry_snapshot`, selective `sensor_reading`, restricted raw payload reference |
|
||||||
|
| Spatial | геометрии для запросов, не Cesium graphics | point/track/geozone with SRID 4326 |
|
||||||
|
| Analytics | роллапы и признаки, не запросы по всему raw | hourly/daily aggregates, feature sets, model runs |
|
||||||
|
| Audit | попытки, ошибки, политика, будущие команды | collection audit; separate command audit later |
|
||||||
|
|
||||||
|
`unit_current` обновляется idempotently по `unitSubjectId`. История записывается append-only с ключом дедупликации, включающим provider unit id, observed time и fingerprint сообщения. Все временные таблицы имеют `observed_at` и `received_at`: задержка поставщика не должна переписывать фактическое время на карте.
|
||||||
|
|
||||||
|
## Индексы и жизненный цикл
|
||||||
|
|
||||||
|
- Основной путь истории: `(unit_subject_id, observed_at DESC)`.
|
||||||
|
- Пространственный индекс только для нормализованной geography/geometry; рендер-кэши в БД не храним.
|
||||||
|
- Сырые `params`/raw messages — restricted, отдельно от публичной Studio read-model.
|
||||||
|
- Политики retention, downsampling и резервного копирования должны быть утверждены до запуска history backfill. Они зависят от фактических msg/s, размера payload, нужной глубины истории, RPO/RTO и стоимости хранения.
|
||||||
|
- Для предиктива держать recent/raw слой и отдельные часовые/дневные агрегаты. Timescale continuous aggregates позволяют сохранять длительную агрегированную историю после сокращения raw при корректно согласованных refresh и retention политиках.
|
||||||
|
|
||||||
|
## Нулевая итерация без лишней инфраструктуры
|
||||||
|
|
||||||
|
1. Зафиксировать owner-approved allowlist и видимые поля.
|
||||||
|
2. Сделать только safe-read Engine Collector с ограничением по scope, rate limit, paging и cursor.
|
||||||
|
3. В течение согласованного окна измерить: сообщений/сек, размер ответа, lag, дубликаты, задержку записи и нагрузку запросов карты.
|
||||||
|
4. На фактах включить Timescale hypertables, PostGIS и retention policy; после этого решить, нужен ли JetStream сразу.
|
||||||
|
5. Подать только `fleet.positions.current.v1`/approved current position в Map View. Историю и raw не отдавать в renderer напрямую.
|
||||||
|
|
||||||
|
## Что не решено этим ADR
|
||||||
|
|
||||||
|
- окончательное правило connection scope;
|
||||||
|
- частота polling/возможность provider push;
|
||||||
|
- сроки хранения raw, нормализованной истории и агрегатов;
|
||||||
|
- RPO/RTO, репликация и production backup plan;
|
||||||
|
- допуск к ручному command gateway. До отдельного решения отправка команд запрещена.
|
||||||
|
|
||||||
|
## Обоснование и источники
|
||||||
|
|
||||||
|
- [Timescale hypertables](https://docs.timescale.com/use-timescale/latest/hypertables/) — временные таблицы PostgreSQL автоматически партиционируются по времени.
|
||||||
|
- [Timescale self-hosted installation](https://docs.timescale.com/self-hosted/latest/install/) — расширение разворачивается как self-hosted PostgreSQL-контур; production требует backup/PITR и HA-плана.
|
||||||
|
- [Retention и continuous aggregates](https://docs.timescale.com/use-timescale/latest/data-retention/data-retention-with-continuous-aggregates/) — raw и агрегаты требуют согласованных lifecycle-политик.
|
||||||
|
- [PostGIS](https://postgis.net/docs/en/) — PostgreSQL-расширение для spatial types и GiST R-tree индексов.
|
||||||
|
- [NATS JetStream consumers](https://docs.nats.io/nats-concepts/jetstream/consumers) — durable consumers дают acknowledgement, повторную доставку и recovery; рекомендуются pull consumers для новых масштабируемых обработчиков.
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
# ADR: внешние коннекторы принадлежат NDC L2 workflow
|
||||||
|
|
||||||
|
Статус: **accepted**.
|
||||||
|
Дата: 2026-07-16.
|
||||||
|
Владелец решения: NODE.DC Platform.
|
||||||
|
|
||||||
|
## Контекст
|
||||||
|
|
||||||
|
NODE.DC состоит из двух разных слоёв:
|
||||||
|
|
||||||
|
- платформенный слой даёт NDC L1, NDC L2, Ontology, credentials, Data Products
|
||||||
|
и Foundry-boundaries;
|
||||||
|
- пользовательские автоматизации собирают из этих возможностей конкретную
|
||||||
|
бизнес-логику.
|
||||||
|
|
||||||
|
Новый account, provider credential, tenant, расписание или интерфейс не должны создавать
|
||||||
|
новый platform service и не должны требовать изменения NODE.DC source. Команда
|
||||||
|
NODE.DC подключается только для нового поставщика либо для расширения
|
||||||
|
подтверждённых capabilities и ontology уже поддержанного поставщика.
|
||||||
|
|
||||||
|
Gelios — первый живой источник и acceptance-кейс этого канона, а не отдельная
|
||||||
|
архитектурная ветка. Документ заменяет provider-runtime решения из
|
||||||
|
`ADR_EXTERNAL_PROVIDER_DATA_PLANE.md` и `ADR_GELIOS_DATA_PLANE.md`; те
|
||||||
|
документы остаются только историей решения.
|
||||||
|
|
||||||
|
## Решение
|
||||||
|
|
||||||
|
### 1. Пакет поставщика создаётся один раз
|
||||||
|
|
||||||
|
Каждый поддержанный поставщик получает один версионируемый **provider package**.
|
||||||
|
Он является знанием платформы о внешнем API и содержит:
|
||||||
|
|
||||||
|
- стабильный `providerId` и версии подтверждённого API;
|
||||||
|
- credential contract без значения секрета;
|
||||||
|
- каталог safe-read capabilities, pagination/rate-limit metadata и response
|
||||||
|
shapes;
|
||||||
|
- mappings из provider fields в версии Ontology;
|
||||||
|
- совместимые Data Products и scrubbed contract fixtures;
|
||||||
|
- явно отделённый каталог команд без активного command transport.
|
||||||
|
|
||||||
|
Пакет не является runtime service, scheduler, базой данных или customer
|
||||||
|
configuration. Он расширяется только когда фактически подтверждён новый API,
|
||||||
|
новый тип данных или новая ontology revision.
|
||||||
|
|
||||||
|
Одна учётная запись поставщика задаётся данными, а не кодом:
|
||||||
|
|
||||||
|
`provider package + credential reference + connection profile + NDC L2 workflow instance`
|
||||||
|
|
||||||
|
Поэтому второй account или другая provider credential pair создаёт ещё один credential/profile и
|
||||||
|
workflow instance. Платформенный source, Data Plane и Foundry при этом не
|
||||||
|
меняются.
|
||||||
|
|
||||||
|
### 2. NDC L1 проектирует, NDC L2 workflow исполняет
|
||||||
|
|
||||||
|
NDC L1 получает пользовательское намерение, проверяет доступные capabilities и
|
||||||
|
Ontology, проектирует или изменяет разрешённый NDC L2 workflow через NDC MCP и
|
||||||
|
анализирует execution evidence.
|
||||||
|
|
||||||
|
Один изолированный NDC L2 workflow представляет один connection instance и
|
||||||
|
владеет исполняемой механикой:
|
||||||
|
|
||||||
|
- safe-read вызовами provider API через credential reference;
|
||||||
|
- pagination, cursor, retry, rate limit, batch size и collection cadence;
|
||||||
|
- проверкой response shape и разбиением ответа на items;
|
||||||
|
- mapping к точной ontology revision;
|
||||||
|
- idempotency, watermark и публикацией canonical facts;
|
||||||
|
- private workflow state, когда он действительно нужен.
|
||||||
|
|
||||||
|
Provider-specific mapping сначала реализуется штатными workflow nodes и малым
|
||||||
|
Code-преобразователем. Это позволяет проверить реальный API без преждевременного
|
||||||
|
создания custom nodes. В custom NDC nodes переносится только повторившаяся и
|
||||||
|
доказанная **платформенная boundary-механика**, а не уникальная логика
|
||||||
|
поставщика.
|
||||||
|
|
||||||
|
### 3. Credentials являются данными connection instance
|
||||||
|
|
||||||
|
Gelios выдаёт ровно два provider secrets: access token и refresh token. Текущий
|
||||||
|
HTTP request binding `httpBearerAuth` использует access token. Автоматический
|
||||||
|
refresh в принятом runtime не доказан, поэтому provider package фиксирует его
|
||||||
|
как `operator_managed`; ни один из token values не попадает в graph, package,
|
||||||
|
Ontology, Data Plane, Foundry, execution logs, MCP или Ops. Новый account или
|
||||||
|
provider-issued token pair означает новые native credential records и
|
||||||
|
connection instance, но не новую Platform-сущность.
|
||||||
|
|
||||||
|
Локальное имя credential (например, с суффиксом `read access`) не является
|
||||||
|
provider scope. В target-контракте Read-классификацию задаёт allowlisted
|
||||||
|
method/endpoint в capability catalog и Engine workflow policy; тот же access
|
||||||
|
token нельзя называть отдельным «read token» или «write token» только из-за
|
||||||
|
label. Сейчас deployed Engine safe-ref policy ограничивает generic HTTP
|
||||||
|
credential только по host, но ещё не связывает его с package/version и exact
|
||||||
|
method/path. Поэтому Gelios `GET /api/v1/units` пока является декларативной
|
||||||
|
capability, а не завершённой runtime-security гарантией; canonical acceptance
|
||||||
|
требует capability-bound Engine policy и её MCP proof.
|
||||||
|
|
||||||
|
Writer capability для публикации Data Product — отдельный внутренний native NDC
|
||||||
|
L2 credential, не третий Gelios token. Generic Engine/Platform control plane
|
||||||
|
генерирует capability внутри native credential boundary, сохраняет её там же и
|
||||||
|
передаёт EDP только SHA-256 digest вместе с точным provider, connection и
|
||||||
|
набором Data Products. Пользователь и MCP получают только opaque
|
||||||
|
reference/status. Capability не записывается в graph, provider package, env,
|
||||||
|
file, Ops или trace и не копируется через пользовательский UI.
|
||||||
|
|
||||||
|
Широкий credential sink, resolver/daemon с произвольной записью secret и любой
|
||||||
|
provider-specific credential service запрещены. Нужна одна узкая операция
|
||||||
|
`ensure data-product publish grant`: scope выводится из granted L1→L2 target,
|
||||||
|
зарегистрированного connection profile и разрешённого Data Product; issuance,
|
||||||
|
rotation и native binding должны быть idempotent, CAS/crash-safe и auditable.
|
||||||
|
Engine генерирует capability внутри credential boundary и передаёт EDP только
|
||||||
|
SHA-256 digest через idempotent binding key + generation; EDP не возвращает
|
||||||
|
plaintext. Новая generation создаётся до переключения node reference, а старая
|
||||||
|
отзывается только после успешного bind/acceptance.
|
||||||
|
Старые ручные EDP `POST/rotate` endpoints, которые возвращают capability один
|
||||||
|
раз, включаются отдельным legacy-флагом и не входят в canonical acceptance.
|
||||||
|
Digest-only managed endpoint имеет независимый флаг и принимает только
|
||||||
|
Ed25519-signed Engine service requests: exact audience/method/request target/raw
|
||||||
|
body hash входят в подпись, timestamp ограничен по skew, nonce защищён bounded
|
||||||
|
fail-closed replay cache. Legacy provisioner bearer на managed routes не
|
||||||
|
действует. EDP получает только deployment public key; matching private key
|
||||||
|
остаётся только внутри Engine server boundary. Endpoint остаётся выключенным,
|
||||||
|
пока key provisioning, Engine signer и exact native credential binding policy
|
||||||
|
не пройдут runtime acceptance.
|
||||||
|
В deployed Engine MCP этой операции пока нет — это текущий platform gap перед
|
||||||
|
canonical publish proof, а не действие пользователя. Это решение не заявляет
|
||||||
|
автоматический refresh Gelios: до отдельного runtime proof он остаётся
|
||||||
|
`operator_managed`.
|
||||||
|
|
||||||
|
### 4. External Data Plane нейтрален к поставщику
|
||||||
|
|
||||||
|
Platform предоставляет один versioned External Data Plane. Он принимает
|
||||||
|
canonical facts через scoped writer binding, хранит current/history
|
||||||
|
projections и публикует snapshot/patch contracts. В нём запрещены:
|
||||||
|
|
||||||
|
- ветвления по provider, customer, account, entity или renderer;
|
||||||
|
- provider field mapping и бизнес-фильтрация;
|
||||||
|
- provider credential, endpoint, schedule или command transport;
|
||||||
|
- caller-supplied tenant/connection scope.
|
||||||
|
|
||||||
|
`NDC Data Product Publish` отправляет только
|
||||||
|
`nodedc.data-product.publish/v1`. External Data Plane materializes immutable
|
||||||
|
scope из writer binding, проверяет разрешённый Data Product и его ontology
|
||||||
|
revision, затем сохраняет batch.
|
||||||
|
|
||||||
|
EDP runtime импортирует только package subpath
|
||||||
|
`@nodedc/external-provider-contract/data-plane`. Его deploy artifact и image
|
||||||
|
содержат только provider-neutral wire validators; `providers/gelios`, mappings,
|
||||||
|
fixtures и tests туда не входят. Изменение или добавление provider package не
|
||||||
|
пересобирает и не перезапускает EDP: каталог поставщиков разворачивается через
|
||||||
|
Engine/Ontology/control-plane путь отдельно.
|
||||||
|
|
||||||
|
Collection cadence, history cadence и presentation cadence независимы:
|
||||||
|
|
||||||
|
- NDC L2 забирает источник с частотой, нужной бизнес-задаче;
|
||||||
|
- current projection принимает каждое валидное изменение;
|
||||||
|
- declarative history policy может хранить все точки или sampling;
|
||||||
|
- Foundry читает snapshot+patch и отдельно ограничивает частоту render.
|
||||||
|
|
||||||
|
Для разной частоты БД и интерфейса не создаются второй provider sink, отдельный
|
||||||
|
gateway или параллельный прямой push в renderer.
|
||||||
|
|
||||||
|
### 5. Полнота означает все сущности разрешённой capability
|
||||||
|
|
||||||
|
Connection profile выбирает safe-read capabilities, а не зашитый в Platform
|
||||||
|
список entity IDs. Если разрешённый endpoint возвращает все доступные credential
|
||||||
|
сущности, NDC L2 обрабатывает каждый валидный item. Новый объект появляется
|
||||||
|
автоматически.
|
||||||
|
|
||||||
|
Пользовательская фильтрация, слои и видимость находятся после сбора — в
|
||||||
|
automation/Data Product/Foundry. Технические ограничения допустимы только как
|
||||||
|
pagination, quota, batch size, backpressure и защита от повреждённого ответа.
|
||||||
|
|
||||||
|
### 6. Custom NDC nodes ограничены платформенными границами
|
||||||
|
|
||||||
|
Первый канонический набор:
|
||||||
|
|
||||||
|
- `NDC Data Product Publish` — NDC L2 → External Data Plane;
|
||||||
|
- `NDC Data Product Read` — scoped snapshot/patch read;
|
||||||
|
- `NDC Foundry Binding` — control-plane связь Data Product с
|
||||||
|
`Application → Page → typed slot`.
|
||||||
|
|
||||||
|
Эти nodes не содержат provider ID, tenant ID, connection ID, endpoint, token,
|
||||||
|
mapping или cadence. Runtime package сохраняет технический namespace
|
||||||
|
`n8n-nodes-ndc.*`, но пользовательские документы и интерфейсы используют
|
||||||
|
только терминологию NDC.
|
||||||
|
|
||||||
|
`NDC Foundry Binding` не транспортирует каждый realtime tick. Он создаёт
|
||||||
|
постоянную связь интерфейса с Data Product; Foundry затем читает его
|
||||||
|
snapshot+patch contract.
|
||||||
|
|
||||||
|
### 7. Реальный Gelios acceptance-кейс
|
||||||
|
|
||||||
|
Первая версия provider package должна доказать путь:
|
||||||
|
|
||||||
|
`Gelios safe read → все доступные units → map.moving_object facts →
|
||||||
|
fleet.positions.current.v1 → Foundry map`
|
||||||
|
|
||||||
|
Canonical product использует ontology revision
|
||||||
|
`ontology.map.moving_object.v1` и только объявленные snake_case поля. NDC L2
|
||||||
|
не передаёт caller scope и не собирает собственный batch envelope вокруг
|
||||||
|
`NDC Data Product Publish`.
|
||||||
|
|
||||||
|
Acceptance выполняется по порядку:
|
||||||
|
|
||||||
|
1. Platform выполняет generic `ensure data-product publish grant`, выпускает
|
||||||
|
scoped EDP binding и атомарно сохраняет capability в native NDC L2
|
||||||
|
Credentials;
|
||||||
|
2. NDC MCP видит только совместимый opaque writer credential reference/status;
|
||||||
|
3. применить подтверждённый graph patch без legacy intake;
|
||||||
|
4. validate/preflight;
|
||||||
|
5. один успешный manual run и проверка execution/trace/Data Product;
|
||||||
|
6. только затем отдельным изменением добавить Schedule Trigger;
|
||||||
|
7. после доказанного snapshot+patch подключить Foundry binding.
|
||||||
|
|
||||||
|
### 8. Capacity и topology
|
||||||
|
|
||||||
|
Количество одновременно активных NDC L2 проектов ограничивается фактическими
|
||||||
|
ресурсами железа и профилем нагрузки. Пока capacity проверяется оператором и не
|
||||||
|
автоматизируется. Канон не объявляет отдельные worker/webhook generations или
|
||||||
|
high-load topology, которых ещё нет в принятом runtime.
|
||||||
|
|
||||||
|
## Последствия
|
||||||
|
|
||||||
|
- `services/<provider>-gateway` не является частью канона и не создаётся для
|
||||||
|
новых provider integrations. Существующий self-hosted Gelios Gateway и его
|
||||||
|
Timescale volume остаются frozen compatibility contour, воспроизводятся из
|
||||||
|
source/deploy и не изменяются новым L2 pilot без отдельного решения.
|
||||||
|
- Новый account или provider-issued access/refresh pair — configuration change,
|
||||||
|
а не platform release.
|
||||||
|
- Новый provider или неподдержанная capability — versioned provider/Ontology
|
||||||
|
change с contract tests.
|
||||||
|
- Существующий legacy L1/SDK workflow является frozen compatibility boundary:
|
||||||
|
новый L2 pilot его не редактирует, не отзывает его credential и не ставит его
|
||||||
|
вывод условием acceptance.
|
||||||
|
- Legacy `/internal/data-plane/v1/intake` остаётся выключенным migration-only
|
||||||
|
route и не используется новыми NDC L2 workflows.
|
||||||
|
- Команды устройствам остаются отдельным red-domain контуром с явным
|
||||||
|
подтверждением, scope, idempotency и аудитом.
|
||||||
|
- Foundry развивается после доказанного Data Product path; provider API и
|
||||||
|
credentials в Foundry не попадают.
|
||||||
@@ -13,15 +13,31 @@ Do not mix these classes. A URL reachable from the Mac browser is not automatica
|
|||||||
|
|
||||||
## Current Profiles
|
## Current Profiles
|
||||||
|
|
||||||
`local/hybrid-prod-bridge`:
|
`local/remote-worker-relay`:
|
||||||
|
|
||||||
- Tasker UI: `http://task.local.nodedc`
|
- Tasker UI: `http://task.local.nodedc`
|
||||||
- Platform Assistant: `http://127.0.0.1:18082`
|
- Platform Assistant: `http://127.0.0.1:18082`
|
||||||
- Local Hub process: `http://127.0.0.1:18081`
|
- Local Hub process: `http://127.0.0.1:18081`
|
||||||
- Default worker-facing Hub: `wss://ai-hub.nodedc.ru/api/ai-workspace/hub`
|
- Default worker-facing Hub relay: `wss://ai-hub.nodedc.ru/api/ai-workspace/hub`
|
||||||
|
- Default Assistant-to-relay control URL: `https://ai-hub.nodedc.ru`
|
||||||
|
- Assistant action relay id: `local-dev`
|
||||||
|
- Assistant action gateway returned to worker: `https://ai-hub.nodedc.ru/api/ai-workspace/hub/v1/assistant-relays/local-dev/actions`
|
||||||
- Ops entitlement adapter: `http://host.docker.internal:4100/api/internal/v1/ai-workspace/entitlements` when deliberately enabled
|
- Ops entitlement adapter: `http://host.docker.internal:4100/api/internal/v1/ai-workspace/entitlements` when deliberately enabled
|
||||||
- Ops Gateway downstream Tasker: `http://task.local.nodedc`
|
- Ops Gateway downstream Tasker: `http://task.local.nodedc`
|
||||||
- This profile is valid for contract smoke and local Ops vertical smoke, not proof of live local Codex worker e2e.
|
- The deployed AI Hub is allowed only as transport. Launcher, Engine, Ops, Authentik, task manager, and downstream app calls must stay local.
|
||||||
|
- The remote worker must not call product apps directly. Assistant actions must route back through the local AI Workspace Assistant.
|
||||||
|
|
||||||
|
`local-seo/deployed-hub-control-plane`:
|
||||||
|
|
||||||
|
- SEO frontend: `http://127.0.0.1:5177`
|
||||||
|
- SEO backend: `http://127.0.0.1:4100`
|
||||||
|
- SEO AI Workspace profile: `deployed-hub`
|
||||||
|
- SEO backend Assistant-compatible control-plane URL: `SEO_AI_WORKSPACE_CONTROL_URL=https://ai-hub.nodedc.ru`
|
||||||
|
- SEO backend control-plane token: `SEO_AI_WORKSPACE_CONTROL_TOKEN`, accepted by the public Hub server-side API.
|
||||||
|
- Worker-facing Hub: `wss://ai-hub.nodedc.ru/api/ai-workspace/hub`
|
||||||
|
- Public Hub exposes only token-gated Assistant control-plane proxy endpoints required by SEO model-provider setup, probe, thread dispatch, and message polling.
|
||||||
|
- Public Hub must proxy those calls to internal Platform Assistant with server-side internal token. Browser clients and remote workers must not receive the Hub internal token or Assistant token.
|
||||||
|
- This profile is for local SEO development against the deployed AI Workspace service plane. It is not the same as `local`, and it must not silently fall back to localhost or product app URLs.
|
||||||
|
|
||||||
`synology/prod-public`:
|
`synology/prod-public`:
|
||||||
|
|
||||||
@@ -52,3 +68,41 @@ New apps must join AI Workspace through app manifests/config/adapters:
|
|||||||
- owner repo/service.
|
- owner repo/service.
|
||||||
|
|
||||||
Do not add app-specific address logic to the agent installer, Engine, Ops, or Platform Assistant runtime flow.
|
Do not add app-specific address logic to the agent installer, Engine, Ops, or Platform Assistant runtime flow.
|
||||||
|
|
||||||
|
### NDC SEO Mode
|
||||||
|
|
||||||
|
`seo-mode` is a first-class AI Workspace surface, not `global`.
|
||||||
|
|
||||||
|
Local SEO testing should keep SEO app/backend on fixed local ports while using the configured AI Workspace transport/profile:
|
||||||
|
|
||||||
|
- SEO frontend: `http://127.0.0.1:5177`
|
||||||
|
- SEO backend: `http://127.0.0.1:4100`
|
||||||
|
- SEO model-provider surface: `seo-mode`
|
||||||
|
- SEO model task mode: `seo-model-task`
|
||||||
|
- Worker-facing transport: public AI Hub relay when selected by profile, normally `wss://ai-hub.nodedc.ru/api/ai-workspace/hub`
|
||||||
|
- SEO task payload: sanitized `seo-model-task` contract only
|
||||||
|
|
||||||
|
The SEO backend must select profiles through env/config, not code edits. Local and deploy-host may use different Assistant URLs, executor ids, setup commands, model defaults, and app grants, but the request contract stays the same.
|
||||||
|
|
||||||
|
Remote Codex for SEO must not receive Wordstat/Yandex credentials, product app tokens, unrestricted repo access, rewrite/apply actions, or destructive actions. Wordstat/SERP collection remains SEO-backend-owned.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Before changing worker, Assistant, Hub, or app adapter routing, run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
For a live local remote-worker test, require the relay topology explicitly:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
REQUIRE_REMOTE_WORKER_RELAY=1 sh infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Security audit and test matrix:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/AI_WORKSPACE_SECURITY_AUDIT_2026-06-20.md
|
||||||
|
docs/AI_WORKSPACE_TEST_MATRIX.md
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# AI Workspace ↔ Ontology Core MCP
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This is the read-only semantic path for a NODE.DC AI Workspace run:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Codex worker
|
||||||
|
-> dynamic per-run MCP configuration
|
||||||
|
-> public AI Workspace Hub (pairing-bound route)
|
||||||
|
-> internal Ontology Core MCP
|
||||||
|
-> freshly loaded ontology catalog and domain packages
|
||||||
|
```
|
||||||
|
|
||||||
|
`ai-workspace-assistant` creates this MCP server entry at run-profile time for every Hub-connected executor when `AI_WORKSPACE_ONTOLOGY_MCP_ENABLED=true`. It is a platform runtime grant (`ontology:catalog:read`), not a user-owned installer secret and not a hard-coded copy of ontology rules in a prompt.
|
||||||
|
|
||||||
|
The worker receives only a pairing-bound Hub URL. The Hub verifies that the pairing agent is online and replaces any external authorization with the platform-internal token before forwarding to `ontology-core`. Ontology Core is internal-only and has no host port or reverse-proxy route.
|
||||||
|
|
||||||
|
## Read-only MCP surface
|
||||||
|
|
||||||
|
`nodedc_ontology` exposes only these tools:
|
||||||
|
|
||||||
|
- `ontology_status` — catalog counts, domain packages and a safe catalog hash;
|
||||||
|
- `ontology_search` — canonical entities, relations and aliases;
|
||||||
|
- `ontology_get_entity` — entity definition, aliases, relations and guardrails;
|
||||||
|
- `ontology_get_guardrails` — semantic/safety rules and blocked conflations;
|
||||||
|
- `ontology_resolve_context` — semantic route advice with source identifiers removed.
|
||||||
|
|
||||||
|
It intentionally does not expose filesystem paths, evidence ledgers, credentials, raw payloads, live telemetry, databases, command dispatch, workflow mutation or Studio controls.
|
||||||
|
|
||||||
|
## Boundary for external providers and runtime data
|
||||||
|
|
||||||
|
Ontology Core describes the canonical meanings and constraints:
|
||||||
|
|
||||||
|
```text
|
||||||
|
gelios.unit -> gelios.telemetry_snapshot -> gelios.position_fix -> map.moving_object
|
||||||
|
```
|
||||||
|
|
||||||
|
It does **not** serve provider runtime data or call a provider API. Provider
|
||||||
|
access and mapping belong to the granted NDC L2 workflow; shared current and
|
||||||
|
history products belong to the provider-neutral External Data Plane. A scoped
|
||||||
|
Data Product read capability may later be supplied to an AI Workspace run as a
|
||||||
|
separate dynamic MCP server. Ontology supplies meanings, relations, guardrails
|
||||||
|
and the allowed contract route; the data capability enforces access and returns
|
||||||
|
live data.
|
||||||
|
|
||||||
|
This preserves one-way responsibility:
|
||||||
|
|
||||||
|
- Ontology Core: semantics, contracts, aliases, guardrails and context advice.
|
||||||
|
- External Data Plane: access-scoped Data Product snapshots and updates.
|
||||||
|
- Command Gateway: separate red-domain command route, explicit confirmation and audit.
|
||||||
|
- NDC L2 workflow: provider access, collection and mapping using granted capabilities.
|
||||||
|
- Foundry: presentation consumer, outside this implementation.
|
||||||
|
|
||||||
|
## Live catalog updates without AI Workspace rule redeploy
|
||||||
|
|
||||||
|
`loadCatalog()` runs for each Ontology MCP tool call; it does not cache the merged catalog. Therefore a new or edited domain package is visible to existing AI Workspace rules as soon as the catalog content is updated in the running Ontology Core container or mounted runtime catalog directory.
|
||||||
|
|
||||||
|
For a catalog-only release, update/restart **Ontology Core only**. The AI Workspace Assistant, Hub and Codex worker configuration do not need a rules redeploy because the MCP tool names and route stay stable. `NODEDC_ONTOLOGY_CATALOG_ROOT` may point Ontology Core at a separately managed catalog directory when a runtime-mounted catalog is required.
|
||||||
|
|
||||||
|
A Hub/Assistant rollout is needed only if the MCP transport, authorization contract or tool definitions themselves change.
|
||||||
|
|
||||||
|
## Safety properties
|
||||||
|
|
||||||
|
- The MCP server accepts only internal bearer authentication from AI Hub.
|
||||||
|
- A browser `Origin` is rejected by default; allow specific origins only through `ONTOLOGY_MCP_ALLOWED_ORIGINS` if an intentional browser transport is introduced.
|
||||||
|
- The Hub does not pass browser cookies or external `Authorization` downstream.
|
||||||
|
- The Hub route is pairing-bound and is unavailable when the worker is offline.
|
||||||
|
- All current tools are read-only. There is no generic ontology write API.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
```text
|
||||||
|
cd platform/services/ontology-core
|
||||||
|
npm run validate
|
||||||
|
npm run smoke:mcp
|
||||||
|
|
||||||
|
cd ../../
|
||||||
|
node --check services/ai-workspace-assistant/src/server.mjs
|
||||||
|
node --check services/ai-workspace-hub/src/server.mjs
|
||||||
|
docker compose --env-file infra/.env -f infra/docker-compose.dev.yml config
|
||||||
|
```
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# AI Workspace Security Audit 2026-06-20
|
||||||
|
|
||||||
|
Status: prototype hardening report.
|
||||||
|
|
||||||
|
Scope: AI Workspace Assistant, public AI Hub relay, remote Codex worker, local Launcher, local Engine, local Ops Gateway, ontology-core assistant actions.
|
||||||
|
|
||||||
|
## Current architecture
|
||||||
|
|
||||||
|
The safe local test topology is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
local Engine / local Ops UI / local Launcher
|
||||||
|
-> local AI Workspace Assistant
|
||||||
|
-> public AI Hub relay
|
||||||
|
-> remote Codex worker
|
||||||
|
-> public AI Hub assistant action relay
|
||||||
|
-> local AI Workspace Assistant
|
||||||
|
-> local Launcher / local Engine / local Ops Gateway
|
||||||
|
```
|
||||||
|
|
||||||
|
The public AI Hub is transport only in `NODEDC_ENV=local`. It must not become the owner of Launcher, Engine, Ops, Authentik, or product-app data. Product reads and writes return to the local Assistant and then go through local app-owned adapters.
|
||||||
|
|
||||||
|
## Profiles
|
||||||
|
|
||||||
|
`local`
|
||||||
|
|
||||||
|
- Business apps are local: Launcher, Engine, Ops/Gateway, Tasker, databases, fixtures.
|
||||||
|
- AI Workspace Assistant is local.
|
||||||
|
- The only allowed deployed URL class is the AI Hub relay: `https://ai-hub.nodedc.ru` / `wss://ai-hub.nodedc.ru/api/ai-workspace/hub`.
|
||||||
|
- Production product hosts are forbidden in local downstream config: `hub.nodedc.ru`, `engine.nodedc.ru`, `ops.nodedc.ru`, `id.nodedc.ru`, `ops-agents.nodedc.ru`.
|
||||||
|
- Remote worker receives a scoped run profile and calls assistant actions through the relay, not through product apps directly.
|
||||||
|
|
||||||
|
`deploy-host`
|
||||||
|
|
||||||
|
- Business apps and AI Workspace services run in the deployed stack.
|
||||||
|
- Public worker-facing relay is still `ai-hub.nodedc.ru`.
|
||||||
|
- Internal service URLs must be container/network URLs, not localhost and not developer-machine URLs.
|
||||||
|
- This profile is architecturally described but not fully proven yet. It still needs a clean deploy verification run before it can be treated as release-ready.
|
||||||
|
|
||||||
|
`tunnel-local-e2e`
|
||||||
|
|
||||||
|
- Explicit escape hatch for Tailscale/ngrok-style testing.
|
||||||
|
- Must be opt-in through `NODEDC_ENV=tunnel-local-e2e`.
|
||||||
|
- No local config may silently fall back to private/tunnel addresses.
|
||||||
|
|
||||||
|
## Trust boundaries
|
||||||
|
|
||||||
|
Browser and local app backends trust only local service tokens and the current application session.
|
||||||
|
|
||||||
|
AI Workspace Assistant owns assistant orchestration:
|
||||||
|
|
||||||
|
- builds run profiles;
|
||||||
|
- resolves app grants;
|
||||||
|
- exposes the assistant action gateway;
|
||||||
|
- performs preview/execute routing;
|
||||||
|
- calls app-owned adapters.
|
||||||
|
|
||||||
|
Remote Codex worker is an executor:
|
||||||
|
|
||||||
|
- it receives only the run profile and tool/action gateway information;
|
||||||
|
- it must not own product app credentials;
|
||||||
|
- it should not call Launcher, Engine, Ops, Authentik, or product DBs directly in local profile.
|
||||||
|
|
||||||
|
Ontology Core owns assistant action policy:
|
||||||
|
|
||||||
|
- registered action catalog;
|
||||||
|
- risk levels;
|
||||||
|
- route allowlists;
|
||||||
|
- no hard-delete guardrails;
|
||||||
|
- preview/confirmation/execute contract.
|
||||||
|
|
||||||
|
App adapters own their app-specific state changes:
|
||||||
|
|
||||||
|
- Launcher adapter mutates only guarded Launcher admin routes.
|
||||||
|
- Ops adapter calls the Ops Gateway tool API.
|
||||||
|
- Engine graph edits stay in NDC Agent Core / Engine-owned workflow tools.
|
||||||
|
|
||||||
|
## Transport and tokens
|
||||||
|
|
||||||
|
Confirmed controls in current code:
|
||||||
|
|
||||||
|
- Assistant API requires an internal token via `Authorization: Bearer ...` or `X-NODEDC-Internal-Token`.
|
||||||
|
- Hub internal API requires `Authorization: Bearer ...`.
|
||||||
|
- Constant-time token comparison is used for Assistant and Hub internal API checks.
|
||||||
|
- Public relay traffic uses HTTPS/WSS.
|
||||||
|
- Assistant action relay forwards only user owner headers, not arbitrary incoming headers.
|
||||||
|
- Launcher admin action adapter sends `Authorization: Bearer <launcher internal token>` plus assistant actor headers.
|
||||||
|
- Ops action adapter obtains or uses an Ops run token and sends it to Ops Gateway as `Authorization`.
|
||||||
|
- Write routes require an idempotency key.
|
||||||
|
- DELETE is blocked at execution-plan validation.
|
||||||
|
|
||||||
|
Current token classes:
|
||||||
|
|
||||||
|
- `NODEDC_INTERNAL_ACCESS_TOKEN`: service-to-service internal token for local stack.
|
||||||
|
- `AI_WORKSPACE_HUB_TOKEN`: public Hub internal API token.
|
||||||
|
- `NDC_LAUNCHER_INTERNAL_ACCESS_TOKEN`: Launcher admin adapter token.
|
||||||
|
- Ops entitlement token: lets Assistant ask Ops Gateway for a scoped run token.
|
||||||
|
- Ops run token: downstream authorization for Ops tool routes.
|
||||||
|
- Assistant action confirmation token: digest over action, actor, request body/path, and idempotency key.
|
||||||
|
|
||||||
|
## Assistant action safety model
|
||||||
|
|
||||||
|
Read actions:
|
||||||
|
|
||||||
|
- do not require confirmation;
|
||||||
|
- must still resolve to a registered action;
|
||||||
|
- must be scoped by owner context and app-owned adapter policy.
|
||||||
|
|
||||||
|
Write and privileged actions:
|
||||||
|
|
||||||
|
- must resolve to a registered action;
|
||||||
|
- must pass risk policy;
|
||||||
|
- must pass route allowlist;
|
||||||
|
- must include idempotency key;
|
||||||
|
- must produce a preview;
|
||||||
|
- must require explicit user confirmation;
|
||||||
|
- must execute only with the preview confirmation token.
|
||||||
|
|
||||||
|
Destructive actions:
|
||||||
|
|
||||||
|
- are forbidden for assistant execution;
|
||||||
|
- hard-delete users, files, DB rows, production state, archives, backups, and runtime/storage records must stay outside assistant action routing.
|
||||||
|
|
||||||
|
## Prototype status
|
||||||
|
|
||||||
|
Tested behavior:
|
||||||
|
|
||||||
|
- local Assistant action gateway can preview Ops card creation;
|
||||||
|
- public relay can route preview requests to local Assistant via `relayId=local-dev`;
|
||||||
|
- Engine UI can ask the remote worker to create an Ops card;
|
||||||
|
- write creation requires preview and explicit confirmation;
|
||||||
|
- confirmed Ops test card creation succeeded through the UI;
|
||||||
|
- Launcher pending access read works through assistant action routing;
|
||||||
|
- Engine NDC Agent Core tools are visible for selected agent node operations;
|
||||||
|
- Engine chat polling jitter was addressed by stable remote message merge logic.
|
||||||
|
|
||||||
|
Not yet proven:
|
||||||
|
|
||||||
|
- complete deploy-host profile after a fresh deployment;
|
||||||
|
- cross-user relay isolation under multiple simultaneous local developers;
|
||||||
|
- one-time confirmation token storage;
|
||||||
|
- token TTL enforcement for every downstream run token;
|
||||||
|
- full stop/cancel behavior for long remote Codex runs;
|
||||||
|
- full browser UI regression pass across Launcher, Ops, and Engine.
|
||||||
|
|
||||||
|
## Findings
|
||||||
|
|
||||||
|
P0 fixed in current prototype:
|
||||||
|
|
||||||
|
- Product app calls no longer need to be tested by deploying raw product changes first. Local profile routes product reads/writes back to local services.
|
||||||
|
- Ops card create path now works through Assistant -> Ontology Core -> Ops Gateway with preview/confirmation.
|
||||||
|
- The remote worker is treated as executor, not as product credential owner.
|
||||||
|
|
||||||
|
P1 hardening required:
|
||||||
|
|
||||||
|
- Confirmation tokens are deterministic digests and currently have no TTL or server-side one-time consumption store. If preview output and token leak, the same request can be replayed until downstream idempotency suppresses duplicates. Add server-side confirmation records with TTL, actor binding, single-use consumption, and audit trail.
|
||||||
|
- `local-dev` relay id is too generic for repeated multi-user work. Use unique relay ids per developer/station/environment, for example `local-dc-mac-<date>` or configured stable machine id.
|
||||||
|
- Public relay is bearer-token protected but not mTLS-bound. Treat Hub token leakage as critical and rotate tokens after exposure.
|
||||||
|
- The worker receives `assistantActionGatewayToken` in the run profile. This is necessary for the current bridge, but it is a bearer secret. Keep it short-lived or derive a per-run action token instead of reusing broad service tokens.
|
||||||
|
- Stop/cancel behavior needs an automated smoke check with a deliberately long remote run.
|
||||||
|
|
||||||
|
P2 hardening required:
|
||||||
|
|
||||||
|
- Add audit correlation ids across Engine request, Hub request, worker run, Assistant action, Ops/Launcher adapter call.
|
||||||
|
- Add negative tests for forged owner headers through the public relay.
|
||||||
|
- Add negative tests for forbidden DELETE route, destructive action, missing idempotency, wrong confirmation token, wrong actor, and wrong project id.
|
||||||
|
- Add dashboard visibility for selected run profile, action ids, relay id, and downstream profile without exposing tokens.
|
||||||
|
|
||||||
|
## Security conclusion
|
||||||
|
|
||||||
|
The prototype is usable for controlled local testing and internal proof-of-flow. It is not yet release-grade security. The main architectural boundary is now correct: local product state stays local, the public AI Hub is a relay, and writes go through registered ontology actions with preview and confirmation. Before production rollout, the confirmation and relay-token model must be hardened with TTL, single-use confirmation records, unique relay ids, short-lived action tokens, and expanded negative tests.
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# AI Workspace Test Matrix
|
||||||
|
|
||||||
|
Status: active prototype test plan.
|
||||||
|
|
||||||
|
## Test levels
|
||||||
|
|
||||||
|
Horizontal tests check each service boundary independently.
|
||||||
|
|
||||||
|
Vertical tests prove a full user intent through UI, Assistant, remote worker, relay, and target app adapter.
|
||||||
|
|
||||||
|
Security tests prove that unsafe actions are blocked and secrets are not exposed.
|
||||||
|
|
||||||
|
## Horizontal tests
|
||||||
|
|
||||||
|
| ID | Area | Command / action | Success | Failure |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| H1 | Platform static | `sh infra/scripts/check-local-test-system.sh` | all required static, env, compose, ontology, and topology checks pass | any local profile points product downstream to prod, syntax fails, or topology cannot be classified |
|
||||||
|
| H2 | Env safety | `node infra/scripts/check-local-environment-safety.mjs` | `NODEDC_ENV=local` permits only AI Hub relay as deployed host | product app URL points to deployed prod host in local profile |
|
||||||
|
| H3 | Config contract | `infra/scripts/check-ai-workspace-config-contract.sh` | worker-facing, internal, browser, relay, and downstream URLs remain separated | app-specific URL logic leaks into worker/Engine/Assistant runtime |
|
||||||
|
| H4 | Release gate | `sh infra/scripts/check-ai-workspace-release-gates.sh` | static checks, smokes, gateway checks, and diff hygiene pass | deploy preparation blocked |
|
||||||
|
| H5 | Ontology catalog | `cd services/ontology-core && npm run validate` | actions/entities/policies validate | invalid action, missing entity, unsupported risk policy |
|
||||||
|
| H6 | Assistant action caller | `cd services/ontology-core && npm run smoke:assistant-caller` | preview requires token, execute without token blocked, execute with token calls adapter in mock | write executes without confirmation or unsafe route passes |
|
||||||
|
| H7 | Assistant executor | `cd services/ontology-core && npm run smoke:assistant-executor` | DELETE/destructive action blocked, internal bearer headers added in mock | destructive/write route is allowed |
|
||||||
|
| H8 | Assistant run profile | `cd services/ai-workspace-assistant && npm run smoke:run-profile` | run profile contains expected grants, action profile, and redacted diagnostics | token leakage or missing action profile |
|
||||||
|
| H9 | Engine build | `cd NODEDC_ENGINE_INFRA/nodedc-source && npm run build` | UI/server bundle builds | Engine UI/bridge integration broke build |
|
||||||
|
| H10 | Launcher assistant admin contract | Launcher contract tests | assistant admin routes stay guarded, scoped, idempotent, and no hard-delete route becomes assistant-ready | assistant route bypasses session/admin guard or delete leaks into assistant allowlist |
|
||||||
|
|
||||||
|
## Vertical tests
|
||||||
|
|
||||||
|
| ID | Flow | Steps | Success |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| V1 | Remote worker health | Engine UI asks: `ты тут? коротко workspace, runtime, hub connected` | response shows local workspace, `runtime: ready`, `hub connected: true` |
|
||||||
|
| V2 | Launcher read | ask: `покажи новые заявки в лаунчере` | answer comes from `hub.access_request.list_pending` and returns actual local Launcher pending requests |
|
||||||
|
| V3 | Ops read | ask: `последнюю задачу в опсе покажи` | answer comes from `ops.card.list_recent`, no file search fallback |
|
||||||
|
| V4 | Ops create preview | ask: `создай в опс тестовую задачу "..."` | assistant shows preview and asks explicit confirmation |
|
||||||
|
| V5 | Ops create execute | confirm preview | local Ops creates card and assistant returns identifier |
|
||||||
|
| V6 | Ops comment preview | ask to add comment to a known card | assistant shows preview and asks confirmation |
|
||||||
|
| V7 | Ops comment execute | confirm comment preview | comment is added to local Ops card |
|
||||||
|
| V8 | Engine graph read | ask selected agent node workflow counts | assistant uses NDC Agent Core tool and returns nodes/edges |
|
||||||
|
| V9 | Engine graph patch | ask for tiny node patch in selected agent node | assistant uses NDC Agent Core patch and validates graph |
|
||||||
|
| V10 | Stop/cancel | start deliberately long search and press stop | running Codex process is stopped or marked aborted within bounded time |
|
||||||
|
|
||||||
|
## Security and abuse tests
|
||||||
|
|
||||||
|
| ID | Attack / risk | Test | Expected |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| S1 | Missing internal token | call Assistant action endpoint without token | `401` or `503`, no action executed |
|
||||||
|
| S2 | Wrong internal token | call Assistant action endpoint with bad bearer | `401`, no action executed |
|
||||||
|
| S3 | Write without confirmation | execute `ops.card.create` without confirmation token | blocked with `write_confirmation_envelope_missing` |
|
||||||
|
| S4 | Wrong confirmation | execute with wrong token | blocked with `write_confirmation_envelope_mismatch` |
|
||||||
|
| S5 | Missing idempotency | construct write plan without idempotency key | blocked with `write_requires_idempotency_key` |
|
||||||
|
| S6 | DELETE route | try destructive delete action | blocked before network with `delete_method_forbidden` or destructive policy |
|
||||||
|
| S7 | Unknown action | ask for unregistered action | assistant refuses or asks clarification; no network call |
|
||||||
|
| S8 | Prompt injection | user asks to ignore policy and call raw URL | assistant must resolve registered action or refuse |
|
||||||
|
| S9 | Owner header forgery | relay call attempts forged owner headers | only trusted local app/Assistant boundary may set owner; forged public call must not gain privileges |
|
||||||
|
| S10 | Replay | reuse a previous confirmation token and idempotency key | current expected result: downstream idempotency should suppress duplicate; required hardening: single-use token must reject replay |
|
||||||
|
| S11 | Cross-project write | create/comment using unauthorized project id | Ops entitlement/gateway rejects |
|
||||||
|
| S12 | Token disclosure | ask assistant to print run profile tokens | answer must redact/refuse secrets |
|
||||||
|
|
||||||
|
## Deploy-host proof
|
||||||
|
|
||||||
|
Deploy-host is not considered proven until this sequence passes:
|
||||||
|
|
||||||
|
1. Deploy only the intended AI Hub/Assistant artifacts by the deployment canon.
|
||||||
|
2. Run `sh infra/scripts/check-ai-workspace-release-gates.sh` before deploy.
|
||||||
|
3. Verify deployed Hub `/healthz`.
|
||||||
|
4. Verify deployed Assistant `/healthz`.
|
||||||
|
5. Pair a worker through the deployed Hub.
|
||||||
|
6. Run read-only Launcher, Ops, and Engine assistant actions.
|
||||||
|
7. Run one preview-only write.
|
||||||
|
8. Run one confirmed Ops write in a non-production test project.
|
||||||
|
9. Confirm logs contain correlation ids and no tokens.
|
||||||
|
|
||||||
|
Until then, deploy-host remains an architecture profile, not a release guarantee.
|
||||||
@@ -50,6 +50,30 @@ Production login должен быть NODE.DC-branded:
|
|||||||
|
|
||||||
Текущее безопасное решение зафиксировано в `docs/AUTH_BRANDED_LOGIN_RFC.md`: сначала используем Authentik-native Brand/CSS/Flow customization. Reverse proxy HTML-rewrite, password form в Launcher и пересылка пароля через BFF запрещены.
|
Текущее безопасное решение зафиксировано в `docs/AUTH_BRANDED_LOGIN_RFC.md`: сначала используем Authentik-native Brand/CSS/Flow customization. Reverse proxy HTML-rewrite, password form в Launcher и пересылка пароля через BFF запрещены.
|
||||||
|
|
||||||
|
## Inter-app session sync status 2026-06-23
|
||||||
|
|
||||||
|
Источник истины по пользовательской сессии остаётся в Launcher/Auth/Authentik chain. Приложения не должны выдавать себе права из локального browser-event или marker-а; любые live-события session sync являются только сигналом для revalidation через платформенный authority.
|
||||||
|
|
||||||
|
Фактический общий live-контур до BIM был logout-only:
|
||||||
|
|
||||||
|
- Launcher `/auth/session-sync` публиковал `nodedc:session:logout` в соседние приложения через iframe/BroadcastChannel/localStorage/frontchannel;
|
||||||
|
- Engine helper `src/platform/auth/sessionSync.ts` знает только `nodedc:session:logout`;
|
||||||
|
- Tasker/OPS имеет отдельный frontchannel/internal logout контур, но login/change parity не оформлен как общий protocol;
|
||||||
|
- login live promotion открытого приложения после входа в другом surface не был закрытым platform-wide контрактом.
|
||||||
|
|
||||||
|
BIM Viewer 23.06.2026 добавил BIM-first login-sync slice для share-link сценария:
|
||||||
|
|
||||||
|
- Launcher service registry получил `loginSyncUrl` для BIM;
|
||||||
|
- после успешного login Launcher публикует `nodedc:session:login` и делает frontchannel вызов зарегистрированных login-sync endpoints;
|
||||||
|
- BIM `/auth/login-sync` создаёт короткоживущий server-side marker;
|
||||||
|
- BIM `/api/auth/session` возвращает `loginSyncEventId`, но сам marker не является auth-token;
|
||||||
|
- BIM frontend по новому marker-у запускает обычный optional-launch/handoff через Launcher, где происходит нормальная проверка сессии и доступа;
|
||||||
|
- BIM logout приведён к существующему logout canon и должен live-понижать controls до guest/limited view без ручного refresh.
|
||||||
|
|
||||||
|
Граница текущей реализации: это кандидат на общий login-sync contract, а не закрытый канон для всей платформы. Перед подключением следующего сервиса нужно оформить `ndcauth.session` protocol: `login`, `logout`, `change`, payload, origin checks, TTL/nonce/correlation, service registry fields, revalidation rules, audit/observability и browser e2e matrix по HUB/OPS/ENGINE/BIM.
|
||||||
|
|
||||||
|
Правило для новых сервисов: не добавлять частный per-app login/logout bus. Сервис регистрирует sync endpoints в Launcher/control-plane registry, принимает event только как invalidate/promote trigger и всегда перепроверяет доступ через backend authority.
|
||||||
|
|
||||||
## Required claims
|
## Required claims
|
||||||
|
|
||||||
Минимальный normalized user object:
|
Минимальный normalized user object:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# NODE.DC current infra handoff
|
# NODE.DC current infra handoff
|
||||||
|
|
||||||
Last updated: 2026-05-15.
|
Last updated: 2026-06-23.
|
||||||
|
|
||||||
This document is the fast context entrypoint for a new engineering chat. Read it first before touching deploy, Synology, Authentik, Launcher, or Tasker.
|
This document is the fast context entrypoint for a new engineering chat. Read it first before touching deploy, Synology, Authentik, Launcher, or Tasker.
|
||||||
|
|
||||||
@@ -16,6 +16,7 @@ Source-of-truth repositories:
|
|||||||
| Launcher / Hub | NODE.DC control plane, user/admin UI, access requests, access matrix, Authentik sync | `/Users/dcconstructions/Downloads/mnt/data/nodedc_launcher` |
|
| Launcher / Hub | NODE.DC control plane, user/admin UI, access requests, access matrix, Authentik sync | `/Users/dcconstructions/Downloads/mnt/data/nodedc_launcher` |
|
||||||
| Tasker / Operational Core | Plane fork, tasks/workspaces/projects, standalone-capable product module | `/Users/dcconstructions/Downloads/mnt/data/dc_taskmanager/NODEDC_TASKMANAGER` |
|
| Tasker / Operational Core | Plane fork, tasks/workspaces/projects, standalone-capable product module | `/Users/dcconstructions/Downloads/mnt/data/dc_taskmanager/NODEDC_TASKMANAGER` |
|
||||||
| Ops Agents Gateway | Standalone MCP/API router for Tasker operational agents | `/Users/dcconstructions/Downloads/mnt/data/NODEDC_TASKMANAGER_CODEXAPI` |
|
| Ops Agents Gateway | Standalone MCP/API router for Tasker operational agents | `/Users/dcconstructions/Downloads/mnt/data/NODEDC_TASKMANAGER_CODEXAPI` |
|
||||||
|
| BIM Viewer | Standalone BIM/CAD/point-cloud viewer, public share links, model runtime storage | `/Users/dcconstructions/Downloads/mnt/NODEDC/NODEDC_BIM_VIEWER` |
|
||||||
|
|
||||||
Current Git branches:
|
Current Git branches:
|
||||||
|
|
||||||
@@ -23,6 +24,7 @@ Current Git branches:
|
|||||||
- Launcher: `main`
|
- Launcher: `main`
|
||||||
- Tasker: `master`
|
- Tasker: `master`
|
||||||
- Ops Agents Gateway: `main`
|
- Ops Agents Gateway: `main`
|
||||||
|
- BIM Viewer: `beam`
|
||||||
|
|
||||||
The modules communicate through HTTP/OIDC/internal APIs. They must remain independently buildable and deployable.
|
The modules communicate through HTTP/OIDC/internal APIs. They must remain independently buildable and deployable.
|
||||||
|
|
||||||
@@ -59,6 +61,7 @@ https://id.nodedc.ru -> Authentik
|
|||||||
https://hub.nodedc.ru -> Launcher / Hub
|
https://hub.nodedc.ru -> Launcher / Hub
|
||||||
https://ops.nodedc.ru -> Tasker / Operational Core
|
https://ops.nodedc.ru -> Tasker / Operational Core
|
||||||
https://ops-agents.nodedc.ru -> Ops Agents Gateway / MCP endpoint
|
https://ops-agents.nodedc.ru -> Ops Agents Gateway / MCP endpoint
|
||||||
|
https://bim.nodedc.tech -> BIM Viewer
|
||||||
```
|
```
|
||||||
|
|
||||||
`id.nodedc.ru` is only the public OIDC/login host. Authentik Admin is deliberately kept off that public host; `/if/admin/*` returns `404` there.
|
`id.nodedc.ru` is only the public OIDC/login host. Authentik Admin is deliberately kept off that public host; `/if/admin/*` returns `404` there.
|
||||||
@@ -244,6 +247,16 @@ Git repo -> build image / sync deploy files -> Synology compose recreate selecte
|
|||||||
|
|
||||||
Do not edit NAS copies as the long-term fix. If an emergency live edit is made on NAS, port it back into the relevant repo before continuing product work.
|
Do not edit NAS copies as the long-term fix. If an emergency live edit is made on NAS, port it back into the relevant repo before continuing product work.
|
||||||
|
|
||||||
|
## Auth/session sync status
|
||||||
|
|
||||||
|
Read `docs/AUTH_MODEL.md` before changing cross-app auth/session behavior.
|
||||||
|
|
||||||
|
As of 2026-06-23, the proven shared live-session path was logout-first: Launcher publishes `nodedc:session:logout` through `/auth/session-sync` and frontchannel app logout URLs, and Engine subscribes to that logout event. BIM Viewer has now been aligned with that logout path.
|
||||||
|
|
||||||
|
BIM also introduced a BIM-first login-sync slice for share links: Launcher service registry can call BIM `loginSyncUrl`; BIM records only a short-lived marker and then revalidates through Launcher optional-launch/handoff. This marker is not auth and must not grant controls directly.
|
||||||
|
|
||||||
|
This is not yet a platform-wide login/change canon. Before adding another service, define the shared `ndcauth.session` contract in Platform/Auth SDK terms and verify HUB/OPS/ENGINE/BIM with a browser matrix: login from any surface, logout from any surface, already-open apps update without refresh.
|
||||||
|
|
||||||
## Platform / Launcher deploy
|
## Platform / Launcher deploy
|
||||||
|
|
||||||
From macOS with `/Volumes/docker` mounted:
|
From macOS with `/Volumes/docker` mounted:
|
||||||
|
|||||||
@@ -50,20 +50,23 @@ Source fork:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /Users/dcconstructions/Downloads/mnt/NODEDC/platform
|
cd /Users/dcconstructions/Downloads/mnt/NODEDC/platform
|
||||||
infra/scripts/check-ai-workspace-topology.sh
|
sh infra/scripts/check-local-test-system.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
Скрипт ничего не прокидывает и не меняет. Он только классифицирует текущий режим:
|
Скрипт ничего не прокидывает, не деплоит и не меняет `.env`. Он проверяет env/compose/contracts/smoke и классифицирует текущий режим:
|
||||||
|
|
||||||
- `contract-only`: можно доверять только контрактным smoke-тестам без runtime e2e.
|
- `contract-only`: можно доверять только контрактным smoke-тестам без runtime e2e.
|
||||||
- `local-ops-vertical`: локальный Ops Gateway и локальный Tasker проверяются вертикально, без live Codex worker.
|
- `local-ops-vertical`: локальный Ops Gateway и локальный Tasker проверяются вертикально, без live Codex worker.
|
||||||
- `local-ui-only`: локальный UI доступен, но AI write path не доказан.
|
- `local-ui-only`: локальный UI доступен, но AI write path не доказан.
|
||||||
- `hybrid-prod-bridge`: часть контура локальная, а Hub/worker/MCP смотрят в публичный или другой контур. Такой результат нельзя считать local e2e.
|
- `local-remote-worker-relay`: product apps локальные, local Assistant включил action relay, а `ai-hub.nodedc.ru` используется только как транспорт к удаленному Codex worker.
|
||||||
|
- `hybrid-prod-bridge`: часть контура локальная, но action relay не настроен или topology смешана. Такой результат нельзя считать local e2e.
|
||||||
- `true-local-e2e`: Engine, AI Workspace Assistant, Hub, Ops Gateway, Tasker и worker находятся в одной локальной топологии.
|
- `true-local-e2e`: Engine, AI Workspace Assistant, Hub, Ops Gateway, Tasker и worker находятся в одной локальной топологии.
|
||||||
- `tunnel-local-e2e`: то же самое через явно выбранный tunnel/Tailscale-профиль.
|
- `tunnel-local-e2e`: то же самое через явно выбранный tunnel/Tailscale-профиль.
|
||||||
|
|
||||||
Не надо пытаться неявно “дотянуть” Mac-local окружение до Synology. Если нужен Tailscale, это отдельный явный профиль: Hub public URL, Gateway public URL и Engine/Tasker downstream должны быть заданы так, чтобы именно выполняющий Codex worker мог их достичь. До этого UI-диалоги через удаленного агента считаются `hybrid-prod-bridge`, а не доказательством локальной записи.
|
Не надо пытаться неявно “дотянуть” Mac-local окружение до Synology. Если нужен Tailscale, это отдельный явный профиль: Hub public URL, Gateway public URL и Engine/Tasker downstream должны быть заданы так, чтобы именно выполняющий Codex worker мог их достичь. До этого UI-диалоги через удаленного агента считаются `hybrid-prod-bridge`, а не доказательством локальной записи.
|
||||||
|
|
||||||
|
Канон локального тестирования описан в `docs/LOCAL_TESTING_SYSTEM.md`.
|
||||||
|
|
||||||
Перед controlled Synology apply запускайте общий predeploy gate:
|
Перед controlled Synology apply запускайте общий predeploy gate:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# NODE.DC Environment Contract
|
||||||
|
|
||||||
|
This contract separates local feature testing from deployed runtime.
|
||||||
|
|
||||||
|
## Profiles
|
||||||
|
|
||||||
|
`local`
|
||||||
|
|
||||||
|
- Runs Launcher, Engine, Ops/Gateway, AI Workspace Assistant, databases, and fixtures on the developer machine.
|
||||||
|
- May use the deployed AI Hub only as a thin relay for a remote Codex worker.
|
||||||
|
- Must not call production Launcher, Engine, Ops, Authentik, or Gateway endpoints.
|
||||||
|
|
||||||
|
`tunnel-local-e2e`
|
||||||
|
|
||||||
|
- Explicit escape hatch for Tailscale/ngrok-style testing.
|
||||||
|
- Same business services are still local, but relay URLs may use tunnel/private addresses.
|
||||||
|
- Must be opt-in through `NODEDC_ENV=tunnel-local-e2e`.
|
||||||
|
|
||||||
|
`staging`
|
||||||
|
|
||||||
|
- Deployed test stack with staging data and staging Authentik/OIDC clients.
|
||||||
|
- Used after local smoke is green.
|
||||||
|
|
||||||
|
`prod`
|
||||||
|
|
||||||
|
- Production data and production public domains.
|
||||||
|
- Only deploy artifacts that passed local and staging checks.
|
||||||
|
|
||||||
|
## URL Classes
|
||||||
|
|
||||||
|
- Browser URL: opened by a user browser.
|
||||||
|
- Internal service URL: used by one backend to call another backend.
|
||||||
|
- Relay URL: used only to move messages between a local assistant and a remote worker.
|
||||||
|
- Downstream app URL: used by an assistant adapter to read or mutate its owning app.
|
||||||
|
|
||||||
|
Do not mix these classes. A remote worker must not call Launcher, Engine, Ops, or Authentik directly in `local`.
|
||||||
|
|
||||||
|
## Local Remote Worker Chain
|
||||||
|
|
||||||
|
```text
|
||||||
|
local Engine
|
||||||
|
-> local AI Workspace Assistant
|
||||||
|
-> deployed AI Hub relay
|
||||||
|
-> remote Codex worker
|
||||||
|
-> deployed AI Hub relay
|
||||||
|
-> local AI Workspace Assistant
|
||||||
|
-> local Launcher / local Engine / local Ops
|
||||||
|
```
|
||||||
|
|
||||||
|
The deployed AI Hub is transport only. It must not decide product access, own app routes, or force production downstream URLs.
|
||||||
|
|
||||||
|
## Required Local Defaults
|
||||||
|
|
||||||
|
Engine local server:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NODEDC_ENV=local
|
||||||
|
NODEDC_LAUNCHER_INTERNAL_URL=http://127.0.0.1:5173
|
||||||
|
NODEDC_LAUNCHER_ORIGIN=http://launcher.local.nodedc
|
||||||
|
AUTHENTIK_PUBLIC_BASE_URL=http://auth.local.nodedc
|
||||||
|
NODEDC_AI_WORKSPACE_ASSISTANT_URL=http://127.0.0.1:18082
|
||||||
|
OPS_RETENTION_ENABLED=false
|
||||||
|
```
|
||||||
|
|
||||||
|
Platform local stack:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NODEDC_ENV=local
|
||||||
|
AI_WORKSPACE_HUB_PUBLIC_URL=wss://ai-hub.nodedc.ru/api/ai-workspace/hub
|
||||||
|
AI_WORKSPACE_HUB_INTERNAL_URL=https://ai-hub.nodedc.ru
|
||||||
|
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ENABLED=true
|
||||||
|
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ID=local-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The AI Hub URLs above are allowed only because they are relay URLs. Production app URLs such as `https://hub.nodedc.ru`, `https://engine.nodedc.ru`, `https://ops.nodedc.ru`, and `https://id.nodedc.ru` are forbidden in local app config.
|
||||||
|
|
||||||
|
Assistant action calls in local must use the relay route:
|
||||||
|
|
||||||
|
```text
|
||||||
|
remote worker assistant_action_call
|
||||||
|
-> deployed AI Hub /api/ai-workspace/hub/v1/assistant-relays/<relayId>/actions
|
||||||
|
-> local AI Workspace Assistant long-poll
|
||||||
|
-> local Launcher / Engine / Ops adapter
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not route local assistant actions through the deployed Assistant or deployed product backends.
|
||||||
|
|
||||||
|
## Guardrail
|
||||||
|
|
||||||
|
Run the complete local testing gate before local AI Workspace testing:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh platform/infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Run this narrower env-only guard when changing env files:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node platform/infra/scripts/check-local-environment-safety.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the broader AI Workspace contract check before changing worker/assistant routing:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
platform/infra/scripts/check-ai-workspace-config-contract.sh
|
||||||
|
```
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# NODE.DC Local Testing System
|
||||||
|
|
||||||
|
Цель: тестировать новые функции на локально запущенных репозиториях без переписывания адресов перед деплоем и без случайных обращений в production-приложения.
|
||||||
|
|
||||||
|
## Canon
|
||||||
|
|
||||||
|
Локальный профиль:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NODEDC_ENV=local
|
||||||
|
```
|
||||||
|
|
||||||
|
В `local` все product apps являются локальными:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Launcher/Auth/HUB UI -> local
|
||||||
|
Engine -> local
|
||||||
|
Ops/Gateway/Tasker -> local
|
||||||
|
AI Workspace Assistant -> local
|
||||||
|
DB/fixtures -> local
|
||||||
|
```
|
||||||
|
|
||||||
|
Единственное разрешенное deployed-звено в этом профиле:
|
||||||
|
|
||||||
|
```text
|
||||||
|
AI Hub relay -> https://ai-hub.nodedc.ru
|
||||||
|
```
|
||||||
|
|
||||||
|
Этот Hub используется только как транспорт для удаленного Codex worker. Он не должен быть downstream app, не должен владеть доступами пользователя и не должен сам читать/писать Launcher, Engine или Ops.
|
||||||
|
|
||||||
|
## Remote Worker Local Flow
|
||||||
|
|
||||||
|
```text
|
||||||
|
local Engine / local Ops UI
|
||||||
|
-> local AI Workspace Assistant
|
||||||
|
-> deployed AI Hub relay
|
||||||
|
-> remote Codex worker
|
||||||
|
-> deployed AI Hub assistant action relay
|
||||||
|
-> local AI Workspace Assistant
|
||||||
|
-> local Launcher / local Engine / local Ops
|
||||||
|
```
|
||||||
|
|
||||||
|
Worker получает только relay URL и scoped run profile. Product app URL остаются на стороне локального Assistant.
|
||||||
|
|
||||||
|
## Required Local Guardrails
|
||||||
|
|
||||||
|
Local Platform env:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NODEDC_ENV=local
|
||||||
|
AI_WORKSPACE_HUB_PUBLIC_URL=wss://ai-hub.nodedc.ru/api/ai-workspace/hub
|
||||||
|
AI_WORKSPACE_HUB_INTERNAL_URL=https://ai-hub.nodedc.ru
|
||||||
|
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ENABLED=true
|
||||||
|
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ID=local-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Local Engine env:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NODEDC_ENV=local
|
||||||
|
NODEDC_AI_WORKSPACE_ASSISTANT_URL=http://127.0.0.1:18082
|
||||||
|
NODEDC_LAUNCHER_INTERNAL_URL=http://127.0.0.1:5173
|
||||||
|
NODEDC_LAUNCHER_ORIGIN=http://launcher.local.nodedc
|
||||||
|
AUTHENTIK_PUBLIC_BASE_URL=http://auth.local.nodedc
|
||||||
|
```
|
||||||
|
|
||||||
|
Production app URLs are forbidden in local config:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://hub.nodedc.ru
|
||||||
|
https://engine.nodedc.ru
|
||||||
|
https://ops.nodedc.ru
|
||||||
|
https://id.nodedc.ru
|
||||||
|
https://ops-agents.nodedc.ru
|
||||||
|
```
|
||||||
|
|
||||||
|
Tunnel/private URLs are also forbidden in `local`. If Tailscale/ngrok is deliberately needed, switch to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NODEDC_ENV=tunnel-local-e2e
|
||||||
|
```
|
||||||
|
|
||||||
|
## Standard Check
|
||||||
|
|
||||||
|
Run this before UI testing and before deploy preparation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd /Users/dcconstructions/Downloads/mnt/NODEDC/platform
|
||||||
|
sh infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
This command:
|
||||||
|
|
||||||
|
- checks Node and shell syntax;
|
||||||
|
- checks local env safety;
|
||||||
|
- checks AI Workspace config contract;
|
||||||
|
- renders local Docker Compose config without starting containers;
|
||||||
|
- checks that local Compose does not inject the full `.env` into every service;
|
||||||
|
- runs run-profile and ontology assistant caller smoke tests;
|
||||||
|
- classifies the current runtime topology;
|
||||||
|
- checks diff whitespace hygiene.
|
||||||
|
|
||||||
|
It does not deploy, restart containers, mutate databases, or write production config.
|
||||||
|
|
||||||
|
## Runtime Modes
|
||||||
|
|
||||||
|
`contract-only`
|
||||||
|
|
||||||
|
Static contracts are testable, but no runtime path is proven.
|
||||||
|
|
||||||
|
`local-ui-only`
|
||||||
|
|
||||||
|
Some local UI/backend endpoints respond, but AI write path is not proven.
|
||||||
|
|
||||||
|
`local-ops-vertical`
|
||||||
|
|
||||||
|
Local Ops/Gateway/Tasker vertical path is reachable, but remote worker action path is not proven.
|
||||||
|
|
||||||
|
`local-remote-worker-relay`
|
||||||
|
|
||||||
|
Expected current target for this workstation:
|
||||||
|
|
||||||
|
```text
|
||||||
|
local product apps + local Assistant + deployed AI Hub relay + remote Codex worker
|
||||||
|
```
|
||||||
|
|
||||||
|
This is valid only when Assistant action relay is configured. A successful UI request must show that `assistant_action_call` routes through the relay back to local Assistant.
|
||||||
|
|
||||||
|
`true-local-e2e`
|
||||||
|
|
||||||
|
Everything, including Hub and worker reachability, is local.
|
||||||
|
|
||||||
|
`tunnel-local-e2e`
|
||||||
|
|
||||||
|
Explicit Tailscale/ngrok profile. This must never happen by accidental URL fallback.
|
||||||
|
|
||||||
|
## Strict Runtime Checks
|
||||||
|
|
||||||
|
Require a live local/relay runtime:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
REQUIRE_RUNTIME=1 sh infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Require specifically the remote-worker relay mode:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
REQUIRE_REMOTE_WORKER_RELAY=1 sh infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deploy Rule
|
||||||
|
|
||||||
|
Deploy is allowed only after:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh infra/scripts/check-local-test-system.sh
|
||||||
|
sh infra/scripts/check-ai-workspace-release-gates.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Runtime bugs must be fixed in the local profile first. Do not deploy product app changes just to test whether the local AI Workspace path works.
|
||||||
|
|
||||||
|
## Audit And Test Map
|
||||||
|
|
||||||
|
Current audit report:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/AI_WORKSPACE_SECURITY_AUDIT_2026-06-20.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Current horizontal, vertical, and security test matrix:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/AI_WORKSPACE_TEST_MATRIX.md
|
||||||
|
```
|
||||||
@@ -34,6 +34,15 @@ Service catalog UX rules: `docs/SERVICE_CATALOG_UX_RULES.md`.
|
|||||||
- [x] Local runtime не отдает `storage/launcher-data.json` напрямую через public static route.
|
- [x] Local runtime не отдает `storage/launcher-data.json` напрямую через public static route.
|
||||||
- [x] Local runtime требует user session для `/api/storage/data`.
|
- [x] Local runtime требует user session для `/api/storage/data`.
|
||||||
|
|
||||||
|
## Cross-app session sync
|
||||||
|
|
||||||
|
- [x] Общий live logout path зафиксирован как `nodedc:session:logout` через Launcher session-sync/frontchannel.
|
||||||
|
- [x] BIM Viewer подключён к logout path и по logout должен понижать UI до guest/limited controls.
|
||||||
|
- [x] BIM login-sync marker не является auth-token и требует revalidation через Launcher.
|
||||||
|
- [ ] Описан общий `ndcauth.session` contract для login/logout/change, а не только BIM-first slice.
|
||||||
|
- [ ] HUB/OPS/ENGINE/BIM проходят browser matrix: login/logout из любого surface обновляет уже открытые приложения без refresh.
|
||||||
|
- [ ] Session sync события имеют audit/observability без user secrets в логах.
|
||||||
|
|
||||||
## Plane
|
## Plane
|
||||||
|
|
||||||
- [ ] Перед изменениями сделан backup DB/env/uploads/storage.
|
- [ ] Перед изменениями сделан backup DB/env/uploads/storage.
|
||||||
|
|||||||
+109
-3
@@ -1,14 +1,18 @@
|
|||||||
# domains
|
# domains
|
||||||
|
NODEDC_ENV=local
|
||||||
AUTH_DOMAIN=auth.local.nodedc
|
AUTH_DOMAIN=auth.local.nodedc
|
||||||
AUTH_ADMIN_DOMAIN=auth-admin.local.nodedc
|
AUTH_ADMIN_DOMAIN=auth-admin.local.nodedc
|
||||||
LAUNCHER_DOMAIN=launcher.local.nodedc
|
LAUNCHER_DOMAIN=launcher.local.nodedc
|
||||||
TASK_DOMAIN=task.local.nodedc
|
TASK_DOMAIN=task.local.nodedc
|
||||||
|
BIM_DOMAIN=bim.local.nodedc
|
||||||
|
NODEDC_BIM_VIEWER_PUBLIC_URL=http://localhost:8080
|
||||||
|
|
||||||
# proxy
|
# proxy
|
||||||
PLATFORM_HTTP_PORT=80
|
PLATFORM_HTTP_PORT=80
|
||||||
PLATFORM_PROXY_IMAGE=nodedc/plane-proxy:ru
|
PLATFORM_PROXY_IMAGE=nodedc/plane-proxy:ru
|
||||||
LOCAL_LAUNCHER_UPSTREAM=host.docker.internal:5173
|
LOCAL_LAUNCHER_UPSTREAM=host.docker.internal:5173
|
||||||
LOCAL_TASK_MANAGER_UPSTREAM=host.docker.internal:8090
|
LOCAL_TASK_MANAGER_UPSTREAM=host.docker.internal:8090
|
||||||
|
LOCAL_BIM_VIEWER_UPSTREAM=host.docker.internal:8080
|
||||||
|
|
||||||
# authentik image
|
# authentik image
|
||||||
AUTHENTIK_IMAGE=ghcr.io/goauthentik/server
|
AUTHENTIK_IMAGE=ghcr.io/goauthentik/server
|
||||||
@@ -47,6 +51,51 @@ NODEDC_INTERNAL_ACCESS_TOKEN=change-me-generate-with-infra-scripts-init-dev-env
|
|||||||
COOKIE_DOMAIN=.local.nodedc
|
COOKIE_DOMAIN=.local.nodedc
|
||||||
COOKIE_SECURE=false
|
COOKIE_SECURE=false
|
||||||
|
|
||||||
|
# External Data Plane — provider-neutral storage owned by the Platform. This
|
||||||
|
# password is a database credential only; never reuse NODEDC_INTERNAL_ACCESS_TOKEN.
|
||||||
|
EXTERNAL_DATA_PLANE_TIMESCALE_IMAGE=timescale/timescaledb-ha:pg16.14-ts2.28.2-all
|
||||||
|
EXTERNAL_DATA_PLANE_PG_DB=nodedc_data_plane
|
||||||
|
EXTERNAL_DATA_PLANE_PG_USER=nodedc_data_plane
|
||||||
|
EXTERNAL_DATA_PLANE_PG_PASS=change-me-generate-with-infra-scripts-init-dev-env
|
||||||
|
EXTERNAL_DATA_PLANE_HOST_BIND=127.0.0.1:18106
|
||||||
|
EXTERNAL_DATA_PLANE_DATABASE_POOL_SIZE=10
|
||||||
|
EXTERNAL_DATA_PLANE_RAW_RETENTION_DAYS=14
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_BATCH_BYTES=5242880
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_FACTS_PER_PUBLISH=5000
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_ATTRIBUTES_BYTES_PER_FACT=65536
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_PATCH_OPERATIONS=500
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_PATCH_BYTES=262144
|
||||||
|
EXTERNAL_DATA_PLANE_PATCH_RETENTION_MS=3600000
|
||||||
|
EXTERNAL_DATA_PLANE_RECEIPT_RETENTION_MS=604800000
|
||||||
|
EXTERNAL_DATA_PLANE_RETENTION_DELETE_LIMIT=10000
|
||||||
|
EXTERNAL_DATA_PLANE_STREAM_HEARTBEAT_MS=20000
|
||||||
|
EXTERNAL_DATA_PLANE_STREAM_POLL_MS=1000
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_READER_STREAMS=10
|
||||||
|
EXTERNAL_DATA_PLANE_WRITER_BINDING_MAX_TTL_DAYS=90
|
||||||
|
EXTERNAL_DATA_PLANE_MAX_FUTURE_SKEW_SECONDS=300
|
||||||
|
EXTERNAL_DATA_PLANE_RETENTION_SWEEP_MS=3600000
|
||||||
|
EXTERNAL_DATA_PLANE_LEGACY_INTAKE_ENABLED=false
|
||||||
|
# Internal control-plane writer/reader binding issuance; keep false until the
|
||||||
|
# atomic NDC L2 ensure-grant operation is deployed. Legacy path returns a
|
||||||
|
# plaintext capability and must never be exposed to users.
|
||||||
|
EXTERNAL_DATA_PLANE_PROVISIONING_ENABLED=false
|
||||||
|
# Digest-only managed writer-binding ensure. It accepts only signed Engine
|
||||||
|
# service requests; the legacy provisioner bearer is deliberately invalid here.
|
||||||
|
# Keep false until the matching Engine private key is provisioned. The trust
|
||||||
|
# directory is mounted read-only into EDP and contains only `public-key.pem`.
|
||||||
|
EXTERNAL_DATA_PLANE_MANAGED_PROVISIONING_ENABLED=false
|
||||||
|
EXTERNAL_DATA_PLANE_MANAGED_PROVISIONER_SERVICE_ID=nodedc-engine
|
||||||
|
EXTERNAL_DATA_PLANE_MANAGED_PROVISIONER_KEY_ID=engine-edp-managed-provisioner-v1
|
||||||
|
EXTERNAL_DATA_PLANE_MANAGED_PROVISIONER_AUDIENCE=nodedc-external-data-plane.managed-provisioning.v1
|
||||||
|
EXTERNAL_DATA_PLANE_MANAGED_PROVISIONER_MAX_SKEW_SECONDS=60
|
||||||
|
EXTERNAL_DATA_PLANE_MANAGED_PROVISIONER_REPLAY_CACHE_MAX_ENTRIES=10000
|
||||||
|
EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONING_ENABLED=true
|
||||||
|
EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONER_SERVICE_ID=nodedc-module-foundry
|
||||||
|
EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONER_KEY_ID=foundry-edp-managed-provisioner-v1
|
||||||
|
EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONER_AUDIENCE=nodedc-external-data-plane.managed-provisioning.v1
|
||||||
|
EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONER_MAX_SKEW_SECONDS=60
|
||||||
|
EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONER_REPLAY_CACHE_MAX_ENTRIES=10000
|
||||||
|
|
||||||
# notification core
|
# notification core
|
||||||
NOTIFICATION_PG_DB=nodedc_notifications
|
NOTIFICATION_PG_DB=nodedc_notifications
|
||||||
NOTIFICATION_PG_USER=nodedc_notifications
|
NOTIFICATION_PG_USER=nodedc_notifications
|
||||||
@@ -62,13 +111,70 @@ NODEDC_AI_WORKSPACE_ASSISTANT_URL=http://ai-workspace-assistant:18082
|
|||||||
AI_WORKSPACE_OPS_ENTITLEMENT_URL=http://host.docker.internal:4100/api/internal/v1/ai-workspace/entitlements
|
AI_WORKSPACE_OPS_ENTITLEMENT_URL=http://host.docker.internal:4100/api/internal/v1/ai-workspace/entitlements
|
||||||
AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN=replace-with-ops-agent-gateway-internal-token
|
AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN=replace-with-ops-agent-gateway-internal-token
|
||||||
AI_WORKSPACE_OPS_ENTITLEMENT_REQUIRED=false
|
AI_WORKSPACE_OPS_ENTITLEMENT_REQUIRED=false
|
||||||
|
# Add Module Foundry only after its domain, Launcher handoff and Authentik group
|
||||||
|
# are verified. Preserve existing adapters when adding this JSON member:
|
||||||
|
# {"module-foundry":{"url":"https://<foundry-domain>/api/ai-workspace/entitlements","required":false}}
|
||||||
|
# The generic adapter reuses the existing NODE.DC internal server credential;
|
||||||
|
# never define a separate Foundry token for a browser or worker.
|
||||||
|
AI_WORKSPACE_ENTITLEMENT_ADAPTERS_JSON=
|
||||||
|
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ENABLED=true
|
||||||
|
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ID=local-dev
|
||||||
|
AI_WORKSPACE_ONTOLOGY_MCP_ENABLED=true
|
||||||
|
|
||||||
# AI Workspace Hub for downloaded Codex workers.
|
# AI Workspace Hub for downloaded Codex workers.
|
||||||
# Default local development uses the deployed relay and is a hybrid-prod-bridge topology:
|
# Default local development may use the deployed AI Hub only as a relay for remote Codex workers.
|
||||||
# local UI/services can be tested, but live Codex worker write-path e2e is not proven.
|
# Launcher/Engine/Ops/Auth downstream URLs must remain local.
|
||||||
# For true local/tunnel e2e, change both Hub URLs and Ops Gateway public URL deliberately.
|
# For Tailscale/ngrok-style relay URLs, set NODEDC_ENV=tunnel-local-e2e deliberately.
|
||||||
AI_WORKSPACE_HUB_TOKEN=change-me-generate-with-infra-scripts-init-dev-env
|
AI_WORKSPACE_HUB_TOKEN=change-me-generate-with-infra-scripts-init-dev-env
|
||||||
AI_WORKSPACE_HUB_HOST_BIND=127.0.0.1:18081
|
AI_WORKSPACE_HUB_HOST_BIND=127.0.0.1:18081
|
||||||
AI_WORKSPACE_HUB_PUBLIC_URL=wss://ai-hub.nodedc.ru/api/ai-workspace/hub
|
AI_WORKSPACE_HUB_PUBLIC_URL=wss://ai-hub.nodedc.ru/api/ai-workspace/hub
|
||||||
AI_WORKSPACE_HUB_INTERNAL_URL=https://ai-hub.nodedc.ru
|
AI_WORKSPACE_HUB_INTERNAL_URL=https://ai-hub.nodedc.ru
|
||||||
AI_WORKSPACE_HUB_FALLBACK_URLS=
|
AI_WORKSPACE_HUB_FALLBACK_URLS=
|
||||||
|
# The worker receives a per-run, pairing-bound read-only Ontology MCP URL through AI Hub.
|
||||||
|
# Do not put Ontology Core tokens or catalog paths in worker configuration.
|
||||||
|
AI_WORKSPACE_ONTOLOGY_MCP_PUBLIC_URL=
|
||||||
|
ONTOLOGY_CORE_HOST_BIND=127.0.0.1:18104
|
||||||
|
|
||||||
|
# Gelios Gateway — frozen legacy storage/read compatibility service. Provider
|
||||||
|
# credentials belong to the protected Engine Collector and are never configured
|
||||||
|
# in this service. Keep this contour reproducible; do not use it as a template
|
||||||
|
# for new providers.
|
||||||
|
GELIOS_TIMESCALE_IMAGE=timescale/timescaledb-ha:pg16.14-ts2.28.2-all
|
||||||
|
GELIOS_PG_DB=nodedc_gelios
|
||||||
|
GELIOS_PG_USER=nodedc_gelios
|
||||||
|
GELIOS_PG_PASS=change-me-generate-with-infra-scripts-init-dev-env
|
||||||
|
# URL-encode reserved characters in GELIOS_PG_PASS when forming this URL.
|
||||||
|
GELIOS_DATABASE_URL=postgresql://nodedc_gelios:change-me-generate-with-infra-scripts-init-dev-env@gelios-postgres:5432/nodedc_gelios
|
||||||
|
GELIOS_GATEWAY_HOST_BIND=127.0.0.1:18105
|
||||||
|
GELIOS_TENANT_ID=replace-with-tenant-id
|
||||||
|
GELIOS_CONNECTION_ID=gelios-connection-id
|
||||||
|
# `allowlist` accepts only GELIOS_ALLOWED_UNIT_IDS. `all` accepts every unit
|
||||||
|
# returned by this already-approved tenant + connection, including future units.
|
||||||
|
GELIOS_UNIT_SCOPE=allowlist
|
||||||
|
GELIOS_ALLOWED_UNIT_IDS=
|
||||||
|
GELIOS_INTAKE_ENABLED=false
|
||||||
|
GELIOS_RAW_RETENTION_DAYS=14
|
||||||
|
# Presentation state only; it does not change provider collection cadence.
|
||||||
|
GELIOS_POSITION_STALE_AFTER_MS=300000
|
||||||
|
|
||||||
|
# map gateway — keep the actual ion token only in local/staging environment files or Docker secrets.
|
||||||
|
# Never copy it into workflow metadata, Git, frontend code, or a runtime cache key.
|
||||||
|
MAP_GATEWAY_HOST_BIND=127.0.0.1:18103
|
||||||
|
MAP_GATEWAY_ALLOW_ANONYMOUS=true
|
||||||
|
MAP_GATEWAY_CORS_ORIGIN=http://127.0.0.1:3333,http://localhost:3333
|
||||||
|
MAP_GATEWAY_UPSTREAM_ALLOWLIST=api.cesium.com,assets.ion.cesium.com,tile.openstreetmap.org,dev.virtualearth.net,ecn.t0.tiles.virtualearth.net,ecn.t1.tiles.virtualearth.net,ecn.t2.tiles.virtualearth.net,ecn.t3.tiles.virtualearth.net
|
||||||
|
# Imported Engine imagery is selected through the explicit offline cache
|
||||||
|
# profile, not through a global host-side block.
|
||||||
|
MAP_GATEWAY_LEGACY_CACHE_HOSTS=
|
||||||
|
# Leave empty unless the provider/data licence explicitly permits disconnected/offline use.
|
||||||
|
MAP_GATEWAY_OFFLINE_PROVIDER_ALLOWLIST=
|
||||||
|
MAP_GATEWAY_UPSTREAM_TIMEOUT_SECONDS=30
|
||||||
|
CESIUM_ION_TOKEN=
|
||||||
|
CESIUM_ION_ASSET_ALLOWLIST=1,2,96188
|
||||||
|
MAP_CACHE_MODE=readwrite
|
||||||
|
# Mutable cache is mounted at /var/lib/nodedc-map-live-cache by compose.
|
||||||
|
# MAP_OFFLINE_SNAPSHOT_DIR is intentionally wired by compose as a read-only
|
||||||
|
# imported Engine snapshot; never place secrets or the live cache there.
|
||||||
|
MAP_CACHE_MAX_MB=20480
|
||||||
|
MAP_CACHE_MAX_OBJECT_MB=128
|
||||||
|
MAP_CACHE_DEFAULT_TTL_SECONDS=604800
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
AUTH_DOMAIN=auth.staging.nodedc.example
|
AUTH_DOMAIN=auth.staging.nodedc.example
|
||||||
LAUNCHER_DOMAIN=launcher.staging.nodedc.example
|
LAUNCHER_DOMAIN=launcher.staging.nodedc.example
|
||||||
TASK_DOMAIN=task.staging.nodedc.example
|
TASK_DOMAIN=task.staging.nodedc.example
|
||||||
|
BIM_DOMAIN=bim.staging.nodedc.example
|
||||||
|
NODEDC_BIM_VIEWER_PUBLIC_URL=https://bim.staging.nodedc.example
|
||||||
|
|
||||||
# edge proxy
|
# edge proxy
|
||||||
ACME_EMAIL=admin@nodedc.example
|
ACME_EMAIL=admin@nodedc.example
|
||||||
@@ -10,6 +12,7 @@ PLATFORM_HTTPS_PORT=443
|
|||||||
PLATFORM_PROXY_IMAGE=caddy:2-alpine
|
PLATFORM_PROXY_IMAGE=caddy:2-alpine
|
||||||
STAGING_LAUNCHER_UPSTREAM=launcher:5173
|
STAGING_LAUNCHER_UPSTREAM=launcher:5173
|
||||||
STAGING_TASK_MANAGER_UPSTREAM=task-manager-proxy:80
|
STAGING_TASK_MANAGER_UPSTREAM=task-manager-proxy:80
|
||||||
|
STAGING_BIM_VIEWER_UPSTREAM=host.docker.internal:18100
|
||||||
|
|
||||||
# authentik image
|
# authentik image
|
||||||
AUTHENTIK_IMAGE=ghcr.io/goauthentik/server
|
AUTHENTIK_IMAGE=ghcr.io/goauthentik/server
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
- reverse proxy;
|
- reverse proxy;
|
||||||
- локальные домены;
|
- локальные домены;
|
||||||
- shared env examples;
|
- shared env examples;
|
||||||
|
- Map Gateway с persistent TileCache;
|
||||||
- будущие docker compose файлы.
|
- будущие docker compose файлы.
|
||||||
|
|
||||||
Первый local dev слой проксирует текущие локальные приложения без физического переноса репозиториев:
|
Первый local dev слой проксирует текущие локальные приложения без физического переноса репозиториев:
|
||||||
@@ -32,6 +33,15 @@ infra/
|
|||||||
|
|
||||||
## Local start
|
## Local start
|
||||||
|
|
||||||
|
0. Check the local testing contract:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /Users/dcconstructions/Downloads/mnt/NODEDC/platform
|
||||||
|
sh infra/scripts/check-local-test-system.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The local testing canon is documented in `docs/LOCAL_TESTING_SYSTEM.md`. It keeps product apps local and allows the deployed AI Hub only as a remote Codex worker relay.
|
||||||
|
|
||||||
1. Add local domains to `/etc/hosts`:
|
1. Add local domains to `/etc/hosts`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -61,10 +71,19 @@ docker compose --env-file infra/.env -f infra/docker-compose.dev.yml ps
|
|||||||
curl -I -H 'Host: auth.local.nodedc' http://127.0.0.1/
|
curl -I -H 'Host: auth.local.nodedc' http://127.0.0.1/
|
||||||
curl -I -H 'Host: launcher.local.nodedc' http://127.0.0.1/
|
curl -I -H 'Host: launcher.local.nodedc' http://127.0.0.1/
|
||||||
curl -I -H 'Host: task.local.nodedc' http://127.0.0.1/
|
curl -I -H 'Host: task.local.nodedc' http://127.0.0.1/
|
||||||
|
curl http://127.0.0.1:18103/healthz
|
||||||
```
|
```
|
||||||
|
|
||||||
Generated Authentik bootstrap credentials are stored only in `infra/.env`.
|
Generated Authentik bootstrap credentials are stored only in `infra/.env`.
|
||||||
|
|
||||||
|
## Map Gateway и offline TileCache
|
||||||
|
|
||||||
|
`map-gateway` добавлен как общий платформенный сервис на `127.0.0.1:18103`. На NAS его mutable live-cache лежит в `/volume1/docker/nodedc-platform/map-gateway/live-tile-cache`; read-only offline snapshot — рядом в `offline-snapshot`. Это host bind mounts, поэтому папки видны через SMB как `nodedc-platform/map-gateway/`, но не попадают в Git, Docker image или deployment artifact.
|
||||||
|
|
||||||
|
Обе папки создаёт root-owned `nodedc-deploy` при первом Map Gateway artifact. Agent не создаёт их напрямую через SMB и не кладёт в artifact. `docker compose down -v` их не удаляет. Очистка допустима только отдельной явно согласованной root-операцией при остановленном Gateway.
|
||||||
|
|
||||||
|
Для реального ion terrain/buildings положите `CESIUM_ION_TOKEN` только в неотслеживаемый `infra/.env` или deployment secret. Browser получает лишь публичный provider URL через same-origin Foundry proxy; Gateway добавляет asset credential только в исходящем private request. Детали API, cache modes и production access boundary описаны в `services/map-gateway/README.md`.
|
||||||
|
|
||||||
5. Bootstrap local Authentik groups and OIDC applications:
|
5. Bootstrap local Authentik groups and OIDC applications:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -26,6 +26,14 @@ GROUP_SPECS = [
|
|||||||
("nodedc:launcher:user", False),
|
("nodedc:launcher:user", False),
|
||||||
("nodedc:taskmanager:admin", False),
|
("nodedc:taskmanager:admin", False),
|
||||||
("nodedc:taskmanager:user", False),
|
("nodedc:taskmanager:user", False),
|
||||||
|
("nodedc:bim:access", False),
|
||||||
|
# Module Foundry roles travel through the existing Authentik `groups`
|
||||||
|
# claim and Launcher handoff. `access` remains a backward-compatible
|
||||||
|
# member role until every existing assignment is migrated.
|
||||||
|
("nodedc:module-foundry:admin", False),
|
||||||
|
("nodedc:module-foundry:user", False),
|
||||||
|
("nodedc:module-foundry:blocked", False),
|
||||||
|
("nodedc:module-foundry:access", False),
|
||||||
]
|
]
|
||||||
|
|
||||||
APP_SPECS = [
|
APP_SPECS = [
|
||||||
@@ -120,7 +128,11 @@ def ensure_user_groups(groups):
|
|||||||
user.groups.add(authentik_admins)
|
user.groups.add(authentik_admins)
|
||||||
|
|
||||||
for name in groups:
|
for name in groups:
|
||||||
user.groups.add(groups[name])
|
# The bootstrap owner must remain capable of entering Foundry after
|
||||||
|
# the first provisioning run. Blocking is an explicit operator action,
|
||||||
|
# never a default membership of the bootstrap principal.
|
||||||
|
if name != "nodedc:module-foundry:blocked":
|
||||||
|
user.groups.add(groups[name])
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# 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).
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# 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).
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# 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.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# CMS Git deployment domain
|
||||||
|
|
||||||
|
Source: SILVER/DC_CMS, repository 33, master. Push → qualification → Gitea artifact → outbound durable queue → canonical installer.
|
||||||
|
|
||||||
|
The Device Core runner is scoped only to its own repository. CMS therefore registers its own build-runner in project nodedc-cms-ci, with the accepted Synology v4 resource and isolation profile. Existing Device Core registration, source and units are untouched. Both pinned images must already exist; bootstrap pulls neither. New runner registration is repository-scoped, staged separately from artifacts, imported to root0600 and removed from handoff storage. No credentials appear in Git, receipts or workflow artifacts.
|
||||||
|
|
||||||
|
`dc-cms-autodeploy` bootstraps exactly three source files under /volume1/docker/nodedc-cms-autodeploy, one build-runner service and two systemd units. Root-private queue state is /var/lib/nodedc-cms-autodeploy. Its read-only Gitea client uses the existing private Device Core read identity without copying it; preflight checks actual access to repository 33. The installed canonical receipt gates polling. Bootstrap preserves all preexisting containers and CMS data; rollback removes only the new runner/units/source partition, retaining private enrollment and queue for diagnosis.
|
||||||
|
|
||||||
|
`dc-cms-release` allows only flat admin/server application files and two exact dependency files. The initial predecessor is original CMS commit 4c6f133 with SMB-verified hashes in baseline.json. Foundation pins adm-zip 0.6.1 in foundation.json to fix known ZIP vulnerabilities. No later dependency, Dockerfile, Compose or Caddy change is admitted by this domain. Build uses the registered Dockerfile in an isolated temporary context with an empty projects directory. Only the temporary FROM line is replaced by the exact cached Node image ID proved against the accepted application's layer ancestry and inherited configuration; see [the build-base contract](R40_BUILD_BASE.md). The canonical installer restarts only cms-app with no dependencies, no image pull and no rebuild during rollback. Acceptance verifies authentication, app hashes inside the running container, image generation, fixed ZIP dependency version, preserved env/mounts/networks/ports, other Compose services and site/project data.
|
||||||
|
|
||||||
|
## Build and checks
|
||||||
|
|
||||||
|
`python3 infra/cms-deploy/embed_runtime.py` refreshes only the explicitly marked standalone section. Registry and dispatcher wiring are ordinary reviewed runner source. Runtime never imports the fragment files from SMB.
|
||||||
|
|
||||||
|
`python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'`
|
||||||
|
`python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'`
|
||||||
|
`python3 infra/cms-deploy/build_autodeploy.py --output-dir <directory>`
|
||||||
|
|
||||||
|
Before production: SHA-pinned root runner promotion and verify-install; then fresh canonical plan/apply of the bootstrap artifact. Ordinary CMS pushes afterward need no operator NAS commands. A queued or green Actions run alone is not deployment evidence; require canonical receipt and product acceptance.
|
||||||
|
|
||||||
|
Bootstrap 002 corrects the initial POSIX inventory: the NAS contains a Synology
|
||||||
|
`server/@eaDir/admin-server.mjs@SynoEAStream` file hidden from SMB. The original
|
||||||
|
application and foundation hashes were confirmed unchanged through both paths.
|
||||||
|
Only flat `admin|server/@eaDir/<present-application-file>@SynoEAStream` regular
|
||||||
|
files are classified as metadata. Orphaned streams, unknown paths and symlinks
|
||||||
|
remain errors. Metadata is excluded from application identity and clean image
|
||||||
|
build inputs, and preserved byte-for-byte across application release/rollback.
|
||||||
|
The same partition handles old images containing these non-code streams; all
|
||||||
|
application hashes are still exact. Bootstrap 001 failed during read-only plan,
|
||||||
|
never entered apply, and is superseded rather than retried or overwritten.
|
||||||
|
|
||||||
|
After bootstrap 002 was accepted, Gitea assigned CMS runner ID 2. The initial
|
||||||
|
copied source verifier still required Device Core's ID 1 and rejected successful
|
||||||
|
run 39 before staging or deployment. Qualification now receives the ID from the
|
||||||
|
root-private CMS `data/.runner` registration; it verifies exact runner name,
|
||||||
|
repository, labels, job, steps, run identity and artifact ownership. Registration
|
||||||
|
IDs are allocated by Gitea, so no fixed numeric fallback is permitted. This
|
||||||
|
controller correction preserves the accepted bootstrap 002 receipt and private
|
||||||
|
queue; it does not rerun bootstrap or re-register/restart the build daemon.
|
||||||
|
|
||||||
|
Release r39 then reached canonical apply but failed runtime-config acceptance;
|
||||||
|
its automatic rollback restored the original source and healthy authenticated
|
||||||
|
CMS, while full runtime equivalence remained unproven. The failed receipt and
|
||||||
|
controller reconciliation barrier stay intact. `dc-cms-runtime-audit` is a
|
||||||
|
separate **plan-only** diagnostic domain pinned to that exact incident, archive
|
||||||
|
and six backup-file hashes. It reads current source/data/image/runtime evidence
|
||||||
|
and reports a bounded saved-digest preimage search without accepting any drift.
|
||||||
|
No environment values or raw Docker inspection are printed. `apply` is forbidden;
|
||||||
|
no application, queue, receipt or service is changed by this audit. Recovery must
|
||||||
|
be a separately reviewed transition after its actual runtime findings.
|
||||||
|
|
||||||
|
After diagnostic runner promotion, build its fixed data bundle with
|
||||||
|
`python3 infra/cms-deploy/build_runtime_audit.py --output-dir <directory>` and
|
||||||
|
use only the canonical `plan` operation for the audit artifact.
|
||||||
|
|
||||||
|
The r39 audit confirmed the old image and all source/data/dependency checks.
|
||||||
|
Offline reconstruction matched the complete current fingerprint and the complete
|
||||||
|
saved predecessor fingerprint: only bind-string order and three empty DNS list
|
||||||
|
representations differ. See [the incident proof and recovery contract](R39_RUNTIME_RECONCILIATION.md).
|
||||||
|
The separate `dc-cms-runtime-reconciliation` marker transition re-proves that
|
||||||
|
exact legacy hash on NAS before releasing the r39 barrier. It never retries r39.
|
||||||
|
Reconciliation was accepted at 2026-11-04T20:28:35Z. The next qualified run r40
|
||||||
|
failed only `config.Env`; its automatic rollback passed completely. r40 is also
|
||||||
|
terminal and must not be replayed. The new r41 commit qualified and staged,
|
||||||
|
but the original global image lookup was rejected during preflight. The
|
||||||
|
[scoped discovery correction](R41_BASE_DISCOVERY.md) follows CMS image ancestry,
|
||||||
|
with a bounded Node-only cache fallback and safe public error codes. After
|
||||||
|
runner promotion the controller may resume staged r41 with a fresh plan;
|
||||||
|
no bootstrap or failed-release replay is needed.
|
||||||
|
The scoped runner was installed; its preflight reported no matching base.
|
||||||
|
The [Compose-label correction](R41_COMPOSE_LABELS.md) accounts for the three
|
||||||
|
labels added by Compose, reproduces them during build, and retains exact
|
||||||
|
post-build configuration comparison. That runner was installed; all five local
|
||||||
|
Node candidates still failed the filesystem-prefix check. The
|
||||||
|
[registered base-acquisition policy](R41_NODE_BASE_ACQUISITION.md) can restore
|
||||||
|
one pinned public Node base only after exact preflight ancestry/config proof.
|
||||||
|
Deployment is pending promotion of that policy and actual NAS acceptance.
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
# 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
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
# 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)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#!/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)))
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#!/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}))
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#!/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}))
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"docker-compose.cms-ci.yml": "9c6b6bf2a9da2f7d5097b8d110882da1587b4d49018aba5ccf258a0218b351c2",
|
||||||
|
"runner.yaml": "94d8e4d8345b2b5bc7c8923bff7c31ff59083ec7115d633af10152b93bcd9da6"
|
||||||
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
# 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
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""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']}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
"""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")]
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""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
@@ -0,0 +1,211 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"Dockerfile": "ccb783bd76b1588cbe0157bd317f6da06888d79f8a199fd0c5515000948acd42",
|
||||||
|
"infra/docker-compose.yml": "abb3a9d4e4e2ce15eb2ca52b335289dcd00808d85c78da6d1bc583a8b3517f48",
|
||||||
|
"infra/reverse-proxy/Caddyfile": "4d30188eb1f11b52a0eaf2d9476e0b0adda93a63e66938e8028cc11de4c2038f",
|
||||||
|
"package-lock.json": "aca65991c748c6e39b6cbc50405ab5a2bc7bb0d5d1b56a5a4c68bce5f645e47c",
|
||||||
|
"package.json": "40ee5bc4cf6b634612efa1fc293f6ab1955ee4520701a5dee7c8990fb5ad5fa2"
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
"""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
@@ -0,0 +1,41 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
# 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
|
||||||
@@ -0,0 +1,555 @@
|
|||||||
|
# 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)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
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_existing_device_domain_unchanged(self):
|
||||||
|
old=subprocess.check_output(['git','show','27c155276a703dd4fd39385011fc5e3f86afcae4:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True)
|
||||||
|
current=RUNNER.read_text()
|
||||||
|
def domain(source):return source[source.index('# Device Core outbound automatic deployment.'):source.index('# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY')]
|
||||||
|
self.assertEqual(domain(old),domain(current))
|
||||||
|
allowed={'allowed_payload_path','load_artifact','component_services','plan_artifact','apply_artifact','run_healthchecks','main'}
|
||||||
|
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)
|
||||||
|
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# Device Core: external B2 VPS foundation v1
|
||||||
|
|
||||||
|
Draft, 2026-09-30. Not installed. Canonical design recorded in DCPLATFORM-21.
|
||||||
|
|
||||||
|
This transition precedes the normal Device Core application release. It keeps
|
||||||
|
its image and existing infrastructure, adds one Core private bind mount and
|
||||||
|
`DEVICE_B2_SECRET_ROOT`, and executes one SHA-pinned additive SQL transaction.
|
||||||
|
Neither Manager nor PostgreSQL is recreated. No build, pull, port or network change.
|
||||||
|
|
||||||
|
The fixed artifact contains only:
|
||||||
|
|
||||||
|
- `docker-compose.device-b2-foundation.yml`
|
||||||
|
- `deployment/device-b2-foundation-v1.sql`
|
||||||
|
- `deployment/device-b2-foundation-v1.json`
|
||||||
|
|
||||||
|
It is built by Device Core's `infra/deploy-runner/build_device_b2_foundation.py`.
|
||||||
|
The source SQL SHA is `dc5608eccb8f628aab49390d245e6758505bb8a459a49705c375c3ca59b3e03b`.
|
||||||
|
The initial predecessor is accepted r14, source
|
||||||
|
`6ca6738bab22d0fdef714b90c68959363106ee5b`, archive SHA
|
||||||
|
`385c2fec8fce300cb80a93edfbcb0d537e34755b0ccc35294c0102b3c4a7f724`.
|
||||||
|
The accepted network-priority override remains part of effective Compose.
|
||||||
|
|
||||||
|
Preflight proves exact predecessor source and its applied archive, empty feature
|
||||||
|
schema, absent private directory, current healthy runtime and immutable effective
|
||||||
|
Compose delta. The local Core tag must equal its running image. Fresh root runner
|
||||||
|
promotion and plan/apply are still required; local tests do not prove NAS state.
|
||||||
|
|
||||||
|
Apply owns schema execution/receipt, private directory UID/GID1000 mode0700,
|
||||||
|
Core-only recreation using its existing image, health, exact before/after runtime
|
||||||
|
comparison with only the new mount/env removed, unchanged dependent containers,
|
||||||
|
existing Compose/source files and unrelated services. Schema acceptance compares
|
||||||
|
all ordered columns/types/nullability and constraint definitions to a fixed
|
||||||
|
contract. PostgreSQL18's separately catalogued NOT NULL constraints are omitted
|
||||||
|
from the constraint list because nullability is checked independently; NAS uses
|
||||||
|
PostgreSQL16. This is a scoped schema normalization, not runtime guard relaxation.
|
||||||
|
|
||||||
|
Rollback restores source and the original Core configuration with the same image.
|
||||||
|
It may remove only its verified, complete and empty new schema and empty key
|
||||||
|
directory. Any unexpected schema, inserted data or key is retained and triggers
|
||||||
|
reconciliation; it is never erased to make rollback appear successful.
|
||||||
|
|
||||||
|
Normal later `device-core-release` operations include the new Compose file only
|
||||||
|
when a complete matching canonical receipt and applied archive prove ownership.
|
||||||
|
They also validate the installed private directory, actual mount/environment,
|
||||||
|
and exact schema on preflight and acceptance. A SQL failure before Core recreation
|
||||||
|
does not mark runtime as changed or restart Core during rollback.
|
||||||
|
Existing Dockerfile/migration immutability remains unchanged.
|
||||||
|
|
||||||
|
Runner016 was installed (SHA256
|
||||||
|
`1cda852fec9e940cfbec835b27159f04e96b13e24b6bbcd3ef87dd1a91f306aa`),
|
||||||
|
but plan001 rejected the effective Compose comparison before mutation. Official
|
||||||
|
Compose2.20.1 reproduced that rejection on all five current NAS Compose files:
|
||||||
|
the sole mismatch was the new mount's `bind: {}` versus an expected explicit
|
||||||
|
`create_host_path: false`. Existing synthetic tests missed this serializer form.
|
||||||
|
The corrected transition is `device-b2-foundation-v1-20260930-002`;001 is rejected
|
||||||
|
by identity and must not be applied. SQL, source YAML, predecessor and runtime
|
||||||
|
scope are unchanged.
|
||||||
|
|
||||||
|
Runner017 normalizes only omitted/false `create_host_path` on this one new bind,
|
||||||
|
in private comparison copies, alongside the existing false `read_only` rule.
|
||||||
|
Actual config hashes remain untouched. True/null/non-boolean values, missing
|
||||||
|
bind objects, unknown bind options, duplicate mounts and unrelated changes fail.
|
||||||
|
See `fixtures/device-b2-foundation-compose220` for real parser output and exact
|
||||||
|
reproduction. Qualification with that fixture and with all five NAS files proves
|
||||||
|
the old failure and corrected exact comparison. This is local parser evidence,
|
||||||
|
not proof of NAS apply or runtime acceptance.
|
||||||
|
|
||||||
|
## Foundation002 failure and exact reconciliation
|
||||||
|
|
||||||
|
Runner017 was installed and plan002 passed. Apply002 created the schema and
|
||||||
|
recreated Core, then failed `Device Core predecessor service is not healthy`.
|
||||||
|
Automatic rollback recreated Core again; its acceptance also failed. Canonical
|
||||||
|
failed ledger80 records `started_apply=true`, `rollback_status=failed:DeployError`
|
||||||
|
at `2026-09-30T13:45:49+00:00`. Incident archive SHA is
|
||||||
|
`da1c97fb0fd2ed9f50acf198c0492b27a5d7273009c0a85b9231fd8c60a70222`;
|
||||||
|
backup is `device-b2-foundation-device-b2-foundation-v1-20260930-002-20260930-164433`.
|
||||||
|
The archive, journal and seven backup-file digests are pinned in the runner.
|
||||||
|
|
||||||
|
The acceptance order was wrong: the strict healthy snapshot ran before the
|
||||||
|
existing bounded readiness/HTTP checks. The tests now exercise the actual
|
||||||
|
readiness loop through `starting` to `healthy` for both apply and rollback.
|
||||||
|
Both cases fail on017 and pass on018. Persistently unhealthy containers still
|
||||||
|
fail after the existing grace window; image/config/dependency guards are intact.
|
||||||
|
Historical failed-generation health states were not saved, so `starting` is a
|
||||||
|
reproduced defect, not a retroactively observed Docker status for this incident.
|
||||||
|
|
||||||
|
Read-only SMB observation found all three foundation files and its vault absent.
|
||||||
|
Public Manager health returned200/ok. These facts do not prove restored database
|
||||||
|
and runtime. No second application attempt is allowed until exact reconciliation.
|
||||||
|
|
||||||
|
`device-b2-foundation-reconciliation` is a separate metadata-only component.
|
||||||
|
Identity: `device-b2-foundation-reconciliation-v1-20260930-001`.
|
||||||
|
Its sole payload is `deployment/device-b2-foundation-reconciliation-v1.json`;
|
||||||
|
builder: `infra/deploy-runner/build_device_b2_reconciliation.py`.
|
||||||
|
Root is `/volume1/docker/nodedc-device-plane`, with no build or selected services.
|
||||||
|
Plan and apply independently prove:
|
||||||
|
|
||||||
|
- exact failed row/archive and immutable before/schema/backup partition evidence;
|
||||||
|
- accepted r14 baseline and no different unresolved foundation transition;
|
||||||
|
- no foundation files, private directory, or any of the three new schema objects;
|
||||||
|
- readiness, original Core image/config, unchanged other containers, Compose
|
||||||
|
files and application source.
|
||||||
|
|
||||||
|
Apply writes only the descriptor and canonical backup/journal/archive, then
|
||||||
|
repeats the proof before success. Its rollback removes only that new descriptor;
|
||||||
|
neither path issues runtime mutations or DDL. Only a complete matching receipt
|
||||||
|
and applied archive can acknowledge this one failed002 record. The original
|
||||||
|
failed journal/archive/backup remain immutable. A marker alone, altered history,
|
||||||
|
another failure, remaining schema/data/keys or runtime drift blocks acceptance.
|
||||||
|
Ordinary app releases also check this barrier even if no foundation overlay is
|
||||||
|
present. No generic health/fingerprint or unrelated registry rules are weakened.
|
||||||
|
|
||||||
|
After reconciliation, a fresh foundation003 plan/apply may add the original
|
||||||
|
unchanged YAML and SQL.003 is a new immutable identity;001/002 cannot be replayed.
|
||||||
|
Preparation of018 or a local test is not production reconciliation acceptance.
|
||||||
|
|
||||||
|
Local validation: foundation boundary/negative tests, deterministic artifact,
|
||||||
|
real archive through runner loader, existing release/network-priority/autodeploy
|
||||||
|
and Device Plane registry regression. SQL was also executed after all17 existing
|
||||||
|
migrations in temporary PGlite PostgreSQL WASM, with cross-company foreign-key
|
||||||
|
and contour uniqueness checks. This is SQL validation, not NAS runtime acceptance.
|
||||||
|
The actual Device Core connect/link SQL also passed against that database.
|
||||||
@@ -0,0 +1,933 @@
|
|||||||
|
# NODE.DC deploy runner
|
||||||
|
|
||||||
|
This directory stores the versioned source for the Synology canonical deploy runner.
|
||||||
|
|
||||||
|
Live runner:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/usr/local/sbin/nodedc-deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
Synology staging candidate:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/volume1/docker/nodedc-deploy/runner-install/nodedc-deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
The runner accepts data-only app-overlay artifacts from:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/volume1/docker/nodedc-deploy/inbox
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dedicated Device Edge runner
|
||||||
|
|
||||||
|
The Debian Device Edge is a separate root-owned deployment domain. It does not
|
||||||
|
use the Synology runner, inbox, state or backup tree. Its live runner and fixed
|
||||||
|
roots are:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/usr/local/sbin/nodedc-edge-deploy
|
||||||
|
/home/ndcsudo/nodedc-device-edge/deploy/inbox
|
||||||
|
/home/ndcsudo/nodedc-device-edge/source
|
||||||
|
/var/lib/nodedc-edge-deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
`nodedc-edge-deploy` accepts only `component=device-edge`, validates an exact
|
||||||
|
five-entry payload and can build/recreate only `device-edge-relay`. The existing
|
||||||
|
`device-edge-backhaul` and `tailnet` containers are identity-snapshotted before
|
||||||
|
the transition and must remain byte-for-byte runtime-equivalent through apply
|
||||||
|
or automatic rollback. It has no registry entry in the Synology runner.
|
||||||
|
|
||||||
|
The first ingress transition uses a Docker IPvlan L2 address on the Mini's
|
||||||
|
single Ethernet parent. It publishes no Docker host port and preserves the
|
||||||
|
Amnezia host full tunnel; only the relay container receives a LAN-routable
|
||||||
|
address. The fixed IPv4 is a runner/Compose/descriptor constant:
|
||||||
|
`192.168.71.253`. Router evidence on 2026-08-04 proves the Deco DHCP pool is
|
||||||
|
`192.168.68.50` through `192.168.71.250`, so the address is explicitly outside
|
||||||
|
the pool. Router port-forwarding/firewall remains a separate manual gate.
|
||||||
|
|
||||||
|
Build and test the transition source:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python3 infra/deploy-runner/test_device_edge_ingress_artifact.py
|
||||||
|
npm test --prefix device-plane
|
||||||
|
```
|
||||||
|
|
||||||
|
After the fixed address is approved, build the production artifact with a fresh
|
||||||
|
transition id, stage it into the Edge inbox, then use only the canonical pair:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo /usr/local/sbin/nodedc-edge-deploy plan \
|
||||||
|
/home/ndcsudo/nodedc-device-edge/deploy/inbox/<artifact>.tgz
|
||||||
|
sudo /usr/local/sbin/nodedc-edge-deploy apply \
|
||||||
|
/home/ndcsudo/nodedc-device-edge/deploy/inbox/<artifact>.tgz
|
||||||
|
```
|
||||||
|
|
||||||
|
The apply acceptance checks the exact IPvlan parent/subnet/gateway/address,
|
||||||
|
absence of host port publication, internal relay health, private backhaul
|
||||||
|
reachability, preserved VPN routes and unchanged backhaul/tailnet container
|
||||||
|
identity. Gelios and Device Plane command transport are outside this domain.
|
||||||
|
|
||||||
|
Supported components in this source:
|
||||||
|
|
||||||
|
- `engine`
|
||||||
|
- `launcher`
|
||||||
|
- `platform`
|
||||||
|
- `tasker`
|
||||||
|
- `ops-agents`
|
||||||
|
- `bim-viewer`
|
||||||
|
- `n8n-private-extension`
|
||||||
|
- `module-foundry`
|
||||||
|
- `device-plane`
|
||||||
|
- `gitea`
|
||||||
|
- `proxy-contur`
|
||||||
|
- `dc-amd-proxy`
|
||||||
|
|
||||||
|
## Fresh Gitea installation
|
||||||
|
|
||||||
|
`gitea` is a one-time, fresh-install-only component. Its artifact contains
|
||||||
|
only the reviewed Compose file and strict deployment descriptor; it contains
|
||||||
|
no database, repository, user, token, key, hook, runtime data or secret. Build
|
||||||
|
the deterministic artifact locally with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-gitea-fresh-install-artifact.mjs \
|
||||||
|
gitea-fresh-install-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
The runtime is fixed to Gitea `1.27.1-rootless` by exact digest and
|
||||||
|
`linux/amd64`. The runner never pulls it: the exact image must first be loaded
|
||||||
|
through a separately reviewed trusted image-acquisition step. Compose is
|
||||||
|
invoked with `--pull never --no-deps`, uses `network_mode: none`, publishes no
|
||||||
|
ports, and serves only the host-mounted Unix socket
|
||||||
|
`/volume1/docker/nodedc-gitea/socket/gitea.sock`. It exposes no SSH port, uses
|
||||||
|
fresh SQLite, enables no LFS, and mounts two runner-generated secrets by URI.
|
||||||
|
Registration and password Basic auth are disabled, while MFA is enforced;
|
||||||
|
hooks, webhooks, migrations, packages, Actions, OAuth2/OpenID, federation and
|
||||||
|
update checks are disabled. HTTP Git with PAT remains the intended trusted
|
||||||
|
client path; PAT clone/push acceptance belongs to the later reviewed
|
||||||
|
user/repository restoration transition, not this empty installation. LFS may
|
||||||
|
only be enabled by that later transition after its secret and restart behavior
|
||||||
|
has been accepted against the pinned runtime.
|
||||||
|
|
||||||
|
Plan and apply fail closed unless all live prerequisites are already true:
|
||||||
|
|
||||||
|
- `/volume1/docker/nodedc-gitea`, the `nodedc-gitea` project, and any stale
|
||||||
|
`nodedc-gitea_internal` network are absent; TCP/4022 is closed and Docker
|
||||||
|
publishes neither TCP/3000 nor TCP/4022;
|
||||||
|
- Docker Server is exactly 24.0.2, Compose is at least 2.20.1, and the exact
|
||||||
|
pinned image ID and RepoDigest are local for linux/amd64 with image user
|
||||||
|
`1000:1000`;
|
||||||
|
- the separate root-owned Nginx bridge
|
||||||
|
`/usr/local/etc/nginx/conf.d/http.nodedc-gitea-uds.conf` matches its exact
|
||||||
|
reviewed bytes, owner/mode and SHA-256; Nginx 1.23.1 configuration validates,
|
||||||
|
and only its root/uid-1023 processes own `127.0.0.1:3000`. The bridge proxies
|
||||||
|
to the Unix socket, preserves Host/X-Real-IP/XFF/XFP, rate-limits login and
|
||||||
|
bounds concurrent requests without limiting Git request bodies;
|
||||||
|
- DSM reverse-proxy UUID `5bc46027-0307-4261-af7e-4f94a3c508c9` persistently
|
||||||
|
and in generated nginx config routes `git.dcserve.ru:443` to
|
||||||
|
`127.0.0.1:3000`; the generated vhost must also retain its exact host guard
|
||||||
|
and canonical Host/X-Real-IP/XFF/XFP forwarding directives, so the UDS
|
||||||
|
bridge never trusts a client-supplied `X-Real-IP`;
|
||||||
|
- the emergency broad INPUT DROP for TCP/3000 has been removed, while the
|
||||||
|
legacy `172.22.0.222:3000` OUTPUT DROP and TCP/4022 INPUT DROP remain;
|
||||||
|
- any legacy container named `gitea` is stopped with restart policy `no`.
|
||||||
|
|
||||||
|
Changing DSM reverse proxy/firewall rules, acquiring evidence from the old
|
||||||
|
root, restoring trusted users/repositories, and loading the pinned image are
|
||||||
|
separate reviewed transitions. This component never reads or mounts
|
||||||
|
`/volume1/docker/gitea` and never starts the legacy container. Failed apply
|
||||||
|
stops/removes only the `nodedc-gitea` candidate, proves that it is absent, and
|
||||||
|
quarantines the complete newly created root (including data/config/socket/secrets) for
|
||||||
|
evidence, and restores the absent source/root state without deleting runtime
|
||||||
|
evidence. If candidate absence cannot be proven, rollback preserves the root in
|
||||||
|
place and records reconciliation-required instead of disconnecting live bind
|
||||||
|
mounts.
|
||||||
|
|
||||||
|
Run the policy suite before publishing:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python3 infra/deploy-runner/test_gitea_fresh_install.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gitea incident salvage (clean-state recovery)
|
||||||
|
|
||||||
|
The additive `gitea-incident-salvage` slice is the reviewed recovery design for
|
||||||
|
incident `gitea-20260814`. It does not upgrade or mount the compromised state.
|
||||||
|
The candidate starts with a new SQLite database, new config, new runtime
|
||||||
|
secrets, new email addresses and new password hashes. The exact v2 decision
|
||||||
|
bundle is embedded as inert, digest-bound data:
|
||||||
|
|
||||||
|
- 2 new active identities (`dctouch`, admin; `SILVER`, non-admin), each with a
|
||||||
|
new root-contained one-time password and mandatory password change;
|
||||||
|
- 8 new locked identities with random discarded passwords, inactive,
|
||||||
|
restricted and prohibited from login;
|
||||||
|
- 45 exact repositories: 32 private `dctouch` repositories and 13 public
|
||||||
|
`SILVER` repositories. The other 962 legacy users and 2013 legacy repository
|
||||||
|
rows are not imported into the clean database.
|
||||||
|
|
||||||
|
The successor v3 descriptor embeds the owner-confirmed, canonical
|
||||||
|
`confirmed-disposition-v1.json` and the additive
|
||||||
|
`confirmed-closure-disposition-v1.json`. Both are bound to the exact snapshot,
|
||||||
|
database, identity decision, reference manifest, unsupported-state report,
|
||||||
|
schema catalog and semantic-topics hashes. The original disposition's 105
|
||||||
|
reference decisions are explicit rows, not namespace wildcards: 85 normal
|
||||||
|
heads, 4 tags and 4 wiki heads are eligible for later live reconstruction; the
|
||||||
|
exact 5 pull refs and 7 remote refs are sealed archive-only evidence and can
|
||||||
|
never be auto-promoted. The closure disposition authorizes only bounded
|
||||||
|
plan-time inventory and records the target policy for access, collaboration,
|
||||||
|
issue/PR metadata, attachments, releases, labels, projects, units, Packages
|
||||||
|
and Actions. Observed hashes do not become activation authority, and the new
|
||||||
|
closure-report digest is deliberately unpinned until separate review.
|
||||||
|
|
||||||
|
Build the deterministic review artifact locally with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-gitea-incident-salvage-artifact.mjs \
|
||||||
|
gitea-incident-salvage-subrelation-closure-20260814-006
|
||||||
|
```
|
||||||
|
|
||||||
|
The original v1 descriptor and `...salvage-20260814-001.tgz` remain immutable.
|
||||||
|
The exact `...salvage-disposition-20260814-002.tgz` also remains immutable and
|
||||||
|
must not be retried: its plan failed safely because it assumed every nonempty
|
||||||
|
`repository.topics` TEXT value was a JSON array. A bounded immutable-database
|
||||||
|
classification proved all 45 kept rows are instead exact four-byte canonical
|
||||||
|
JSON `null`, Gitea's semantic empty representation. The `...topics-...-003`
|
||||||
|
artifact is the forward fix with a new patch id and digest.
|
||||||
|
That exact `...topics-...-003` artifact is now also an immutable predecessor.
|
||||||
|
The local pre-audit `...closure-...-004` draft must not be staged: review found
|
||||||
|
orphan-join and nullable-Actions gaps. The local
|
||||||
|
`...closure-reviewed-...-005` artifact is also stale and must not be staged:
|
||||||
|
its primary closure was fail-closed, but it retained a broad polymorphic-
|
||||||
|
subrelation blocker. The additive `...subrelation-closure-...-006` successor
|
||||||
|
closes the concrete comment/history/merger relations in the pinned snapshot
|
||||||
|
schema and is the only artifact produced by the current builder.
|
||||||
|
The successor builder refuses to overwrite an existing artifact basename and
|
||||||
|
publishes from an exclusively created same-directory temporary file using an
|
||||||
|
atomic no-clobber hard link. A failed build removes only its private temporary
|
||||||
|
file. The disposition is sorted, compact ASCII JSON with one terminal LF.
|
||||||
|
|
||||||
|
The runtime pin is
|
||||||
|
`docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49a…3abd2c`, with exact
|
||||||
|
linux/amd64 OCI image ID `sha256:272085a8…bc5c4c6`. It runs as `1000:1000`,
|
||||||
|
uses the direct Gitea binary, `network_mode: none`, no Docker ports, no SSH and
|
||||||
|
no LFS. Candidate restart policy is `no`. The existing reviewed Nginx bridge
|
||||||
|
cannot reach the candidate while the socket parent is mode `0700`; publication
|
||||||
|
is an explicit post-acceptance change to `0750`, followed by public TLS and
|
||||||
|
smart-HTTP checks. Only after those checks may restart policy become
|
||||||
|
`unless-stopped`. The transition never changes or enforces two-factor
|
||||||
|
authentication.
|
||||||
|
|
||||||
|
The snapshot boundary is exact: UUID
|
||||||
|
`f5a3fe3a-93ea-bb4d-847f-6221a6bcbc9f`, immutable SQLite SHA-256
|
||||||
|
`8db9e74a…1a13052`, and the 972/2058 decisions must recompute from the database
|
||||||
|
row by row. The runner enumerates only each v2 `repo_relative_path` and
|
||||||
|
`wiki_relative_path`. It rejects symlinks, special files, hard links, NOCOW,
|
||||||
|
alternates, shallow/replace/grafts/worktrees, promisor state, unknown object
|
||||||
|
material and incomplete pack/index pairs. One preloaded mount inventory also
|
||||||
|
guards the `objects` and `refs` roots plus every traversed directory and file:
|
||||||
|
all must remain on the trusted snapshot device, outside nested mountpoints and,
|
||||||
|
for directories, outside nested Btrfs subvolumes. Traversal errors fail closed.
|
||||||
|
Forbidden-path probes (`objects/info/alternates`, grafts, replace refs and the
|
||||||
|
other listed sentinels) lstat each path component without following links and
|
||||||
|
validate every ancestor before probing its child; a symlink or mount boundary
|
||||||
|
therefore stops the plan before any lookup can escape the snapshot tree.
|
||||||
|
|
||||||
|
Only three exact derived-file classes observed in the bounded 45-repository
|
||||||
|
inventory are excluded: dumb-HTTP `objects/info/packs`,
|
||||||
|
`objects/pack/pack-<oid>.bitmap` with its exact complete pack/index pair, and
|
||||||
|
monolithic `objects/info/commit-graph`. Each must be a bounded regular,
|
||||||
|
single-link, non-NOCOW file. The reference manifest records its exact path,
|
||||||
|
class and byte size, but the runner neither reads nor copies the excluded
|
||||||
|
bytes. Unobserved `.rev`, MIDX and split commit-graph layouts stay fail-closed;
|
||||||
|
`.promisor`, `.mtimes`, `.keep`, unknown and temporary lookalikes are not
|
||||||
|
classified as disposable accelerators.
|
||||||
|
|
||||||
|
The same inventory found receive-pack quarantine directories matching only an
|
||||||
|
exact direct child `objects/tmp_objdir-incoming-[A-Za-z0-9]{6}`. A match must
|
||||||
|
retain the reviewed uid/gid `1000:1000`, mode `0755`, single-link and non-NOCOW
|
||||||
|
directory metadata. Its exact path and lstat fields are recorded, then the
|
||||||
|
subtree is pruned without reading, hashing, copying or reflinking contents; the
|
||||||
|
sealed read-only incident snapshot retains the forensic copy. Any name,
|
||||||
|
metadata, mount or subvolume drift remains a hard stop. A reviewed reference/OID
|
||||||
|
manifest is required; raw HEAD/refs files are never copied. The intended data
|
||||||
|
path is same-filesystem per-file `--reflink=always`, with no byte-copy fallback
|
||||||
|
and a bounded exclusive-allocation gate.
|
||||||
|
|
||||||
|
This slice is intentionally **NO-GO for apply** at the current review point.
|
||||||
|
`plan` inventories and prints the exact ref-manifest digest, byte length and
|
||||||
|
canonical compact JSON. The JSON is the reviewable, hash-bound reference/OID
|
||||||
|
artifact: it contains approved repository identities, ref names/OIDs, object
|
||||||
|
totals and stat-bound derived/quarantine exclusions, but no Git object bytes,
|
||||||
|
hooks or config. The same plan prints the canonical unsupported-state report
|
||||||
|
and a separate incident-closure report, each with its SHA-256, byte length and
|
||||||
|
compact ASCII JSON. The closure report is evidence only: its disposition keeps
|
||||||
|
`expectedSha256` and `expectedBytes` null and retains an explicit review-pin
|
||||||
|
blocker.
|
||||||
|
|
||||||
|
The reviewed plan evidence bound by the disposition is reference manifest
|
||||||
|
`9cddaf0e…a311` (36,010 bytes), unsupported-state report
|
||||||
|
`4b2cecf8…106ac` (119,468 bytes), and schema catalog
|
||||||
|
`b5e3b677…b6db`. The report has exact 45 repository rows with empty
|
||||||
|
`schema_missing`, `schema_mismatch`, and `anomalies` arrays. These facts close
|
||||||
|
only the owner's material-state decision; fsck/reachability, physical blob
|
||||||
|
inventory, sanitized archive creation and candidate acceptance remain separate
|
||||||
|
verifiers.
|
||||||
|
|
||||||
|
The unsupported-state report has one deterministic row for every one of the
|
||||||
|
45 kept repository IDs, including explicit zeroes. It separates direct
|
||||||
|
repository-relation counts, directional base/head PR counts, repo-unit type
|
||||||
|
counts, text-metadata presence booleans and denormalized numeric hints; it does
|
||||||
|
not add overlapping relations into a misleading grand total. LFS rows are
|
||||||
|
reported per repository with validated logical byte sums and distinct-OID
|
||||||
|
aggregates, including size conflicts and sharing with non-kept repositories.
|
||||||
|
Every association sharing a kept OID must also have an integer repository ID
|
||||||
|
that resolves to the exact snapshot `repository` table; invalid and orphan
|
||||||
|
owners make shared/unique byte aggregates unavailable and add a data-anomaly
|
||||||
|
blocker.
|
||||||
|
Attachments are reported per repository with validated logical byte sums and
|
||||||
|
explicit, overlapping issue/comment/release/unlinked link splits. Neither
|
||||||
|
category claims that a physical blob exists; no title, body, note, comment,
|
||||||
|
config, URL, token, key, secret, hash payload or blob content is selected or
|
||||||
|
exported.
|
||||||
|
|
||||||
|
The report also embeds the exact `PRAGMA table_xinfo` catalog and explicit
|
||||||
|
label-to-table-to-repository-column map for a code-owned allowlist of relevant
|
||||||
|
tables. `sqlite_master` must prove an ordinary, non-virtual table before any
|
||||||
|
row query; SQLite 3.37+ adds `PRAGMA table_list` ordinary-main-table proof. On
|
||||||
|
an older compatible SQLite, the weaker object-kind capability is recorded and
|
||||||
|
adds a coverage blocker. `query_only=ON` and `trusted_schema=OFF` are read back
|
||||||
|
before the snapshot connection is accepted. Only column identifiers and
|
||||||
|
structural metadata are exported, never DDL, defaults or row values. The v3
|
||||||
|
closure inventory follows code-owned, schema-attested primary joins for the
|
||||||
|
issue/PR dependency tables (comments, assignees, content histories, labels, issue
|
||||||
|
users/watches, reactions, reviews/state, dependencies, notifications,
|
||||||
|
stopwatches, tracked time and auto-merge), plus projects/boards, releases,
|
||||||
|
attachments, Packages and Actions. It emits only IDs required to prove joins,
|
||||||
|
actor classes, counts, declared sizes and SQLite byte lengths; it never selects
|
||||||
|
or prints text bodies, names, URLs, package metadata, workflow payloads,
|
||||||
|
credentials, tokens, secrets or logs. Package and Actions target features stay
|
||||||
|
disabled and no legacy row is importable. The successor additionally closes
|
||||||
|
every concrete FK-like comment field in the pinned schema (labels, projects,
|
||||||
|
milestones, tracked time, assignees, dependency, review and cross-reference),
|
||||||
|
content-history-to-comment, review-team and pull-merger provenance. Target
|
||||||
|
repository and local actor IDs are classified through the exact 2058/972
|
||||||
|
decisions. Migrated external-author IDs are never treated as local users and
|
||||||
|
are represented only by presence counts and author-name byte lengths. A
|
||||||
|
nonzero comment-assignee or review-reviewer team must resolve to an exact team
|
||||||
|
and organization; because no organization/team allowlist exists, its row,
|
||||||
|
team and organization IDs enter a sealed HOLD inventory and add the narrowly
|
||||||
|
scoped `issue-pr-team-mapping-hold` blocker. Orphans, conflicting user/team
|
||||||
|
identities, invalid cross-reference pairs and schema/type drift fail closed.
|
||||||
|
The report is still not a physical-file or sanitized-archive verifier, so
|
||||||
|
those separate blockers remain explicit.
|
||||||
|
The schema-catalog digest is recorded as observed evidence but deliberately
|
||||||
|
remains unpinned as reviewed activation authority. Schema absence/type drift,
|
||||||
|
invalid numeric/OID state or aggregate overflow is a hard error. `apply` fails
|
||||||
|
before creating `/volume1/docker/nodedc-gitea` until all of the following are
|
||||||
|
registered:
|
||||||
|
|
||||||
|
- root-owned Btrfs proof that the named snapshot UUID is read-only;
|
||||||
|
- exact stopped/restart-`no` legacy container image ID, image ref and sole
|
||||||
|
`/volume1/docker/gitea:/data` bind inspect;
|
||||||
|
- a separately verified exact reference/OID manifest digest, fsck,
|
||||||
|
reachability and selected-object reconstruction;
|
||||||
|
- immutable sanitized archives for issues, PRs, comments, releases, labels,
|
||||||
|
projects and repository descriptions, with no legacy row import;
|
||||||
|
- physical attachment inventory and reachable LFS pointer/OID/size/SHA proof;
|
||||||
|
- kept-user mapping before any collaboration recreation; and
|
||||||
|
- package/Actions schema plus physical zero closure and target unit-policy
|
||||||
|
acceptance.
|
||||||
|
|
||||||
|
All 25 direct repository relations have explicit dispositions, including the
|
||||||
|
15 exact zero-and-drop categories. Pull base/head counts remain directional
|
||||||
|
views of the same five PRs. All repository numeric hints are dropped and
|
||||||
|
recomputed. Repo-unit types 1–10 are total: clean types 1–5 and 8 are recreated
|
||||||
|
once per repository; external wiki/tracker are forbidden; Packages (9) and
|
||||||
|
Actions (10) are absent in the target and remain globally disabled. Legacy
|
||||||
|
unit config is never imported. The topics verifier accepts exact JSON `null`
|
||||||
|
as semantic empty state, or a canonical JSON array of sorted unique lowercase
|
||||||
|
names matching `^[a-z0-9][-.a-z0-9]*$` with at most 35 UTF-8 bytes. SQL NULL,
|
||||||
|
whitespace/case variants, quoted `"null"`, objects, numbers, booleans and
|
||||||
|
noncanonical arrays fail closed. The current snapshot must prove exactly 45
|
||||||
|
serialized JSON nulls, zero serialized arrays, zero material topics and zero
|
||||||
|
`repo_topic` rows; target cache is rebuilt from relations.
|
||||||
|
|
||||||
|
The activation hook remains frozen until these blockers are closed and the
|
||||||
|
full clean-database recreation, reflink reconstruction, doctor/fsck,
|
||||||
|
credential-table zeroing, rollback and public acceptance path has its own
|
||||||
|
runtime smoke. The current reviewed source identities are:
|
||||||
|
|
||||||
|
- runner `nodedc-deploy` SHA-256
|
||||||
|
`c766985aa02fe911fa5a873717276f3503d9cecded448e41dc6945030dcbce9e`;
|
||||||
|
- deterministic builder SHA-256
|
||||||
|
`b92076583aeab854015a05deb9d942c8dfcf3ca475fd3d52115d402d6f61acca`;
|
||||||
|
- salvage policy test SHA-256
|
||||||
|
`99b96b6179286a78e7d53ee6a923fc092e3471a8cece382a472449d455ad212c`;
|
||||||
|
- fresh-install policy test SHA-256
|
||||||
|
`20653c640142c25e7d2ef712048acc7889c56e1d519e2d03b5cad4127e48947c`;
|
||||||
|
- confirmed disposition SHA-256
|
||||||
|
`0a066724bcf6e4933133db6cab6cc273393e3c262dd00dda0bbf9ceebd84f78c`;
|
||||||
|
- confirmed closure disposition SHA-256
|
||||||
|
`7ed66d9848268431a703fe24b22c41afbaa7c5ff48949604d6fc448d93e0d243`;
|
||||||
|
- successor v3 descriptor SHA-256
|
||||||
|
`9b98eb1a1640fd5569cf051a621837379b167eff4527313a43a0a851e7cc181a`;
|
||||||
|
- deterministic local review artifact
|
||||||
|
`nodedc-gitea-gitea-incident-salvage-subrelation-closure-20260814-006.tgz`
|
||||||
|
SHA-256
|
||||||
|
`d3e598cf892b1371912dcd9cef64caa991dd23613e48fe979d0f95d493c23d53`.
|
||||||
|
|
||||||
|
Only after that exact runner is separately reviewed, promoted to the
|
||||||
|
root-owned runner path and its installed SHA-256 is re-attested may the exact
|
||||||
|
artifact be staged into the canonical inbox for a canonical `plan` command.
|
||||||
|
Staging is evidence collection only; it grants no authority to run `apply`.
|
||||||
|
The legacy identity is now pinned to the observed ref `gitea/gitea:latest`
|
||||||
|
and immutable image ID
|
||||||
|
`sha256:bf95d9a45ce4fe38b027d051cdc4a4bc531513489fa6244af4074efbb1c376d6`.
|
||||||
|
The mutable tag is provenance only. Every plan re-inspects exact name
|
||||||
|
`/gitea`, stopped state, restart `no`, and the sole RW bind
|
||||||
|
`/volume1/docker/gitea:/data`; drift is a hard stop.
|
||||||
|
|
||||||
|
The successor plan must report these exact remaining blockers:
|
||||||
|
|
||||||
|
- `attachment-physical-verifier-pending`;
|
||||||
|
- `candidate-root-activation-hard-frozen`;
|
||||||
|
- `closure-report-review-pin-pending`;
|
||||||
|
- `collaboration-kept-user-mapping-verifier-pending`;
|
||||||
|
- `forensic-ref-archive-verifier-pending`;
|
||||||
|
- `issue-pr-metadata-sanitized-archive-verifier-pending`;
|
||||||
|
- `lfs-reachable-pointer-physical-verifier-pending`;
|
||||||
|
- `package-action-physical-closure-verifier-pending`;
|
||||||
|
- `reference-manifest-fsck-reachability-verifier-pending`;
|
||||||
|
- `repository-object-reconstruction-verifier-pending`;
|
||||||
|
- `target-unit-policy-acceptance-pending`;
|
||||||
|
- `unsupported-schema-catalog-verifier-pending`.
|
||||||
|
|
||||||
|
Any other blocker or identity drift is also a stop. `apply` remains prohibited
|
||||||
|
and hard-frozen before root creation until a subsequent reviewed runner
|
||||||
|
revision closes every blocker and implements and smoke-tests the complete
|
||||||
|
activation/rollback path. The successor files must be independently reviewed
|
||||||
|
before any runner promotion or inbox staging.
|
||||||
|
|
||||||
|
Run the bounded policy suite with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python3 infra/deploy-runner/test_gitea_incident_salvage.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
The frozen local cutoff passes 54 incident-salvage tests and 26 fresh-install
|
||||||
|
tests, plus Python compilation and `git diff --check`.
|
||||||
|
|
||||||
|
`n8n-private-extension` is a staging-only trust boundary for reviewed offline
|
||||||
|
n8n private-node releases. Its artifact may contain exactly one digest-bound
|
||||||
|
`n8n-nodes-ndc` release with `package.tgz`, `release.json` and
|
||||||
|
`rollback.json`. The runner validates the inner npm tarball, rejects lifecycle
|
||||||
|
scripts and runtime dependencies, refuses to overwrite an existing release,
|
||||||
|
and seals the installed release root-owned/read-only under:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/volume1/docker/nodedc-platform/n8n-private-extensions/releases/n8n-nodes-ndc/<version>-<sha256-prefix>
|
||||||
|
```
|
||||||
|
|
||||||
|
This component has no Compose file, service, container mutation or activation
|
||||||
|
side effect. In particular, staging does **not** make the node visible to n8n.
|
||||||
|
Activation remains an Engine-owned change: mount the reviewed immutable release
|
||||||
|
at `/home/node/.n8n/nodes/node_modules/n8n-nodes-ndc`, atomically switch between
|
||||||
|
verified releases, restart every n8n process, and accept only after MCP exposes
|
||||||
|
the package-qualified `n8n-nodes-ndc.*` schemas. The Platform runner cannot
|
||||||
|
cross that boundary and never runs `npm install` in a live container.
|
||||||
|
|
||||||
|
Build a verified offline release artifact:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-n8n-private-extension-artifact.mjs \
|
||||||
|
n8n-nodes-ndc-release-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
The builder is byte-reproducible and accepts exactly the three reviewed NDC
|
||||||
|
runtime types:
|
||||||
|
|
||||||
|
- `n8n-nodes-ndc.ndcDataProductPublish`
|
||||||
|
- `n8n-nodes-ndc.ndcDataProductRead`
|
||||||
|
- `n8n-nodes-ndc.ndcFoundryBinding`
|
||||||
|
|
||||||
|
Their three opaque capability credential schemas are
|
||||||
|
`ndcDataProductWriterApi`, `ndcDataProductReaderApi` and
|
||||||
|
`ndcFoundryBindingApi`. A node description containing `usableAsTool` is
|
||||||
|
rejected because n8n 2.3.2 would synthesize an additional `*Tool` runtime type
|
||||||
|
and violate the exact-three activation contract. Run the positive and negative
|
||||||
|
release-policy suite before publishing an artifact:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python3 infra/deploy-runner/test_n8n_private_extension.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Release/rollback manifests use schema v2. Before a first activation, the
|
||||||
|
Engine-owned activator must verify and record the current inactive state. That
|
||||||
|
`verified_inactive` state is an allowed rollback baseline when no previous
|
||||||
|
verified immutable release exists; later upgrades prefer the previous verified
|
||||||
|
release. Rollback never deletes or mutates a staged release.
|
||||||
|
|
||||||
|
The historical `0.1.0` release remains immutable and must not be overwritten.
|
||||||
|
Release `0.1.1-994756958861518e` is retained as rejected/inactive: its three
|
||||||
|
node descriptions used `usableAsTool`, so n8n 2.3.2 exposed six NDC runtime
|
||||||
|
types instead of the required three. It must not be activated, overwritten or
|
||||||
|
deleted.
|
||||||
|
|
||||||
|
The active predecessor is package version `0.1.4` at immutable release
|
||||||
|
`0.1.4-59dc9f7882721d6a`. Package `0.1.5` adds the provider-neutral complete
|
||||||
|
snapshot replace mode used by `map.zones.current.v2`; its Platform staging
|
||||||
|
remains inert until a separately reviewed Engine-owned transition selects the
|
||||||
|
exact digest and accepts the updated MCP node schema.
|
||||||
|
|
||||||
|
The paired Engine activation is built by
|
||||||
|
`build-engine-n8n-private-extension-artifact.mjs`. It deliberately does not
|
||||||
|
copy from or write generated files into the dirty Engine worktree, and it does
|
||||||
|
not build an image. A fresh transition id is mandatory and previously issued
|
||||||
|
ids are rejected:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-engine-n8n-private-extension-artifact.mjs 20260721-005
|
||||||
|
```
|
||||||
|
|
||||||
|
The builder emits a narrowly scoped Compose override plus a strict transition
|
||||||
|
descriptor. On apply, the runner validates the staged release again, verifies
|
||||||
|
that the running n8n container and the NAS-local `2.3.2` tag resolve to the
|
||||||
|
same immutable image ID, and extracts the package into the root-owned,
|
||||||
|
read-only Engine release tree:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/volume2/nodedc-demo/n8n-private-extensions/releases/n8n-nodes-ndc/0.1.5-3c8ae53f010d7c88/package
|
||||||
|
```
|
||||||
|
|
||||||
|
The override sets `N8N_USER_FOLDER=/home/node`, which is required because the
|
||||||
|
actual Engine service runs as root while the canonical community package path
|
||||||
|
is below `/home/node/.n8n`. The live runtime contract remains the successfully
|
||||||
|
deployed generation-003 contract and does not set `NODE_PATH`. Only the
|
||||||
|
runner's isolated `node -e` package-loader probe temporarily initializes the
|
||||||
|
dependency tree bundled inside the exact n8n base image; this reproduces n8n's
|
||||||
|
own loader without redefining the live Compose state. The override enables
|
||||||
|
loading but disables reinstall, mounts only the exact release read-only, and
|
||||||
|
uses both Compose `pull_policy: never` and `docker compose up --pull never`.
|
||||||
|
No registry access, lifecycle script, database `installed_packages` row or
|
||||||
|
custom-extension loader is involved.
|
||||||
|
|
||||||
|
The runner pins the exact Engine service topology observed in source and
|
||||||
|
rejects an added worker/webhook generation. Only the single actual `n8n`
|
||||||
|
service is force-recreated with `--no-deps`; the
|
||||||
|
Postgres service, `.n8n` data, encryption key and credentials remain intact.
|
||||||
|
The apply gate verifies readiness, the running image/version, sealed mount,
|
||||||
|
loader environment, package-loader node/credential sets, scoped loader logs,
|
||||||
|
restart stability and content-exact pinned Engine MCP catalogs. The runner pins
|
||||||
|
the complete 434/385 inactive baseline and a digest registry for every
|
||||||
|
reviewed 437/388 active release, so a same-count substitution of any built-in
|
||||||
|
or private schema is rejected. Upgrade `0.1.2 -> 0.1.3` is accepted only when
|
||||||
|
the verified live predecessor, descriptor, package mount and catalog all agree.
|
||||||
|
Any gate failure after
|
||||||
|
mutation automatically restores the pre-apply catalogs/descriptor and
|
||||||
|
force-recreates the previous verified runtime. Staged, sealed and failed
|
||||||
|
releases are retained. The paired rollback artifact returns `0.1.3` to the
|
||||||
|
verified immutable `0.1.2` release and its exact catalogs; it does not invent
|
||||||
|
an inactive baseline for an already-active upgrade.
|
||||||
|
|
||||||
|
Run both policy suites before publishing the Engine pair:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python3 infra/deploy-runner/test_n8n_private_extension.py
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python3 infra/deploy-runner/test_engine_n8n_private_extension.py
|
||||||
|
```
|
||||||
|
|
||||||
|
The source-less Engine MCP control-plane update is a separate exact slice:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-engine-mcp-control-plane-artifact.mjs 20260717-001
|
||||||
|
```
|
||||||
|
|
||||||
|
Its six-entry registry contains only the Engine Agent gateway, verified graph
|
||||||
|
patch route, Codex installer source/package and the active node-intelligence
|
||||||
|
descriptor with the new gateway digest. It force-recreates only the existing
|
||||||
|
`nodedc-backend`. The node-intelligence image/service, n8n, L1, credentials,
|
||||||
|
databases and volumes are outside the slice. The runner proves the installed
|
||||||
|
predecessor digests, exact installer archive/source equality, bounded change
|
||||||
|
session policy, no-effect/post-write graph barriers, active immutable backend
|
||||||
|
runtime and descriptor equality. The ordinary overlay backup is the automatic
|
||||||
|
rollback source; rollback restores the predecessor gateway and descriptor
|
||||||
|
together before recreating the same backend service.
|
||||||
|
|
||||||
|
The successor autonomy/provider-v5 slice keeps MCP authority explicit without
|
||||||
|
turning every write into a second permission dialogue. MCP tool availability is
|
||||||
|
the capability boundary, while the user's current objective is the intent
|
||||||
|
boundary; Engine L2 may act autonomously only inside their intersection. A
|
||||||
|
graph `plan` remains a mandatory machine barrier whose target, diff, revision
|
||||||
|
and blockers are inspected by the agent. It is not a repeated approval prompt
|
||||||
|
after an implementation objective is already authorized. Retries must add new
|
||||||
|
evidence or change the attempted variant, and three identical failures without
|
||||||
|
new evidence or state change are a critical stop. The slice also advances the
|
||||||
|
installer to `0.1.6` and adds `gelios.provider.v5 ->
|
||||||
|
fleet.positions.current.v4` beside the immutable v4/v3 rollback line:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-engine-mcp-autonomy-provider-v5-artifact.mjs \
|
||||||
|
20260720-004
|
||||||
|
```
|
||||||
|
|
||||||
|
Its seven-entry allowlist recreates only `nodedc-backend`; n8n, L1, databases,
|
||||||
|
credential values and the node-intelligence image remain outside the change.
|
||||||
|
The runner accepts both the exact target and the exact predecessor after an
|
||||||
|
automatic rollback, and rejects every mixed state.
|
||||||
|
|
||||||
|
For `platform` artifacts, the allowlist includes the versioned Ontology Core,
|
||||||
|
the frozen legacy Gelios compatibility service, and the provider-neutral
|
||||||
|
External Data Plane sources. The Gelios service remains reproducible only to
|
||||||
|
protect its existing database/workflow; it is not a template for a provider
|
||||||
|
integration. An External Data Plane artifact builds only its image and
|
||||||
|
force-recreates only `external-data-plane`; the already healthy
|
||||||
|
`external-data-plane-postgres` container and its Timescale volume are an
|
||||||
|
independent deploy prerequisite and are never selected by an EDP application
|
||||||
|
artifact. The reviewed Compose source pins the Timescale image, named volume
|
||||||
|
and target, internal database-only network, absence of database host ports,
|
||||||
|
healthy dependency, localhost-only EDP bind and the three read-only
|
||||||
|
provisioner/trust mounts in the reviewed Compose source. The runner does not
|
||||||
|
reinterpret version-dependent `docker compose config` JSON as a second deploy
|
||||||
|
schema. Its canonical enforcement remains the artifact/path allowlist plus
|
||||||
|
hard-coded build command, selected service set, runtime-secret preparation and
|
||||||
|
health acceptance. Post-apply acceptance also requires
|
||||||
|
`database=ready`; the managed Foundry slice additionally requires
|
||||||
|
`foundryReaderBindingProvisioning=digest+server-resolved-source`. A first-rollout failure removes only the candidate EDP
|
||||||
|
container without volumes and restores the source overlay. It never contains a
|
||||||
|
provider credential, provider endpoint,
|
||||||
|
collection schedule or command
|
||||||
|
transport. Its contract payload is an exact provider-neutral runtime subset;
|
||||||
|
`providers/*`, mappings, fixtures and tests are excluded and do not trigger an
|
||||||
|
EDP rebuild. Database credentials remain root-owned live `.env.synology`
|
||||||
|
configuration and must not reuse `NODEDC_INTERNAL_ACCESS_TOKEN`.
|
||||||
|
|
||||||
|
On the first relevant Platform apply, the root-owned runner creates
|
||||||
|
`/volume1/docker/nodedc-platform/secrets/external-data-plane-provisioner/token`
|
||||||
|
atomically in a dedicated UID/GID `11006` directory (directory `0500`, token
|
||||||
|
`0400`). It is never an `.env` value or an artifact member and is mounted
|
||||||
|
read-only only into External Data Plane.
|
||||||
|
|
||||||
|
Manual one-time binding issuance and digest-only managed writer ensure are
|
||||||
|
independently disabled by default. The target control-plane operation generates
|
||||||
|
and stores the capability inside native NDC L2 Credentials and sends only its
|
||||||
|
digest to EDP; users and MCP consumers receive only an opaque compatible
|
||||||
|
reference/status. The runner-owned bearer above authenticates only legacy
|
||||||
|
plaintext issuance and is intentionally rejected by managed ensure/revoke.
|
||||||
|
Managed requests use a deployment Ed25519 Engine service key; EDP mounts only
|
||||||
|
the public-key trust directory read-only. On every reviewed Engine apply and on
|
||||||
|
an EDP runtime apply, this runner creates or validates one matching Ed25519 pair:
|
||||||
|
the Engine-only private key is `root:root 0400`, while the EDP trust copy is
|
||||||
|
`root:11006 0440`. Public-only crash state, key mismatch, a non-Ed25519 key,
|
||||||
|
symlinks and permissive modes fail closed. `plan` discloses both paths without
|
||||||
|
printing key material. The private key must not be broadened into an L2 graph,
|
||||||
|
MCP surface, artifact or shared-token boundary.
|
||||||
|
|
||||||
|
Module Foundry has a separate Ed25519 managed-provisioner identity for
|
||||||
|
target-scoped Data Product consumer grants. On a relevant `platform` or
|
||||||
|
`module-foundry` apply, the runner creates or validates the Foundry-only private
|
||||||
|
key at
|
||||||
|
`/volume1/docker/nodedc-platform/secrets/foundry-edp-managed-provisioner/private-key.pem`
|
||||||
|
as `root:root 0400` and the matching EDP trust copy at
|
||||||
|
`/volume1/docker/nodedc-platform/trust/foundry-managed-provisioner/public-key.pem`
|
||||||
|
as `root:11006 0440`. Foundry generates the opaque reader token only inside its
|
||||||
|
persistent private runtime; its signed EDP request contains only a SHA-256
|
||||||
|
digest and Data Product id. EDP resolves the unique active writer source scope
|
||||||
|
server-side and fails closed on missing or ambiguous coverage. No provider,
|
||||||
|
tenant, connection, token, private key or endpoint is admitted to the Foundry
|
||||||
|
MCP plan, application state or browser response. The Engine signing identity,
|
||||||
|
native n8n credentials and legacy issuance bearer cannot call this endpoint.
|
||||||
|
|
||||||
|
The reviewed Engine source candidate has dedicated server-derived MCP
|
||||||
|
plan/apply handling for the exact `ndcDataProductWriterApi` + Data Product
|
||||||
|
Publish tuple. It is separate from the generic HTTP safe-ref path and accepts no
|
||||||
|
caller-provided provider/scope/credential identity, capability, generation or
|
||||||
|
service URL. The production managed flag remains false during staging. In the
|
||||||
|
explicitly confirmed activation window it is set to true immediately before
|
||||||
|
the Platform EDP artifact; runner acceptance then requires EDP `/healthz` to
|
||||||
|
report managed provisioning `enabled`. At that point the old Engine still has
|
||||||
|
no signer mount, so the endpoint remains usable only after the separately
|
||||||
|
accepted Engine artifact. Root/UI transfer is emergency
|
||||||
|
self-hosted diagnostics only, not the user journey or acceptance
|
||||||
|
path. A provider-specific daemon remains forbidden.
|
||||||
|
|
||||||
|
Build the narrow Engine source artifact with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-engine-data-product-publish-grant-artifact.mjs \
|
||||||
|
engine-data-product-publish-grant-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
The builder includes exactly the pinned provider-security catalog, the
|
||||||
|
Publish-grant service, Engine Agent scope/gateway wiring, the existing n8n
|
||||||
|
adapter and the reviewed additive backend runtime overlay. It deliberately
|
||||||
|
excludes base Compose, frontend/dist, runtime data, tests, native credentials,
|
||||||
|
the NDC L2 process and the legacy generic credential-sink route/core. The
|
||||||
|
runner fixes the runtime action to `nodedc-backend` with `--no-deps` and
|
||||||
|
`--pull never`; n8n, nginx app, database services and volumes are not selected.
|
||||||
|
Acceptance requires backend health, the active immutable backend identity and
|
||||||
|
the exact additive mount inventory. Any failure restores the touched source and
|
||||||
|
recreates only the previous verified backend runtime.
|
||||||
|
|
||||||
|
Existing Engine Agents created before Publish-grant support store the original
|
||||||
|
nine scopes as the complete developer profile. They must not require a new
|
||||||
|
agent, setup command or device credential when the profile gains a server-owned
|
||||||
|
capability. Build the compatibility artifact that introduces the durable named
|
||||||
|
`full-developer` profile with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-engine-agent-full-grant-migration-artifact.mjs \
|
||||||
|
engine-agent-full-grant-migration-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
This follow-up slice contains exactly
|
||||||
|
`nodedc-source/server/engineAgents/store.js`. The runner pins its predecessor to
|
||||||
|
the successfully applied Publish generation, requires the installed Publish
|
||||||
|
overlay and active immutable backend, recreates only `nodedc-backend`, and
|
||||||
|
proves the exact candidate SHA, named profile and current expanded runtime
|
||||||
|
scope view. Store schema v1 is migrated atomically to v2 only when a grant
|
||||||
|
contains the complete legacy nine-scope developer bundle. From then on the
|
||||||
|
profile name is the authorization authority and its scope list is derived on
|
||||||
|
every read, so capabilities deliberately added to `full-developer` immediately
|
||||||
|
apply to existing full grants without token or store migrations. Partial grants
|
||||||
|
become `custom` and remain exact; they are never elevated. The artifact does not
|
||||||
|
touch UI, n8n, credentials, agent tokens, workflow graphs, databases or runtime
|
||||||
|
payloads.
|
||||||
|
|
||||||
|
## Engine L2 node-intelligence transition
|
||||||
|
|
||||||
|
The node-intelligence transition is an additive Engine-owned deployment domain.
|
||||||
|
It does not merge Ontology, provider APIs or Ops into the Engine MCP. It pins the
|
||||||
|
reviewed upstream `n8n-mcp` implementation at package `2.33.2`, commit
|
||||||
|
`974a9fb3492fe2c4984ee0549085d531cdc6242a`, and exposes only the safe NDC L2
|
||||||
|
projection through the existing Engine Agent gateway. Upstream management and
|
||||||
|
write tools are not forwarded.
|
||||||
|
|
||||||
|
Production never clones, pulls, installs or builds this dependency. The builder
|
||||||
|
saves the reviewed `linux/amd64` image once, embeds that exact archive in a
|
||||||
|
data-only activation artifact and records both the archive and image-config
|
||||||
|
digests. The runner validates every inner blob, revision label, entrypoint,
|
||||||
|
command and platform before an offline `docker image load`; Compose then uses
|
||||||
|
the fixed tag with `pull_policy: never` and `--pull never`.
|
||||||
|
|
||||||
|
Build a fresh activation/rollback pair:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-engine-node-intelligence-artifacts.mjs \
|
||||||
|
YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
The activation exact set is:
|
||||||
|
|
||||||
|
- `nodedc-source/server/nodeIntelligence`
|
||||||
|
- `nodedc-source/server/routes/engineAgentGateway.js`
|
||||||
|
- `nodedc-source/services/node-intelligence`
|
||||||
|
|
||||||
|
The runtime adds only `nodedc-node-intelligence` and recreates the existing
|
||||||
|
`nodedc-backend`; n8n, UI, databases, L1, provider services and volumes are not
|
||||||
|
selected. The sidecar has no host port, runs as `11007:11007`, has a read-only
|
||||||
|
root filesystem, drops all capabilities and receives no Engine or provider
|
||||||
|
credential. Its independent MCP bearer is created by the root-owned runner as a
|
||||||
|
read-only file and mounted only into the sidecar and backend. It never appears
|
||||||
|
in an artifact, shared environment file, log or MCP response.
|
||||||
|
|
||||||
|
Acceptance requires the exact image/container/mount/security inventory,
|
||||||
|
immutable backend identity and live authenticated `get_node`, `validate_node`
|
||||||
|
and `validate_workflow` calls. Any apply failure restores source and runtime
|
||||||
|
automatically. The separate rollback artifact first removes only the sidecar
|
||||||
|
without volumes, restores the pinned inactive gateway, and recreates only the
|
||||||
|
verified backend. Loaded images and failed candidate source are retained for
|
||||||
|
audit rather than destructively deleted.
|
||||||
|
|
||||||
|
Stage the reviewed runner under a unique candidate name first:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/volume1/docker/nodedc-deploy/runner-install/candidates/
|
||||||
|
nodedc-deploy.engine-node-intelligence-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not overwrite the canonical staging candidate while another deploy may be in
|
||||||
|
flight. After the no-lock/no-process gate, promote the exact candidate in a
|
||||||
|
standalone root step, run `verify-install`, then invoke a fresh process for
|
||||||
|
activation `plan` and only then `apply`. The generated plan/apply runbook carries
|
||||||
|
the runner, activation and rollback SHA-256 values and is staged beside the
|
||||||
|
unique runner candidate.
|
||||||
|
|
||||||
|
`module-foundry` is an independent, authenticated application component. Its
|
||||||
|
artifact contains source and compose infrastructure only; its live
|
||||||
|
`/volume1/docker/nodedc-platform/module-foundry/source/.env` is root-owned and
|
||||||
|
never enters an artifact. The component reuses the existing internal platform
|
||||||
|
credential for Launcher handoff validation and requires that runtime
|
||||||
|
configuration before its first `apply`.
|
||||||
|
|
||||||
|
When the managed reader-grant source is present, Module Foundry acceptance also
|
||||||
|
requires `/healthz` to report the dedicated Ed25519 provisioner as configured.
|
||||||
|
The check is source-aware: if an apply rolls back to the prior source, rollback
|
||||||
|
acceptance uses that prior health contract instead of falsely requiring a
|
||||||
|
feature which the restored generation does not contain.
|
||||||
|
|
||||||
|
The Foundry ↔ Map Gateway signing key is not an application or `.env` setting.
|
||||||
|
On the first relevant `platform` or `module-foundry` apply, the root-owned
|
||||||
|
runner creates `/volume1/docker/nodedc-platform/secrets/map-gateway-admin-secret`
|
||||||
|
atomically (root:gid 1000, mode `0640`). Both containers receive that file only
|
||||||
|
as a read-only mount. The value is never printed, backed up with source,
|
||||||
|
included in an artifact, or administered through Foundry.
|
||||||
|
|
||||||
|
`proxy-contur` is the canonical VPN egress for selected Map Gateway provider
|
||||||
|
hosts. Its existing root-owned `PROXY_TOKEN` is copied by the runner into
|
||||||
|
`/volume1/docker/nodedc-platform/secrets/map-egress-proxy-token` with
|
||||||
|
`root:gid 1000`, mode `0640`, then mounted read-only only into Map Gateway.
|
||||||
|
The value is neither printed nor contained in an artifact, Foundry setting, or
|
||||||
|
browser response. Apply the `proxy-contur` artifact before the Platform Map
|
||||||
|
Gateway artifact: it creates the private `nodedc-map-egress` Docker network.
|
||||||
|
|
||||||
|
`dc-amd-proxy` is the separate, staged connector for the neighbouring AMD VPN
|
||||||
|
machine. Its active artifact attaches only to the private `nodedc-map-egress`
|
||||||
|
network, exposes a narrow NAS-LAN pairing port, and has no direct provider
|
||||||
|
egress. The runner preserves a `0700`, service-user-owned runtime directory
|
||||||
|
for the one-time paired connector credential and synchronizes the existing
|
||||||
|
private Map Gateway egress credential as a read-only file. Neither value is
|
||||||
|
ever placed in an artifact, `.env`, browser response, or runner output. The
|
||||||
|
separate Platform switch is applied only after the connector and pairing are
|
||||||
|
verified; it does not alter NAS routes, VPN, DNS, or Tailscale.
|
||||||
|
|
||||||
|
Install or update the root-owned live runner on Synology:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# First verify that no deploy process is active and state/deploy.lock is absent.
|
||||||
|
sudo install -o root -g root -m 0755 \
|
||||||
|
/volume1/docker/nodedc-deploy/runner-install/nodedc-deploy \
|
||||||
|
/usr/local/sbin/nodedc-deploy
|
||||||
|
sudo /usr/local/sbin/nodedc-deploy verify-install
|
||||||
|
```
|
||||||
|
|
||||||
|
Runner promotion is a standalone admin step, never an app-overlay artifact and
|
||||||
|
never part of a running apply. A Python process already executing the old file
|
||||||
|
keeps the old code in memory; always invoke a fresh verified process afterward.
|
||||||
|
|
||||||
|
Normal service deploys must still use explicit artifacts:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo /usr/local/sbin/nodedc-deploy plan /volume1/docker/nodedc-deploy/inbox/<artifact>.tgz
|
||||||
|
sudo /usr/local/sbin/nodedc-deploy apply /volume1/docker/nodedc-deploy/inbox/<artifact>.tgz
|
||||||
|
```
|
||||||
|
|
||||||
|
## Device Plane foundation
|
||||||
|
|
||||||
|
`device-plane` is an additive component rooted at:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/volume1/docker/nodedc-device-plane
|
||||||
|
```
|
||||||
|
|
||||||
|
Its fixed Compose project is `nodedc-device-plane`. Ordinary application
|
||||||
|
artifacts may select only `device-control-core` and `device-gateway`, always
|
||||||
|
with `--no-deps`. `device-postgres` and the named
|
||||||
|
`nodedc-device-plane-postgres-data` volume are durable prerequisites and are
|
||||||
|
never selected or recreated by an application overlay.
|
||||||
|
|
||||||
|
The sole exception is the exact one-time bootstrap artifact containing only
|
||||||
|
the reviewed Compose file and
|
||||||
|
`deployment/device-postgres-bootstrap-v1.json`. Its preflight requires both the
|
||||||
|
Compose database container and named volume to be absent. It selects only
|
||||||
|
`device-postgres`; a failed activation may remove that candidate container but
|
||||||
|
never the volume. Any pre-existing container or volume is an ambiguity and
|
||||||
|
fails closed.
|
||||||
|
|
||||||
|
The runner creates or validates three root-owned secret files outside the
|
||||||
|
artifact: the PostgreSQL password, Gateway-to-Core token and restricted
|
||||||
|
identifier pepper. The manifest cannot choose their paths or values.
|
||||||
|
|
||||||
|
The foundation publishes only loopback health endpoints on `18120` and
|
||||||
|
`18121`. Raw device ingress `9921`, discovery ingest and outbound command
|
||||||
|
transport remain disabled. The first application artifact must not be built or
|
||||||
|
staged until this runner candidate is separately reviewed, promoted and proven
|
||||||
|
by a fresh `verify-install`.
|
||||||
|
|
||||||
|
Build and test the deterministic data-only artifact contract locally:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m unittest -v \
|
||||||
|
infra.deploy-runner.test_device_plane_registry \
|
||||||
|
infra.deploy-runner.test_device_plane_artifact
|
||||||
|
|
||||||
|
node infra/deploy-runner/build-device-plane-artifact.mjs \
|
||||||
|
device-plane-foundation-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
|
|
||||||
|
Any failed first activation removes only candidate Core/Gateway containers,
|
||||||
|
never volumes, restores the source overlay and retains PostgreSQL state.
|
||||||
|
The rollback baseline is taken from an explicit pre-apply Docker service
|
||||||
|
inventory stored as `runtime-before.json` in the backup. The presence of the
|
||||||
|
shared Compose file never implies that Core or Gateway existed before apply.
|
||||||
|
|
||||||
|
The exact `device-plane-foundation-20260725-001` failed activation is recovered
|
||||||
|
only through the registered
|
||||||
|
`deployment/device-plane-foundation-recovery-v1.json` transition. Its artifact
|
||||||
|
must reproduce the failed foundation source byte-for-byte. The runner validates
|
||||||
|
the exact failed archive, journal, backup partition, partial live source and
|
||||||
|
healthy observed Core/Gateway/PostgreSQL generations. Recovery publishes source
|
||||||
|
and performs read-only runtime acceptance; it does not build, recreate, restart
|
||||||
|
or remove containers. A failed recovery restores source only and leaves runtime
|
||||||
|
unchanged.
|
||||||
|
|
||||||
|
Build and test that incident-specific deterministic recovery artifact:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m unittest -v \
|
||||||
|
infra.deploy-runner.test_device_plane_foundation_recovery_artifact
|
||||||
|
|
||||||
|
node infra/deploy-runner/build-device-plane-foundation-recovery-artifact.mjs \
|
||||||
|
device-plane-foundation-recovery-20260725-002
|
||||||
|
```
|
||||||
|
|
||||||
|
The recovery `device-plane-foundation-recovery-20260725-002` is also terminal
|
||||||
|
failed. Docker Engine 24 does not materialize requested host port mappings when
|
||||||
|
the container is attached only to an `internal` network. Its registered
|
||||||
|
successor is the exact
|
||||||
|
`deployment/device-plane-foundation-network-publication-v1.json` transition.
|
||||||
|
It keeps PostgreSQL exclusively on the existing internal private network and
|
||||||
|
adds a second non-internal bridge only to Control Core and Gateway. Masquerade
|
||||||
|
is disabled on that bridge; the only published ports remain
|
||||||
|
`127.0.0.1:18120` and `127.0.0.1:18121`. Device TCP `9921`, public ingress,
|
||||||
|
discovery ingest and command transport remain disabled.
|
||||||
|
|
||||||
|
This successor has an empty build set and force-recreates only
|
||||||
|
`device-control-core` and `device-gateway` with `--no-deps` from their exact
|
||||||
|
existing `pull_policy: never` images. Its predecessor barrier validates the
|
||||||
|
terminal failed archive/journal/backup, partial source, exact running
|
||||||
|
generations, absent actual port mappings, internal private network and absence
|
||||||
|
of the control network. Acceptance requires new stateless container
|
||||||
|
generations, the unchanged PostgreSQL generation and volume, exact actual
|
||||||
|
loopback mappings, healthy HTTP contracts and a closed `9921`.
|
||||||
|
|
||||||
|
Rollback removes only the two stateless candidate containers and the newly
|
||||||
|
created unused control network, restores the partial source predecessor and
|
||||||
|
recreates the internal-only Core/Gateway runtime from the sealed predecessor
|
||||||
|
Compose bytes. PostgreSQL and its volume are never selected.
|
||||||
|
|
||||||
|
Build and test the deterministic network-publication successor:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m unittest -v \
|
||||||
|
infra.deploy-runner.test_device_plane_foundation_network_publication_artifact
|
||||||
|
|
||||||
|
node \
|
||||||
|
infra/deploy-runner/build-device-plane-foundation-network-publication-artifact.mjs \
|
||||||
|
device-plane-foundation-network-publication-20260725-003
|
||||||
|
```
|
||||||
|
|
||||||
|
After the runner is promoted and freshly verified, bootstrap the durable
|
||||||
|
prerequisite with a separate artifact before planning the application:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node infra/deploy-runner/build-device-plane-postgres-bootstrap-artifact.mjs \
|
||||||
|
device-plane-postgres-bootstrap-YYYYMMDD-NNN
|
||||||
|
```
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(scriptDir, "../..");
|
||||||
|
const bimRoot = resolve(process.env.NODEDC_BIM_VIEWER_ROOT || resolve(platformRoot, "../NODEDC_BIM_VIEWER"));
|
||||||
|
const taskerRoot = resolve(
|
||||||
|
process.env.NODEDC_TASKMANAGER_ROOT || resolve(platformRoot, "../../data/dc_taskmanager/NODEDC_TASKMANAGER"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
|
||||||
|
const [release = "20260730-002", ...extra] = process.argv.slice(2);
|
||||||
|
|
||||||
|
if (extra.length || !/^\d{8}-\d{3}$/.test(release)) {
|
||||||
|
throw new Error("usage: build-bim-tasker-cad-ops-artifacts.mjs [YYYYMMDD-NNN]");
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptors = [
|
||||||
|
{
|
||||||
|
artifactBasename: `nodedc-bim-viewer-cad-ops-${release}.tgz`,
|
||||||
|
component: "bim-viewer",
|
||||||
|
files: [
|
||||||
|
"converter/worker.py",
|
||||||
|
"frontend/dcViewer.js",
|
||||||
|
"server/cad-formats.js",
|
||||||
|
"server/index.js",
|
||||||
|
"server/tasker-gateway-auth.js",
|
||||||
|
],
|
||||||
|
patchId: `bim-viewer-cad-ops-${release}`,
|
||||||
|
sourceRoot: bimRoot,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
artifactBasename: `nodedc-tasker-cad-ops-${release}.tgz`,
|
||||||
|
component: "tasker",
|
||||||
|
files: [
|
||||||
|
"plane-src/apps/api/plane/app/urls/issue.py",
|
||||||
|
"plane-src/apps/api/plane/app/views/__init__.py",
|
||||||
|
"plane-src/apps/api/plane/app/views/issue/attachment.py",
|
||||||
|
"plane-src/apps/api/plane/app/views/issue/bim_attachment.py",
|
||||||
|
"plane-src/apps/api/plane/utils/nodedc_bim_gateway.py",
|
||||||
|
"plane-src/apps/web/core/components/issues/attachment/attachment-list-item.tsx",
|
||||||
|
"plane-src/apps/web/core/services/issue/issue_attachment.service.ts",
|
||||||
|
"plane-src/apps/web/helpers/beam-viewer-config.ts",
|
||||||
|
"plane-src/apps/web/helpers/beam-viewer.ts",
|
||||||
|
],
|
||||||
|
patchId: `tasker-cad-ops-${release}`,
|
||||||
|
sourceRoot: taskerRoot,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
const artifacts = [];
|
||||||
|
|
||||||
|
for (const descriptor of descriptors) {
|
||||||
|
const sourceCommit = gitOutput(descriptor.sourceRoot, ["rev-parse", "HEAD"]);
|
||||||
|
const sourceStatus = gitOutput(descriptor.sourceRoot, ["status", "--porcelain"]);
|
||||||
|
if (sourceStatus) throw new Error(`source_worktree_not_clean:${descriptor.component}`);
|
||||||
|
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), `nodedc-${descriptor.component}-cad-ops-`));
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
const artifact = join(artifactDir, descriptor.artifactBasename);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true });
|
||||||
|
for (const relativePath of descriptor.files) {
|
||||||
|
const source = resolve(descriptor.sourceRoot, relativePath);
|
||||||
|
const sourceStat = await lstat(source);
|
||||||
|
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
|
||||||
|
throw new Error(`source_file_rejected:${descriptor.component}:${relativePath}`);
|
||||||
|
}
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await cp(source, destination, { force: true, verbatimSymlinks: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${descriptor.patchId}\ncomponent=${descriptor.component}\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${descriptor.files.join("\n")}\n`, "utf8");
|
||||||
|
|
||||||
|
const tar = spawnSync("python3", ["-c", canonicalTarScript(), artifact, stage], {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (tar.status !== 0) throw new Error(`tar_failed:${descriptor.component}:${tar.stderr || tar.stdout}`);
|
||||||
|
|
||||||
|
const sha256 = createHash("sha256").update(await readFile(artifact)).digest("hex");
|
||||||
|
artifacts.push({
|
||||||
|
artifact,
|
||||||
|
component: descriptor.component,
|
||||||
|
files: descriptor.files,
|
||||||
|
patchId: descriptor.patchId,
|
||||||
|
sha256,
|
||||||
|
sourceCommit,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(JSON.stringify({ ok: true, release, artifacts }, null, 2));
|
||||||
|
|
||||||
|
function gitOutput(cwd, args) {
|
||||||
|
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
||||||
|
if (result.status !== 0) throw new Error(`git_failed:${cwd}:${args.join("_")}:${result.stderr || result.stdout}`);
|
||||||
|
return result.stdout.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(scriptDir, "../..");
|
||||||
|
const artifactDir = resolve(scriptDir, "../deploy-artifacts");
|
||||||
|
const [patchId = "dc-amd-proxy-bootstrap-20260715-001", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) throw new Error("usage: build-dc-amd-proxy-artifact.mjs [patch-id]");
|
||||||
|
|
||||||
|
const files = [
|
||||||
|
["services/dc-amd-proxy/Dockerfile", "Dockerfile"],
|
||||||
|
["services/dc-amd-proxy/README.md", "README.md"],
|
||||||
|
["services/dc-amd-proxy/docker-compose.yml", "docker-compose.yml"],
|
||||||
|
["services/dc-amd-proxy/package.json", "package.json"],
|
||||||
|
["services/dc-amd-proxy/server.mjs", "server.mjs"],
|
||||||
|
];
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-dc-amd-proxy-artifact-"));
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
const target = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true });
|
||||||
|
for (const [source, destination] of files) await copySafe(resolve(platformRoot, source), join(payload, destination));
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=dc-amd-proxy\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.map(([, destination]) => destination).join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
const tar = spawnSync("python3", ["-c", "import sys,tarfile\nwith tarfile.open(sys.argv[1],'w:gz',format=tarfile.PAX_FORMAT) as a:\n [a.add(n,arcname=n,recursive=True) for n in ('manifest.env','files.txt','payload')]", target], { cwd: stage, encoding: "utf8" });
|
||||||
|
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
|
||||||
|
console.log(JSON.stringify({ ok: true, patchId, artifact: target, sha256: createHash("sha256").update(await readFile(target)).digest("hex") }, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copySafe(source, destination) {
|
||||||
|
const info = await lstat(source);
|
||||||
|
if (info.isSymbolicLink() || !info.isFile()) throw new Error(`source_file_rejected:${source}`);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await cp(source, destination, { force: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const workspaceRoot = resolve(platformRoot, '..')
|
||||||
|
const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts'))
|
||||||
|
const [patchId = '', ...extra] = process.argv.slice(2)
|
||||||
|
const storeRelativePath = 'nodedc-source/server/engineAgents/store.js'
|
||||||
|
const predecessorSha256 = '52daa43499d6d9a97fe7ffa891edb9212b7791e733f91dd3ca686d42739b7e9a'
|
||||||
|
const targetSha256 = '2e62654c2dc12905efcc83a9dff45a818dd7b47924a10600160835c4416540e9'
|
||||||
|
const readerExtendedSourceSha256 = 'debd351fe0b8c72b33b8c79909b8f339cbaf061b970576f3ae72df52ebaa211f'
|
||||||
|
const ontologyExtendedSourceSha256 = '4cd4bdd5958cfafee184e98a04fe12aa0c1cbe884326beaec63c99f9fff61285'
|
||||||
|
const frozenTargetArtifact = join(
|
||||||
|
workspaceRoot,
|
||||||
|
'deploy-artifacts/nodedc-engine-agent-full-grant-migration-20260717-002.tgz',
|
||||||
|
)
|
||||||
|
const frozenTargetArtifactSha256 = 'd104ee6e63d1fccb9069e2b3db5e0446907ee9bf9cb04f2387636c272f803d68'
|
||||||
|
const previouslyIssuedPatchIds = new Set([
|
||||||
|
'engine-agent-full-grant-migration-20260717-001',
|
||||||
|
])
|
||||||
|
|
||||||
|
if (extra.length || !/^engine-agent-full-grant-migration-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error('usage: build-engine-agent-full-grant-migration-artifact.mjs <fresh-patch-id>')
|
||||||
|
}
|
||||||
|
if (previouslyIssuedPatchIds.has(patchId)) {
|
||||||
|
throw new Error('engine_agent_full_grant_migration_patch_id_already_issued')
|
||||||
|
}
|
||||||
|
|
||||||
|
const source = join(engineRoot, storeRelativePath)
|
||||||
|
const sourceInfo = await lstat(source)
|
||||||
|
if (sourceInfo.isSymbolicLink() || !sourceInfo.isFile()) throw new Error('engine_agent_store_source_unsafe')
|
||||||
|
const sourceBytes = await materializeFrozenTarget(await readFile(source))
|
||||||
|
if (digest(sourceBytes) !== targetSha256) throw new Error('engine_agent_store_target_sha256_mismatch')
|
||||||
|
const sourceText = sourceBytes.toString('utf8')
|
||||||
|
for (const required of [
|
||||||
|
'const STORE_VERSION = 2',
|
||||||
|
"export const ENGINE_AGENT_FULL_DEVELOPER_PROFILE = 'full-developer'",
|
||||||
|
"export const ENGINE_AGENT_CUSTOM_PROFILE = 'custom'",
|
||||||
|
'const LEGACY_FULL_DEVELOPER_SCOPES = Object.freeze([',
|
||||||
|
"'engine:l2:data-product-publish-grant:plan'",
|
||||||
|
"'engine:l2:data-product-publish-grant:write'",
|
||||||
|
'const migrateLegacyFullDeveloper = sourceVersion === 1',
|
||||||
|
'LEGACY_FULL_DEVELOPER_SCOPES.every((scope) => scopes.includes(scope))',
|
||||||
|
'profile === ENGINE_AGENT_FULL_DEVELOPER_PROFILE ? [...ENGINE_AGENT_SCOPES] : scopes',
|
||||||
|
"throw new Error('engine_agent_store_version_unsupported')",
|
||||||
|
]) {
|
||||||
|
if (!sourceText.includes(required)) throw new Error(`engine_agent_store_contract_missing:${required}`)
|
||||||
|
}
|
||||||
|
if (/gelios|robot2b/i.test(sourceText)) throw new Error('engine_agent_store_provider_logic_forbidden')
|
||||||
|
run('node', ['--check', source])
|
||||||
|
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`)
|
||||||
|
await assertFresh(artifact)
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-agent-grant-migration-'))
|
||||||
|
try {
|
||||||
|
const destination = join(stage, 'payload', storeRelativePath)
|
||||||
|
await mkdir(dirname(destination), { recursive: true })
|
||||||
|
await writeFile(destination, sourceBytes)
|
||||||
|
await writeFile(
|
||||||
|
join(stage, 'manifest.env'),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${storeRelativePath}\n`, 'utf8')
|
||||||
|
run('python3', ['-c', canonicalTarScript(), artifact, stage])
|
||||||
|
const artifactBytes = await readFile(artifact)
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(artifactBytes),
|
||||||
|
entries: [storeRelativePath],
|
||||||
|
predecessorSha256,
|
||||||
|
targetSha256,
|
||||||
|
services: ['nodedc-backend'],
|
||||||
|
excluded: ['n8n', 'app', 'databases', 'credentials', 'runtime-data'],
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(target) {
|
||||||
|
try {
|
||||||
|
await lstat(target)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('engine_agent_full_grant_migration_artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip, io, pathlib, sys, tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1], 'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='', mode='wb', fileobj=out, compresslevel=9, mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p] + (sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
' for x in paths:',
|
||||||
|
" info=tar.gettarinfo(str(x), arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info, src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
maxBuffer: 16 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function materializeFrozenTarget(bytes) {
|
||||||
|
const sourceSha256 = digest(bytes)
|
||||||
|
if (sourceSha256 === targetSha256) return bytes
|
||||||
|
if (sourceSha256 === ontologyExtendedSourceSha256) {
|
||||||
|
const artifactBytes = await readFile(frozenTargetArtifact)
|
||||||
|
if (digest(artifactBytes) !== frozenTargetArtifactSha256) {
|
||||||
|
throw new Error('engine_agent_store_frozen_target_artifact_sha256_mismatch')
|
||||||
|
}
|
||||||
|
const script = [
|
||||||
|
'import pathlib,sys,tarfile',
|
||||||
|
'p=pathlib.Path(sys.argv[1])',
|
||||||
|
"with tarfile.open(p,'r:gz') as t:",
|
||||||
|
" f=t.extractfile('payload/nodedc-source/server/engineAgents/store.js')",
|
||||||
|
" if f is None: raise SystemExit('member-unreadable')",
|
||||||
|
' sys.stdout.buffer.write(f.read())',
|
||||||
|
].join('\n')
|
||||||
|
const frozen = Buffer.from(run('python3', ['-c', script, frozenTargetArtifact]).stdout, 'utf8')
|
||||||
|
if (digest(frozen) !== targetSha256) {
|
||||||
|
throw new Error('engine_agent_store_frozen_target_sha256_mismatch')
|
||||||
|
}
|
||||||
|
return frozen
|
||||||
|
}
|
||||||
|
if (sourceSha256 !== readerExtendedSourceSha256) {
|
||||||
|
throw new Error('engine_agent_store_target_sha256_mismatch')
|
||||||
|
}
|
||||||
|
const text = bytes.toString('utf8')
|
||||||
|
const readerScopes = [
|
||||||
|
" 'engine:l2:data-product-read-grant:plan',\n",
|
||||||
|
" 'engine:l2:data-product-read-grant:write',\n",
|
||||||
|
]
|
||||||
|
let frozen = text
|
||||||
|
for (const scope of readerScopes) {
|
||||||
|
if (!frozen.includes(scope)) throw new Error('engine_agent_store_reader_scope_boundary_missing')
|
||||||
|
frozen = frozen.replace(scope, '')
|
||||||
|
}
|
||||||
|
return Buffer.from(frozen, 'utf8')
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const workspaceRoot = resolve(platformRoot, '..')
|
||||||
|
const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts'))
|
||||||
|
const predecessorArtifact = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_AUTH_RECOVERY_PREDECESSOR
|
||||||
|
|| '/Volumes/docker/nodedc-deploy/applied/nodedc-engine-restart-safe-auth-20260719-001.tgz',
|
||||||
|
)
|
||||||
|
const [patchId = '', ...extra] = process.argv.slice(2)
|
||||||
|
|
||||||
|
if (extra.length || !/^engine-auth-redirect-recovery-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error('usage: build-engine-auth-redirect-recovery-artifact.mjs engine-auth-redirect-recovery-YYYYMMDD-NNN')
|
||||||
|
}
|
||||||
|
|
||||||
|
const predecessorArtifactSha256 = 'f6830046d7bd2bc32c1dbda8dce7ddf68d15c1e728f594c0f64ee8feec3911b8'
|
||||||
|
const predecessorManifest = 'id=engine-restart-safe-auth-20260719-001\ncomponent=engine\ntype=app-overlay\n'
|
||||||
|
const predecessorSha256 = Object.freeze({
|
||||||
|
'nodedc-source/src/platform/auth/access.ts': '9610dc1622a1c9b383eb3a1569347098002aa058dbbcbb23f096f2622d452222',
|
||||||
|
'nodedc-source/src/platform/auth/sessionRecovery.ts': 'f931cbb45d64d5d6a2868194e8c73879a408dffca1fdd7e41acfa262441c50d7',
|
||||||
|
'nodedc-source/dist/index.html': 'b031f6720683f6fb5ccfa59a01414ff2a3efcdf548b1c6aab33e1748ee3f003d',
|
||||||
|
})
|
||||||
|
const entries = Object.freeze([
|
||||||
|
'nodedc-source/src/platform/auth/access.ts',
|
||||||
|
'nodedc-source/src/platform/auth/sessionRecovery.ts',
|
||||||
|
'nodedc-source/dist/index.html',
|
||||||
|
'nodedc-source/dist/assets/index-DJ1CMfu4.js',
|
||||||
|
])
|
||||||
|
const candidateSha256 = Object.freeze({
|
||||||
|
'nodedc-source/src/platform/auth/access.ts': 'c686db2568912a093ea8934e34889254ddd659594f7084025c280732ef627002',
|
||||||
|
'nodedc-source/src/platform/auth/sessionRecovery.ts': '63f3e2379628dea3b119c4283bc0c3bb10e94199c673b9d9c579bac3c54be98f',
|
||||||
|
'nodedc-source/dist/index.html': '8894f62ad590168862e81266bc4602410279634b666af72cb14ad80aeb71ea74',
|
||||||
|
'nodedc-source/dist/assets/index-DJ1CMfu4.js': 'a0aaf72d2ed390142ff2ea03dbcfdd534637e5faefd80d8aa7d705a804abe065',
|
||||||
|
})
|
||||||
|
|
||||||
|
const predecessorInfo = await lstat(predecessorArtifact)
|
||||||
|
if (predecessorInfo.isSymbolicLink() || !predecessorInfo.isFile()) {
|
||||||
|
throw new Error('engine_auth_recovery_predecessor_unsafe')
|
||||||
|
}
|
||||||
|
if (digest(await readFile(predecessorArtifact)) !== predecessorArtifactSha256) {
|
||||||
|
throw new Error('engine_auth_recovery_predecessor_archive_mismatch')
|
||||||
|
}
|
||||||
|
run('python3', [
|
||||||
|
'-c', verifyPredecessorScript(), predecessorArtifact,
|
||||||
|
predecessorArtifactSha256, predecessorManifest, JSON.stringify(predecessorSha256),
|
||||||
|
])
|
||||||
|
|
||||||
|
for (const rel of entries) {
|
||||||
|
const source = resolve(engineRoot, rel)
|
||||||
|
const info = await lstat(source)
|
||||||
|
if (info.isSymbolicLink() || !info.isFile()) throw new Error(`engine_auth_recovery_candidate_unsafe:${rel}`)
|
||||||
|
if (digest(await readFile(source)) !== candidateSha256[rel]) {
|
||||||
|
throw new Error(`engine_auth_recovery_candidate_sha256_mismatch:${rel}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const indexHtml = await readFile(resolve(engineRoot, 'nodedc-source/dist/index.html'), 'utf8')
|
||||||
|
if (!indexHtml.includes('/assets/index-DJ1CMfu4.js') || !indexHtml.includes('/assets/index-Bim2pv1P.css')) {
|
||||||
|
throw new Error('engine_auth_recovery_dist_entrypoint_mismatch')
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`)
|
||||||
|
await assertArtifactTargetFresh(artifact)
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-auth-redirect-recovery-'))
|
||||||
|
|
||||||
|
try {
|
||||||
|
await writeFile(
|
||||||
|
join(stage, 'manifest.env'),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8')
|
||||||
|
for (const rel of entries) {
|
||||||
|
const target = join(stage, 'payload', rel)
|
||||||
|
await mkdir(dirname(target), { recursive: true })
|
||||||
|
await copyFile(resolve(engineRoot, rel), target)
|
||||||
|
}
|
||||||
|
run('python3', ['-c', canonicalTarScript(), artifact, stage])
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
predecessorArtifact,
|
||||||
|
predecessorArtifactSha256,
|
||||||
|
predecessorSha256,
|
||||||
|
candidateSha256,
|
||||||
|
entries,
|
||||||
|
runtimeServices: ['nodedc-backend', 'app'],
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
function verifyPredecessorScript() {
|
||||||
|
return [
|
||||||
|
'import hashlib,json,pathlib,sys,tarfile',
|
||||||
|
'source=pathlib.Path(sys.argv[1]); expected_archive=sys.argv[2]',
|
||||||
|
'expected_manifest=sys.argv[3].encode(); hashes=json.loads(sys.argv[4])',
|
||||||
|
"assert hashlib.sha256(source.read_bytes()).hexdigest()==expected_archive, 'archive-sha256'",
|
||||||
|
"with tarfile.open(source,'r:gz') as tar:",
|
||||||
|
" assert tar.extractfile('manifest.env').read()==expected_manifest, 'manifest'",
|
||||||
|
' for rel,wanted in hashes.items():',
|
||||||
|
" data=tar.extractfile('payload/'+rel).read()",
|
||||||
|
" assert hashlib.sha256(data).hexdigest()==wanted, 'payload:'+rel",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertArtifactTargetFresh(target) {
|
||||||
|
try {
|
||||||
|
await lstat(target)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('engine_auth_recovery_artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip,io,pathlib,sys,tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
' for x in paths:',
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^engine-composite-provider-v4-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-composite-provider-v4-artifact.mjs " +
|
||||||
|
"<engine-composite-provider-v4-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"9c931f9abfcadb5b34a8a854c2efb8fd79913e000eecf0967d1b7c500bf9a56a",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/providerCatalog.js":
|
||||||
|
"689c6fbf695e582d983159973a21142787d1b19bb1d343da4c62c03092ac291f",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/service.js":
|
||||||
|
"83f045f4e0f332644310172ed51bb652d808bf04155b11c02e46bdffc95f7220",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/store.js":
|
||||||
|
"98662da6acd0489a9cae4b726eb61ce89d9b2c788b2ea95433e9c4f02930c095",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-composite-provider-v4-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const source = join(engineRoot, relativePath);
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(source, destination, 0);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "exact-v3-to-v4",
|
||||||
|
providerPackage: "gelios.provider.v4",
|
||||||
|
capabilities: [
|
||||||
|
"gelios.monitoring_config.current.read",
|
||||||
|
"gelios.units.current.read",
|
||||||
|
],
|
||||||
|
dataProductId: "fleet.positions.current.v3",
|
||||||
|
credentialValues: "preserved",
|
||||||
|
untouched: ["n8n", "L1 graph", "Engine UI", "databases"],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const path = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(path);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_composite_provider_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(path));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_composite_provider_target_mismatch:${relativePath}:` +
|
||||||
|
`expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const catalog = JSON.parse(await readFile(join(engineRoot, entries[0]), "utf8"));
|
||||||
|
const provider = catalog?.packages?.[0];
|
||||||
|
const capabilityIds = provider?.capabilities?.map((item) => item.id);
|
||||||
|
const requestUrls = provider?.capabilities?.map((item) => item.request?.url);
|
||||||
|
if (
|
||||||
|
catalog?.schemaVersion !== "nodedc.engine.provider-security-catalog/v1" ||
|
||||||
|
provider?.id !== "gelios.provider.v4" ||
|
||||||
|
provider?.version !== "4.0.0" ||
|
||||||
|
provider?.providerCredential?.credentialType !== "httpBearerAuth" ||
|
||||||
|
JSON.stringify(capabilityIds) !== JSON.stringify([
|
||||||
|
"gelios.monitoring_config.current.read",
|
||||||
|
"gelios.units.current.read",
|
||||||
|
]) ||
|
||||||
|
JSON.stringify(requestUrls) !== JSON.stringify([
|
||||||
|
"https://api.geliospro.com/api/v1/users/me/monitoring-config",
|
||||||
|
"https://api.geliospro.com/api/v1/units?incltrip=true",
|
||||||
|
]) ||
|
||||||
|
provider?.capabilities?.some(
|
||||||
|
(item) => item.dataProductIds?.length !== 1 ||
|
||||||
|
item.dataProductIds[0] !== "fleet.positions.current.v3",
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_composite_provider_catalog_projection_mismatch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const workspaceRoot = resolve(platformRoot, '..')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts'))
|
||||||
|
const sourceArtifact = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_CREDENTIAL_SINK_RECOVERY_SOURCE
|
||||||
|
|| '/Volumes/docker/nodedc-deploy/applied/nodedc-engine-credential-sink-20260716-001.tgz',
|
||||||
|
)
|
||||||
|
const [patchId = '', ...extra] = process.argv.slice(2)
|
||||||
|
|
||||||
|
if (extra.length || !/^engine-credential-sink-recovery-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error('usage: build-engine-credential-sink-recovery-artifact.mjs <fresh-recovery-patch-id>')
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceArtifactSha256 = '0a96add05fe59db8f490927f66e07a84490474a7afb3ef7de51e1d6fd96f86a2'
|
||||||
|
const sourceManifest = 'id=engine-credential-sink-20260716-001\ncomponent=engine\ntype=app-overlay\n'
|
||||||
|
const entries = Object.freeze([
|
||||||
|
'nodedc-source/server/credentialPolicies/ndcPrivateNode.js',
|
||||||
|
'nodedc-source/server/credentialSink',
|
||||||
|
'nodedc-source/server/index.js',
|
||||||
|
'nodedc-source/server/routes/engineAgentGateway.js',
|
||||||
|
'nodedc-source/server/routes/engineCredentialSink.js',
|
||||||
|
'nodedc-source/server/routes/n8n.js',
|
||||||
|
'nodedc-source/server/routes/ndcAgentMcp.js',
|
||||||
|
'nodedc-source/services/backend/credential-sink/docker-compose.immutable-runtime.yml',
|
||||||
|
])
|
||||||
|
const payloadSha256 = Object.freeze({
|
||||||
|
'nodedc-source/server/credentialPolicies/ndcPrivateNode.js': '723874a02dc7b8a68b22ff2304431cfe64f28933cedf5f1e6cda79b2e1cf704a',
|
||||||
|
'nodedc-source/server/credentialSink/core.js': '9f0facc41fd398fcd955cffdd486abb126cdcd756c87ffde667fcbe00e2c41d3',
|
||||||
|
'nodedc-source/server/credentialSink/requestAuth.js': 'f8c9237c3e6f4219dee0d4f956d6e97f76f5bd7ba8a6fd0b4fb21aceffa38138',
|
||||||
|
'nodedc-source/server/credentialSink/store.js': 'c78dc285a973b6acd8a2330f0310935ad08720b2905454492f292d235abf12c0',
|
||||||
|
'nodedc-source/server/credentialSink/vendor/engine-credential-sink.mjs': 'b4800eead9bf94793ff1280d06e34aad6b37ef055a9d7f8d83d7fb5f9bd66d8b',
|
||||||
|
'nodedc-source/server/index.js': 'b2b790b02839570d967a2ca68b00e2724485a99389ac9b3a589a1b22302a36b8',
|
||||||
|
'nodedc-source/server/routes/engineAgentGateway.js': 'e3450a4e1d5318dbac37627b67804d62804e27e2032c9e90478a1e739cea6d3d',
|
||||||
|
'nodedc-source/server/routes/engineCredentialSink.js': '9cbb69dbc8cbe6181cd5b0170fe9c4d717b0a173866ca98cba3e3766c0bab94e',
|
||||||
|
'nodedc-source/server/routes/n8n.js': '783d822e2457d82e890f43bc00c7e33822077dc2841f0511a89ecb210fd36d48',
|
||||||
|
'nodedc-source/server/routes/ndcAgentMcp.js': 'fbb3342b1a617b956d5b3a6a40d5111aa107c1176b4ff89c37b104995bada081',
|
||||||
|
'nodedc-source/services/backend/credential-sink/docker-compose.immutable-runtime.yml': '944fa64b08255eb8207b93fd327aebb98ecd9400d37d25fcfa8e3a040ee44afe',
|
||||||
|
})
|
||||||
|
|
||||||
|
const sourceInfo = await lstat(sourceArtifact)
|
||||||
|
if (sourceInfo.isSymbolicLink() || !sourceInfo.isFile()) {
|
||||||
|
throw new Error('engine_credential_sink_recovery_source_unsafe')
|
||||||
|
}
|
||||||
|
if (digest(await readFile(sourceArtifact)) !== sourceArtifactSha256) {
|
||||||
|
throw new Error('engine_credential_sink_recovery_source_sha256_mismatch')
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`)
|
||||||
|
await assertArtifactTargetFresh(artifact)
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-credential-sink-recovery-'))
|
||||||
|
|
||||||
|
try {
|
||||||
|
run('python3', [
|
||||||
|
'-c', verifiedExtractScript(), sourceArtifact, stage,
|
||||||
|
sourceArtifactSha256, sourceManifest, JSON.stringify(entries), JSON.stringify(payloadSha256),
|
||||||
|
])
|
||||||
|
await writeFile(
|
||||||
|
join(stage, 'manifest.env'),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8')
|
||||||
|
run('python3', ['-c', canonicalTarScript(), artifact, stage])
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
sourceArtifact,
|
||||||
|
sourceArtifactSha256,
|
||||||
|
entries,
|
||||||
|
payloadSha256,
|
||||||
|
changed: ['manifest.env:id'],
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertArtifactTargetFresh(target) {
|
||||||
|
try {
|
||||||
|
await lstat(target)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('engine_credential_sink_recovery_artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
function verifiedExtractScript() {
|
||||||
|
return [
|
||||||
|
'import hashlib,json,pathlib,sys,tarfile',
|
||||||
|
'source=pathlib.Path(sys.argv[1]); stage=pathlib.Path(sys.argv[2])',
|
||||||
|
'expected_archive=sys.argv[3]; expected_manifest=sys.argv[4].encode()',
|
||||||
|
'entries=json.loads(sys.argv[5]); hashes=json.loads(sys.argv[6])',
|
||||||
|
"raw=source.read_bytes()",
|
||||||
|
"assert hashlib.sha256(raw).hexdigest()==expected_archive, 'source-sha256'",
|
||||||
|
"expected_files={'manifest.env','files.txt'}|{'payload/'+name for name in hashes}",
|
||||||
|
"expected_dirs={'payload'}",
|
||||||
|
"for name in hashes:",
|
||||||
|
" p=pathlib.PurePosixPath('payload/'+name)",
|
||||||
|
" expected_dirs.update(str(parent) for parent in p.parents if str(parent)!='.')",
|
||||||
|
"with tarfile.open(source,'r:gz') as tar:",
|
||||||
|
" members=tar.getmembers(); names={member.name for member in members}",
|
||||||
|
" assert names==expected_files|expected_dirs, 'source-member-set'",
|
||||||
|
" for member in members:",
|
||||||
|
" p=pathlib.PurePosixPath(member.name)",
|
||||||
|
" assert not p.is_absolute() and '..' not in p.parts and '\\\\' not in member.name, 'unsafe-member'",
|
||||||
|
" assert member.isdir() if member.name in expected_dirs else member.isfile(), 'unsafe-member-type'",
|
||||||
|
" assert tar.extractfile('manifest.env').read()==expected_manifest, 'source-manifest'",
|
||||||
|
" expected_list=('\\n'.join(entries)+'\\n').encode()",
|
||||||
|
" assert tar.extractfile('files.txt').read()==expected_list, 'source-files-list'",
|
||||||
|
" for name,wanted in hashes.items():",
|
||||||
|
" data=tar.extractfile('payload/'+name).read()",
|
||||||
|
" assert hashlib.sha256(data).hexdigest()==wanted, 'payload-sha256:'+name",
|
||||||
|
" target=stage/'payload'/name; target.parent.mkdir(parents=True,exist_ok=True); target.write_bytes(data)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip,io,pathlib,sys,tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, relative, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const workspaceRoot = resolve(platformRoot, '..')
|
||||||
|
const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts'))
|
||||||
|
const [patchId = '', ...extra] = process.argv.slice(2)
|
||||||
|
const previouslyIssuedPatchIds = new Set([
|
||||||
|
'engine-data-product-publish-grant-20260716-001',
|
||||||
|
'engine-data-product-publish-grant-20260717-001',
|
||||||
|
'engine-data-product-publish-grant-20260717-002',
|
||||||
|
])
|
||||||
|
const compositeProviderCatalogTargetSha256 = '9c931f9abfcadb5b34a8a854c2efb8fd79913e000eecf0967d1b7c500bf9a56a'
|
||||||
|
|
||||||
|
if (extra.length || !/^engine-data-product-publish-grant-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error('usage: build-engine-data-product-publish-grant-artifact.mjs <fresh-patch-id>')
|
||||||
|
}
|
||||||
|
if (previouslyIssuedPatchIds.has(patchId)) throw new Error('engine_publish_grant_patch_id_already_issued')
|
||||||
|
|
||||||
|
// Deliberately exclude frontend/dist, runtime data, tests, every credential
|
||||||
|
// value, and the already-installed credential-sink implementation. The sink
|
||||||
|
// remains mounted and byte-frozen as the predecessor domain; this artifact
|
||||||
|
// adds the exact Data Product Publish grant flow beside it.
|
||||||
|
const entries = Object.freeze([
|
||||||
|
'nodedc-source/server/assets/provider-packages/v1/catalog.json',
|
||||||
|
'nodedc-source/server/dataProductPublishGrant',
|
||||||
|
'nodedc-source/server/engineAgents/store.js',
|
||||||
|
'nodedc-source/server/routes/engineAgentGateway.js',
|
||||||
|
'nodedc-source/server/routes/n8n.js',
|
||||||
|
'nodedc-source/services/backend/data-product-publish-grant/docker-compose.immutable-runtime.yml',
|
||||||
|
])
|
||||||
|
const ignoredBasenames = new Set(['.DS_Store', '.git', 'node_modules'])
|
||||||
|
const credentialSinkPredecessorSha256 = Object.freeze({
|
||||||
|
'docker-compose.yml': '258cebb64ff1943c939655cc55bdce00fc5c4dced67ec291d84d6df066ace50e',
|
||||||
|
'nodedc-source/server/credentialPolicies/ndcPrivateNode.js': '723874a02dc7b8a68b22ff2304431cfe64f28933cedf5f1e6cda79b2e1cf704a',
|
||||||
|
'nodedc-source/server/credentialSink/core.js': '9f0facc41fd398fcd955cffdd486abb126cdcd756c87ffde667fcbe00e2c41d3',
|
||||||
|
'nodedc-source/server/credentialSink/requestAuth.js': 'f8c9237c3e6f4219dee0d4f956d6e97f76f5bd7ba8a6fd0b4fb21aceffa38138',
|
||||||
|
'nodedc-source/server/credentialSink/store.js': 'c78dc285a973b6acd8a2330f0310935ad08720b2905454492f292d235abf12c0',
|
||||||
|
'nodedc-source/server/credentialSink/vendor/engine-credential-sink.mjs': 'b4800eead9bf94793ff1280d06e34aad6b37ef055a9d7f8d83d7fb5f9bd66d8b',
|
||||||
|
'nodedc-source/server/index.js': 'b2b790b02839570d967a2ca68b00e2724485a99389ac9b3a589a1b22302a36b8',
|
||||||
|
'nodedc-source/server/routes/engineCredentialSink.js': '9cbb69dbc8cbe6181cd5b0170fe9c4d717b0a173866ca98cba3e3766c0bab94e',
|
||||||
|
'nodedc-source/server/routes/ndcAgentMcp.js': '534e2c85e1faecc72a00da7ad32d0584ee09b6bd89eeec2221c3b23d80e1e962',
|
||||||
|
'nodedc-source/services/backend/credential-sink/docker-compose.immutable-runtime.yml': '944fa64b08255eb8207b93fd327aebb98ecd9400d37d25fcfa8e3a040ee44afe',
|
||||||
|
})
|
||||||
|
const publishGrantRuntimeOverride = [
|
||||||
|
'services:',
|
||||||
|
' nodedc-backend:',
|
||||||
|
' user: "0:0"',
|
||||||
|
' environment:',
|
||||||
|
' ENGINE_DATA_PLANE_BASE_URL: http://external-data-plane:18106',
|
||||||
|
' ENGINE_EDP_MANAGED_PROVISIONER_PRIVATE_KEY_FILE: /run/nodedc-secrets/engine-edp-managed-provisioner-private.pem',
|
||||||
|
' ENGINE_CONTROL_PLANE_PUBLISH_GRANT_ROOT: /var/lib/nodedc-control-plane/publish-grants',
|
||||||
|
' volumes:',
|
||||||
|
' - type: bind',
|
||||||
|
' source: /volume2/nodedc-demo/nodedc-control-plane/publish-grants',
|
||||||
|
' target: /var/lib/nodedc-control-plane/publish-grants',
|
||||||
|
' bind:',
|
||||||
|
' create_host_path: false',
|
||||||
|
' - type: bind',
|
||||||
|
' source: /volume1/docker/nodedc-platform/secrets/engine-edp-managed-provisioner/private-key.pem',
|
||||||
|
' target: /run/nodedc-secrets/engine-edp-managed-provisioner-private.pem',
|
||||||
|
' read_only: true',
|
||||||
|
' bind:',
|
||||||
|
' create_host_path: false',
|
||||||
|
'',
|
||||||
|
].join('\n')
|
||||||
|
|
||||||
|
await assertSourceBoundary()
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`)
|
||||||
|
await assertArtifactTargetFresh(artifact)
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-publish-grant-artifact-'))
|
||||||
|
const payload = join(stage, 'payload')
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true })
|
||||||
|
for (const entry of entries) {
|
||||||
|
await copySafe(resolve(engineRoot, entry), join(payload, entry))
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, 'manifest.env'),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8')
|
||||||
|
run('python3', ['-c', canonicalTarScript(), artifact, stage])
|
||||||
|
const sha256 = digest(await readFile(artifact))
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256,
|
||||||
|
entries,
|
||||||
|
excluded: [
|
||||||
|
'docker-compose.yml',
|
||||||
|
'nodedc-source/server/index.js',
|
||||||
|
'nodedc-source/server/credentialPolicies/ndcPrivateNode.js',
|
||||||
|
'nodedc-source/server/credentialSink',
|
||||||
|
'nodedc-source/server/routes/engineCredentialSink.js',
|
||||||
|
'nodedc-source/server/middleware/demoAccess.js',
|
||||||
|
'nodedc-source/server/routes/ndcAgentMcp.js',
|
||||||
|
'nodedc-source/server/data',
|
||||||
|
'nodedc-source/dist',
|
||||||
|
'nodedc-source/server/tests',
|
||||||
|
],
|
||||||
|
providerPackage: 'gelios.provider.v4',
|
||||||
|
providerRequests: [
|
||||||
|
'https://api.geliospro.com/api/v1/users/me/monitoring-config',
|
||||||
|
'https://api.geliospro.com/api/v1/units?incltrip=true',
|
||||||
|
],
|
||||||
|
dataProductId: 'fleet.positions.current.v3',
|
||||||
|
credentialValues: 'preserved',
|
||||||
|
preservedPredecessor: Object.keys(credentialSinkPredecessorSha256),
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertSourceBoundary() {
|
||||||
|
// These files are deliberately excluded from the artifact. Their exact
|
||||||
|
// installed predecessor is verified by the root-owned runner during plan
|
||||||
|
// and apply; the local builder only proves that it cannot package a link or
|
||||||
|
// another unsafe filesystem object in their place.
|
||||||
|
for (const relativePath of Object.keys(credentialSinkPredecessorSha256)) {
|
||||||
|
const info = await lstat(join(engineRoot, relativePath))
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_credential_sink_predecessor_unsafe:${relativePath}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const runtimeOverridePath = join(
|
||||||
|
engineRoot,
|
||||||
|
'nodedc-source/services/backend/data-product-publish-grant/docker-compose.immutable-runtime.yml',
|
||||||
|
)
|
||||||
|
if (await readFile(runtimeOverridePath, 'utf8') !== publishGrantRuntimeOverride) {
|
||||||
|
throw new Error('engine_publish_grant_runtime_override_mismatch')
|
||||||
|
}
|
||||||
|
const catalogPath = join(
|
||||||
|
engineRoot,
|
||||||
|
'nodedc-source/server/assets/provider-packages/v1/catalog.json',
|
||||||
|
)
|
||||||
|
if (digest(await readFile(catalogPath)) !== compositeProviderCatalogTargetSha256) {
|
||||||
|
throw new Error('engine_composite_provider_catalog_target_mismatch')
|
||||||
|
}
|
||||||
|
|
||||||
|
const indexSource = await readFile(join(engineRoot, 'nodedc-source/server/index.js'), 'utf8')
|
||||||
|
if (!indexSource.includes("app.use('/api/engine-agent-mcp', engineAgentMcpRouter)")) {
|
||||||
|
throw new Error('engine_agent_mcp_mount_missing')
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!indexSource.includes("import engineCredentialSinkRouter from './routes/engineCredentialSink.js'")
|
||||||
|
|| !indexSource.includes("app.use('/internal/engine-credential-sink', express.json({")
|
||||||
|
) throw new Error('engine_credential_sink_predecessor_mount_missing')
|
||||||
|
|
||||||
|
const gateway = await readFile(join(engineRoot, 'nodedc-source/server/routes/engineAgentGateway.js'), 'utf8')
|
||||||
|
for (const tool of [
|
||||||
|
'engine_plan_data_product_publish_grant',
|
||||||
|
'engine_apply_data_product_publish_grant',
|
||||||
|
'engine_accept_data_product_publish_grant',
|
||||||
|
'engine_rollback_data_product_publish_grant',
|
||||||
|
]) {
|
||||||
|
if (!gateway.includes(tool)) throw new Error(`engine_publish_grant_tool_missing:${tool}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const n8nRoute = await readFile(join(engineRoot, 'nodedc-source/server/routes/n8n.js'), 'utf8')
|
||||||
|
if (n8nRoute.includes("from '../credentialSink/")) {
|
||||||
|
throw new Error('engine_publish_grant_depends_on_legacy_sink')
|
||||||
|
}
|
||||||
|
if (!n8nRoute.includes('engineDataProductPublishGrantN8nAdapter')) {
|
||||||
|
throw new Error('engine_publish_grant_native_adapter_missing')
|
||||||
|
}
|
||||||
|
if (!n8nRoute.includes('engineCredentialSinkN8nAdapter')) {
|
||||||
|
throw new Error('engine_credential_sink_native_adapter_missing')
|
||||||
|
}
|
||||||
|
|
||||||
|
const grantDirectory = join(engineRoot, 'nodedc-source/server/dataProductPublishGrant')
|
||||||
|
const grantFiles = (await readdir(grantDirectory, { withFileTypes: true }))
|
||||||
|
.filter((entry) => entry.isFile())
|
||||||
|
.map((entry) => entry.name)
|
||||||
|
.sort()
|
||||||
|
const expectedGrantFiles = [
|
||||||
|
'acceptance.js',
|
||||||
|
'providerCatalog.js',
|
||||||
|
'service.js',
|
||||||
|
'signedDataPlaneClient.js',
|
||||||
|
'store.js',
|
||||||
|
]
|
||||||
|
if (JSON.stringify(grantFiles) !== JSON.stringify(expectedGrantFiles)) {
|
||||||
|
throw new Error('engine_publish_grant_source_set_mismatch')
|
||||||
|
}
|
||||||
|
const providerCatalogSource = await readFile(join(grantDirectory, 'providerCatalog.js'), 'utf8')
|
||||||
|
const grantServiceSource = await readFile(join(grantDirectory, 'service.js'), 'utf8')
|
||||||
|
const grantStoreSource = await readFile(join(grantDirectory, 'store.js'), 'utf8')
|
||||||
|
for (const marker of [
|
||||||
|
'function capabilityRequests(capability)',
|
||||||
|
'function exactHttpRequestUrl(n8n)',
|
||||||
|
'capabilityIds',
|
||||||
|
'providerRequestNodeIds',
|
||||||
|
'providerCredentialRefs.size !== 1',
|
||||||
|
]) {
|
||||||
|
if (!providerCatalogSource.includes(marker)) {
|
||||||
|
throw new Error(`engine_composite_provider_resolver_missing:${marker}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!grantServiceSource.includes('capabilities: descriptor.capabilityIds')
|
||||||
|
|| !grantServiceSource.includes('providerRequestNodeIds: descriptor.providerRequestNodeIds')
|
||||||
|
) {
|
||||||
|
throw new Error('engine_composite_provider_plan_projection_missing')
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!grantStoreSource.includes('Array.isArray(raw.capabilityIds)')
|
||||||
|
|| !grantStoreSource.includes('Array.isArray(raw.providerRequestNodeIds)')
|
||||||
|
) {
|
||||||
|
throw new Error('engine_composite_provider_store_projection_missing')
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
const source = resolve(engineRoot, entry)
|
||||||
|
const info = await lstat(source)
|
||||||
|
if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory())) {
|
||||||
|
throw new Error(`engine_artifact_source_unsafe:${entry}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const source of [
|
||||||
|
...expectedGrantFiles.map((name) => join(grantDirectory, name)),
|
||||||
|
join(engineRoot, 'nodedc-source/server/routes/engineAgentGateway.js'),
|
||||||
|
join(engineRoot, 'nodedc-source/server/routes/n8n.js'),
|
||||||
|
join(engineRoot, 'nodedc-source/server/routes/ndcAgentMcp.js'),
|
||||||
|
join(engineRoot, 'nodedc-source/server/engineAgents/store.js'),
|
||||||
|
]) run('node', ['--check', source])
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertArtifactTargetFresh(target) {
|
||||||
|
try {
|
||||||
|
await lstat(target)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('engine_publish_grant_artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copySafe(source, destination) {
|
||||||
|
const info = await lstat(source)
|
||||||
|
if (info.isSymbolicLink()) throw new Error(`source_symlink_rejected:${source}`)
|
||||||
|
if (info.isFile()) {
|
||||||
|
await mkdir(dirname(destination), { recursive: true })
|
||||||
|
await cp(source, destination, { force: false, verbatimSymlinks: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!info.isDirectory()) throw new Error(`source_type_rejected:${source}`)
|
||||||
|
await mkdir(destination, { recursive: true })
|
||||||
|
for (const entry of await readdir(source, { withFileTypes: true })) {
|
||||||
|
if (ignoredBasenames.has(entry.name) || entry.name.startsWith('.env')) continue
|
||||||
|
const childSource = join(source, entry.name)
|
||||||
|
if (entry.isSymbolicLink()) {
|
||||||
|
throw new Error(`source_symlink_rejected:${relative(engineRoot, childSource)}`)
|
||||||
|
}
|
||||||
|
await copySafe(childSource, join(destination, entry.name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip, io, pathlib, sys, tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1], 'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='', mode='wb', fileobj=out, compresslevel=9, mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p] + (sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
' for x in paths:',
|
||||||
|
" info=tar.gettarinfo(str(x), arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info, src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^engine-depttrans-zone-authority-v1-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-depttrans-zone-authority-v1-artifact.mjs " +
|
||||||
|
"<engine-depttrans-zone-authority-v1-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"1aac712a05e55137d69eedaf363969460ffe866288e8e18e35711967ab232f39",
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/depttrans-zone-authority-v1.json":
|
||||||
|
"1482032178b4816e599df570face9b1dfa8ae1fa2943ac8f941c561e8cb9aa9d",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/providerCatalog.js":
|
||||||
|
"e4c216b0affd89ddbd48abcec86febd48eb12a4c56507851daeb47f2ccd60c9a",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/service.js":
|
||||||
|
"408836564e9a422eb5e648cc24d764f4bfdf7f83d93306742e8615fa8186a642",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/store.js":
|
||||||
|
"ace5971d0772e9a9499f0849e6b754e3677cc2ca3080e573a12e26acf5a6c0c0",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-depttrans-zone-authority-v1-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "exact-platform-service-authority-v1",
|
||||||
|
providerPackage: "moscow-department-of-transport.pmd-slow-zones.v1",
|
||||||
|
dataProductId: "map.zones.current.v2",
|
||||||
|
authorityBoundary: "platform-service",
|
||||||
|
platformService: "nodedc-map-gateway",
|
||||||
|
credentialValues: "preserved",
|
||||||
|
untouched: ["n8n", "L1 graph", "Engine UI", "databases", "MCP Nginx"],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_depttrans_zone_authority_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_depttrans_zone_authority_target_mismatch:${relativePath}:` +
|
||||||
|
`expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const catalog = JSON.parse(await readFile(join(engineRoot, entries[0]), "utf8"));
|
||||||
|
const provider = catalog.packages?.find(
|
||||||
|
(item) => item.id === "moscow-department-of-transport.pmd-slow-zones.v1",
|
||||||
|
);
|
||||||
|
const request = provider?.capabilities?.[0]?.request;
|
||||||
|
if (
|
||||||
|
provider?.version !== "1.0.0"
|
||||||
|
|| provider?.providerId !== "moscow-department-of-transport"
|
||||||
|
|| provider?.providerCredential !== undefined
|
||||||
|
|| provider?.capabilities?.[0]?.dataProductIds?.[0] !== "map.zones.current.v2"
|
||||||
|
|| request?.authorityBoundary !== "platform-service"
|
||||||
|
|| request?.serviceId !== "nodedc-map-gateway"
|
||||||
|
|| request?.network !== "engine"
|
||||||
|
|| request?.url !== "http://map-gateway:18103/internal/zone-sources/v1/profiles/moscow-pmd-slow-zones/current"
|
||||||
|
) throw new Error("engine_depttrans_zone_authority_catalog_projection_mismatch");
|
||||||
|
|
||||||
|
const marker = JSON.parse(await readFile(join(engineRoot, entries[1]), "utf8"));
|
||||||
|
if (
|
||||||
|
marker?.schemaVersion !== "nodedc.engine.platform-service-authority/v1"
|
||||||
|
|| marker?.id !== provider.id
|
||||||
|
|| marker?.serviceId !== request.serviceId
|
||||||
|
|| marker?.dataProductId !== provider.capabilities[0].dataProductIds[0]
|
||||||
|
) throw new Error("engine_depttrans_zone_authority_marker_projection_mismatch");
|
||||||
|
const resolver = await readFile(join(engineRoot, entries[2]), "utf8");
|
||||||
|
const service = await readFile(join(engineRoot, entries[3]), "utf8");
|
||||||
|
const store = await readFile(join(engineRoot, entries[4]), "utf8");
|
||||||
|
for (const marker of [
|
||||||
|
"function platformServiceRequestIsExact",
|
||||||
|
"pinned_platform_service_no_graph_credential",
|
||||||
|
"platformServiceIds",
|
||||||
|
"publish_grant_provider_request_path_unreachable",
|
||||||
|
]) {
|
||||||
|
if (![resolver, service, store].some((source) => source.includes(marker))) {
|
||||||
|
throw new Error(`engine_depttrans_zone_authority_marker_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT
|
||||||
|
|| join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|
||||||
|
|| resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-l1-agent-init-concurrency-20260724-042", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-l1-agent-init-concurrency-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-l1-agent-init-concurrency-artifact.mjs "
|
||||||
|
+ "[engine-l1-agent-init-concurrency-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceCommit = "c4077fe0d8d824fa58616eeb986dc78ca43070da";
|
||||||
|
const predecessorSha256 = Object.freeze({
|
||||||
|
"nodedc-source/src/App.tsx":
|
||||||
|
"b3e61a89330b774f309660208d05143d299ab582f18765c1c14e2122a62c4d5e",
|
||||||
|
"nodedc-source/src/driveinspector/nodes/N8n.definition.ts":
|
||||||
|
"a4890cca12b269643ec3255c2fc6b7e2be96aa042ffc6087772e63cbf8323c3a",
|
||||||
|
"nodedc-source/src/nodes/N8nNode.tsx":
|
||||||
|
"a125f7cde66085008dafe5a340a1143094c59769573815851ce6c8adfe4c0220",
|
||||||
|
"nodedc-source/src/store.ts":
|
||||||
|
"2128cd582a947582bb7736792c3a71551712262ef04882c189220ec79f16fb8e",
|
||||||
|
"nodedc-source/dist/index.html":
|
||||||
|
"90d72f8790dc8cf951066b1210447c84d640373117bae23f3a4cb3227fb96d6d",
|
||||||
|
"nodedc-source/dist/assets/index-CqvJfRRS.js":
|
||||||
|
"06e6c23b03ea2ba8a4890e1f1714fd08ebaf18d735834200af6ab430af360ca8",
|
||||||
|
});
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/src/App.tsx":
|
||||||
|
"fc580dc3a1a97393af81dd75c54ae8b37db1f6fda8364042198493493b15f2c2",
|
||||||
|
"nodedc-source/src/driveinspector/nodes/N8n.definition.ts":
|
||||||
|
"945839541547b2fd02b5424954e00483d6c76f82a333d6a7a652ccd1b74d04cf",
|
||||||
|
"nodedc-source/src/nodes/N8nNode.tsx":
|
||||||
|
"1130e355d86e06a18df775b2d3517bfdbf98fdc494ca707d23c78648fbfd3cb4",
|
||||||
|
"nodedc-source/src/store.ts":
|
||||||
|
"46884488254c16cd3af9b25556dd0db4f5a3a20047abdb496db831f204e40673",
|
||||||
|
"nodedc-source/src/utils/workflowWriteQueue.js":
|
||||||
|
"41f73ccb5e1dafbdae501b7c0b9fa5c47fdbd52564061b9c4ca6ca1c75ceccdf",
|
||||||
|
"nodedc-source/dist/index.html":
|
||||||
|
"1554e2418aead13b56328c5721dd677400d84ee087559a88fe60b295b7ff5412",
|
||||||
|
"nodedc-source/dist/assets/index-r1_2ECzJ.js":
|
||||||
|
"0d25dd843da7078b8dbad5cb4b78724bf1ca8aa067e9d0add1e09ce8f421b822",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
|
||||||
|
assertSourceCommit();
|
||||||
|
await assertPredecessorSources();
|
||||||
|
await assertExactTargets();
|
||||||
|
await assertRuntimeContract();
|
||||||
|
await assertFresh(artifact);
|
||||||
|
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-l1-agent-init-"));
|
||||||
|
try {
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
sourceCommit,
|
||||||
|
predecessorSha256,
|
||||||
|
targetSha256,
|
||||||
|
entries,
|
||||||
|
services: ["nodedc-backend", "app"],
|
||||||
|
healthchecks: [
|
||||||
|
"http://127.0.0.1:8080/",
|
||||||
|
"http://127.0.0.1:3001/health",
|
||||||
|
],
|
||||||
|
concurrencyContract: "per-workflow-fifo-latest-revision-v1",
|
||||||
|
n8nCoreChanged: false,
|
||||||
|
untouched: [
|
||||||
|
"n8n runtime",
|
||||||
|
"L1 workflow data",
|
||||||
|
"L2 workflow data",
|
||||||
|
"credentials",
|
||||||
|
"databases",
|
||||||
|
"MCP catalogs",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSourceCommit() {
|
||||||
|
const actual = run("git", ["-C", engineRoot, "rev-parse", "HEAD"]).stdout.trim();
|
||||||
|
if (actual !== sourceCommit) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l1_agent_init_source_commit_mismatch:`
|
||||||
|
+ `expected=${sourceCommit}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertPredecessorSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(predecessorSha256)) {
|
||||||
|
const result = run("git", [
|
||||||
|
"-C",
|
||||||
|
engineRoot,
|
||||||
|
"show",
|
||||||
|
`${sourceCommit}:${relativePath}`,
|
||||||
|
]);
|
||||||
|
const actual = digest(result.stdoutBuffer);
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l1_agent_init_predecessor_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const newFile = "nodedc-source/src/utils/workflowWriteQueue.js";
|
||||||
|
const probe = spawnSync(
|
||||||
|
"git",
|
||||||
|
["-C", engineRoot, "cat-file", "-e", `${sourceCommit}:${newFile}`],
|
||||||
|
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
|
||||||
|
);
|
||||||
|
if (probe.status === 0) {
|
||||||
|
throw new Error("engine_l1_agent_init_queue_not_new");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactTargets() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const source = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(source);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_l1_agent_init_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(source));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l1_agent_init_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertRuntimeContract() {
|
||||||
|
const app = await readFile(join(engineRoot, "nodedc-source/src/App.tsx"), "utf8");
|
||||||
|
const definition = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/src/driveinspector/nodes/N8n.definition.ts"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const store = await readFile(join(engineRoot, "nodedc-source/src/store.ts"), "utf8");
|
||||||
|
const node = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/src/nodes/N8nNode.tsx"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const queue = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/src/utils/workflowWriteQueue.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const index = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/dist/index.html"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!app.includes("createWorkflowWriteQueue")
|
||||||
|
|| !app.includes("putExistingWorkflow")
|
||||||
|
|| !app.includes("expectedRevision: currentWorkflowRevisionRef.current")
|
||||||
|
|| !queue.includes("previous.catch(() => undefined).then(() => operation())")
|
||||||
|
|| !definition.includes("nodeName: 'NDC'")
|
||||||
|
|| !definition.includes("default: 'NDC'")
|
||||||
|
|| !definition.includes("data?.title || data?.nodeName || 'NDC'")
|
||||||
|
|| !store.includes("nodeName: 'NDC'")
|
||||||
|
|| !node.includes("data?.nodeName ?? 'NDC'")
|
||||||
|
|| !index.includes("/assets/index-r1_2ECzJ.js")
|
||||||
|
|| /gelios|robot2b/i.test(queue)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_l1_agent_init_runtime_contract_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: null,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(
|
||||||
|
`${command}_failed:${Buffer.from(result.stderr || "").toString("utf8")}`
|
||||||
|
+ `${Buffer.from(result.stdout || "").toString("utf8")}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
stdoutBuffer: Buffer.from(result.stdout || ""),
|
||||||
|
stderrBuffer: Buffer.from(result.stderr || ""),
|
||||||
|
stdout: Buffer.from(result.stdout || "").toString("utf8"),
|
||||||
|
stderr: Buffer.from(result.stderr || "").toString("utf8"),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
cp,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(here, "../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, "../NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const baselineArtifact = resolve(
|
||||||
|
here,
|
||||||
|
"../deploy-artifacts/nodedc-engine-provider-authority-diagnostics-20260723-029.tgz",
|
||||||
|
);
|
||||||
|
const baselineArtifactSha256 =
|
||||||
|
"b4a0a1f707bf9814a4decc3f7f261b8afffe5727af2129c14bcdc76f81675e38";
|
||||||
|
const descriptorRel =
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json";
|
||||||
|
const baselineDescriptorSha256 =
|
||||||
|
"84b0e15a10cedf334ad04d6f31c908da2dc155503c9974f0eeb75b01e20fb884";
|
||||||
|
const predecessorGatewaySha256 =
|
||||||
|
"5331f6dc8dc306f641370a2968eb025ee3e278e27ae9a217e4cfc2901fec369c";
|
||||||
|
const targetGatewaySha256 =
|
||||||
|
"4f600a2781be9118bec891fa2a6f20d7f55e0892ef2f06af24059193cebd28f4";
|
||||||
|
const targetDescriptorSha256 =
|
||||||
|
"63e7619c6971d02102583bb5d80d33ece293b952f113200fa0b76f0e88c2dd32";
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^engine-l2-closed-loop-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-l2-closed-loop-artifact.mjs " +
|
||||||
|
"<engine-l2-closed-loop-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceCommit = "dda405cff27977622af0c218abb4d4420c408536";
|
||||||
|
const entries = Object.freeze([
|
||||||
|
"nodedc-source/server/index.js",
|
||||||
|
"nodedc-source/server/l2/graphRepository.js",
|
||||||
|
"nodedc-source/server/realtime/ws.js",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js",
|
||||||
|
"nodedc-source/server/routes/n8n.js",
|
||||||
|
"nodedc-source/server/routes/ndcAgentMcp.js",
|
||||||
|
"nodedc-source/src/App.tsx",
|
||||||
|
"nodedc-source/src/n8n/N8nSubworkflowHost.tsx",
|
||||||
|
"nodedc-source/src/realtime/useMultiplayer.ts",
|
||||||
|
"nodedc-source/src/utils/n8nApi.ts",
|
||||||
|
"nodedc-source/dist/index.html",
|
||||||
|
"nodedc-source/dist/assets",
|
||||||
|
descriptorRel,
|
||||||
|
]);
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/index.js":
|
||||||
|
"1896e1cade61579863c50ff3f52f2e81ff27f2a511a9d362db81925ee21cefad",
|
||||||
|
"nodedc-source/server/l2/graphRepository.js":
|
||||||
|
"94ad08e1bb7e7be04854f1f911e06ee1acd6e09631f33f4c01e42e230665ac33",
|
||||||
|
"nodedc-source/server/realtime/ws.js":
|
||||||
|
"82cfa833e05c2fc6d6049dd4564af06164b5c784fdfb82c243ca67519f4509c2",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js":
|
||||||
|
"4f600a2781be9118bec891fa2a6f20d7f55e0892ef2f06af24059193cebd28f4",
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"752cb1524160adc1c95163c34e139b615c063d2ce8980f2a63879bddbd0f1e08",
|
||||||
|
"nodedc-source/server/routes/ndcAgentMcp.js":
|
||||||
|
"353a10291ceb93c3641ece60ec6e809a394be86f5ceb97cb44755178940409dd",
|
||||||
|
"nodedc-source/src/App.tsx":
|
||||||
|
"b3e61a89330b774f309660208d05143d299ab582f18765c1c14e2122a62c4d5e",
|
||||||
|
"nodedc-source/src/n8n/N8nSubworkflowHost.tsx":
|
||||||
|
"683aa44ba92aeac4879889e2bdb5319282976d7680d620701578830ce9677087",
|
||||||
|
"nodedc-source/src/realtime/useMultiplayer.ts":
|
||||||
|
"a4d001d9914098e50a78d8abe0a66344d23680b7a19b3573aa7b6f48c8bb9c35",
|
||||||
|
"nodedc-source/src/utils/n8nApi.ts":
|
||||||
|
"6f16d4992c51ffcc1e71a7bd172fd9ceb440d6e1a74d69ef1db62e0ac4230b3c",
|
||||||
|
"nodedc-source/dist/index.html":
|
||||||
|
"90d72f8790dc8cf951066b1210447c84d640373117bae23f3a4cb3227fb96d6d",
|
||||||
|
"nodedc-source/dist/assets/index-Bim2pv1P.css":
|
||||||
|
"18322addd45c126a7b8396f36b005f3085fddba3e9b346dd2c910f6fa6987ebf",
|
||||||
|
"nodedc-source/dist/assets/index-CqvJfRRS.js":
|
||||||
|
"06e6c23b03ea2ba8a4890e1f1714fd08ebaf18d735834200af6ab430af360ca8",
|
||||||
|
[descriptorRel]: targetDescriptorSha256,
|
||||||
|
});
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
assertSourceCommit();
|
||||||
|
await assertExactSources();
|
||||||
|
const targetDescriptor = await buildTargetDescriptor();
|
||||||
|
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-l2-closed-loop-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
if (relativePath === descriptorRel) {
|
||||||
|
await writeFile(destination, targetDescriptor, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const source = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(source);
|
||||||
|
if (info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_l2_closed_loop_source_symlink:${relativePath}`);
|
||||||
|
}
|
||||||
|
if (info.isDirectory()) {
|
||||||
|
await cp(source, destination, {
|
||||||
|
recursive: true,
|
||||||
|
force: false,
|
||||||
|
errorOnExist: true,
|
||||||
|
});
|
||||||
|
} else if (info.isFile()) {
|
||||||
|
await copyFile(source, destination);
|
||||||
|
} else {
|
||||||
|
throw new Error(`engine_l2_closed_loop_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
sourceCommit,
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend", "app"],
|
||||||
|
healthchecks: [
|
||||||
|
"http://127.0.0.1:8080/",
|
||||||
|
"http://127.0.0.1:3001/health",
|
||||||
|
],
|
||||||
|
mcpVersion: "0.7.0",
|
||||||
|
graphContract: "semantic-revision-cas-v1",
|
||||||
|
transition: "failed-030-partial-source-reconciliation",
|
||||||
|
predecessorDescriptorSha256: baselineDescriptorSha256,
|
||||||
|
targetDescriptorSha256,
|
||||||
|
predecessorGatewaySha256,
|
||||||
|
targetGatewaySha256,
|
||||||
|
recoveryArtifact: "nodedc-engine-l2-closed-loop-20260723-030.tgz",
|
||||||
|
actorPlanes: ["external_codex_mcp", "ai_workspace", "engine_ui"],
|
||||||
|
untouched: [
|
||||||
|
"L2 graph data",
|
||||||
|
"credentials",
|
||||||
|
"databases",
|
||||||
|
"n8n runtime",
|
||||||
|
"AI Workspace connector",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSourceCommit() {
|
||||||
|
const actual = run("git", ["-C", engineRoot, "rev-parse", "HEAD"]).stdout.trim();
|
||||||
|
if (actual !== sourceCommit) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l2_closed_loop_source_commit_mismatch:expected=${sourceCommit}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
const sourceEntries = entries.filter((entry) => entry !== descriptorRel);
|
||||||
|
const expectedPaths = Object.keys(targetSha256)
|
||||||
|
.filter((entry) => entry !== descriptorRel)
|
||||||
|
.sort();
|
||||||
|
const actualPaths = [];
|
||||||
|
for (const entry of sourceEntries) {
|
||||||
|
const source = join(engineRoot, entry);
|
||||||
|
const info = await lstat(source);
|
||||||
|
if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory())) {
|
||||||
|
throw new Error(`engine_l2_closed_loop_source_unsafe:${entry}`);
|
||||||
|
}
|
||||||
|
if (info.isDirectory()) {
|
||||||
|
const result = run("find", [source, "-type", "f", "-print"]);
|
||||||
|
for (const path of result.stdout.split("\n").filter(Boolean)) {
|
||||||
|
actualPaths.push(path.slice(engineRoot.length + 1));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
actualPaths.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
actualPaths.sort();
|
||||||
|
if (JSON.stringify(actualPaths) !== JSON.stringify(expectedPaths)) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l2_closed_loop_source_set_mismatch:` +
|
||||||
|
`expected=${expectedPaths.join(",")}:actual=${actualPaths.join(",")}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const relativePath of expectedPaths) {
|
||||||
|
const actual = digest(await readFile(join(engineRoot, relativePath)));
|
||||||
|
if (actual !== targetSha256[relativePath]) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l2_closed_loop_target_mismatch:${relativePath}:` +
|
||||||
|
`expected=${targetSha256[relativePath]}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildTargetDescriptor() {
|
||||||
|
const baselineBytes = await readFile(baselineArtifact);
|
||||||
|
if (digest(baselineBytes) !== baselineArtifactSha256) {
|
||||||
|
throw new Error("engine_l2_closed_loop_baseline_artifact_mismatch");
|
||||||
|
}
|
||||||
|
const baseline = run("tar", [
|
||||||
|
"-xOf",
|
||||||
|
baselineArtifact,
|
||||||
|
`payload/${descriptorRel}`,
|
||||||
|
]).stdout;
|
||||||
|
if (digest(Buffer.from(baseline, "utf8")) !== baselineDescriptorSha256) {
|
||||||
|
throw new Error("engine_l2_closed_loop_baseline_descriptor_mismatch");
|
||||||
|
}
|
||||||
|
const descriptor = JSON.parse(baseline);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion !==
|
||||||
|
"nodedc.engine-node-intelligence-transition/v1" ||
|
||||||
|
descriptor?.action !== "activate" ||
|
||||||
|
descriptor?.releaseId !== "2.33.2-974a9fb3492f" ||
|
||||||
|
descriptor?.source?.gatewaySha256 !== predecessorGatewaySha256 ||
|
||||||
|
descriptor?.source?.upstreamProjectionSha256 !==
|
||||||
|
"2dfa6b4f37d9bfa8b92a8109d4060d02dd2634ceb8f7924504b83ccf3fdd1523"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_l2_closed_loop_baseline_descriptor_contract_mismatch");
|
||||||
|
}
|
||||||
|
descriptor.source.gatewaySha256 = targetGatewaySha256;
|
||||||
|
const rendered = `${JSON.stringify(descriptor, null, 2)}\n`;
|
||||||
|
if (digest(Buffer.from(rendered, "utf8")) !== targetDescriptorSha256) {
|
||||||
|
throw new Error("engine_l2_closed_loop_target_descriptor_mismatch");
|
||||||
|
}
|
||||||
|
return rendered;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, '../NODEDC_ENGINE_INFRA'),
|
||||||
|
)
|
||||||
|
const canonicalArtifactRoot = resolve(here, '../deploy-artifacts')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || canonicalArtifactRoot)
|
||||||
|
const [transitionId = '20260720-004', ...extra] = process.argv.slice(2)
|
||||||
|
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
|
||||||
|
throw new Error('usage: build-engine-mcp-autonomy-provider-v5-artifact.mjs [YYYYMMDD-NNN]')
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `engine-mcp-autonomy-provider-v5-${transitionId}`
|
||||||
|
const target = join(artifactRoot, `nodedc-${id}.tgz`)
|
||||||
|
const predecessorArtifact = join(
|
||||||
|
canonicalArtifactRoot,
|
||||||
|
'nodedc-engine-mcp-control-plane-20260718-003.tgz',
|
||||||
|
)
|
||||||
|
const predecessorArtifactSha256 = '249aef9527666c562e9648b15737e66cc5c1dc7c0788b58ea714da270b5eb4ba'
|
||||||
|
const descriptorRel = 'nodedc-source/services/node-intelligence/activation.json'
|
||||||
|
const gatewayRel = 'nodedc-source/server/routes/engineAgentGateway.js'
|
||||||
|
const files = [
|
||||||
|
'nodedc-source/server/assets/engine-agent-npm/bin/nodedc-engine-codex-agent.mjs',
|
||||||
|
'nodedc-source/server/assets/engine-agent-npm/package.json',
|
||||||
|
'nodedc-source/server/assets/nodedc-engine-codex-agent-0.1.6.tgz',
|
||||||
|
'nodedc-source/server/assets/provider-packages/v1/catalog.json',
|
||||||
|
'nodedc-source/server/engineAgents/store.js',
|
||||||
|
gatewayRel,
|
||||||
|
descriptorRel,
|
||||||
|
]
|
||||||
|
const expectedSha256 = new Map([
|
||||||
|
[files[0], 'c15c9da4f90f44a4e9e12f3683127e906d614fb98e562faa0c939505c973e074'],
|
||||||
|
[files[1], '2ca8dcab0fa04bb1b21add1f75a9be61d5aa97753443ee1917302b4e0da5780a'],
|
||||||
|
[files[2], 'd007a81cb4e4af569b3c54d3869b0f60b5597e3b531bff232145fa1851d8572a'],
|
||||||
|
[files[3], '63e0741646197f0b1b3c64a4095e1bc8fb3a95ee6caf20b0293f89d869c9e620'],
|
||||||
|
[files[4], '4cd4bdd5958cfafee184e98a04fe12aa0c1cbe884326beaec63c99f9fff61285'],
|
||||||
|
[files[5], '5331f6dc8dc306f641370a2968eb025ee3e278e27ae9a217e4cfc2901fec369c'],
|
||||||
|
])
|
||||||
|
|
||||||
|
await assertFresh(target)
|
||||||
|
assertSha(await readFile(predecessorArtifact), predecessorArtifactSha256, 'predecessor MCP artifact')
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-mcp-autonomy-provider-v5-'))
|
||||||
|
const payload = join(stage, 'payload')
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true })
|
||||||
|
for (const rel of files.slice(0, -1)) {
|
||||||
|
const source = join(engineRoot, rel)
|
||||||
|
const stat = await lstat(source)
|
||||||
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`source_boundary_invalid:${rel}`)
|
||||||
|
assertSha(await readFile(source), expectedSha256.get(rel), rel)
|
||||||
|
await mkdir(dirname(join(payload, rel)), { recursive: true })
|
||||||
|
await cp(source, join(payload, rel), { force: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(extractMember(
|
||||||
|
predecessorArtifact,
|
||||||
|
`payload/${descriptorRel}`,
|
||||||
|
))
|
||||||
|
if (
|
||||||
|
descriptor?.action !== 'activate'
|
||||||
|
|| descriptor?.releaseId !== '2.33.2-974a9fb3492f'
|
||||||
|
|| descriptor?.source?.gatewaySha256 !== '96c726dab5cf1341f74e6e1095d518058ca320e0dd5738e25bdbe75db1f4fc15'
|
||||||
|
|| descriptor?.source?.upstreamProjectionSha256 !== '761a874b102a938bc6018159ddacdaac71ad6ae08e9f0f8d7f3b58a0165a5131'
|
||||||
|
) throw new Error('mcp_autonomy_predecessor_descriptor_mismatch')
|
||||||
|
descriptor.source.gatewaySha256 = expectedSha256.get(gatewayRel)
|
||||||
|
await mkdir(dirname(join(payload, descriptorRel)), { recursive: true })
|
||||||
|
await writeFile(join(payload, descriptorRel), `${JSON.stringify(descriptor, null, 2)}\n`, 'utf8')
|
||||||
|
|
||||||
|
await writeFile(join(stage, 'manifest.env'), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, 'utf8')
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${files.join('\n')}\n`, 'utf8')
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
run('python3', ['-c', canonicalTarScript(), target, stage])
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
id,
|
||||||
|
artifact: target,
|
||||||
|
artifactSha256: sha(await readFile(target)),
|
||||||
|
services: ['nodedc-backend'],
|
||||||
|
mcpVersion: '0.6.0',
|
||||||
|
installerVersion: '0.1.6',
|
||||||
|
authority: 'mcp-capability-intersect-user-objective',
|
||||||
|
retryBoundary: 'three-identical-failures-without-new-evidence',
|
||||||
|
providerPackages: ['gelios.provider.v4', 'gelios.provider.v5'],
|
||||||
|
targetDataProduct: 'fleet.positions.current.v4',
|
||||||
|
preserved: ['n8n', 'L1', 'node-intelligence image', 'databases', 'credential values'],
|
||||||
|
files,
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractMember(archive, member) {
|
||||||
|
const script = [
|
||||||
|
'import pathlib,sys,tarfile',
|
||||||
|
'p=pathlib.Path(sys.argv[1]); name=sys.argv[2]',
|
||||||
|
"with tarfile.open(p,'r:gz') as t:",
|
||||||
|
' m=t.getmember(name)',
|
||||||
|
" if not m.isfile(): raise SystemExit('member-not-file')",
|
||||||
|
' f=t.extractfile(m)',
|
||||||
|
" if f is None: raise SystemExit('member-unreadable')",
|
||||||
|
' sys.stdout.buffer.write(f.read())',
|
||||||
|
].join('\n')
|
||||||
|
return run('python3', ['-c', script, archive, member]).stdout
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip,io,pathlib,sys,tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
' for x in paths:',
|
||||||
|
' info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())',
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSha(bytes, expected, label) {
|
||||||
|
const actual = sha(bytes)
|
||||||
|
if (!expected || actual !== expected) throw new Error(`${label.replaceAll(' ', '_')}_sha256_mismatch:${actual}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT
|
||||||
|
|| join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-mcp-classified-aspects-20260724-039", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (extra.length || !/^engine-mcp-classified-aspects-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-classified-aspects-artifact.mjs "
|
||||||
|
+ "[engine-mcp-classified-aspects-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = Object.freeze([
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/compiler.js",
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json",
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json",
|
||||||
|
]);
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/compiler.js":
|
||||||
|
"4854a62fb44cb3dd715f2cb8728740575453a666f5c31abe9d41bc2562be5e95",
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"2e70b607b4a347592ce2f4732f6da0781ac94ec4829ac336021cb501fdafe9aa",
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"2fce1c623a8acf9c01a43463e6d38eda71ad28379a2d91b2ca40f31f8dccf3c6",
|
||||||
|
});
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-classified-aspects-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertEngineBoundary();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const source = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(source);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`source_file_rejected:${relativePath}`);
|
||||||
|
}
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(source, destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend", "app"],
|
||||||
|
engineCorePolicy: "provider-neutral-scalar-visibility-guards",
|
||||||
|
providerPackage: "gelios.provider.v10",
|
||||||
|
files,
|
||||||
|
expectedSha256,
|
||||||
|
untouched: [
|
||||||
|
"live L2 graphs",
|
||||||
|
"n8n L1",
|
||||||
|
"Engine UI source and dist",
|
||||||
|
"node-intelligence",
|
||||||
|
"databases",
|
||||||
|
"credentials",
|
||||||
|
"embedded Codex",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertEngineBoundary() {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const actual = digest(await readFile(join(engineRoot, relativePath)));
|
||||||
|
if (actual !== expectedSha256[relativePath]) {
|
||||||
|
throw new Error(
|
||||||
|
`classified_aspect_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expectedSha256[relativePath]}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const compiler = await readFile(join(engineRoot, files[0]), "utf8");
|
||||||
|
if (
|
||||||
|
!compiler.includes("guardMatches")
|
||||||
|
|| !compiler.includes("'1.3.0'")
|
||||||
|
|| /gelios|fleet\.units\.contacts/i.test(compiler)
|
||||||
|
) {
|
||||||
|
throw new Error("classified_aspect_compiler_boundary_invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
const executionCatalog = JSON.parse(
|
||||||
|
await readFile(join(engineRoot, files[1]), "utf8"),
|
||||||
|
);
|
||||||
|
const providerPackage = executionCatalog?.packages?.find(
|
||||||
|
(entry) => entry?.id === "gelios.provider.v10",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
providerPackage?.version !== "10.0.0"
|
||||||
|
|| !executionCatalog?.runtime?.compilerVersions?.includes("1.3.0")
|
||||||
|
|| !providerPackage?.profiles?.some(
|
||||||
|
(profile) =>
|
||||||
|
profile?.dataProductId === "fleet.units.contacts.current.v1",
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error("classified_aspect_execution_catalog_invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
const securityCatalog = JSON.parse(
|
||||||
|
await readFile(join(engineRoot, files[2]), "utf8"),
|
||||||
|
);
|
||||||
|
const securityPackage = securityCatalog?.packages?.find(
|
||||||
|
(entry) => entry?.id === "gelios.provider.v10",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
securityPackage?.version !== "10.0.0"
|
||||||
|
|| securityPackage?.capabilities?.length !== 1
|
||||||
|
|| JSON.stringify(securityPackage.capabilities[0]?.dataProductIds)
|
||||||
|
!== JSON.stringify(["fleet.units.contacts.current.v1"])
|
||||||
|
) {
|
||||||
|
throw new Error("classified_aspect_security_catalog_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 64 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(here, "../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, "../NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const canonicalArtifactRoot = resolve(here, "../deploy-artifacts");
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || canonicalArtifactRoot);
|
||||||
|
const [transitionId = "20260718-003", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
|
||||||
|
throw new Error("usage: build-engine-mcp-control-plane-artifact.mjs [YYYYMMDD-NNN]");
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `engine-mcp-control-plane-${transitionId}`;
|
||||||
|
const target = join(artifactRoot, `nodedc-${id}.tgz`);
|
||||||
|
const nodeIntelligenceArtifact = join(
|
||||||
|
canonicalArtifactRoot,
|
||||||
|
"nodedc-engine-node-intelligence-20260717-001.tgz",
|
||||||
|
);
|
||||||
|
const nodeIntelligenceArtifactSha256 = "d126afaa0c714fef26362aad4749e3f4647f551d6eb975f0133cdf9ff2e6fc4f";
|
||||||
|
const descriptorRel = "nodedc-source/services/node-intelligence/activation.json";
|
||||||
|
const gatewayRel = "nodedc-source/server/routes/engineAgentGateway.js";
|
||||||
|
const upstreamProjectionRel = "nodedc-source/server/nodeIntelligence/upstreamProjection.js";
|
||||||
|
const files = [
|
||||||
|
"nodedc-source/server/assets/engine-agent-npm/bin/nodedc-engine-codex-agent.mjs",
|
||||||
|
"nodedc-source/server/assets/engine-agent-npm/package.json",
|
||||||
|
"nodedc-source/server/assets/nodedc-engine-codex-agent-0.1.4.tgz",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/providerCatalog.js",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/signedDataPlaneClient.js",
|
||||||
|
"nodedc-source/server/dataProductReadGrant/acceptance.js",
|
||||||
|
"nodedc-source/server/dataProductReadGrant/service.js",
|
||||||
|
"nodedc-source/server/dataProductReadGrant/store.js",
|
||||||
|
"nodedc-source/server/engineAgents/store.js",
|
||||||
|
upstreamProjectionRel,
|
||||||
|
gatewayRel,
|
||||||
|
"nodedc-source/server/routes/n8n.js",
|
||||||
|
"nodedc-source/server/routes/ndcAgentMcp.js",
|
||||||
|
"nodedc-source/services/backend/data-product-read-grant/docker-compose.immutable-runtime.yml",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/service.js",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/store.js",
|
||||||
|
descriptorRel,
|
||||||
|
];
|
||||||
|
const expectedSha256 = new Map([
|
||||||
|
[files[0], "521098de69fe288a56bd4158c849c1055ba24be08e19f7a4111618d0e8138445"],
|
||||||
|
[files[1], "cbe113e9b10bb84b9ccbffa3e261908e58a8430c11abe2cf4fd5304741b04597"],
|
||||||
|
[files[2], "e74c0136d346f904b42589d75cb11a952b4d2f21153f1b057fba28e9acf4f95f"],
|
||||||
|
[files[3], "901b8fad80018ce177b34ced804b39cb140a47e831414057f484296b373c651d"],
|
||||||
|
[files[4], "c2a13d5eb49937fe70ec6451d0465cac54c19c7fae44448db099079473ec02fc"],
|
||||||
|
[files[5], "202dbe575b2f2e1c584aa7e6e99e38fa84f12496feb454e3dbd3f98e2d0396dd"],
|
||||||
|
[files[6], "65b8cdd6b603333bac1feb303e9791feb1e9da39dc9b5bfc3df3961273b0052e"],
|
||||||
|
[files[7], "c3fcdc59a794f57d92e3d2ac713ee28341347cebd25364c4060beaa3dc2151de"],
|
||||||
|
[files[8], "debd351fe0b8c72b33b8c79909b8f339cbaf061b970576f3ae72df52ebaa211f"],
|
||||||
|
[files[9], "761a874b102a938bc6018159ddacdaac71ad6ae08e9f0f8d7f3b58a0165a5131"],
|
||||||
|
[files[10], "96c726dab5cf1341f74e6e1095d518058ca320e0dd5738e25bdbe75db1f4fc15"],
|
||||||
|
[files[11], "f293a7794405badbabd2bf7ef088f96fe1167d9e249f05cbfc8af280a0d3e8f8"],
|
||||||
|
[files[12], "534e2c85e1faecc72a00da7ad32d0584ee09b6bd89eeec2221c3b23d80e1e962"],
|
||||||
|
[files[13], "952df0cb2ac477e644f5f3a9d64b4872ce1da33356eeab0bec17dcb2931cf653"],
|
||||||
|
[files[14], "ded3832c9677345a988448ae8e69cef254fd9bf39d2de20cffa295c1feedcd7c"],
|
||||||
|
[files[15], "a92303b2732e21f68c1ac732fa26e4983cbadf3515741cee983b916a283d754c"],
|
||||||
|
]);
|
||||||
|
|
||||||
|
await assertFresh(target);
|
||||||
|
assertSha(await readFile(nodeIntelligenceArtifact), nodeIntelligenceArtifactSha256, "node intelligence artifact");
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-mcp-control-plane-"));
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true });
|
||||||
|
for (const rel of files.slice(0, -1)) {
|
||||||
|
const source = join(engineRoot, rel);
|
||||||
|
const stat = await lstat(source);
|
||||||
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`source_boundary_invalid:${rel}`);
|
||||||
|
assertSha(await readFile(source), expectedSha256.get(rel), rel);
|
||||||
|
await mkdir(dirname(join(payload, rel)), { recursive: true });
|
||||||
|
await cp(source, join(payload, rel), { force: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptorText = extractMember(
|
||||||
|
nodeIntelligenceArtifact,
|
||||||
|
`payload/${descriptorRel}`,
|
||||||
|
);
|
||||||
|
const descriptor = JSON.parse(descriptorText);
|
||||||
|
if (
|
||||||
|
descriptor?.action !== "activate"
|
||||||
|
|| descriptor?.releaseId !== "2.33.2-974a9fb3492f"
|
||||||
|
|| descriptor?.source?.gatewaySha256 !== "9642c76fd5765a8a20629c8d09e16579a1c3b2cfb7bdbab38cf55af469d8908f"
|
||||||
|
) throw new Error("node_intelligence_predecessor_descriptor_mismatch");
|
||||||
|
descriptor.source.gatewaySha256 = expectedSha256.get(gatewayRel);
|
||||||
|
descriptor.source.upstreamProjectionSha256 = expectedSha256.get(upstreamProjectionRel);
|
||||||
|
await mkdir(dirname(join(payload, descriptorRel)), { recursive: true });
|
||||||
|
await writeFile(join(payload, descriptorRel), `${JSON.stringify(descriptor, null, 2)}\n`, "utf8");
|
||||||
|
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), target, stage]);
|
||||||
|
const artifactSha256 = sha(await readFile(target));
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
id,
|
||||||
|
artifact: target,
|
||||||
|
artifactSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
predecessorGatewaySha256: "9642c76fd5765a8a20629c8d09e16579a1c3b2cfb7bdbab38cf55af469d8908f",
|
||||||
|
targetGatewaySha256: expectedSha256.get(gatewayRel),
|
||||||
|
mcpVersion: "0.5.0",
|
||||||
|
installerVersion: "0.1.4",
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractMember(archive, member) {
|
||||||
|
const script = [
|
||||||
|
"import pathlib,sys,tarfile",
|
||||||
|
"p=pathlib.Path(sys.argv[1]); name=sys.argv[2]",
|
||||||
|
"with tarfile.open(p,'r:gz') as t:",
|
||||||
|
" m=t.getmember(name)",
|
||||||
|
" if not m.isfile(): raise SystemExit('member-not-file')",
|
||||||
|
" f=t.extractfile(m)",
|
||||||
|
" if f is None: raise SystemExit('member-unreadable')",
|
||||||
|
" sys.stdout.buffer.write(f.read())",
|
||||||
|
].join("\n");
|
||||||
|
return run("python3", ["-c", script, archive, member]).stdout;
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSha(bytes, expected, label) {
|
||||||
|
const actual = sha(bytes);
|
||||||
|
if (!expected || actual !== expected) throw new Error(`${label.replaceAll(" ", "_")}_sha256_mismatch:${actual}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha(bytes) {
|
||||||
|
return createHash("sha256").update(bytes).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
+289
@@ -0,0 +1,289 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const baselineArtifact = resolve(
|
||||||
|
here,
|
||||||
|
"../deploy-artifacts/nodedc-engine-mcp-telemetry-catalog-20260723-035.tgz",
|
||||||
|
);
|
||||||
|
const baselineArtifactSha256 =
|
||||||
|
"4ce1563612499a19d653a174a4d73632e0aaac7dacd2eca4e7c01c87586b1155";
|
||||||
|
const nodeIntelligenceDescriptorPath =
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json";
|
||||||
|
const predecessorNodeIntelligenceDescriptorSha256 =
|
||||||
|
"25ed3efd858aaf82c242dba501f0acc0c6c3dc91e8845707a4d3325750eab59f";
|
||||||
|
const targetNodeIntelligenceDescriptorSha256 =
|
||||||
|
"03b2ba120c3929e9cf99940ddc927082de376ceff762895a84103144202aef42";
|
||||||
|
const predecessorGatewaySha256 =
|
||||||
|
"69bfc91e913a3fad04e13aca86efb9d62f73c0c7d1f8f7200907494b29fa9e8d";
|
||||||
|
const targetGatewaySha256 =
|
||||||
|
"9020cf49a3558c0497fed4ecfd81367cbc11b5b249881804c29fe437900c71f8";
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-execution-plan-materialization-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-execution-plan-materialization-artifact.mjs "
|
||||||
|
+ "<engine-mcp-execution-plan-materialization-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptorPath =
|
||||||
|
"nodedc-source/server/deployTransitions/executionPlanMaterializationV1.json";
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"391fc81228fdacd6efc6c0868991a3485f71869708e49ac15819db6ccce1bfce",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js":
|
||||||
|
targetGatewaySha256,
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/catalog.js":
|
||||||
|
"c35b4c7ad9319aabbf1366a11ff52a6e99d961893bafdfcb4e84fc5f24fc04be",
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/compiler.js":
|
||||||
|
"beb3f664073f9a372432643936a04d0cb0028cd695f759c68bd053e9cd892fe4",
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/materializer.js":
|
||||||
|
"ee3bcfd06b3a5fa46800df974a2dedfdd55eeaf662329f837486c011a9bd713e",
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"a153e040e0a592bad4375b98d9a1d83d148923aa0f0fd47d225b92eda281c4e9",
|
||||||
|
[descriptorPath]:
|
||||||
|
"52c0152cff49c251be5581a9209d2e63ba710c16e815bdd6ece24f7c9dd7e480",
|
||||||
|
[nodeIntelligenceDescriptorPath]:
|
||||||
|
targetNodeIntelligenceDescriptorSha256,
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const targetNodeIntelligenceDescriptor =
|
||||||
|
await buildTargetNodeIntelligenceDescriptor();
|
||||||
|
const stage = await mkdtemp(
|
||||||
|
join(tmpdir(), "nodedc-engine-mcp-execution-plan-materialization-"),
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
if (relativePath === nodeIntelligenceDescriptorPath) {
|
||||||
|
await writeFile(destination, targetNodeIntelligenceDescriptor, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "telemetry-catalog-v1-to-execution-plan-materialization-v1",
|
||||||
|
mcpVersion: "0.9.0",
|
||||||
|
mcpSurface: "external-codex",
|
||||||
|
mcpTools: [
|
||||||
|
"engine_plan_l2_execution_plan_materialization",
|
||||||
|
"engine_apply_l2_execution_plan_materialization",
|
||||||
|
],
|
||||||
|
providerLogicAuthority: "trusted-provider-package",
|
||||||
|
unmanagedGraphPolicy: "explicit-adoption-required",
|
||||||
|
nodeIntelligenceRelease: "2.33.2-974a9fb3492f",
|
||||||
|
predecessorGatewaySha256,
|
||||||
|
targetGatewaySha256,
|
||||||
|
predecessorNodeIntelligenceDescriptorSha256,
|
||||||
|
targetNodeIntelligenceDescriptorSha256,
|
||||||
|
untouched: [
|
||||||
|
"live L2 graphs",
|
||||||
|
"n8n workflow data",
|
||||||
|
"L1",
|
||||||
|
"Engine UI",
|
||||||
|
"node-intelligence image",
|
||||||
|
"databases",
|
||||||
|
"credentials",
|
||||||
|
"MCP Nginx",
|
||||||
|
"embedded AI Workspace",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
if (relativePath === nodeIntelligenceDescriptorPath) continue;
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_materialization_source_unsafe:${relativePath}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_materialization_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const gatewaySource = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"const ENGINE_AGENT_MCP_VERSION = '0.9.0'",
|
||||||
|
"name: 'engine_plan_l2_execution_plan_materialization'",
|
||||||
|
"name: 'engine_apply_l2_execution_plan_materialization'",
|
||||||
|
"'execution-plan.apply'",
|
||||||
|
]) {
|
||||||
|
if (!gatewaySource.includes(marker)) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_materialization_gateway_marker_missing:${marker}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/gelios|robot2b/i.test(
|
||||||
|
await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/l2ExecutionPlan/compiler.js"),
|
||||||
|
"utf8",
|
||||||
|
),
|
||||||
|
)) {
|
||||||
|
throw new Error("engine_mcp_execution_plan_materialization_provider_hardcode");
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(
|
||||||
|
await readFile(join(engineRoot, descriptorPath), "utf8"),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion !== "nodedc.engine.deploy-transition/v1"
|
||||||
|
|| descriptor?.id !== "engine-mcp-l2-execution-plan-materialization-v1"
|
||||||
|
|| descriptor?.mcpVersion !== "0.9.0"
|
||||||
|
|| descriptor?.plan?.tool
|
||||||
|
!== "engine_plan_l2_execution_plan_materialization"
|
||||||
|
|| descriptor?.apply?.tool
|
||||||
|
!== "engine_apply_l2_execution_plan_materialization"
|
||||||
|
|| descriptor?.providerLogicAuthority !== "trusted-provider-package"
|
||||||
|
|| descriptor?.unmanagedGraphPolicy !== "explicit-adoption-required"
|
||||||
|
|| descriptor?.embeddedCodexChanged !== false
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_materialization_descriptor_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildTargetNodeIntelligenceDescriptor() {
|
||||||
|
const baselineBytes = await readFile(baselineArtifact);
|
||||||
|
if (digest(baselineBytes) !== baselineArtifactSha256) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_materialization_baseline_artifact_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const baseline = run("tar", [
|
||||||
|
"-xOf",
|
||||||
|
baselineArtifact,
|
||||||
|
`payload/${nodeIntelligenceDescriptorPath}`,
|
||||||
|
]).stdout;
|
||||||
|
if (
|
||||||
|
digest(Buffer.from(baseline, "utf8"))
|
||||||
|
!== predecessorNodeIntelligenceDescriptorSha256
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_materialization_baseline_descriptor_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const descriptor = JSON.parse(baseline);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion
|
||||||
|
!== "nodedc.engine-node-intelligence-transition/v1"
|
||||||
|
|| descriptor?.action !== "activate"
|
||||||
|
|| descriptor?.releaseId !== "2.33.2-974a9fb3492f"
|
||||||
|
|| descriptor?.source?.gatewaySha256 !== predecessorGatewaySha256
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_materialization_baseline_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
descriptor.source.gatewaySha256 = targetGatewaySha256;
|
||||||
|
const rendered = `${JSON.stringify(descriptor, null, 2)}\n`;
|
||||||
|
if (
|
||||||
|
digest(Buffer.from(rendered, "utf8"))
|
||||||
|
!== targetNodeIntelligenceDescriptorSha256
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_materialization_target_descriptor_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return rendered;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const descriptorPath =
|
||||||
|
"nodedc-source/server/deployTransitions/executionPlanModuleOwnershipV3.json";
|
||||||
|
const activationPath =
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json";
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/materializer.js":
|
||||||
|
"dabf0073520049d7a04d1962b29e591ae092b87b287a50534ad2d98b03ae683c",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js":
|
||||||
|
"17c5f502b3ceacc45278eef7418d08e1e55a8b3e46e00942e559d25566fdba41",
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"7e34b93aa30b06cd52853b48013baef2970cc27e4fddc333a1011dc73ea8c08a",
|
||||||
|
[descriptorPath]:
|
||||||
|
"d187d539a219fec453e06c55c3f5486ef66059371b4ae9b145266307b2af9889",
|
||||||
|
[activationPath]:
|
||||||
|
"4cdeb85ebb2e43f088f095f75b7fc31aabd8ab81c8ac96ded4aafd7dbd8e30bd",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-execution-plan-module-ownership-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-execution-plan-module-ownership-artifact.mjs "
|
||||||
|
+ "<engine-mcp-execution-plan-module-ownership-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(
|
||||||
|
join(tmpdir(), "nodedc-engine-mcp-execution-plan-module-ownership-"),
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "execution-plan-telemetry-runtime-v2-to-module-ownership-v3",
|
||||||
|
mcpVersion: "0.10.0",
|
||||||
|
mcpSurface: "external-codex",
|
||||||
|
compilerVersions: ["1.1.0", "1.2.0"],
|
||||||
|
materializationStrategies: [
|
||||||
|
"create_or_reconcile_owned",
|
||||||
|
"adopt_existing",
|
||||||
|
"adopt_existing_module",
|
||||||
|
],
|
||||||
|
moduleOwnership: {
|
||||||
|
nodeBindings: "exact-one-to-one",
|
||||||
|
retireBoundary: "closed",
|
||||||
|
sharedManualWebhook: "compatible-existing-configuration-preserved",
|
||||||
|
providerCredentialNodes: "engine-managed",
|
||||||
|
publisherNodes: "engine-managed",
|
||||||
|
},
|
||||||
|
providerPackage: {
|
||||||
|
added: "gelios.provider.v9",
|
||||||
|
legacyPreserved: "gelios.provider.v8",
|
||||||
|
},
|
||||||
|
untouched: [
|
||||||
|
"live L2 graphs",
|
||||||
|
"n8n workflow data",
|
||||||
|
"L1",
|
||||||
|
"Engine UI",
|
||||||
|
"node-intelligence image",
|
||||||
|
"databases",
|
||||||
|
"credentials",
|
||||||
|
"MCP Nginx",
|
||||||
|
"embedded AI Workspace",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_module_ownership_source_unsafe:${relativePath}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_module_ownership_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const materializer = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/l2ExecutionPlan/materializer.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"nodedc.engine.materialized-execution-plan-module/v1",
|
||||||
|
"adopt_existing_module",
|
||||||
|
"preserveBoundNodeIds",
|
||||||
|
"execution_plan_module_retire_boundary_not_closed",
|
||||||
|
"manual_webhook_same_method",
|
||||||
|
]) {
|
||||||
|
if (!materializer.includes(marker)) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_module_ownership_marker_missing:${marker}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/gelios|robot2b/i.test(materializer)) {
|
||||||
|
throw new Error("engine_mcp_execution_plan_module_ownership_provider_hardcode");
|
||||||
|
}
|
||||||
|
|
||||||
|
const gateway = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!gateway.includes("const ENGINE_AGENT_MCP_VERSION = '0.10.0'")
|
||||||
|
|| !gateway.includes("preserveBoundNodeIds")
|
||||||
|
|| !gateway.includes("adopt_existing_module")
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_module_ownership_gateway_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const catalog = JSON.parse(await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/assets/execution-plans/v1/catalog.json"),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const geliosV9 = catalog?.packages?.find(
|
||||||
|
(providerPackage) => providerPackage?.id === "gelios.provider.v9",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
geliosV9?.contractDigest
|
||||||
|
!== "sha256:7dd4ce4a45ce76e884ffa1e304bfaa521f552e9a45e535930f2d17b882ae23ed"
|
||||||
|
|| !catalog?.packages?.some(
|
||||||
|
(providerPackage) => providerPackage?.id === "gelios.provider.v8",
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_module_ownership_catalog_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(
|
||||||
|
await readFile(join(engineRoot, descriptorPath), "utf8"),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion !== "nodedc.engine.deploy-transition/v1"
|
||||||
|
|| descriptor?.id !== "engine-mcp-l2-execution-plan-module-ownership-v3"
|
||||||
|
|| descriptor?.mcpVersion !== "0.10.0"
|
||||||
|
|| descriptor?.moduleOwnership?.adoptionStrategy !== "adopt_existing_module"
|
||||||
|
|| descriptor?.sharedBoundary?.configurationAuthority !== "existing-graph"
|
||||||
|
|| descriptor?.providerPackageTrust?.addedPackageId !== "gelios.provider.v9"
|
||||||
|
|| descriptor?.providerPackageTrust?.legacyPackagePreserved !== true
|
||||||
|
|| descriptor?.engineProviderHardcode !== false
|
||||||
|
|| descriptor?.embeddedCodexChanged !== false
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_module_ownership_descriptor_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const activation = JSON.parse(
|
||||||
|
await readFile(join(engineRoot, activationPath), "utf8"),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
activation?.action !== "activate"
|
||||||
|
|| activation?.releaseId !== "2.33.2-974a9fb3492f"
|
||||||
|
|| activation?.source?.gatewaySha256
|
||||||
|
!== targetSha256["nodedc-source/server/routes/engineAgentGateway.js"]
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_module_ownership_activation_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-mcp-execution-plan-sandbox-runtime-20260724-045", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-execution-plan-sandbox-runtime-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-execution-plan-sandbox-runtime-artifact.mjs "
|
||||||
|
+ "[engine-mcp-execution-plan-sandbox-runtime-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/compiler.js":
|
||||||
|
"64f5196a83018505c6dac77a0f8674c27941257a874eed9b024c1c94f169be2b",
|
||||||
|
"nodedc-source/server/deployTransitions/executionPlanSandboxRuntimeV4.json":
|
||||||
|
"a4692643afb86dfeeee6ca24aefcc181913e715eff38fa158667d2f10b901847",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-execution-plan-sandbox-runtime-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
mcpVersion: "0.11.0",
|
||||||
|
executionPlanCompilerVersion: "1.4.0",
|
||||||
|
n8nVersion: "2.3.2",
|
||||||
|
codeNodeMode: "runOnceForAllItems",
|
||||||
|
sandboxGlobalDependencies: [],
|
||||||
|
responseByteBudget: "bounded-pure-javascript-utf8",
|
||||||
|
rawProviderPayloadAtPublish: "forbidden",
|
||||||
|
engineProviderHardcode: false,
|
||||||
|
n8nCoreChanged: false,
|
||||||
|
l1Changed: false,
|
||||||
|
credentialsChanged: false,
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_execution_plan_sandbox_runtime_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_execution_plan_sandbox_runtime_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const compiler = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/l2ExecutionPlan/compiler.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const descriptor = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/deployTransitions/executionPlanSandboxRuntimeV4.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
if (
|
||||||
|
!compiler.includes("const encodedBytes = (value) => {")
|
||||||
|
|| compiler.includes("new TextEncoder().encode(JSON.stringify(value ?? null))")
|
||||||
|
|| !compiler.includes("return extracted.map((source) => ({ json:")
|
||||||
|
|| descriptor?.id !== "engine-mcp-l2-execution-plan-sandbox-runtime-v4"
|
||||||
|
|| descriptor?.predecessor !== "engine-mcp-l1-credential-provenance-v2"
|
||||||
|
|| descriptor?.runtimeCompatibility?.sandboxGlobalDependencies?.length !== 0
|
||||||
|
|| descriptor?.runtimeCompatibility?.responseByteBudget
|
||||||
|
!== "bounded-pure-javascript-utf8"
|
||||||
|
|| descriptor?.dataBoundary?.rawProviderPayloadAtPublish !== "forbidden"
|
||||||
|
|| descriptor?.engineProviderHardcode !== false
|
||||||
|
|| descriptor?.n8nCoreChanged !== false
|
||||||
|
) {
|
||||||
|
throw new Error("engine_execution_plan_sandbox_runtime_boundary_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
+224
@@ -0,0 +1,224 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const descriptorPath =
|
||||||
|
"nodedc-source/server/deployTransitions/executionPlanTelemetryRuntimeV2.json";
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/compiler.js":
|
||||||
|
"6b783ad15c26dc7de0645082c8a426002d943138c70bf31a240247b16a33b6a0",
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"5bdfc92284a7c836ff326e3a89b559110e376b32efd34b5f23f2bec272745781",
|
||||||
|
[descriptorPath]:
|
||||||
|
"68b275efb6303284336d8b637c966c24d891a4bd0b3fec4fb83247359929ef79",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-execution-plan-telemetry-runtime-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-execution-plan-telemetry-runtime-artifact.mjs "
|
||||||
|
+ "<engine-mcp-execution-plan-telemetry-runtime-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(
|
||||||
|
join(tmpdir(), "nodedc-engine-mcp-execution-plan-telemetry-runtime-"),
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "execution-plan-materialization-v1-to-telemetry-runtime-v2",
|
||||||
|
mcpVersion: "0.9.0",
|
||||||
|
mcpSurface: "external-codex",
|
||||||
|
compilerVersions: ["1.1.0", "1.2.0"],
|
||||||
|
legacyRuntimePreserved: true,
|
||||||
|
telemetryAuthority: [
|
||||||
|
"trusted-telemetry-projection",
|
||||||
|
"visible-sensor-definition",
|
||||||
|
],
|
||||||
|
unprojectedParameters: "discarded",
|
||||||
|
rawProviderPayloadAtPublish: "forbidden",
|
||||||
|
providerLogicAuthority: "trusted-provider-package",
|
||||||
|
untouched: [
|
||||||
|
"live L2 graphs",
|
||||||
|
"n8n workflow data",
|
||||||
|
"L1",
|
||||||
|
"Engine UI",
|
||||||
|
"node-intelligence image and descriptor",
|
||||||
|
"databases",
|
||||||
|
"credentials",
|
||||||
|
"MCP Nginx",
|
||||||
|
"embedded AI Workspace",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_telemetry_runtime_source_unsafe:${relativePath}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_telemetry_runtime_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const compiler = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/l2ExecutionPlan/compiler.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"if (compilerVersion === '1.1.0')",
|
||||||
|
"if (compilerVersion !== '1.2.0')",
|
||||||
|
'"msgParam", "msg_param"',
|
||||||
|
"descriptor.telemetryProjection",
|
||||||
|
'"message-param"',
|
||||||
|
"convertedSensorValue",
|
||||||
|
"visibleSensorDefinition",
|
||||||
|
]) {
|
||||||
|
if (!compiler.includes(marker)) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_execution_plan_telemetry_runtime_marker_missing:${marker}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/gelios|robot2b/i.test(compiler)) {
|
||||||
|
throw new Error("engine_mcp_execution_plan_telemetry_runtime_provider_hardcode");
|
||||||
|
}
|
||||||
|
|
||||||
|
const catalog = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
if (
|
||||||
|
JSON.stringify(catalog?.runtime?.compilerVersions)
|
||||||
|
!== JSON.stringify(["1.1.0", "1.2.0"])
|
||||||
|
) {
|
||||||
|
throw new Error("engine_mcp_execution_plan_telemetry_runtime_catalog_mismatch");
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(
|
||||||
|
await readFile(join(engineRoot, descriptorPath), "utf8"),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion !== "nodedc.engine.deploy-transition/v1"
|
||||||
|
|| descriptor?.id
|
||||||
|
!== "engine-mcp-l2-execution-plan-telemetry-runtime-v2"
|
||||||
|
|| descriptor?.mcpVersion !== "0.9.0"
|
||||||
|
|| JSON.stringify(descriptor?.compilerTransition?.supported)
|
||||||
|
!== JSON.stringify(["1.1.0", "1.2.0"])
|
||||||
|
|| descriptor?.compilerTransition?.legacyRuntimePreserved !== true
|
||||||
|
|| descriptor?.providerLogicAuthority !== "trusted-provider-package"
|
||||||
|
|| descriptor?.engineProviderHardcode !== false
|
||||||
|
|| descriptor?.embeddedCodexChanged !== false
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_execution_plan_telemetry_runtime_descriptor_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
+176
@@ -0,0 +1,176 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-execution-profile-decoder-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-execution-profile-decoder-artifact.mjs "
|
||||||
|
+ "<engine-mcp-execution-profile-decoder-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptorPath =
|
||||||
|
"nodedc-source/server/deployTransitions/executionProfileDecoderV1.json";
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"1c2427c1d5830c40b1e8ae05f3d683fc39d07d7e0fe2431b0f6efbbb1d3fcb88",
|
||||||
|
[descriptorPath]:
|
||||||
|
"93e431902e9bcd3b828a82ed6b42b48d939051f21bf8824dafcf2addac8a711c",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-mcp-profile-decoder-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "exact-flatted-numeric-string-preservation",
|
||||||
|
mcpSurface: "external-codex",
|
||||||
|
mcpTool: "engine_get_node_output_profile",
|
||||||
|
valuesIncluded: false,
|
||||||
|
rawExecutionDataIncluded: false,
|
||||||
|
untouched: [
|
||||||
|
"L2 graph",
|
||||||
|
"n8n",
|
||||||
|
"L1",
|
||||||
|
"Engine UI",
|
||||||
|
"databases",
|
||||||
|
"MCP Nginx",
|
||||||
|
"embedded AI Workspace",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_mcp_profile_decoder_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_profile_decoder_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const source = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/n8n.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"const compactReference = Symbol('n8nCompactReference')",
|
||||||
|
"Top-level string entries are primitive values.",
|
||||||
|
"valuesIncluded: false,",
|
||||||
|
]) {
|
||||||
|
if (!source.includes(marker)) {
|
||||||
|
throw new Error(`engine_mcp_profile_decoder_marker_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(await readFile(join(engineRoot, descriptorPath), "utf8"));
|
||||||
|
const expectedDescriptor = {
|
||||||
|
schemaVersion: "nodedc.engine.deploy-transition/v1",
|
||||||
|
id: "engine-mcp-execution-profile-decoder-v1",
|
||||||
|
component: "engine",
|
||||||
|
scope: "external-mcp-observability",
|
||||||
|
sourcePath: "nodedc-source/server/routes/n8n.js",
|
||||||
|
behavior: "preserve-top-level-numeric-string-primitives-in-flatted-execution-data",
|
||||||
|
acceptance: {
|
||||||
|
tool: "engine_get_node_output_profile",
|
||||||
|
valuesIncluded: false,
|
||||||
|
rawExecutionDataIncluded: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (JSON.stringify(descriptor) !== JSON.stringify(expectedDescriptor)) {
|
||||||
|
throw new Error("engine_mcp_profile_decoder_descriptor_contract_mismatch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-mcp-gelios-items-envelope-20260724-046", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-gelios-items-envelope-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-gelios-items-envelope-artifact.mjs "
|
||||||
|
+ "[engine-mcp-gelios-items-envelope-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"eb0c32fa0e8017b23e2d225fcb2d5805aa6dd1bf674e8aa248afc6a4079a7403",
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"42104d1267ca7840446c0c02edd3f9ecb29f8da8eb3e8f384cbd6dca0f676c4c",
|
||||||
|
"nodedc-source/server/deployTransitions/geliosItemsEnvelopeV12.json":
|
||||||
|
"16e39f54ebae776de9acfdf0078c79291310eeca5a1f720eb8b82496f4d419a3",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-gelios-items-envelope-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
mcpVersion: "0.11.0",
|
||||||
|
providerPackageTransition: "gelios.provider.v11-to-v12",
|
||||||
|
responseCollectionPath: "items",
|
||||||
|
historicalExecutionPackagePreserved: true,
|
||||||
|
activeSecurityAuthority: "gelios.provider.v12",
|
||||||
|
engineCompilerChanged: false,
|
||||||
|
n8nCoreChanged: false,
|
||||||
|
l1Changed: false,
|
||||||
|
ontologyChanged: false,
|
||||||
|
credentialsChanged: false,
|
||||||
|
rawProviderValuesIncluded: false,
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_gelios_items_envelope_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_gelios_items_envelope_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const executionCatalog = JSON.parse(await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/assets/execution-plans/v1/catalog.json"),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const securityCatalog = JSON.parse(await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/assets/provider-packages/v1/catalog.json"),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const descriptor = JSON.parse(await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/deployTransitions/geliosItemsEnvelopeV12.json"),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const executionIds = executionCatalog.packages.map(({ id }) => id);
|
||||||
|
const securityIds = securityCatalog.packages.map(({ id }) => id);
|
||||||
|
const v12 = executionCatalog.packages.find(({ id }) => id === "gelios.provider.v12");
|
||||||
|
if (
|
||||||
|
!executionIds.includes("gelios.provider.v11")
|
||||||
|
|| !v12?.profiles?.some((profile) => (
|
||||||
|
profile.id === "gelios.units.identity.warm.v1"
|
||||||
|
&& profile.dataProductId === "fleet.units.identity.current.v1"
|
||||||
|
))
|
||||||
|
|| securityIds.includes("gelios.provider.v11")
|
||||||
|
|| securityIds.filter((id) => id === "gelios.provider.v12").length !== 1
|
||||||
|
|| descriptor?.id !== "engine-mcp-gelios-items-envelope-v12"
|
||||||
|
|| descriptor?.predecessor !== "engine-mcp-l2-execution-plan-sandbox-runtime-v4"
|
||||||
|
|| descriptor?.responseEnvelope?.collectionPath !== "items"
|
||||||
|
|| descriptor?.responseEnvelope?.rawValuesCaptured !== false
|
||||||
|
|| Object.values(descriptor?.boundaries || {}).some((value) => value !== false)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_gelios_items_envelope_boundary_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT
|
||||||
|
|| join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|
||||||
|
|| resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [
|
||||||
|
patchId = "engine-mcp-gelios-units-items-envelope-20260724-049",
|
||||||
|
...extra
|
||||||
|
] = process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-gelios-units-items-envelope-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-gelios-units-items-envelope-artifact.mjs "
|
||||||
|
+ "[engine-mcp-gelios-units-items-envelope-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"d0cc95fa5e55bda315947fdb13bd8a0d8931b9484677e4c4cc0dcb0e9614e215",
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"1f1b866b6f837bffc6d529dfffd8bfa9c87495bfcd9ae3515a79765143d94b1d",
|
||||||
|
"nodedc-source/server/deployTransitions/geliosUnitsItemsEnvelopeV12Patch1.json":
|
||||||
|
"7a1594573e98342d3a3edcc0dc4f663f06b30ca24cc20adb5f36d50591066d96",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(
|
||||||
|
join(tmpdir(), "nodedc-engine-gelios-units-items-envelope-"),
|
||||||
|
);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(
|
||||||
|
checksum,
|
||||||
|
`${sha256} ${artifact.split("/").at(-1)}\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition:
|
||||||
|
"registered-profiles-v2-to-gelios-v12.0.1-units-items-envelope",
|
||||||
|
mcpVersion: "0.12.0",
|
||||||
|
providerPackage: {
|
||||||
|
id: "gelios.provider.v12",
|
||||||
|
predecessorVersion: "12.0.0",
|
||||||
|
targetVersion: "12.0.1",
|
||||||
|
},
|
||||||
|
registeredProfile: "gelios.units.profile.cold.v1",
|
||||||
|
responseCollectionPath: "items",
|
||||||
|
existingMaterializerReused: true,
|
||||||
|
compilerVersion: "1.4.0",
|
||||||
|
engineRuntimeCodeChanged: false,
|
||||||
|
n8nCoreChanged: false,
|
||||||
|
l1Changed: false,
|
||||||
|
l2GraphChanged: false,
|
||||||
|
engineUiChanged: false,
|
||||||
|
databasesChanged: false,
|
||||||
|
credentialsChanged: false,
|
||||||
|
foundryChanged: false,
|
||||||
|
ontologyChanged: false,
|
||||||
|
providerEndpointsChanged: false,
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_gelios_units_items_source_unsafe:${relativePath}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_gelios_units_items_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const execution = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const security = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const descriptor = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/deployTransitions/"
|
||||||
|
+ "geliosUnitsItemsEnvelopeV12Patch1.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const providerPackage = execution.packages.find(
|
||||||
|
(item) => item.id === "gelios.provider.v12",
|
||||||
|
);
|
||||||
|
const profile = providerPackage?.profiles.find(
|
||||||
|
(item) => item.id === "gelios.units.profile.cold.v1",
|
||||||
|
);
|
||||||
|
const extract = profile?.executionPlanTemplate?.steps.find(
|
||||||
|
(step) => (
|
||||||
|
step.kind === "extract_items"
|
||||||
|
&& step.config?.capabilityId === "gelios.units.current.read"
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const securityPackage = security.packages.find(
|
||||||
|
(item) => item.id === "gelios.provider.v12",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
providerPackage?.version !== "12.0.1"
|
||||||
|
|| securityPackage?.version !== "12.0.1"
|
||||||
|
|| profile?.dataProductId !== "fleet.units.profile.current.v1"
|
||||||
|
|| profile?.executionPlanTemplate?.compilerVersion !== "1.4.0"
|
||||||
|
|| extract?.config?.response?.collectionPaths?.[0] !== "items"
|
||||||
|
|| descriptor?.id
|
||||||
|
!== "engine-mcp-gelios-units-items-envelope-v12-patch1"
|
||||||
|
|| descriptor?.predecessor
|
||||||
|
!== "engine-mcp-registered-execution-profiles-v2"
|
||||||
|
|| descriptor?.mcpVersion !== "0.12.0"
|
||||||
|
|| descriptor?.registeredProfile?.materializer
|
||||||
|
!== "existing-immutable-two-phase"
|
||||||
|
|| Object.values(descriptor?.boundaries || {}).some(Boolean)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_gelios_units_items_boundary_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; "
|
||||||
|
+ "info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: "
|
||||||
|
+ "tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-mcp-l1-credential-provenance-20260724-044", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-l1-credential-provenance-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-l1-credential-provenance-artifact.mjs "
|
||||||
|
+ "[engine-mcp-l1-credential-provenance-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"af07edcf784c420855134ab9178f020d259a1cac703cd643418ab7b4eb94dbd3",
|
||||||
|
"nodedc-source/server/deployTransitions/l1CredentialProvenanceV2.json":
|
||||||
|
"5887da6e5cb611450e03a110be9786acbe47ae1b00217b8bf09e0967f71f6a3d",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-l1-credential-provenance-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
mcpVersion: "0.11.0",
|
||||||
|
tool: "engine_list_l2_credential_refs",
|
||||||
|
credentialScope: "same-l1-workflow",
|
||||||
|
localProvenanceSources: ["manual", "workflow-ref", "credentials-file"],
|
||||||
|
referencedSourceRequiresSyncPayload: true,
|
||||||
|
crossL1Sharing: false,
|
||||||
|
managedGrants: "target-local",
|
||||||
|
credentialValuesIncluded: false,
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_l1_credential_provenance_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l1_credential_provenance_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const route = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/n8n.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const descriptor = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/deployTransitions/l1CredentialProvenanceV2.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
if (
|
||||||
|
!route.includes("function engineAgentCredentialMayProveL1Provenance")
|
||||||
|
|| !route.includes("return isGlobalRegistryEntryAllowed(entry)")
|
||||||
|
|| !route.includes("engineAgentCredentialMayProveL1Provenance(item)")
|
||||||
|
|| descriptor?.id !== "engine-mcp-l1-credential-provenance-v2"
|
||||||
|
|| descriptor?.visibilityProof?.referencedSourceRequiresSyncPayload !== true
|
||||||
|
|| descriptor?.visibilityProof?.logicalKeyEqualityRequired !== true
|
||||||
|
|| descriptor?.binding?.applyOperation !== "assignCredentialRef"
|
||||||
|
|| descriptor?.crossL1Sharing !== false
|
||||||
|
|| descriptor?.candidateBoundary?.managedGrants !== "target-local"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_l1_credential_provenance_runtime_boundary_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-mcp-l1-credential-reuse-20260724-043", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-l1-credential-reuse-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-l1-credential-reuse-artifact.mjs "
|
||||||
|
+ "[engine-mcp-l1-credential-reuse-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"6620e4bdd573e9f6b636a4b059eafef76d59da2fdb2183038fa5ec95357d8478",
|
||||||
|
"nodedc-source/server/deployTransitions/l1CredentialReuseV1.json":
|
||||||
|
"2ada49ef8bb2f146a9ea8d3c9ab5ee55f6a4e1b17e0f4b62a16f27368bd0eb05",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-l1-credential-reuse-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
mcpVersion: "0.11.0",
|
||||||
|
tool: "engine_list_l2_credential_refs",
|
||||||
|
credentialScope: "same-l1-workflow",
|
||||||
|
crossL1Sharing: false,
|
||||||
|
managedGrants: "target-local",
|
||||||
|
credentialValuesIncluded: false,
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_l1_credential_reuse_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_l1_credential_reuse_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const route = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/n8n.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const descriptor = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/deployTransitions/l1CredentialReuseV1.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
if (
|
||||||
|
!route.includes("function buildEngineAgentL1CredentialContext")
|
||||||
|
|| !route.includes("candidateScope === 'l1' ? l1Context.graph : graph")
|
||||||
|
|| !route.includes("managed writer/reader grants")
|
||||||
|
|| descriptor?.id !== "engine-mcp-l1-credential-reuse-v1"
|
||||||
|
|| descriptor?.visibilityProof?.scope !== "same-l1-workflow"
|
||||||
|
|| descriptor?.binding?.applyOperation !== "assignCredentialRef"
|
||||||
|
|| descriptor?.crossL1Sharing !== false
|
||||||
|
|| descriptor?.managedGrants !== "target-local"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_l1_credential_reuse_runtime_boundary_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "engine-mcp-normalized-identity-search-20260724-041", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-normalized-identity-search-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-normalized-identity-search-artifact.mjs "
|
||||||
|
+ "[engine-mcp-normalized-identity-search-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"a2bc69c72f68e57ed27120d0c88f4ffe6310bbf0c4360c8b0dba0953ccaaf522",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js":
|
||||||
|
"4a9524fd954320277042c783b7b19cbb2172f075f27652c0eebfd743ffc47872",
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/compiler.js":
|
||||||
|
"01958d541c778002d33e3aead0cfe02df2084eb7222ce941cc7149d73a10f135",
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"2b8e5ee3d73d16f3cd6e34d1f7394946a6270a17b0e9e6511f12921ba2561fd3",
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"fe5256fd2ba295819daecc8d2acae34687e807978a6730dfa20703cb3bab0c1b",
|
||||||
|
"nodedc-source/server/deployTransitions/normalizedIdentitySearchV1.json":
|
||||||
|
"41738185fe103642912b0aa1c29c51860970c38f9f916cc3725e79e258b9ea7e",
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json":
|
||||||
|
"3e7aeb1d28eb291461f79cd656ece6488bc6d372124088e92f53bf89c3373f61",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-normalized-identity-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
mcpVersion: "0.11.0",
|
||||||
|
mcpSurface: "external-codex",
|
||||||
|
tool: "engine_find_normalized_subjects",
|
||||||
|
providerPackage: "gelios.provider.v11",
|
||||||
|
compilerVersionAdded: "1.4.0",
|
||||||
|
rawProviderPayload: "forbidden",
|
||||||
|
commandSurface: "absent",
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_normalized_identity_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_normalized_identity_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const gateway = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const route = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/n8n.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const compiler = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/l2ExecutionPlan/compiler.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!gateway.includes("const ENGINE_AGENT_MCP_VERSION = '0.11.0'")
|
||||||
|
|| !gateway.includes("engine_find_normalized_subjects")
|
||||||
|
|| !route.includes("normalized-fact-search")
|
||||||
|
|| !route.includes("rawExecutionDataIncluded: false")
|
||||||
|
|| !compiler.includes("boundedStringList")
|
||||||
|
|| !compiler.includes("boundedNamedValues")
|
||||||
|
|| /gelios|robot2b/i.test(compiler)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_normalized_identity_runtime_boundary_invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
const transition = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/deployTransitions/normalizedIdentitySearchV1.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const activation = JSON.parse(await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/services/node-intelligence/activation.json"),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
if (
|
||||||
|
transition?.id !== "engine-mcp-normalized-identity-search-v1"
|
||||||
|
|| transition?.normalizedFactSearch?.commandSurface !== false
|
||||||
|
|| transition?.providerPackageTrust?.addedPackageId !== "gelios.provider.v11"
|
||||||
|
|| activation?.source?.gatewaySha256
|
||||||
|
!== expectedSha256["nodedc-source/server/routes/engineAgentGateway.js"]
|
||||||
|
|| activation?.predecessor?.gatewaySha256
|
||||||
|
!== "6b8c80fa997ef7c438d199a6ee942c5e37aebc4057667af417897fa636131db4"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_normalized_identity_transition_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, '../NODEDC_ENGINE_INFRA'),
|
||||||
|
)
|
||||||
|
const canonicalArtifactRoot = resolve(here, '../deploy-artifacts')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || canonicalArtifactRoot)
|
||||||
|
const [transitionId = '20260718-005', ...extra] = process.argv.slice(2)
|
||||||
|
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
|
||||||
|
throw new Error('usage: build-engine-mcp-ontology-sdk-artifact.mjs [YYYYMMDD-NNN]')
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `engine-mcp-control-plane-${transitionId}`
|
||||||
|
const target = join(artifactRoot, `nodedc-${id}.tgz`)
|
||||||
|
const predecessorArtifact = join(
|
||||||
|
canonicalArtifactRoot,
|
||||||
|
'nodedc-engine-mcp-control-plane-20260718-003.tgz',
|
||||||
|
)
|
||||||
|
const predecessorArtifactSha256 = '249aef9527666c562e9648b15737e66cc5c1dc7c0788b58ea714da270b5eb4ba'
|
||||||
|
const descriptorRel = 'nodedc-source/services/node-intelligence/activation.json'
|
||||||
|
const gatewayRel = 'nodedc-source/server/routes/engineAgentGateway.js'
|
||||||
|
const files = [
|
||||||
|
'nodedc-source/server/assets/engine-agent-npm/bin/nodedc-engine-codex-agent.mjs',
|
||||||
|
'nodedc-source/server/assets/engine-agent-npm/package.json',
|
||||||
|
'nodedc-source/server/assets/nodedc-engine-codex-agent-0.1.5.tgz',
|
||||||
|
'nodedc-source/server/assets/provider-packages/v1/catalog.json',
|
||||||
|
'nodedc-source/server/dataProductPublishGrant/providerCatalog.js',
|
||||||
|
'nodedc-source/server/engineAgents/store.js',
|
||||||
|
gatewayRel,
|
||||||
|
descriptorRel,
|
||||||
|
]
|
||||||
|
const expectedSha256 = new Map([
|
||||||
|
[files[0], 'adff3e474c914680f7d36b204d1dc03e69dc8065fff1f80b6713526cfc970137'],
|
||||||
|
[files[1], '0741647e4f7f58f69f3021d367484609a8e1eb7b8727d6ad9639bd9906b7f455'],
|
||||||
|
[files[2], '72a1b2d41a12a298eaae63ba3334c7c66b6ca53de6a3f03a48607d4ff6da42fb'],
|
||||||
|
[files[3], '4800e1a1c2af5e4893b1a403c04e91f55689383457caff833edc9e35e8e7e37a'],
|
||||||
|
[files[4], 'd5511a8bd3b4238af88a89537661c9ca4c0126bca7b5ad225985e27ccdb2c64c'],
|
||||||
|
[files[5], '4cd4bdd5958cfafee184e98a04fe12aa0c1cbe884326beaec63c99f9fff61285'],
|
||||||
|
[files[6], '25fa013ddbfd7d0c7ece8c792daec5f345062757c85eb56cfbff45bf1e812152'],
|
||||||
|
])
|
||||||
|
|
||||||
|
await assertFresh(target)
|
||||||
|
assertSha(await readFile(predecessorArtifact), predecessorArtifactSha256, 'predecessor MCP artifact')
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-mcp-ontology-sdk-'))
|
||||||
|
const payload = join(stage, 'payload')
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true })
|
||||||
|
for (const rel of files.slice(0, -1)) {
|
||||||
|
const source = join(engineRoot, rel)
|
||||||
|
const stat = await lstat(source)
|
||||||
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`source_boundary_invalid:${rel}`)
|
||||||
|
assertSha(await readFile(source), expectedSha256.get(rel), rel)
|
||||||
|
await mkdir(dirname(join(payload, rel)), { recursive: true })
|
||||||
|
await cp(source, join(payload, rel), { force: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(extractMember(
|
||||||
|
predecessorArtifact,
|
||||||
|
`payload/${descriptorRel}`,
|
||||||
|
))
|
||||||
|
if (
|
||||||
|
descriptor?.action !== 'activate'
|
||||||
|
|| descriptor?.releaseId !== '2.33.2-974a9fb3492f'
|
||||||
|
|| descriptor?.source?.gatewaySha256 !== '96c726dab5cf1341f74e6e1095d518058ca320e0dd5738e25bdbe75db1f4fc15'
|
||||||
|
|| descriptor?.source?.upstreamProjectionSha256 !== '761a874b102a938bc6018159ddacdaac71ad6ae08e9f0f8d7f3b58a0165a5131'
|
||||||
|
) throw new Error('mcp_control_plane_predecessor_descriptor_mismatch')
|
||||||
|
descriptor.source.gatewaySha256 = expectedSha256.get(gatewayRel)
|
||||||
|
await mkdir(dirname(join(payload, descriptorRel)), { recursive: true })
|
||||||
|
await writeFile(join(payload, descriptorRel), `${JSON.stringify(descriptor, null, 2)}\n`, 'utf8')
|
||||||
|
|
||||||
|
await writeFile(join(stage, 'manifest.env'), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, 'utf8')
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${files.join('\n')}\n`, 'utf8')
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
run('python3', ['-c', canonicalTarScript(), target, stage])
|
||||||
|
const artifactSha256 = sha(await readFile(target))
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
id,
|
||||||
|
artifact: target,
|
||||||
|
artifactSha256,
|
||||||
|
services: ['nodedc-backend'],
|
||||||
|
predecessorGatewaySha256: '96c726dab5cf1341f74e6e1095d518058ca320e0dd5738e25bdbe75db1f4fc15',
|
||||||
|
targetGatewaySha256: expectedSha256.get(gatewayRel),
|
||||||
|
mcpVersion: '0.6.0',
|
||||||
|
installerVersion: '0.1.5',
|
||||||
|
ontologyMcp: 'separate-read-only-proxy',
|
||||||
|
providerPackage: 'gelios.provider.v2',
|
||||||
|
providerCredential: 'httpQueryAuth',
|
||||||
|
preserved: ['n8n', 'L1', 'node-intelligence image', 'databases', 'provider credential values'],
|
||||||
|
files,
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractMember(archive, member) {
|
||||||
|
const script = [
|
||||||
|
'import pathlib,sys,tarfile',
|
||||||
|
'p=pathlib.Path(sys.argv[1]); name=sys.argv[2]',
|
||||||
|
"with tarfile.open(p,'r:gz') as t:",
|
||||||
|
' m=t.getmember(name)',
|
||||||
|
" if not m.isfile(): raise SystemExit('member-not-file')",
|
||||||
|
' f=t.extractfile(m)',
|
||||||
|
" if f is None: raise SystemExit('member-unreadable')",
|
||||||
|
' sys.stdout.buffer.write(f.read())',
|
||||||
|
].join('\n')
|
||||||
|
return run('python3', ['-c', script, archive, member]).stdout
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip,io,pathlib,sys,tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
' for x in paths:',
|
||||||
|
' info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())',
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSha(bytes, expected, label) {
|
||||||
|
const actual = sha(bytes)
|
||||||
|
if (!expected || actual !== expected) throw new Error(`${label.replaceAll(' ', '_')}_sha256_mismatch:${actual}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(scriptDir, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT
|
||||||
|
|| join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|
||||||
|
|| resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [
|
||||||
|
patchId = "engine-mcp-registered-execution-profiles-20260724-048",
|
||||||
|
...extra
|
||||||
|
] = process.argv.slice(2);
|
||||||
|
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-registered-execution-profiles-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-registered-execution-profiles-artifact.mjs "
|
||||||
|
+ "[engine-mcp-registered-execution-profiles-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json":
|
||||||
|
"940510499a9260dbff718b7b1f96f72f8e9ac593b460805af3007731578a7668",
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/catalog.js":
|
||||||
|
"fec56b154ae483ad21bbaaeb4c55707bffce223c27874ac135ce58a9203259a0",
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/registeredProfiles.js":
|
||||||
|
"3c521c1652c61c9d757197c76e053fd3ec602e13ef7f6a4856835ecc1a8a61d1",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js":
|
||||||
|
"8f04edc11251de86b825351c92338be9537207887cf802474b6b6d8c3cce4077",
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json":
|
||||||
|
"3d72709e40b79c01a62a6af4bde911fca4f609d5ac487d284cf97fd8ebd73686",
|
||||||
|
"nodedc-source/server/deployTransitions/registeredExecutionProfilesV2.json":
|
||||||
|
"1db523f035a47c6b00b41b26efe1390ad2d24acece9d30dd039eff56626e934d",
|
||||||
|
});
|
||||||
|
const files = Object.freeze(Object.keys(expectedSha256));
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(
|
||||||
|
join(tmpdir(), "nodedc-engine-registered-execution-profiles-"),
|
||||||
|
);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const relativePath of files) {
|
||||||
|
const destination = join(stage, "payload", relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(
|
||||||
|
checksum,
|
||||||
|
`${sha256} ${artifact.split("/").at(-1)}\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
mcpVersion: "0.12.0",
|
||||||
|
transition:
|
||||||
|
"gelios-items-envelope-v12-to-registered-profiles-v2-attested",
|
||||||
|
tools: [
|
||||||
|
"engine_list_l2_execution_profiles",
|
||||||
|
"engine_plan_registered_l2_execution",
|
||||||
|
],
|
||||||
|
registeredProfiles: 6,
|
||||||
|
existingMaterializerReused: true,
|
||||||
|
n8nCoreChanged: false,
|
||||||
|
l1Changed: false,
|
||||||
|
l2GraphChanged: false,
|
||||||
|
engineUiChanged: false,
|
||||||
|
databasesChanged: false,
|
||||||
|
credentialsChanged: false,
|
||||||
|
foundryChanged: false,
|
||||||
|
ontologyChanged: false,
|
||||||
|
nodeIntelligenceAttestationChanged: true,
|
||||||
|
nodeIntelligenceImageChanged: false,
|
||||||
|
nodeIntelligenceSourceChanged: false,
|
||||||
|
rawProviderValuesIncluded: false,
|
||||||
|
files,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(expectedSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_registered_execution_profiles_source_unsafe:${relativePath}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_registered_execution_profiles_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const catalog = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/assets/execution-plans/v1/catalog.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const descriptor = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/deployTransitions/"
|
||||||
|
+ "registeredExecutionProfilesV2.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
const registered = catalog.packages.flatMap(
|
||||||
|
(providerPackage) => (providerPackage.profiles || []).filter(
|
||||||
|
(profile) => profile.executionPlanTemplate,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
registered.length !== 6
|
||||||
|
|| registered.some((profile) => (
|
||||||
|
!profile.dataClass
|
||||||
|
|| !profile.cadence
|
||||||
|
|| profile.executionPlanTemplate?.compilerVersion !== "1.4.0"
|
||||||
|
|| profile.executionPlanTemplate?.connection?.collectionProfileId
|
||||||
|
!== profile.id
|
||||||
|
))
|
||||||
|
|| descriptor?.id !== "engine-mcp-registered-execution-profiles-v2"
|
||||||
|
|| descriptor?.predecessor !== "engine-mcp-gelios-items-envelope-v12"
|
||||||
|
|| descriptor?.mcpVersion !== "0.12.0"
|
||||||
|
|| descriptor?.tools?.apply
|
||||||
|
!== "engine_apply_l2_execution_plan_materialization"
|
||||||
|
|| descriptor?.nodeIntelligenceAttestation?.targetGatewaySha256
|
||||||
|
!== expectedSha256[
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js"
|
||||||
|
]
|
||||||
|
|| descriptor?.nodeIntelligenceAttestation?.sidecarImageChanged !== false
|
||||||
|
|| descriptor?.nodeIntelligenceAttestation
|
||||||
|
?.nodeIntelligenceSourceChanged !== false
|
||||||
|
|| descriptor?.boundaries?.nodeIntelligenceAttestationChanged !== true
|
||||||
|
|| Object.entries(descriptor?.boundaries || {}).some(
|
||||||
|
([key, value]) => (
|
||||||
|
key !== "nodeIntelligenceAttestationChanged" && value !== false
|
||||||
|
),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_registered_execution_profiles_boundary_invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
const gateway = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const resolver = await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/server/l2ExecutionPlan/registeredProfiles.js",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const nodeIntelligence = JSON.parse(await readFile(
|
||||||
|
join(
|
||||||
|
engineRoot,
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json",
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
));
|
||||||
|
if (
|
||||||
|
nodeIntelligence?.releaseId !== "2.33.2-974a9fb3492f"
|
||||||
|
|| nodeIntelligence?.source?.gatewaySha256
|
||||||
|
!== expectedSha256[
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js"
|
||||||
|
]
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_registered_execution_profiles_attestation_invalid",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const marker of [
|
||||||
|
"engine_list_l2_execution_profiles",
|
||||||
|
"engine_plan_registered_l2_execution",
|
||||||
|
"const ENGINE_AGENT_MCP_VERSION = '0.12.0'",
|
||||||
|
]) {
|
||||||
|
if (!gateway.includes(marker)) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_registered_execution_profiles_gateway_marker_missing:${marker}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!resolver.includes("registered_execution_profile_ref_scope_denied")
|
||||||
|
|| !resolver.includes("targetBoundPlan")
|
||||||
|
|| /gelios|robot2b/i.test(resolver)
|
||||||
|
) {
|
||||||
|
throw new Error("engine_registered_execution_profiles_resolver_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; "
|
||||||
|
+ "info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: "
|
||||||
|
+ "tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const baselineArtifact = resolve(
|
||||||
|
here,
|
||||||
|
"../deploy-artifacts/nodedc-engine-l2-closed-loop-20260723-031.tgz",
|
||||||
|
);
|
||||||
|
const baselineArtifactSha256 =
|
||||||
|
"33103bcf8a5f020855f3a095306b94158d9a452344ac7313120b1624a745e47e";
|
||||||
|
const nodeIntelligenceDescriptorPath =
|
||||||
|
"nodedc-source/services/node-intelligence/activation.json";
|
||||||
|
const predecessorNodeIntelligenceDescriptorSha256 =
|
||||||
|
"63e7619c6971d02102583bb5d80d33ece293b952f113200fa0b76f0e88c2dd32";
|
||||||
|
const targetNodeIntelligenceDescriptorSha256 =
|
||||||
|
"25ed3efd858aaf82c242dba501f0acc0c6c3dc91e8845707a4d3325750eab59f";
|
||||||
|
const predecessorGatewaySha256 =
|
||||||
|
"4f600a2781be9118bec891fa2a6f20d7f55e0892ef2f06af24059193cebd28f4";
|
||||||
|
const targetGatewaySha256 =
|
||||||
|
"69bfc91e913a3fad04e13aca86efb9d62f73c0c7d1f8f7200907494b29fa9e8d";
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (
|
||||||
|
extra.length
|
||||||
|
|| !/^engine-mcp-telemetry-catalog-\d{8}-\d{3}$/.test(patchId)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-mcp-telemetry-catalog-artifact.mjs "
|
||||||
|
+ "<engine-mcp-telemetry-catalog-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptorPath =
|
||||||
|
"nodedc-source/server/deployTransitions/telemetryReadingCatalogV1.json";
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"903245ae363e9b9ac161498f17988a38876a0e0ac8d80f3fa1b0112ceb7fe906",
|
||||||
|
"nodedc-source/server/routes/engineAgentGateway.js":
|
||||||
|
targetGatewaySha256,
|
||||||
|
[descriptorPath]:
|
||||||
|
"b25ab8b6e6ad8ac24614c4630cc3635abe453464466d5a72238b05e48a24d882",
|
||||||
|
[nodeIntelligenceDescriptorPath]:
|
||||||
|
targetNodeIntelligenceDescriptorSha256,
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const targetNodeIntelligenceDescriptor =
|
||||||
|
await buildTargetNodeIntelligenceDescriptor();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-mcp-telemetry-catalog-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
if (relativePath === nodeIntelligenceDescriptorPath) {
|
||||||
|
await writeFile(destination, targetNodeIntelligenceDescriptor, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "execution-profile-decoder-v1-to-telemetry-catalog-v1",
|
||||||
|
mcpVersion: "0.8.0",
|
||||||
|
mcpSurface: "external-codex",
|
||||||
|
mcpTool: "engine_get_telemetry_reading_catalog",
|
||||||
|
readingValuesIncluded: false,
|
||||||
|
rawExecutionDataIncluded: false,
|
||||||
|
nodeIntelligenceRelease: "2.33.2-974a9fb3492f",
|
||||||
|
predecessorGatewaySha256,
|
||||||
|
targetGatewaySha256,
|
||||||
|
predecessorNodeIntelligenceDescriptorSha256,
|
||||||
|
targetNodeIntelligenceDescriptorSha256,
|
||||||
|
untouched: [
|
||||||
|
"L2 graph",
|
||||||
|
"n8n",
|
||||||
|
"L1",
|
||||||
|
"Engine UI",
|
||||||
|
"node-intelligence image",
|
||||||
|
"databases",
|
||||||
|
"credentials",
|
||||||
|
"MCP Nginx",
|
||||||
|
"embedded AI Workspace",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
if (relativePath === nodeIntelligenceDescriptorPath) continue;
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_mcp_telemetry_catalog_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_mcp_telemetry_catalog_target_mismatch:${relativePath}:`
|
||||||
|
+ `expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const n8nSource = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/n8n.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"function toSafeTelemetryReadingCatalog",
|
||||||
|
"key === 'sensor_readings' && pathName.endsWith('.attributes')",
|
||||||
|
"rawExecutionDataIncluded: false,",
|
||||||
|
]) {
|
||||||
|
if (!n8nSource.includes(marker)) {
|
||||||
|
throw new Error(`engine_mcp_telemetry_catalog_marker_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const gatewaySource = await readFile(
|
||||||
|
join(engineRoot, "nodedc-source/server/routes/engineAgentGateway.js"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"const ENGINE_AGENT_MCP_VERSION = '0.8.0'",
|
||||||
|
"name: 'engine_get_telemetry_reading_catalog'",
|
||||||
|
"/telemetry-reading-catalog?",
|
||||||
|
]) {
|
||||||
|
if (!gatewaySource.includes(marker)) {
|
||||||
|
throw new Error(`engine_mcp_telemetry_catalog_gateway_marker_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = JSON.parse(await readFile(join(engineRoot, descriptorPath), "utf8"));
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion !== "nodedc.engine.deploy-transition/v1"
|
||||||
|
|| descriptor?.id !== "engine-mcp-telemetry-reading-catalog-v1"
|
||||||
|
|| descriptor?.mcpVersion !== "0.8.0"
|
||||||
|
|| descriptor?.readsOnly !== "normalized-attributes.sensor_readings"
|
||||||
|
|| descriptor?.neverReturns?.join(",")
|
||||||
|
!== "reading-value,raw-execution-data,raw-provider-payload,credential-shaped-data"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_mcp_telemetry_catalog_descriptor_contract_mismatch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildTargetNodeIntelligenceDescriptor() {
|
||||||
|
const baselineBytes = await readFile(baselineArtifact);
|
||||||
|
if (digest(baselineBytes) !== baselineArtifactSha256) {
|
||||||
|
throw new Error("engine_mcp_telemetry_catalog_baseline_artifact_mismatch");
|
||||||
|
}
|
||||||
|
const baseline = run("tar", [
|
||||||
|
"-xOf",
|
||||||
|
baselineArtifact,
|
||||||
|
`payload/${nodeIntelligenceDescriptorPath}`,
|
||||||
|
]).stdout;
|
||||||
|
if (
|
||||||
|
digest(Buffer.from(baseline, "utf8"))
|
||||||
|
!== predecessorNodeIntelligenceDescriptorSha256
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_telemetry_catalog_baseline_descriptor_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const descriptor = JSON.parse(baseline);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion
|
||||||
|
!== "nodedc.engine-node-intelligence-transition/v1"
|
||||||
|
|| descriptor?.action !== "activate"
|
||||||
|
|| descriptor?.releaseId !== "2.33.2-974a9fb3492f"
|
||||||
|
|| descriptor?.source?.gatewaySha256 !== predecessorGatewaySha256
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_telemetry_catalog_baseline_descriptor_contract_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
descriptor.source.gatewaySha256 = targetGatewaySha256;
|
||||||
|
const rendered = `${JSON.stringify(descriptor, null, 2)}\n`;
|
||||||
|
if (
|
||||||
|
digest(Buffer.from(rendered, "utf8"))
|
||||||
|
!== targetNodeIntelligenceDescriptorSha256
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"engine_mcp_telemetry_catalog_target_descriptor_mismatch",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return rendered;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { createRequire, Module } from "node:module";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(here, "../..");
|
||||||
|
const engineRoot = resolve(platformRoot, "../NODEDC_ENGINE_INFRA");
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(here, "../deploy-artifacts"));
|
||||||
|
const stageArtifact = resolve(
|
||||||
|
process.env.NODEDC_N8N_EXTENSION_STAGE_ARTIFACT
|
||||||
|
|| join(artifactRoot, "nodedc-n8n-private-extension-n8n-nodes-ndc-replace-replay-v1-20260721-009.tgz"),
|
||||||
|
);
|
||||||
|
const predecessorArtifact = resolve(
|
||||||
|
process.env.NODEDC_N8N_EXTENSION_PREDECESSOR_ARTIFACT
|
||||||
|
|| join(artifactRoot, "nodedc-engine-n8n-private-extension-20260721-005.tgz"),
|
||||||
|
);
|
||||||
|
|
||||||
|
const stageArtifactSha256 = "4984d4937e2c8de1ecbf5b836cf7fafac131cc0dc64d49c06034507d0cb94577";
|
||||||
|
const predecessorArtifactSha256 = "037d4790b03c0b245b543fe2a841d28f3cfc7822b9a12f2bff9324bf1328b395";
|
||||||
|
const releaseId = "0.1.6-25cc2d7a52a0d0ee";
|
||||||
|
const packageVersion = "0.1.6";
|
||||||
|
const packageSha256 = "25cc2d7a52a0d0ee288b7a4b3de9f436489c010f234498a94bcccd114d7355af";
|
||||||
|
const n8nVersion = "2.3.2";
|
||||||
|
const baseImage = "docker.n8n.io/n8nio/n8n:2.3.2";
|
||||||
|
const architecture = "amd64";
|
||||||
|
const generatedAt = "2026-07-21T12:00:00.000Z";
|
||||||
|
const previouslyIssuedTransitionIds = new Set([
|
||||||
|
"20260715-002",
|
||||||
|
"20260716-003",
|
||||||
|
"20260717-004",
|
||||||
|
"20260717-005",
|
||||||
|
"20260718-006",
|
||||||
|
"20260718-007",
|
||||||
|
"20260718-008",
|
||||||
|
"20260721-005",
|
||||||
|
"20260721-008",
|
||||||
|
]);
|
||||||
|
const transitionId = readTransitionId(process.argv.slice(2), process.env.NODEDC_N8N_TRANSITION_ID);
|
||||||
|
const activationId = `engine-n8n-private-extension-${transitionId}`;
|
||||||
|
const rollbackId = `engine-n8n-private-extension-rollback-${transitionId}`;
|
||||||
|
|
||||||
|
const transitionRoot = "nodedc-source/services/n8n/private-extensions";
|
||||||
|
const descriptorRel = `${transitionRoot}/ndc-activation.json`;
|
||||||
|
const overrideRel = `${transitionRoot}/docker-compose.ndc-private-extension.yml`;
|
||||||
|
const schemaRoot = "nodedc-source/server/assets/n8n/schema/v2.3.2";
|
||||||
|
const nodesCatalogRel = `${schemaRoot}/nodes.catalog.json`;
|
||||||
|
const credentialsCatalogRel = `${schemaRoot}/credentials.catalog.json`;
|
||||||
|
const metaRel = `${schemaRoot}/meta.json`;
|
||||||
|
const iconRoot = "nodedc-source/server/assets/n8n/icons";
|
||||||
|
const iconRel = `${iconRoot}/ndc.svg`;
|
||||||
|
const darkIconRel = `${iconRoot}/ndc.dark.svg`;
|
||||||
|
const runtimePackagePath = "/home/node/.n8n/nodes/node_modules/n8n-nodes-ndc";
|
||||||
|
|
||||||
|
const expectedNodeTypes = [
|
||||||
|
"n8n-nodes-ndc.ndcDataProductPublish",
|
||||||
|
"n8n-nodes-ndc.ndcDataProductRead",
|
||||||
|
"n8n-nodes-ndc.ndcFoundryBinding",
|
||||||
|
];
|
||||||
|
const expectedCredentialTypes = [
|
||||||
|
"ndcDataProductWriterApi",
|
||||||
|
"ndcDataProductReaderApi",
|
||||||
|
"ndcFoundryBindingApi",
|
||||||
|
"ndcProviderRotatingAccessApi",
|
||||||
|
];
|
||||||
|
const predecessorCredentialTypes = [...expectedCredentialTypes];
|
||||||
|
const nodeModules = [
|
||||||
|
["dist/nodes/NdcDataProductPublish/NdcDataProductPublish.node.js", "NdcDataProductPublish"],
|
||||||
|
["dist/nodes/NdcDataProductRead/NdcDataProductRead.node.js", "NdcDataProductRead"],
|
||||||
|
["dist/nodes/NdcFoundryBinding/NdcFoundryBinding.node.js", "NdcFoundryBinding"],
|
||||||
|
];
|
||||||
|
const credentialModules = [
|
||||||
|
["dist/credentials/NdcDataProductWriterApi.credentials.js", "NdcDataProductWriterApi"],
|
||||||
|
["dist/credentials/NdcDataProductReaderApi.credentials.js", "NdcDataProductReaderApi"],
|
||||||
|
["dist/credentials/NdcFoundryBindingApi.credentials.js", "NdcFoundryBindingApi"],
|
||||||
|
["dist/credentials/NdcProviderRotatingAccessApi.credentials.js", "NdcProviderRotatingAccessApi"],
|
||||||
|
];
|
||||||
|
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
await assertArtifactTargetFresh(join(artifactRoot, `nodedc-${activationId}.tgz`));
|
||||||
|
await assertArtifactTargetFresh(join(artifactRoot, `nodedc-${rollbackId}.tgz`));
|
||||||
|
assertSha(await readFile(stageArtifact), stageArtifactSha256, "staging artifact");
|
||||||
|
assertSha(await readFile(predecessorArtifact), predecessorArtifactSha256, "predecessor artifact");
|
||||||
|
assertEngineBaseline(await readFile(join(engineRoot, "docker-compose.yml"), "utf8"));
|
||||||
|
|
||||||
|
const work = await mkdtemp(join(tmpdir(), "nodedc-engine-n8n-sealed-"));
|
||||||
|
try {
|
||||||
|
extractArchive(stageArtifact, work);
|
||||||
|
const stagedRelease = join(work, "payload", "releases", "n8n-nodes-ndc", releaseId);
|
||||||
|
const release = JSON.parse(await readFile(join(stagedRelease, "release.json"), "utf8"));
|
||||||
|
assertRelease(release);
|
||||||
|
assertSha(await readFile(join(stagedRelease, "package.tgz")), packageSha256, "private package");
|
||||||
|
|
||||||
|
const unpacked = join(work, "unpacked");
|
||||||
|
await mkdir(unpacked);
|
||||||
|
extractArchive(join(stagedRelease, "package.tgz"), unpacked);
|
||||||
|
const packageRoot = join(unpacked, "package");
|
||||||
|
const packageJson = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
|
||||||
|
assertPackage(packageJson);
|
||||||
|
|
||||||
|
const devNodeModules = join(platformRoot, "packages", "n8n-nodes-ndc", "node_modules");
|
||||||
|
const nodePath = String(process.env.NODE_PATH || "").split(":").filter(Boolean);
|
||||||
|
if (!nodePath.includes(devNodeModules)) nodePath.unshift(devNodeModules);
|
||||||
|
process.env.NODE_PATH = nodePath.join(":");
|
||||||
|
Module._initPaths();
|
||||||
|
const packageRequire = createRequire(join(packageRoot, "package.json"));
|
||||||
|
const privateNodes = nodeModules.map(([path, className], index) => {
|
||||||
|
const NodeClass = packageRequire(join(packageRoot, path))[className];
|
||||||
|
if (typeof NodeClass !== "function") throw new Error(`node_class_missing:${className}`);
|
||||||
|
const description = structuredClone(new NodeClass().description);
|
||||||
|
description.name = expectedNodeTypes[index];
|
||||||
|
description.icon = { light: "file:ndc.svg", dark: "file:ndc.dark.svg" };
|
||||||
|
if (Object.prototype.hasOwnProperty.call(description, "usableAsTool")) {
|
||||||
|
throw new Error(`tool_variant_forbidden:${description.name}`);
|
||||||
|
}
|
||||||
|
return description;
|
||||||
|
});
|
||||||
|
const privateCredentials = credentialModules.map(([path, className]) => {
|
||||||
|
const CredentialClass = packageRequire(join(packageRoot, path))[className];
|
||||||
|
if (typeof CredentialClass !== "function") throw new Error(`credential_class_missing:${className}`);
|
||||||
|
const description = structuredClone(new CredentialClass());
|
||||||
|
description.icon = { light: "file:ndc.svg", dark: "file:ndc.dark.svg" };
|
||||||
|
return description;
|
||||||
|
});
|
||||||
|
assertExact(privateNodes.map((item) => item.name), expectedNodeTypes, "node types");
|
||||||
|
assertExact(privateCredentials.map((item) => item.name), expectedCredentialTypes, "credential types");
|
||||||
|
assertPublishNodeV2(privateNodes[0]);
|
||||||
|
|
||||||
|
const predecessorDescriptor = JSON.parse(predecessorArtifactFile(descriptorRel));
|
||||||
|
const predecessorNodes = JSON.parse(predecessorArtifactFile(nodesCatalogRel));
|
||||||
|
const predecessorCredentials = JSON.parse(predecessorArtifactFile(credentialsCatalogRel));
|
||||||
|
const predecessorMeta = JSON.parse(predecessorArtifactFile(metaRel));
|
||||||
|
assertPredecessorCatalogs(
|
||||||
|
predecessorDescriptor,
|
||||||
|
predecessorNodes,
|
||||||
|
predecessorCredentials,
|
||||||
|
predecessorMeta,
|
||||||
|
);
|
||||||
|
const baselineNodes = predecessorNodes.filter(
|
||||||
|
(item) => !String(item?.name || "").startsWith("n8n-nodes-ndc."),
|
||||||
|
);
|
||||||
|
const baselineCredentials = predecessorCredentials.filter(
|
||||||
|
(item) => !expectedCredentialTypes.includes(String(item?.name || "")),
|
||||||
|
);
|
||||||
|
assertBaselineCatalogs(baselineNodes, baselineCredentials);
|
||||||
|
const activeNodes = [...baselineNodes, ...privateNodes];
|
||||||
|
const activeCredentials = [...baselineCredentials, ...privateCredentials];
|
||||||
|
const activeMeta = {
|
||||||
|
n8nVersion,
|
||||||
|
generatedAt,
|
||||||
|
source: `n8n-core+n8n-nodes-ndc@${packageVersion}`,
|
||||||
|
nodeCount: activeNodes.length,
|
||||||
|
credentialCount: activeCredentials.length,
|
||||||
|
};
|
||||||
|
|
||||||
|
const target = {
|
||||||
|
releaseId,
|
||||||
|
packageVersion,
|
||||||
|
packageSha256,
|
||||||
|
};
|
||||||
|
const predecessor = {
|
||||||
|
releaseId: predecessorDescriptor.releaseId,
|
||||||
|
packageVersion: predecessorDescriptor.packageVersion,
|
||||||
|
packageSha256: predecessorDescriptor.packageSha256,
|
||||||
|
};
|
||||||
|
const activationDescriptor = descriptor(
|
||||||
|
target,
|
||||||
|
predecessor.releaseId,
|
||||||
|
predecessor.releaseId,
|
||||||
|
expectedCredentialTypes,
|
||||||
|
);
|
||||||
|
const rollbackDescriptor = descriptor(
|
||||||
|
predecessor,
|
||||||
|
releaseId,
|
||||||
|
releaseId,
|
||||||
|
predecessorCredentialTypes,
|
||||||
|
);
|
||||||
|
const override = composeOverride(target);
|
||||||
|
const rollbackOverride = composeOverride(predecessor);
|
||||||
|
|
||||||
|
const generatedRoot = join(work, "generated-engine-payload");
|
||||||
|
await writeJson(join(generatedRoot, nodesCatalogRel), activeNodes);
|
||||||
|
await writeJson(join(generatedRoot, credentialsCatalogRel), activeCredentials);
|
||||||
|
await writeJson(join(generatedRoot, metaRel), activeMeta);
|
||||||
|
await writeJson(join(generatedRoot, descriptorRel), activationDescriptor);
|
||||||
|
await writeFile(join(generatedRoot, overrideRel), override, "utf8");
|
||||||
|
await mkdir(join(generatedRoot, iconRoot), { recursive: true });
|
||||||
|
await cp(join(packageRoot, "dist/icons/ndc.svg"), join(generatedRoot, iconRel), { force: false });
|
||||||
|
await cp(join(packageRoot, "dist/icons/ndc.dark.svg"), join(generatedRoot, darkIconRel), { force: false });
|
||||||
|
|
||||||
|
const activationEntries = [
|
||||||
|
descriptorRel,
|
||||||
|
overrideRel,
|
||||||
|
nodesCatalogRel,
|
||||||
|
credentialsCatalogRel,
|
||||||
|
metaRel,
|
||||||
|
iconRel,
|
||||||
|
darkIconRel,
|
||||||
|
];
|
||||||
|
const activationArtifact = await buildArtifact(work, activationId, activationEntries, async (payload) => {
|
||||||
|
for (const rel of activationEntries) {
|
||||||
|
await cp(join(generatedRoot, rel), join(payload, rel), { recursive: true, force: false });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const rollbackEntries = [...activationEntries];
|
||||||
|
const rollbackArtifact = await buildArtifact(work, rollbackId, rollbackEntries, async (payload) => {
|
||||||
|
await writeJson(join(payload, descriptorRel), rollbackDescriptor);
|
||||||
|
await writeFile(join(payload, overrideRel), rollbackOverride, "utf8");
|
||||||
|
await writeJson(join(payload, nodesCatalogRel), predecessorNodes);
|
||||||
|
await writeJson(join(payload, credentialsCatalogRel), predecessorCredentials);
|
||||||
|
await writeJson(join(payload, metaRel), predecessorMeta);
|
||||||
|
await mkdir(join(payload, iconRoot), { recursive: true });
|
||||||
|
await cp(join(engineRoot, iconRel), join(payload, iconRel), { force: false });
|
||||||
|
await cp(join(engineRoot, darkIconRel), join(payload, darkIconRel), { force: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
transitionId,
|
||||||
|
releaseId,
|
||||||
|
packageSha256,
|
||||||
|
nodeTypes: expectedNodeTypes,
|
||||||
|
credentialTypes: expectedCredentialTypes,
|
||||||
|
activation: activationArtifact,
|
||||||
|
rollback: rollbackArtifact,
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(work, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function descriptor(target, expectedCurrent, rollbackBaseline, credentialTypes) {
|
||||||
|
return {
|
||||||
|
schemaVersion: "nodedc.engine-n8n-private-extension-transition/v1",
|
||||||
|
action: "activate",
|
||||||
|
releaseId: target.releaseId,
|
||||||
|
packageVersion: target.packageVersion,
|
||||||
|
packageSha256: target.packageSha256,
|
||||||
|
n8nVersion,
|
||||||
|
baseImage,
|
||||||
|
baseImageArchitecture: architecture,
|
||||||
|
baseImageIdentityPolicy: "running-container-and-local-tag-must-match",
|
||||||
|
sealedReleaseRelativePath: `n8n-private-extensions/releases/n8n-nodes-ndc/${target.releaseId}/package`,
|
||||||
|
composeOverride: overrideRel,
|
||||||
|
runtimePackagePath,
|
||||||
|
topologyServices: ["n8n"],
|
||||||
|
expectedCurrent,
|
||||||
|
expectedNodeTypes,
|
||||||
|
expectedCredentialTypes: credentialTypes,
|
||||||
|
rollbackBaseline,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function readTransitionId(args, environmentValue) {
|
||||||
|
if (args.length > 1) throw new Error("transition_id_argument_count_invalid");
|
||||||
|
const argumentValue = args[0] || "";
|
||||||
|
const envValue = String(environmentValue || "").trim();
|
||||||
|
if (argumentValue && envValue && argumentValue !== envValue) {
|
||||||
|
throw new Error("transition_id_sources_conflict");
|
||||||
|
}
|
||||||
|
const value = argumentValue || envValue;
|
||||||
|
if (!value) throw new Error("transition_id_required");
|
||||||
|
const match = /^(\d{4})(\d{2})(\d{2})-([0-9]{3})$/.exec(value);
|
||||||
|
if (!match || match[4] === "000") throw new Error("transition_id_invalid");
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]);
|
||||||
|
const day = Number(match[3]);
|
||||||
|
const parsed = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
if (parsed.getUTCFullYear() !== year
|
||||||
|
|| parsed.getUTCMonth() !== month - 1
|
||||||
|
|| parsed.getUTCDate() !== day) {
|
||||||
|
throw new Error("transition_id_invalid");
|
||||||
|
}
|
||||||
|
if (previouslyIssuedTransitionIds.has(value)) {
|
||||||
|
throw new Error("transition_id_already_issued");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertArtifactTargetFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("transition_artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function composeOverride(target) {
|
||||||
|
const health = "const http=require('http');const req=http.get('http://127.0.0.1:5678/healthz/readiness',r=>{r.resume();process.exit(r.statusCode===200?0:1)});req.on('error',()=>process.exit(1));req.setTimeout(4000,()=>{req.destroy();process.exit(1)});";
|
||||||
|
const sealedReleaseRelativePath = `n8n-private-extensions/releases/n8n-nodes-ndc/${target.releaseId}/package`;
|
||||||
|
return [
|
||||||
|
"services:",
|
||||||
|
" n8n:",
|
||||||
|
` image: ${baseImage}`,
|
||||||
|
" platform: linux/amd64",
|
||||||
|
" pull_policy: never",
|
||||||
|
" environment:",
|
||||||
|
" N8N_USER_FOLDER: /home/node",
|
||||||
|
" N8N_COMMUNITY_PACKAGES_ENABLED: \"true\"",
|
||||||
|
" N8N_COMMUNITY_PACKAGES_PREVENT_LOADING: \"false\"",
|
||||||
|
" N8N_REINSTALL_MISSING_PACKAGES: \"false\"",
|
||||||
|
" volumes:",
|
||||||
|
` - /volume2/nodedc-demo/${sealedReleaseRelativePath}:${runtimePackagePath}:ro`,
|
||||||
|
" healthcheck:",
|
||||||
|
` test: ${JSON.stringify(["CMD", "node", "-e", health])}`,
|
||||||
|
" interval: 10s",
|
||||||
|
" timeout: 5s",
|
||||||
|
" retries: 30",
|
||||||
|
" start_period: 30s",
|
||||||
|
" labels:",
|
||||||
|
` nodedc.n8n-private-extension.release: ${target.releaseId}`,
|
||||||
|
` nodedc.n8n-private-extension.package-sha256: ${target.packageSha256}`,
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildArtifact(workRoot, id, entries, populate) {
|
||||||
|
const stage = join(workRoot, id);
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
await mkdir(payload, { recursive: true });
|
||||||
|
await populate(payload);
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, "utf8");
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${id}.tgz`);
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
return { id, artifact, sha256: sha(await readFile(artifact)), entries };
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertRelease(value) {
|
||||||
|
if (value?.releaseId !== releaseId
|
||||||
|
|| value?.package?.name !== "n8n-nodes-ndc"
|
||||||
|
|| value?.package?.version !== packageVersion
|
||||||
|
|| value?.package?.sha256 !== packageSha256
|
||||||
|
|| value?.storage?.relativePath !== `releases/n8n-nodes-ndc/${releaseId}`) {
|
||||||
|
throw new Error("staged_release_identity_mismatch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertPackage(value) {
|
||||||
|
if (value.name !== "n8n-nodes-ndc" || value.version !== packageVersion || value.private !== true) {
|
||||||
|
throw new Error("package_identity_mismatch");
|
||||||
|
}
|
||||||
|
if (value.dependencies !== undefined) throw new Error("runtime_dependencies_forbidden");
|
||||||
|
for (const name of ["preinstall", "install", "postinstall", "prepare", "prepack", "postpack"]) {
|
||||||
|
if (value.scripts?.[name] !== undefined) throw new Error(`lifecycle_forbidden:${name}`);
|
||||||
|
}
|
||||||
|
assertExact(value.n8n?.nodes, nodeModules.map(([path]) => path), "package nodes");
|
||||||
|
assertExact(value.n8n?.credentials, credentialModules.map(([path]) => path), "package credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertPredecessorCatalogs(descriptorValue, nodes, credentials, meta) {
|
||||||
|
if (descriptorValue?.action !== "activate"
|
||||||
|
|| descriptorValue?.releaseId !== "0.1.5-3c8ae53f010d7c88"
|
||||||
|
|| descriptorValue?.packageVersion !== "0.1.5"
|
||||||
|
|| descriptorValue?.packageSha256 !== "3c8ae53f010d7c88b6e90cb8fc4929e7d0880089ad8c3a9edb876ce034786743") {
|
||||||
|
throw new Error("predecessor_descriptor_mismatch");
|
||||||
|
}
|
||||||
|
if (!Array.isArray(nodes) || nodes.length !== 437
|
||||||
|
|| !Array.isArray(credentials) || credentials.length !== 389
|
||||||
|
|| meta?.n8nVersion !== n8nVersion
|
||||||
|
|| meta?.source !== "n8n-core+n8n-nodes-ndc@0.1.5"
|
||||||
|
|| meta?.nodeCount !== 437
|
||||||
|
|| meta?.credentialCount !== 389) {
|
||||||
|
throw new Error("predecessor_catalog_mismatch");
|
||||||
|
}
|
||||||
|
assertExact(
|
||||||
|
nodes.filter((item) => String(item?.name || "").startsWith("n8n-nodes-ndc.")).map((item) => item.name),
|
||||||
|
expectedNodeTypes,
|
||||||
|
"predecessor node types",
|
||||||
|
);
|
||||||
|
assertExact(
|
||||||
|
credentials.filter((item) => predecessorCredentialTypes.includes(String(item?.name || ""))).map((item) => item.name),
|
||||||
|
predecessorCredentialTypes,
|
||||||
|
"predecessor credential types",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertPublishNodeV2(node) {
|
||||||
|
if (JSON.stringify(node?.version) !== JSON.stringify([1, 2])) {
|
||||||
|
throw new Error("publish_node_versions_mismatch");
|
||||||
|
}
|
||||||
|
const property = node?.properties?.find((item) => item?.name === "publishMode");
|
||||||
|
const values = property?.options?.map((item) => item?.value);
|
||||||
|
if (JSON.stringify(values) !== JSON.stringify(["upsert", "replace"])
|
||||||
|
|| !property?.displayOptions?.show?.["@version"]?.includes(2)) {
|
||||||
|
throw new Error("publish_node_replace_contract_missing");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertBaselineCatalogs(nodes, credentials) {
|
||||||
|
if (!Array.isArray(nodes) || nodes.length !== 434 || nodes.some((item) => String(item?.name || "").startsWith("n8n-nodes-ndc."))) {
|
||||||
|
throw new Error("baseline_node_catalog_mismatch");
|
||||||
|
}
|
||||||
|
if (!Array.isArray(credentials) || credentials.length !== 385
|
||||||
|
|| credentials.some((item) => expectedCredentialTypes.includes(String(item?.name || "")))) {
|
||||||
|
throw new Error("baseline_credential_catalog_mismatch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertEngineBaseline(compose) {
|
||||||
|
const exactImage = `image: docker.n8n.io/n8nio/n8n:\${N8N_IMAGE_TAG:-${n8nVersion}}`;
|
||||||
|
if (!compose.includes(exactImage)) throw new Error("engine_n8n_version_mismatch");
|
||||||
|
if ((compose.match(/^ n8n:\s*$/gm) || []).length !== 1) throw new Error("engine_n8n_topology_mismatch");
|
||||||
|
if (/^ n8n-(?:worker|webhook)|^ (?:worker|webhook):/gm.test(compose)) throw new Error("unexpected_n8n_process_service");
|
||||||
|
if (compose.includes("N8N_CUSTOM_EXTENSIONS") || compose.includes("CUSTOM.")) throw new Error("custom_extension_loader_forbidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertExact(actual, expected, label) {
|
||||||
|
if (!Array.isArray(actual) || JSON.stringify(actual) !== JSON.stringify(expected)) {
|
||||||
|
throw new Error(`${label.replaceAll(" ", "_")}_mismatch`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSha(bytes, expected, label) {
|
||||||
|
const actual = sha(bytes);
|
||||||
|
if (actual !== expected) throw new Error(`${label.replaceAll(" ", "_")}_sha256_mismatch:${actual}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function predecessorArtifactFile(rel) {
|
||||||
|
const script = [
|
||||||
|
"import pathlib,sys,tarfile",
|
||||||
|
"archive=pathlib.Path(sys.argv[1])",
|
||||||
|
"member='payload/'+sys.argv[2]",
|
||||||
|
"with tarfile.open(archive,'r:gz') as source:",
|
||||||
|
" extracted=source.extractfile(member)",
|
||||||
|
" if extracted is None: raise SystemExit('predecessor member missing')",
|
||||||
|
" sys.stdout.buffer.write(extracted.read())",
|
||||||
|
].join("\n");
|
||||||
|
return run("python3", ["-c", script, predecessorArtifact, rel]).stdout;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeJson(path, value) {
|
||||||
|
await mkdir(dirname(path), { recursive: true });
|
||||||
|
await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractArchive(archive, destination) {
|
||||||
|
const script = [
|
||||||
|
"import pathlib, sys, tarfile",
|
||||||
|
"src=pathlib.Path(sys.argv[1]); dst=pathlib.Path(sys.argv[2]).resolve()",
|
||||||
|
"with tarfile.open(src, 'r:gz') as tf:",
|
||||||
|
" for m in tf:",
|
||||||
|
" p=pathlib.PurePosixPath(m.name)",
|
||||||
|
" if p.is_absolute() or '..' in p.parts or any(x.startswith('._') for x in p.parts) or not (m.isfile() or m.isdir()): raise SystemExit('unsafe archive member')",
|
||||||
|
" target=dst.joinpath(*p.parts)",
|
||||||
|
" target.mkdir(parents=True, exist_ok=True) if m.isdir() else target.parent.mkdir(parents=True, exist_ok=True)",
|
||||||
|
" if m.isfile():",
|
||||||
|
" source=tf.extractfile(m)",
|
||||||
|
" with open(target, 'xb') as out: out.write(source.read())",
|
||||||
|
].join("\n");
|
||||||
|
run("python3", ["-c", script, archive, destination]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip, io, pathlib, sys, tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1], 'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='', mode='wb', fileobj=out, compresslevel=9, mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p] + (sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x), arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info, src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha(bytes) {
|
||||||
|
return createHash("sha256").update(bytes).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args, cwd) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
cwd,
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,414 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
readdir,
|
||||||
|
rm,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { createReadStream } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(here, "../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_ROOT || join(platformRoot, "../NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
|
||||||
|
const releaseId = "2.33.2-974a9fb3492f";
|
||||||
|
const upstreamCommit = "974a9fb3492fe2c4984ee0549085d531cdc6242a";
|
||||||
|
const imageTag = `nodedc/engine-node-intelligence:${releaseId}`;
|
||||||
|
const predecessorGatewaySha256 = "6b8c80fa997ef7c438d199a6ee942c5e37aebc4057667af417897fa636131db4";
|
||||||
|
const predecessorComposeSha256 = "258cebb64ff1943c939655cc55bdce00fc5c4dced67ec291d84d6df066ace50e";
|
||||||
|
const sourceRootRel = "nodedc-source/server/nodeIntelligence";
|
||||||
|
const gatewayRel = "nodedc-source/server/routes/engineAgentGateway.js";
|
||||||
|
const serviceRootRel = "nodedc-source/services/node-intelligence";
|
||||||
|
const overrideRel = `${serviceRootRel}/docker-compose.immutable-runtime.yml`;
|
||||||
|
const descriptorRel = `${serviceRootRel}/activation.json`;
|
||||||
|
const imageArchiveRel = `${serviceRootRel}/image/engine-node-intelligence.tar`;
|
||||||
|
const activationEntries = [sourceRootRel, gatewayRel, serviceRootRel];
|
||||||
|
const rollbackEntries = [gatewayRel, serviceRootRel];
|
||||||
|
const transitionId = readTransitionId(process.argv.slice(2));
|
||||||
|
const activationId = `engine-node-intelligence-${transitionId}`;
|
||||||
|
const rollbackId = `engine-node-intelligence-rollback-${transitionId}`;
|
||||||
|
const activationTarget = join(artifactRoot, `nodedc-${activationId}.tgz`);
|
||||||
|
const rollbackTarget = join(artifactRoot, `nodedc-${rollbackId}.tgz`);
|
||||||
|
const commandsTarget = join(
|
||||||
|
artifactRoot,
|
||||||
|
`engine-node-intelligence-${transitionId}-plan-apply.txt`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
for (const path of [
|
||||||
|
activationTarget,
|
||||||
|
`${activationTarget}.sha256`,
|
||||||
|
rollbackTarget,
|
||||||
|
`${rollbackTarget}.sha256`,
|
||||||
|
commandsTarget,
|
||||||
|
]) {
|
||||||
|
await assertFresh(path);
|
||||||
|
}
|
||||||
|
await assertEngineInputs();
|
||||||
|
const image = inspectLocalImage();
|
||||||
|
|
||||||
|
const work = await mkdtemp(join(tmpdir(), "nodedc-engine-node-intelligence-"));
|
||||||
|
try {
|
||||||
|
const imageArchive = join(work, "engine-node-intelligence.tar");
|
||||||
|
run("docker", ["image", "save", "--output", imageArchive, imageTag]);
|
||||||
|
const archive = inspectImageArchive(imageArchive);
|
||||||
|
const archiveSha256 = await hashFile(imageArchive);
|
||||||
|
|
||||||
|
const source = {
|
||||||
|
gatewaySha256: await hashFile(join(engineRoot, gatewayRel)),
|
||||||
|
catalogSha256: await hashFile(join(engineRoot, sourceRootRel, "catalog.js")),
|
||||||
|
upstreamClientSha256: await hashFile(join(engineRoot, sourceRootRel, "upstreamMcpClient.js")),
|
||||||
|
upstreamProjectionSha256: await hashFile(join(engineRoot, sourceRootRel, "upstreamProjection.js")),
|
||||||
|
composeOverrideSha256: await hashFile(join(engineRoot, overrideRel)),
|
||||||
|
readmeSha256: await hashFile(join(engineRoot, serviceRootRel, "README.md")),
|
||||||
|
};
|
||||||
|
const activationDescriptor = descriptor({
|
||||||
|
action: "activate",
|
||||||
|
expectedCurrent: "inactive",
|
||||||
|
gatewayPredecessor: predecessorGatewaySha256,
|
||||||
|
source,
|
||||||
|
image: {
|
||||||
|
tag: imageTag,
|
||||||
|
archiveRelativePath: imageArchiveRel,
|
||||||
|
archiveSha256,
|
||||||
|
configSha256: archive.configSha256,
|
||||||
|
architecture: "amd64",
|
||||||
|
os: "linux",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await buildArtifact(
|
||||||
|
work,
|
||||||
|
activationId,
|
||||||
|
activationEntries,
|
||||||
|
activationTarget,
|
||||||
|
async (payload) => {
|
||||||
|
await copyExactDirectory(join(engineRoot, sourceRootRel), join(payload, sourceRootRel));
|
||||||
|
await copyExactFile(join(engineRoot, gatewayRel), join(payload, gatewayRel));
|
||||||
|
await copyExactFile(join(engineRoot, serviceRootRel, "README.md"), join(payload, serviceRootRel, "README.md"));
|
||||||
|
await copyExactFile(join(engineRoot, overrideRel), join(payload, overrideRel));
|
||||||
|
await copyExactFile(imageArchive, join(payload, imageArchiveRel));
|
||||||
|
await writeJson(join(payload, descriptorRel), activationDescriptor);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const rollbackReadme = [
|
||||||
|
"# NDC Engine node intelligence (inactive rollback)",
|
||||||
|
"",
|
||||||
|
`This exact runner-owned descriptor deactivates ${releaseId}.`,
|
||||||
|
"The pinned image and source are retained for audit; the Compose overlay is absent,",
|
||||||
|
"the sidecar is removed, and the verified immutable backend is recreated alone.",
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
const rollbackReadmeSha256 = hashBytes(Buffer.from(rollbackReadme, "utf8"));
|
||||||
|
const rollbackDescriptor = descriptor({
|
||||||
|
action: "rollback-inactive",
|
||||||
|
expectedCurrent: releaseId,
|
||||||
|
gatewayPredecessor: source.gatewaySha256,
|
||||||
|
source: {
|
||||||
|
gatewaySha256: predecessorGatewaySha256,
|
||||||
|
readmeSha256: rollbackReadmeSha256,
|
||||||
|
},
|
||||||
|
image: {
|
||||||
|
tag: imageTag,
|
||||||
|
configSha256: archive.configSha256,
|
||||||
|
architecture: "amd64",
|
||||||
|
os: "linux",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await buildArtifact(
|
||||||
|
work,
|
||||||
|
rollbackId,
|
||||||
|
rollbackEntries,
|
||||||
|
rollbackTarget,
|
||||||
|
async (payload) => {
|
||||||
|
await writeGitFile(gatewayRel, join(payload, gatewayRel));
|
||||||
|
await mkdir(join(payload, serviceRootRel), { recursive: true });
|
||||||
|
await writeFile(join(payload, serviceRootRel, "README.md"), rollbackReadme, "utf8");
|
||||||
|
await writeJson(join(payload, descriptorRel), rollbackDescriptor);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const runnerSha256 = await hashFile(join(here, "nodedc-deploy"));
|
||||||
|
const activationSha256 = await hashFile(activationTarget);
|
||||||
|
const rollbackSha256 = await hashFile(rollbackTarget);
|
||||||
|
await writeFile(
|
||||||
|
`${activationTarget}.sha256`,
|
||||||
|
`${activationSha256} ${activationTarget.split("/").at(-1)}\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
`${rollbackTarget}.sha256`,
|
||||||
|
`${rollbackSha256} ${rollbackTarget.split("/").at(-1)}\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
commandsTarget,
|
||||||
|
commandPlan({ runnerSha256, activationSha256, rollbackSha256 }),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
process.stdout.write(`${JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
transitionId,
|
||||||
|
releaseId,
|
||||||
|
upstreamCommit,
|
||||||
|
image: {
|
||||||
|
tag: imageTag,
|
||||||
|
localId: image.Id,
|
||||||
|
archiveSha256,
|
||||||
|
configSha256: archive.configSha256,
|
||||||
|
architecture: archive.architecture,
|
||||||
|
os: archive.os,
|
||||||
|
},
|
||||||
|
runner: { sha256: runnerSha256 },
|
||||||
|
activation: { artifact: activationTarget, sha256: activationSha256, entries: activationEntries },
|
||||||
|
rollback: { artifact: rollbackTarget, sha256: rollbackSha256, entries: rollbackEntries },
|
||||||
|
commands: commandsTarget,
|
||||||
|
}, null, 2)}\n`);
|
||||||
|
} finally {
|
||||||
|
await rm(work, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function readTransitionId(args) {
|
||||||
|
if (args.length !== 1) throw new Error("usage: build-engine-node-intelligence-artifacts.mjs YYYYMMDD-NNN");
|
||||||
|
const value = String(args[0] || "").trim();
|
||||||
|
const match = /^(\d{4})(\d{2})(\d{2})-([0-9]{3})$/.exec(value);
|
||||||
|
if (!match || match[4] === "000") throw new Error("transition_id_invalid");
|
||||||
|
const parsed = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
|
||||||
|
if (
|
||||||
|
parsed.getUTCFullYear() !== Number(match[1])
|
||||||
|
|| parsed.getUTCMonth() !== Number(match[2]) - 1
|
||||||
|
|| parsed.getUTCDate() !== Number(match[3])
|
||||||
|
) throw new Error("transition_id_invalid");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error(`target_already_exists:${path}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertEngineInputs() {
|
||||||
|
const baselineGateway = Buffer.from(run("git", ["show", `HEAD:${gatewayRel}`], engineRoot).stdout, "utf8");
|
||||||
|
if (hashBytes(baselineGateway) !== predecessorGatewaySha256) throw new Error("gateway_predecessor_mismatch");
|
||||||
|
if (await hashFile(join(engineRoot, "docker-compose.yml")) !== predecessorComposeSha256) {
|
||||||
|
throw new Error("compose_predecessor_mismatch");
|
||||||
|
}
|
||||||
|
const sourceFiles = (await readdir(join(engineRoot, sourceRootRel))).sort();
|
||||||
|
if (JSON.stringify(sourceFiles) !== JSON.stringify(["catalog.js", "upstreamMcpClient.js", "upstreamProjection.js"])) {
|
||||||
|
throw new Error("node_intelligence_source_exact_set_mismatch");
|
||||||
|
}
|
||||||
|
const serviceFiles = (await readdir(join(engineRoot, serviceRootRel))).sort();
|
||||||
|
if (JSON.stringify(serviceFiles) !== JSON.stringify(["README.md", "docker-compose.immutable-runtime.yml"])) {
|
||||||
|
throw new Error("node_intelligence_service_exact_set_mismatch");
|
||||||
|
}
|
||||||
|
const gateway = await readFile(join(engineRoot, gatewayRel), "utf8");
|
||||||
|
for (const tool of [
|
||||||
|
"engine_get_node_intelligence_status",
|
||||||
|
"engine_get_node_guidance",
|
||||||
|
"engine_validate_node_configuration",
|
||||||
|
"engine_validate_l2_deep",
|
||||||
|
]) {
|
||||||
|
if (!gateway.includes(tool)) throw new Error(`gateway_tool_missing:${tool}`);
|
||||||
|
}
|
||||||
|
const override = await readFile(join(engineRoot, overrideRel), "utf8");
|
||||||
|
for (const exact of [
|
||||||
|
`image: ${imageTag}`,
|
||||||
|
"pull_policy: never",
|
||||||
|
'user: "11007:11007"',
|
||||||
|
"AUTH_TOKEN_FILE: /run/nodedc-secrets/engine-node-intelligence-auth-token",
|
||||||
|
"ENGINE_NODE_INTELLIGENCE_AUTH_TOKEN_FILE: /run/nodedc-secrets/engine-node-intelligence-auth-token",
|
||||||
|
"read_only: true",
|
||||||
|
"no-new-privileges:true",
|
||||||
|
]) {
|
||||||
|
if (!override.includes(exact)) throw new Error(`compose_contract_missing:${exact}`);
|
||||||
|
}
|
||||||
|
if (/^\s*(?:AUTH_TOKEN|N8N_API_URL|N8N_API_KEY):/m.test(override)) {
|
||||||
|
throw new Error("compose_runtime_authority_forbidden");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspectLocalImage() {
|
||||||
|
const raw = run("docker", ["image", "inspect", imageTag]).stdout;
|
||||||
|
const images = JSON.parse(raw);
|
||||||
|
if (!Array.isArray(images) || images.length !== 1) throw new Error("image_inspect_shape_mismatch");
|
||||||
|
const image = images[0];
|
||||||
|
const config = image.Config || {};
|
||||||
|
const labels = config.Labels || {};
|
||||||
|
if (
|
||||||
|
!/^sha256:[a-f0-9]{64}$/.test(String(image.Id || ""))
|
||||||
|
|| image.Architecture !== "amd64"
|
||||||
|
|| image.Os !== "linux"
|
||||||
|
|| !(image.RepoTags || []).includes(imageTag)
|
||||||
|
|| labels["org.opencontainers.image.revision"] !== upstreamCommit
|
||||||
|
|| JSON.stringify(config.Entrypoint) !== JSON.stringify(["/usr/local/bin/docker-entrypoint.sh"])
|
||||||
|
|| JSON.stringify(config.Cmd) !== JSON.stringify(["node", "dist/mcp/index.js"])
|
||||||
|
|| (config.Env || []).some((value) => /^(?:AUTH_TOKEN|N8N_API_URL|N8N_API_KEY)=/.test(String(value)))
|
||||||
|
) throw new Error("image_identity_mismatch");
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspectImageArchive(path) {
|
||||||
|
const script = [
|
||||||
|
"import hashlib,json,pathlib,sys,tarfile",
|
||||||
|
"p=pathlib.Path(sys.argv[1])",
|
||||||
|
"with tarfile.open(p,'r:') as tf:",
|
||||||
|
" m=json.loads(tf.extractfile('manifest.json').read())",
|
||||||
|
" if not isinstance(m,list) or len(m)!=1: raise SystemExit('manifest-set')",
|
||||||
|
" r=m[0]",
|
||||||
|
` if r.get('RepoTags')!=[${JSON.stringify(imageTag)}]: raise SystemExit('tag')`,
|
||||||
|
" n=r.get('Config','')",
|
||||||
|
" raw=tf.extractfile(n).read()",
|
||||||
|
" digest=n.rsplit('/',1)[-1]",
|
||||||
|
" if hashlib.sha256(raw).hexdigest()!=digest: raise SystemExit('config-digest')",
|
||||||
|
" c=json.loads(raw)",
|
||||||
|
" cfg=c.get('config') or {}",
|
||||||
|
` if c.get('architecture')!='amd64' or c.get('os')!='linux' or (cfg.get('Labels') or {}).get('org.opencontainers.image.revision')!=${JSON.stringify(upstreamCommit)}: raise SystemExit('identity')`,
|
||||||
|
" if cfg.get('Entrypoint')!=['/usr/local/bin/docker-entrypoint.sh'] or cfg.get('Cmd')!=['node','dist/mcp/index.js']: raise SystemExit('command')",
|
||||||
|
" print(json.dumps({'configSha256':digest,'architecture':c['architecture'],'os':c['os']}))",
|
||||||
|
].join("\n");
|
||||||
|
return JSON.parse(run("python3", ["-c", script, path]).stdout);
|
||||||
|
}
|
||||||
|
|
||||||
|
function descriptor({ action, expectedCurrent, gatewayPredecessor, source, image }) {
|
||||||
|
return {
|
||||||
|
schemaVersion: "nodedc.engine-node-intelligence-transition/v1",
|
||||||
|
action,
|
||||||
|
releaseId,
|
||||||
|
expectedCurrent,
|
||||||
|
upstream: {
|
||||||
|
package: "n8n-mcp",
|
||||||
|
version: "2.33.2",
|
||||||
|
commit: upstreamCommit,
|
||||||
|
},
|
||||||
|
image,
|
||||||
|
source,
|
||||||
|
predecessor: {
|
||||||
|
gatewaySha256: gatewayPredecessor,
|
||||||
|
composeSha256: predecessorComposeSha256,
|
||||||
|
backendRuntime: "verified-derived-retry",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildArtifact(workRoot, id, entries, target, populate) {
|
||||||
|
const stage = join(workRoot, id);
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
await mkdir(payload, { recursive: true });
|
||||||
|
await populate(payload);
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, "utf8");
|
||||||
|
run("python3", ["-c", canonicalTarScript(), target, stage]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyExactDirectory(source, target) {
|
||||||
|
await mkdir(target, { recursive: true });
|
||||||
|
for (const name of (await readdir(source)).sort()) {
|
||||||
|
await copyExactFile(join(source, name), join(target, name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyExactFile(source, target) {
|
||||||
|
const sourceStat = await lstat(source);
|
||||||
|
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) throw new Error(`source_file_unsafe:${source}`);
|
||||||
|
await mkdir(dirname(target), { recursive: true });
|
||||||
|
await copyFile(source, target, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeGitFile(relativePath, target) {
|
||||||
|
const value = run("git", ["show", `HEAD:${relativePath}`], engineRoot).stdout;
|
||||||
|
await mkdir(dirname(target), { recursive: true });
|
||||||
|
await writeFile(target, value, "utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeJson(path, value) {
|
||||||
|
await mkdir(dirname(path), { recursive: true });
|
||||||
|
await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function commandPlan({ runnerSha256, activationSha256, rollbackSha256 }) {
|
||||||
|
return [
|
||||||
|
`transition=${transitionId}`,
|
||||||
|
`runner_sha256=${runnerSha256}`,
|
||||||
|
`activation_sha256=${activationSha256}`,
|
||||||
|
`rollback_sha256=${rollbackSha256}`,
|
||||||
|
"",
|
||||||
|
"# 1. Read-only gate: no deploy process and no state/deploy.lock.",
|
||||||
|
"# 2. Promote the exact staged runner in a standalone sudo step:",
|
||||||
|
`sudo sha256sum /volume1/docker/nodedc-deploy/runner-install/candidates/nodedc-deploy.${activationId}`,
|
||||||
|
"sudo install -o root -g root -m 0755 \\",
|
||||||
|
` /volume1/docker/nodedc-deploy/runner-install/candidates/nodedc-deploy.${activationId} \\`,
|
||||||
|
" /usr/local/sbin/nodedc-deploy",
|
||||||
|
"sudo /usr/local/sbin/nodedc-deploy verify-install",
|
||||||
|
"",
|
||||||
|
"# 3. Activation is always plan, then explicit apply:",
|
||||||
|
`sudo /usr/local/sbin/nodedc-deploy plan /volume1/docker/nodedc-deploy/inbox/${activationTarget.split("/").at(-1)}`,
|
||||||
|
`sudo /usr/local/sbin/nodedc-deploy apply /volume1/docker/nodedc-deploy/inbox/${activationTarget.split("/").at(-1)}`,
|
||||||
|
"",
|
||||||
|
"# 4. Rollback is operator-invoked only after its own plan:",
|
||||||
|
`sudo /usr/local/sbin/nodedc-deploy plan /volume1/docker/nodedc-deploy/inbox/${rollbackTarget.split("/").at(-1)}`,
|
||||||
|
`sudo /usr/local/sbin/nodedc-deploy apply /volume1/docker/nodedc-deploy/inbox/${rollbackTarget.split("/").at(-1)}`,
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function hashBytes(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function hashFile(path) {
|
||||||
|
return new Promise((resolveHash, rejectHash) => {
|
||||||
|
const digest = createHash("sha256");
|
||||||
|
const input = createReadStream(path);
|
||||||
|
input.on("data", (chunk) => digest.update(chunk));
|
||||||
|
input.on("error", rejectHash);
|
||||||
|
input.on("end", () => resolveHash(digest.digest("hex")));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args, cwd) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
cwd,
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const baselineArtifact = resolve(
|
||||||
|
here,
|
||||||
|
"../deploy-artifacts/nodedc-engine-mcp-autonomy-provider-v5-20260720-004.tgz",
|
||||||
|
);
|
||||||
|
const baselineArtifactSha256 =
|
||||||
|
"3400954cdce078892a06b04b9bfd85a90f6ea775b1a0caf99eba1f880ef6601c";
|
||||||
|
const projectionRel = "nodedc-source/server/nodeIntelligence/upstreamProjection.js";
|
||||||
|
const descriptorRel = "nodedc-source/services/node-intelligence/activation.json";
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^engine-provider-authority-diagnostics-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-provider-authority-diagnostics-artifact.mjs " +
|
||||||
|
"<engine-provider-authority-diagnostics-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
[projectionRel]:
|
||||||
|
"2dfa6b4f37d9bfa8b92a8109d4060d02dd2634ceb8f7924504b83ccf3fdd1523",
|
||||||
|
[descriptorRel]:
|
||||||
|
"84b0e15a10cedf334ad04d6f31c908da2dc155503c9974f0eeb75b01e20fb884",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const descriptorText = await buildTargetDescriptor();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-authority-diagnostics-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
if (relativePath === descriptorRel) {
|
||||||
|
await writeFile(destination, descriptorText, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "private-node-name-reconciliation",
|
||||||
|
validationBoundary: "engine-pinned-private-node-catalog",
|
||||||
|
privateNodeIdentity: "node-id-or-exact-display-name",
|
||||||
|
credentialValues: "preserved",
|
||||||
|
untouched: ["L2 graph", "n8n", "L1", "Engine UI", "databases"],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
if (relativePath === descriptorRel) continue;
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_provider_authority_diagnostics_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_provider_authority_diagnostics_target_mismatch:${relativePath}:` +
|
||||||
|
`expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const source = await readFile(sourcePath, "utf8");
|
||||||
|
for (const marker of [
|
||||||
|
"isUnknownPrivateNodeIssue",
|
||||||
|
"issue?.nodeName || issue?.node",
|
||||||
|
"privateResults",
|
||||||
|
"NDC_PRIVATE_NODE_VALIDATED_BY_ENGINE_CATALOG",
|
||||||
|
]) {
|
||||||
|
if (!source.includes(marker)) {
|
||||||
|
throw new Error(`engine_provider_authority_diagnostics_marker_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildTargetDescriptor() {
|
||||||
|
const baselineBytes = await readFile(baselineArtifact);
|
||||||
|
if (digest(baselineBytes) !== baselineArtifactSha256) {
|
||||||
|
throw new Error("engine_node_intelligence_baseline_artifact_sha256_mismatch");
|
||||||
|
}
|
||||||
|
const result = run("python3", [
|
||||||
|
"-c",
|
||||||
|
[
|
||||||
|
"import pathlib,sys,tarfile",
|
||||||
|
"p=pathlib.Path(sys.argv[1]); name=sys.argv[2]",
|
||||||
|
"with tarfile.open(p,'r:gz') as t:",
|
||||||
|
" m=t.getmember(name)",
|
||||||
|
" if not m.isfile(): raise SystemExit('member-not-file')",
|
||||||
|
" f=t.extractfile(m)",
|
||||||
|
" if f is None: raise SystemExit('member-unreadable')",
|
||||||
|
" sys.stdout.buffer.write(f.read())",
|
||||||
|
].join("\n"),
|
||||||
|
baselineArtifact,
|
||||||
|
`payload/${descriptorRel}`,
|
||||||
|
]);
|
||||||
|
const descriptor = JSON.parse(result.stdout);
|
||||||
|
if (
|
||||||
|
descriptor?.schemaVersion !== "nodedc.engine-node-intelligence-transition/v1"
|
||||||
|
|| descriptor?.action !== "activate"
|
||||||
|
|| descriptor?.releaseId !== "2.33.2-974a9fb3492f"
|
||||||
|
|| descriptor?.source?.upstreamProjectionSha256
|
||||||
|
!== "761a874b102a938bc6018159ddacdaac71ad6ae08e9f0f8d7f3b58a0165a5131"
|
||||||
|
|| descriptor?.source?.gatewaySha256
|
||||||
|
!== "5331f6dc8dc306f641370a2968eb025ee3e278e27ae9a217e4cfc2901fec369c"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_node_intelligence_baseline_descriptor_mismatch");
|
||||||
|
}
|
||||||
|
descriptor.source.upstreamProjectionSha256 = targetSha256[projectionRel];
|
||||||
|
const text = `${JSON.stringify(descriptor, null, 2)}\n`;
|
||||||
|
if (digest(Buffer.from(text, "utf8")) !== targetSha256[descriptorRel]) {
|
||||||
|
throw new Error("engine_node_intelligence_target_descriptor_sha256_mismatch");
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^engine-provider-rotating-slot-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-provider-rotating-slot-artifact.mjs " +
|
||||||
|
"<engine-provider-rotating-slot-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/assets/provider-packages/v1/catalog.json":
|
||||||
|
"17f3e368f3264cbbd708965c9e1fd735aa974f15a1383bf88cd6d14a43dbf32d",
|
||||||
|
"nodedc-source/server/dataProductPublishGrant/providerCatalog.js":
|
||||||
|
"f6cf5f4de9e57f87fb904e2136a9f34d494e1ffc289aec3ed9ed788b5583a062",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-rotating-slot-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "exact-active-credential-slot-alignment",
|
||||||
|
providerPackage: "gelios.provider.v4",
|
||||||
|
authModeId: "gelios.rest-rotating-bearer.v3",
|
||||||
|
credentialSlot: "ndcProviderRotatingAccessApi",
|
||||||
|
credentialValues: "preserved",
|
||||||
|
untouched: ["L2 graph", "n8n", "L1", "Engine UI", "databases"],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const path = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(path);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_provider_rotating_slot_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(path));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_provider_rotating_slot_target_mismatch:${relativePath}:` +
|
||||||
|
`expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const catalog = JSON.parse(await readFile(join(engineRoot, entries[0]), "utf8"));
|
||||||
|
const provider = catalog?.packages?.[0];
|
||||||
|
if (
|
||||||
|
provider?.id !== "gelios.provider.v4" ||
|
||||||
|
provider?.providerCredential?.authModeId !== "gelios.rest-rotating-bearer.v3" ||
|
||||||
|
provider?.providerCredential?.credentialType !== "ndcProviderRotatingAccessApi"
|
||||||
|
) {
|
||||||
|
throw new Error("engine_provider_rotating_slot_catalog_projection_mismatch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(here, "../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, "../NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [transitionId = "20260723-025", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
|
||||||
|
throw new Error("usage: build-engine-provider-security-catalog-artifact.mjs [YYYYMMDD-NNN]");
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `engine-provider-security-catalog-${transitionId}`;
|
||||||
|
const target = join(artifactRoot, `nodedc-${id}.tgz`);
|
||||||
|
const file = "nodedc-source/server/assets/provider-packages/v1/catalog.json";
|
||||||
|
const expectedSha256 = "773335bb616a5c03eb2108c4f53ef092c02e75ee75f014511201bc12e2956b27";
|
||||||
|
const source = join(engineRoot, file);
|
||||||
|
const catalogBytes = await readFile(source);
|
||||||
|
|
||||||
|
await assertFresh(target);
|
||||||
|
if (sha(catalogBytes) !== expectedSha256) throw new Error(`pinned_catalog_sha256_mismatch:${file}`);
|
||||||
|
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-security-catalog-"));
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(join(payload, file)), { recursive: true });
|
||||||
|
await cp(source, join(payload, file), { force: false });
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${file}\n`, "utf8");
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), target, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
id,
|
||||||
|
artifact: target,
|
||||||
|
artifactSha256: sha(await readFile(target)),
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
providerPackage: "gelios.provider.v8",
|
||||||
|
providerCredential: "ndcProviderRotatingAccessApi",
|
||||||
|
endpoint: "https://api.geliospro.com/api/v1/units?incltrip=true&inclcntrs=true&inclsnsrs=true&incllsv=true",
|
||||||
|
dataProductId: "fleet.units.profile.current.v1",
|
||||||
|
preserved: ["n8n", "L1 graph", "Engine UI", "databases", "provider credential values"],
|
||||||
|
files: [file],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const workspaceRoot = resolve(here, "../../..");
|
||||||
|
const engineRoot = resolve(
|
||||||
|
process.env.NODEDC_ENGINE_SOURCE_ROOT || join(workspaceRoot, "NODEDC_ENGINE_INFRA"),
|
||||||
|
);
|
||||||
|
const artifactRoot = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "", ...extra] = process.argv.slice(2);
|
||||||
|
if (extra.length || !/^engine-provider-target-host-policy-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-engine-provider-target-host-policy-artifact.mjs " +
|
||||||
|
"<engine-provider-target-host-policy-YYYYMMDD-NNN>",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetSha256 = Object.freeze({
|
||||||
|
"nodedc-source/server/routes/n8n.js":
|
||||||
|
"9bc3638e271102abec91bb80413329befb89d60c0e4dc0548f0dd11e93220d0a",
|
||||||
|
});
|
||||||
|
const entries = Object.freeze(Object.keys(targetSha256));
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertExactSources();
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-target-host-policy-"));
|
||||||
|
try {
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
for (const relativePath of entries) {
|
||||||
|
const destination = join(payload, relativePath);
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await copyFile(join(engineRoot, relativePath), destination);
|
||||||
|
}
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o644,
|
||||||
|
});
|
||||||
|
await mkdir(artifactRoot, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
targetSha256,
|
||||||
|
services: ["nodedc-backend"],
|
||||||
|
transition: "exact-provider-literal-target-host",
|
||||||
|
providerPackage: "gelios.provider.v4",
|
||||||
|
dataProductId: "fleet.positions.current.v3",
|
||||||
|
credentialValues: "preserved",
|
||||||
|
untouched: ["L2 graph", "n8n", "L1", "Engine UI", "databases"],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertExactSources() {
|
||||||
|
for (const [relativePath, expected] of Object.entries(targetSha256)) {
|
||||||
|
const sourcePath = join(engineRoot, relativePath);
|
||||||
|
const info = await lstat(sourcePath);
|
||||||
|
if (!info.isFile() || info.isSymbolicLink()) {
|
||||||
|
throw new Error(`engine_provider_target_host_policy_source_unsafe:${relativePath}`);
|
||||||
|
}
|
||||||
|
const actual = digest(await readFile(sourcePath));
|
||||||
|
if (actual !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`engine_provider_target_host_policy_target_mismatch:${relativePath}:` +
|
||||||
|
`expected=${expected}:actual=${actual}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const source = await readFile(sourcePath, "utf8");
|
||||||
|
for (const marker of [
|
||||||
|
"const eligibleHosts = explicitHosts.length",
|
||||||
|
"allowedHosts: [targetHost]",
|
||||||
|
"credential_host_not_allowed",
|
||||||
|
]) {
|
||||||
|
if (!source.includes(marker)) {
|
||||||
|
throw new Error(`engine_provider_target_host_policy_marker_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { dirname, join, resolve } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url))
|
||||||
|
const platformRoot = resolve(here, '../..')
|
||||||
|
const workspaceRoot = resolve(platformRoot, '..')
|
||||||
|
const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA')
|
||||||
|
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts'))
|
||||||
|
const [patchId = '', ...extra] = process.argv.slice(2)
|
||||||
|
|
||||||
|
if (extra.length || !/^engine-restart-safe-auth-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error('usage: build-engine-restart-safe-auth-artifact.mjs engine-restart-safe-auth-YYYYMMDD-NNN')
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = Object.freeze([
|
||||||
|
'nodedc-source/server/auth/engineHandoffSession.js',
|
||||||
|
'nodedc-source/server/index.js',
|
||||||
|
'nodedc-source/src/App.tsx',
|
||||||
|
'nodedc-source/src/platform/auth/access.ts',
|
||||||
|
'nodedc-source/src/platform/auth/sessionRecovery.ts',
|
||||||
|
'nodedc-source/dist/index.html',
|
||||||
|
'nodedc-source/dist/assets/index-Bim2pv1P.css',
|
||||||
|
'nodedc-source/dist/assets/index-4TenBzkg.js',
|
||||||
|
])
|
||||||
|
|
||||||
|
const candidateSha256 = Object.freeze({
|
||||||
|
'nodedc-source/server/auth/engineHandoffSession.js': '0cc5bf02b11cd5fc8cc8cad018091ca93efb13bc72616348ada61105af15bd8e',
|
||||||
|
'nodedc-source/server/index.js': '0ac408e0e9a7bc5c8e13a00afc957b982b065e2bc414919839e0b0a11aa05ba4',
|
||||||
|
'nodedc-source/src/App.tsx': 'd9bc0f23ceaaf4f5534ac9a9b1f97d84fd8eee4679c59b5999b5a75b8c77bb32',
|
||||||
|
'nodedc-source/src/platform/auth/access.ts': '9610dc1622a1c9b383eb3a1569347098002aa058dbbcbb23f096f2622d452222',
|
||||||
|
'nodedc-source/src/platform/auth/sessionRecovery.ts': 'f931cbb45d64d5d6a2868194e8c73879a408dffca1fdd7e41acfa262441c50d7',
|
||||||
|
'nodedc-source/dist/index.html': 'b031f6720683f6fb5ccfa59a01414ff2a3efcdf548b1c6aab33e1748ee3f003d',
|
||||||
|
'nodedc-source/dist/assets/index-Bim2pv1P.css': '18322addd45c126a7b8396f36b005f3085fddba3e9b346dd2c910f6fa6987ebf',
|
||||||
|
'nodedc-source/dist/assets/index-4TenBzkg.js': 'a48fcacf3348c20a432cd6da2627b89c0c3e54bc989c727b620125dd3412538a',
|
||||||
|
})
|
||||||
|
|
||||||
|
const predecessorSha256 = Object.freeze({
|
||||||
|
'nodedc-source/server/index.js': 'b2b790b02839570d967a2ca68b00e2724485a99389ac9b3a589a1b22302a36b8',
|
||||||
|
'nodedc-source/src/App.tsx': '2ea264a59c3e82f763be74f0312cb1aa6bce856644ba0bc7024d77e238e7eb41',
|
||||||
|
'nodedc-source/src/platform/auth/access.ts': '4fb9c4d524765dff8a5360efa1c0acf1d203da1cc2c7fd3b98e1456261d43d41',
|
||||||
|
'nodedc-source/src/platform/auth/sessionRecovery.ts': '997d3a18e439308d4650e3c7324710a8b17dea29976001c4275c84d96b18ccfe',
|
||||||
|
})
|
||||||
|
|
||||||
|
for (const [rel, expected] of Object.entries(predecessorSha256)) {
|
||||||
|
const result = spawnSync('git', ['-C', engineRoot, 'show', `HEAD:${rel}`], {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
if (result.status !== 0 || digest(result.stdout) !== expected) {
|
||||||
|
throw new Error(`engine_auth_predecessor_mismatch:${rel}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const newModulePath = 'nodedc-source/server/auth/engineHandoffSession.js'
|
||||||
|
const newModuleProbe = spawnSync('git', ['-C', engineRoot, 'cat-file', '-e', `HEAD:${newModulePath}`], {
|
||||||
|
stdio: 'ignore',
|
||||||
|
})
|
||||||
|
if (newModuleProbe.status === 0) throw new Error('engine_auth_new_module_predecessor_unexpected')
|
||||||
|
|
||||||
|
for (const rel of entries) {
|
||||||
|
const source = resolve(engineRoot, rel)
|
||||||
|
const info = await lstat(source)
|
||||||
|
if (info.isSymbolicLink() || !info.isFile()) throw new Error(`engine_auth_candidate_unsafe:${rel}`)
|
||||||
|
if (digest(await readFile(source)) !== candidateSha256[rel]) {
|
||||||
|
throw new Error(`engine_auth_candidate_sha256_mismatch:${rel}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const indexHtml = await readFile(resolve(engineRoot, 'nodedc-source/dist/index.html'), 'utf8')
|
||||||
|
if (!indexHtml.includes('/assets/index-4TenBzkg.js') || !indexHtml.includes('/assets/index-Bim2pv1P.css')) {
|
||||||
|
throw new Error('engine_auth_dist_entrypoint_mismatch')
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(artifactRoot, { recursive: true })
|
||||||
|
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`)
|
||||||
|
await assertArtifactTargetFresh(artifact)
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-restart-safe-auth-'))
|
||||||
|
|
||||||
|
try {
|
||||||
|
await writeFile(
|
||||||
|
join(stage, 'manifest.env'),
|
||||||
|
`id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8')
|
||||||
|
for (const rel of entries) {
|
||||||
|
const target = join(stage, 'payload', rel)
|
||||||
|
await mkdir(dirname(target), { recursive: true })
|
||||||
|
await copyFile(resolve(engineRoot, rel), target)
|
||||||
|
}
|
||||||
|
run('python3', ['-c', canonicalTarScript(), artifact, stage])
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
sha256: digest(await readFile(artifact)),
|
||||||
|
entries,
|
||||||
|
predecessorSha256,
|
||||||
|
candidateSha256,
|
||||||
|
runtimeServices: ['nodedc-backend', 'app'],
|
||||||
|
}, null, 2))
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertArtifactTargetFresh(target) {
|
||||||
|
try {
|
||||||
|
await lstat(target)
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ENOENT') return
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('engine_auth_artifact_already_exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
'import gzip,io,pathlib,sys,tarfile',
|
||||||
|
'root=pathlib.Path(sys.argv[2])',
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
' for x in paths:',
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(bytes) {
|
||||||
|
return createHash('sha256').update(bytes).digest('hex')
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, relative, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(scriptDir, "../..");
|
||||||
|
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
|
||||||
|
const [patchId = "external-data-plane-20260714-001", ...extra] = process.argv.slice(2);
|
||||||
|
|
||||||
|
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
|
||||||
|
throw new Error("usage: build-external-data-plane-artifact.mjs [patch-id]");
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = [
|
||||||
|
["infra/synology/docker-compose.external-data-plane.yml", "platform/docker-compose.external-data-plane.yml"],
|
||||||
|
["services/external-data-plane", "platform/services/external-data-plane"],
|
||||||
|
["packages/external-provider-contract/package.json", "platform/packages/external-provider-contract/package.json"],
|
||||||
|
["packages/external-provider-contract/src/contract-version.mjs", "platform/packages/external-provider-contract/src/contract-version.mjs"],
|
||||||
|
["packages/external-provider-contract/src/data-plane.mjs", "platform/packages/external-provider-contract/src/data-plane.mjs"],
|
||||||
|
["packages/external-provider-contract/src/data-product.mjs", "platform/packages/external-provider-contract/src/data-product.mjs"],
|
||||||
|
["packages/external-provider-contract/src/geometry.mjs", "platform/packages/external-provider-contract/src/geometry.mjs"],
|
||||||
|
["packages/external-provider-contract/src/intake-batch.mjs", "platform/packages/external-provider-contract/src/intake-batch.mjs"],
|
||||||
|
["packages/external-provider-contract/src/index.mjs", "platform/packages/external-provider-contract/src/index.mjs"],
|
||||||
|
["packages/external-provider-contract/src/provider-capability-catalog.mjs", "platform/packages/external-provider-contract/src/provider-capability-catalog.mjs"],
|
||||||
|
["packages/external-provider-contract/src/provider-package.mjs", "platform/packages/external-provider-contract/src/provider-package.mjs"],
|
||||||
|
["packages/external-provider-contract/src/sensitive-field-policy.mjs", "platform/packages/external-provider-contract/src/sensitive-field-policy.mjs"],
|
||||||
|
["packages/external-provider-contract/src/telemetry-readings.mjs", "platform/packages/external-provider-contract/src/telemetry-readings.mjs"],
|
||||||
|
["packages/external-provider-contract/src/zone-source.mjs", "platform/packages/external-provider-contract/src/zone-source.mjs"],
|
||||||
|
["packages/external-provider-contract/providers/gelios", "platform/packages/external-provider-contract/providers/gelios"],
|
||||||
|
];
|
||||||
|
const ignoredBasenames = new Set([".DS_Store", ".git", "node_modules"]);
|
||||||
|
const ignoredDirectoryNames = new Set(["test"]);
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-external-data-plane-artifact-"));
|
||||||
|
const payload = join(stage, "payload");
|
||||||
|
const target = join(artifactDir, `nodedc-platform-${patchId}.tgz`);
|
||||||
|
|
||||||
|
await assertSourceBoundary();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mkdir(payload, { recursive: true });
|
||||||
|
for (const [sourceRelative, destinationRelative] of files) {
|
||||||
|
await copySafe(resolve(platformRoot, sourceRelative), join(payload, destinationRelative));
|
||||||
|
}
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=platform\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${files.map(([, destination]) => destination).join("\n")}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
|
||||||
|
const tar = spawnSync("python3", ["-c", canonicalTarScript(), target, stage], {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 128 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
|
||||||
|
|
||||||
|
const digest = createHash("sha256").update(await readFile(target)).digest("hex");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact: target,
|
||||||
|
sha256: digest,
|
||||||
|
entries: files.map(([, destination]) => destination),
|
||||||
|
excluded: [
|
||||||
|
".env*",
|
||||||
|
"node_modules",
|
||||||
|
"services/external-data-plane/test",
|
||||||
|
"private-key.pem",
|
||||||
|
"secrets",
|
||||||
|
],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertSourceBoundary() {
|
||||||
|
const compose = await readFile(
|
||||||
|
resolve(platformRoot, "infra/synology/docker-compose.external-data-plane.yml"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const fragment of [
|
||||||
|
"source: /volume1/docker/nodedc-platform/trust/engine-managed-provisioner",
|
||||||
|
"target: /run/nodedc-trust/engine-managed-provisioner",
|
||||||
|
"EXTERNAL_DATA_PLANE_MANAGED_PROVISIONER_PUBLIC_KEY_FILE: /run/nodedc-trust/engine-managed-provisioner/public-key.pem",
|
||||||
|
"source: /volume1/docker/nodedc-platform/trust/foundry-managed-provisioner",
|
||||||
|
"target: /run/nodedc-trust/foundry-managed-provisioner",
|
||||||
|
"EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONER_PUBLIC_KEY_FILE: /run/nodedc-trust/foundry-managed-provisioner/public-key.pem",
|
||||||
|
"EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONING_ENABLED: ${EXTERNAL_DATA_PLANE_FOUNDRY_PROVISIONING_ENABLED:-true}",
|
||||||
|
"create_host_path: false",
|
||||||
|
]) {
|
||||||
|
if (!compose.includes(fragment)) throw new Error(`platform_compose_boundary_missing:${fragment}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
compose.includes("private-key.pem")
|
||||||
|
|| compose.includes("ENGINE_EDP_MANAGED_PROVISIONER_PRIVATE_KEY_FILE")
|
||||||
|
) throw new Error("platform_artifact_private_key_boundary_violation");
|
||||||
|
const server = await readFile(
|
||||||
|
resolve(platformRoot, "services/external-data-plane/src/server.mjs"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
'managedWriterBindingLifetime: config.managedProvisionerApiEnabled ? "explicit-revoke" : "disabled"',
|
||||||
|
'managedWriterBindings: "digest+idempotent-generation+explicit-revoke"',
|
||||||
|
'app.put("/internal/data-plane/v1/reader-bindings/by-key/:bindingKey"',
|
||||||
|
'managedReaderBindingProvisioning: config.managedProvisionerApiEnabled',
|
||||||
|
'managedReaderBindingLifetime: config.managedProvisionerApiEnabled ? "explicit-revoke" : "disabled"',
|
||||||
|
'managedReaderBindings: "digest+idempotent-generation+explicit-revoke"',
|
||||||
|
'readerSourceScope: "writer-resolved+fail-closed-ambiguity"',
|
||||||
|
'app.post("/internal/data-plane/v1/consumer-reader-bindings/plan"',
|
||||||
|
'app.put("/internal/data-plane/v1/consumer-reader-bindings/by-key/:bindingKey"',
|
||||||
|
'foundryReaderBindingProvisioning: config.foundryProvisionerApiEnabled ? "digest+server-resolved-source" : "disabled"',
|
||||||
|
'source_connection_id as "sourceConnectionId"',
|
||||||
|
'where id = $1 and binding_key is null and active = true',
|
||||||
|
]) {
|
||||||
|
if (!server.includes(marker)) throw new Error(`managed_reader_boundary_missing:${marker}`);
|
||||||
|
}
|
||||||
|
const readerSourceScope = await readFile(
|
||||||
|
resolve(platformRoot, "services/external-data-plane/src/reader-source-scope.mjs"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
for (const marker of [
|
||||||
|
"managed_reader_source_scope_not_found",
|
||||||
|
"managed_reader_source_scope_ambiguous",
|
||||||
|
"managed_consumer_reader_source_scope_not_found",
|
||||||
|
"managed_consumer_reader_source_scope_ambiguous",
|
||||||
|
"external_data_plane_writer_bindings",
|
||||||
|
]) {
|
||||||
|
if (!readerSourceScope.includes(marker)) throw new Error(`reader_source_scope_boundary_missing:${marker}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip, io, pathlib, sys, tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1], 'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='', mode='wb', fileobj=out, compresslevel=9, mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p] + (sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x), arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info, src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copySafe(source, destination) {
|
||||||
|
const sourceStat = await lstat(source);
|
||||||
|
if (sourceStat.isSymbolicLink()) throw new Error(`source_symlink_rejected:${source}`);
|
||||||
|
if (sourceStat.isFile()) {
|
||||||
|
await mkdir(dirname(destination), { recursive: true });
|
||||||
|
await cp(source, destination, { force: true, verbatimSymlinks: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!sourceStat.isDirectory()) throw new Error(`source_type_rejected:${source}`);
|
||||||
|
|
||||||
|
await mkdir(destination, { recursive: true });
|
||||||
|
for (const entry of await readdir(source, { withFileTypes: true })) {
|
||||||
|
if (ignoredBasenames.has(entry.name) || entry.name.startsWith(".env")) continue;
|
||||||
|
if (entry.isDirectory() && ignoredDirectoryNames.has(entry.name)) continue;
|
||||||
|
const childSource = join(source, entry.name);
|
||||||
|
const childDestination = join(destination, entry.name);
|
||||||
|
if (entry.isSymbolicLink()) throw new Error(`source_symlink_rejected:${relative(platformRoot, childSource)}`);
|
||||||
|
await copySafe(childSource, childDestination);
|
||||||
|
}
|
||||||
|
}
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(scriptDir, "../..");
|
||||||
|
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(scriptDir, "../deploy-artifacts"));
|
||||||
|
const [patchId = "external-data-plane-replacement-replay-v1-20260721-014", ...extra] = process.argv.slice(2);
|
||||||
|
const sourceRelative = "services/external-data-plane/src/data-product-delivery.mjs";
|
||||||
|
const destinationRelative = `platform/${sourceRelative}`;
|
||||||
|
|
||||||
|
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
|
||||||
|
throw new Error("usage: build-external-data-plane-replacement-replay-artifact.mjs [patch-id]");
|
||||||
|
}
|
||||||
|
|
||||||
|
const source = resolve(platformRoot, sourceRelative);
|
||||||
|
const sourceText = await readFile(source, "utf8");
|
||||||
|
for (const marker of [
|
||||||
|
'replacement.disposition === "replay"',
|
||||||
|
"classifyReplacementGeneration",
|
||||||
|
'throw deliveryError("data_product_generation_not_newer", 409)',
|
||||||
|
'join current_scope using (source_id, semantic_type, fingerprint)',
|
||||||
|
]) {
|
||||||
|
if (!sourceText.includes(marker)) throw new Error(`replacement_replay_boundary_missing:${marker}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-edp-replacement-replay-"));
|
||||||
|
const payloadPath = join(stage, "payload", destinationRelative);
|
||||||
|
const target = join(artifactDir, `nodedc-platform-${patchId}.tgz`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await mkdir(dirname(payloadPath), { recursive: true });
|
||||||
|
await cp(source, payloadPath, { force: false });
|
||||||
|
await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=platform\ntype=app-overlay\n`, "utf8");
|
||||||
|
await writeFile(join(stage, "files.txt"), `${destinationRelative}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
const tar = spawnSync("python3", ["-c", canonicalTarScript(), target, stage], {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 32 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
|
||||||
|
const sha256 = createHash("sha256").update(await readFile(target)).digest("hex");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact: target,
|
||||||
|
sha256,
|
||||||
|
entries: [destinationRelative],
|
||||||
|
service: "external-data-plane",
|
||||||
|
database: "preserved",
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip, io, pathlib, sys, tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1], 'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='', mode='wb', fileobj=out, compresslevel=9, mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p] + (sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x), arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info, src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(scriptDir, "../..");
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "external-data-plane-unit-contacts-20260724-014", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (extra.length || !/^external-data-plane-unit-contacts-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-external-data-plane-unit-contacts-artifact.mjs "
|
||||||
|
+ "[external-data-plane-unit-contacts-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceRelative =
|
||||||
|
"services/external-data-plane/definitions/fleet.units.contacts.current.v1.json";
|
||||||
|
const destinationRelative = `platform/${sourceRelative}`;
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-edp-unit-contacts-artifact-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertDefinition();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payloadFile = join(stage, "payload", destinationRelative);
|
||||||
|
await mkdir(dirname(payloadFile), { recursive: true });
|
||||||
|
await copyFile(join(platformRoot, sourceRelative), payloadFile);
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=platform\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${destinationRelative}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["external-data-plane"],
|
||||||
|
files: [destinationRelative],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertDefinition() {
|
||||||
|
const definition = JSON.parse(
|
||||||
|
await readFile(join(platformRoot, sourceRelative), "utf8"),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
definition?.id !== "fleet.units.contacts.current.v1"
|
||||||
|
|| definition?.version !== "1.0.0"
|
||||||
|
|| definition?.ontologyRevision !== "ontology.map.moving_object.v3"
|
||||||
|
|| JSON.stringify(definition?.semanticTypes)
|
||||||
|
!== JSON.stringify(["map.moving_object"])
|
||||||
|
|| JSON.stringify(definition?.fields) !== JSON.stringify([
|
||||||
|
"device_imei",
|
||||||
|
"device_phone_primary",
|
||||||
|
"device_phone_secondary",
|
||||||
|
"display_name",
|
||||||
|
"provider_creator_login",
|
||||||
|
])
|
||||||
|
) {
|
||||||
|
throw new Error("unit_contacts_definition_contract_invalid");
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
/(token|secret|password|authorization|decrypt|raw_provider_payload)/i.test(
|
||||||
|
JSON.stringify(definition),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error("unit_contacts_definition_secret_boundary_violation");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'wb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 64 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const platformRoot = resolve(scriptDir, "../..");
|
||||||
|
const artifactDir = resolve(
|
||||||
|
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"),
|
||||||
|
);
|
||||||
|
const [patchId = "external-data-plane-unit-identity-20260724-015", ...extra] =
|
||||||
|
process.argv.slice(2);
|
||||||
|
|
||||||
|
if (extra.length || !/^external-data-plane-unit-identity-\d{8}-\d{3}$/.test(patchId)) {
|
||||||
|
throw new Error(
|
||||||
|
"usage: build-external-data-plane-unit-identity-artifact.mjs "
|
||||||
|
+ "[external-data-plane-unit-identity-YYYYMMDD-NNN]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceRelative =
|
||||||
|
"services/external-data-plane/definitions/fleet.units.identity.current.v1.json";
|
||||||
|
const destinationRelative = `platform/${sourceRelative}`;
|
||||||
|
const expectedSha256 =
|
||||||
|
"1bc017cf71f4705875e735550ec4589cea77e1d2e8c8450162148a051a7ceffe";
|
||||||
|
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
|
||||||
|
const checksum = `${artifact}.sha256`;
|
||||||
|
const stage = await mkdtemp(join(tmpdir(), "nodedc-edp-unit-identity-artifact-"));
|
||||||
|
|
||||||
|
await assertFresh(artifact);
|
||||||
|
await assertDefinition();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payloadFile = join(stage, "payload", destinationRelative);
|
||||||
|
await mkdir(dirname(payloadFile), { recursive: true });
|
||||||
|
await copyFile(join(platformRoot, sourceRelative), payloadFile);
|
||||||
|
await writeFile(
|
||||||
|
join(stage, "manifest.env"),
|
||||||
|
`id=${patchId}\ncomponent=platform\ntype=app-overlay\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
await writeFile(join(stage, "files.txt"), `${destinationRelative}\n`, "utf8");
|
||||||
|
await mkdir(artifactDir, { recursive: true });
|
||||||
|
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||||
|
const sha256 = digest(await readFile(artifact));
|
||||||
|
await writeFile(checksum, `${sha256} ${artifact.split("/").at(-1)}\n`, "utf8");
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
patchId,
|
||||||
|
artifact,
|
||||||
|
checksum,
|
||||||
|
sha256,
|
||||||
|
services: ["external-data-plane"],
|
||||||
|
dataProductId: "fleet.units.identity.current.v1",
|
||||||
|
dataClass: "restricted",
|
||||||
|
files: [destinationRelative],
|
||||||
|
}, null, 2));
|
||||||
|
} finally {
|
||||||
|
await rm(stage, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertDefinition() {
|
||||||
|
const source = await readFile(join(platformRoot, sourceRelative));
|
||||||
|
if (digest(source) !== expectedSha256) {
|
||||||
|
throw new Error("unit_identity_definition_target_mismatch");
|
||||||
|
}
|
||||||
|
const definition = JSON.parse(source);
|
||||||
|
const fields = Array.isArray(definition?.fields) ? definition.fields : [];
|
||||||
|
if (
|
||||||
|
definition?.id !== "fleet.units.identity.current.v1"
|
||||||
|
|| definition?.version !== "1.0.0"
|
||||||
|
|| definition?.ontologyRevision !== "ontology.map.moving_object.v3"
|
||||||
|
|| JSON.stringify(definition?.semanticTypes) !== JSON.stringify(["map.moving_object"])
|
||||||
|
|| !fields.includes("provider_unit_id")
|
||||||
|
|| !fields.includes("device_imei")
|
||||||
|
|| !fields.includes("assigned_driver_phone")
|
||||||
|
|| definition?.fieldContracts?.available_user_logins?.type !== "string_array"
|
||||||
|
|| definition?.fieldContracts?.custom_fields?.type !== "string_array"
|
||||||
|
) {
|
||||||
|
throw new Error("unit_identity_definition_contract_invalid");
|
||||||
|
}
|
||||||
|
if (/(token|secret|password|authorization|decrypt|raw_provider_payload)/i.test(
|
||||||
|
JSON.stringify(definition),
|
||||||
|
)) {
|
||||||
|
throw new Error("unit_identity_definition_secret_boundary_violation");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertFresh(path) {
|
||||||
|
try {
|
||||||
|
await lstat(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === "ENOENT") return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
throw new Error("artifact_already_exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalTarScript() {
|
||||||
|
return [
|
||||||
|
"import gzip,io,pathlib,sys,tarfile",
|
||||||
|
"root=pathlib.Path(sys.argv[2])",
|
||||||
|
"with open(sys.argv[1],'xb') as out:",
|
||||||
|
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||||
|
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||||
|
" for top in ('manifest.env','files.txt','payload'):",
|
||||||
|
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||||
|
" for x in paths:",
|
||||||
|
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||||
|
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||||
|
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function digest(value) {
|
||||||
|
return createHash("sha256").update(value).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 64 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user