Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b984de10a | ||
|
|
27c155276a | ||
|
|
39a2239563 | ||
|
|
1e191868be | ||
|
|
9dcd520503 | ||
|
|
7374ca57d7 | ||
|
|
50dc3b1a2c | ||
|
|
93b91a4b1e | ||
|
|
aba78dea98 | ||
|
|
feeb0766c0 |
@@ -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,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic data-only receipt for the exact B2 foundation002 incident."""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
|
||||
loader = importlib.machinery.SourceFileLoader('b2_reconciliation_builder_runner', str(Path(__file__).with_name('nodedc-deploy')))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
R = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(R)
|
||||
|
||||
|
||||
def build(destination):
|
||||
data = {
|
||||
'manifest.env': ('id=' + R.DEVICE_B2_RECON_ID + '\ncomponent=device-b2-foundation-reconciliation\ntype=app-overlay\n').encode(),
|
||||
'files.txt': (R.DEVICE_B2_RECON_ENTRY + '\n').encode(),
|
||||
'payload/' + R.DEVICE_B2_RECON_ENTRY: (json.dumps(R.device_b2_reconciliation_descriptor(), indent=2) + '\n').encode(),
|
||||
}
|
||||
destination = Path(destination)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with destination.open('xb') as output:
|
||||
with gzip.GzipFile(filename='', mode='wb', fileobj=output, mtime=0) as gz:
|
||||
with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as archive:
|
||||
for name, value in sorted(data.items()):
|
||||
member = tarfile.TarInfo(name)
|
||||
member.size = len(value)
|
||||
member.mode = 0o644
|
||||
member.mtime = 0
|
||||
archive.addfile(member, io.BytesIO(value))
|
||||
return {'id': R.DEVICE_B2_RECON_ID, 'component': 'device-b2-foundation-reconciliation',
|
||||
'artifact': str(destination), 'sha256': hashlib.sha256(destination.read_bytes()).hexdigest(),
|
||||
'entries': [R.DEVICE_B2_RECON_ENTRY], 'services': [], 'build': [], 'runtimeMutation': False}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--output', required=True)
|
||||
print(json.dumps(build(parser.parse_args().output), indent=2))
|
||||
@@ -0,0 +1,36 @@
|
||||
# B2 foundation: Compose 2.20.1 serialization regression
|
||||
|
||||
These JSON files are real `config --format json` output, generated from the
|
||||
synthetic, secret-free `base.yml` and the exact production `override.yml`.
|
||||
No Docker daemon, container, worker or production mutation is involved.
|
||||
|
||||
Official Docker Compose v2.20.1 Darwin arm64 release binary SHA256:
|
||||
`e5449e23d14740092c4e764dd9e66cc693d8b02747167c045fd4edfd64fda958`.
|
||||
Source: <https://github.com/docker/compose/releases/tag/v2.20.1>.
|
||||
This is the upstream parser version; the NAS build is
|
||||
`2.20.1-6047-g6817716`, not this exact binary.
|
||||
|
||||
Generate from this directory, using a separately SHA-verified binary:
|
||||
|
||||
```sh
|
||||
"$COMPOSE_BINARY" -p nodedc-device-plane --env-file /dev/null \
|
||||
--project-directory /volume1/docker/nodedc-device-plane \
|
||||
-f base.yml config --format json > base.json
|
||||
"$COMPOSE_BINARY" -p nodedc-device-plane --env-file /dev/null \
|
||||
--project-directory /volume1/docker/nodedc-device-plane \
|
||||
-f base.yml -f override.yml config --format json > candidate.json
|
||||
```
|
||||
|
||||
JSON whitespace is formatted with Python `json.dumps(..., indent=2)`.
|
||||
The new mount emits `bind: {}` and omits `read_only`: both booleans are false.
|
||||
Runner016 incorrectly expected an explicit `create_host_path: false` property.
|
||||
Runner017 removes that exact false property only from the new B2 mount inside
|
||||
comparison copies. Raw config, its digest, fixed YAML, all old mounts and
|
||||
other properties stay exact. True/null/numeric/string values and unknown bind
|
||||
options are rejected. The source YAML must still explicitly disable directory
|
||||
creation; accepting this JSON output cannot authorize a different YAML.
|
||||
|
||||
The same failure and fix were also reproduced using all five current NAS
|
||||
Compose files through SMB, without reading any referenced secret file.
|
||||
Only filenames, hashes and comparison outcomes are retained in public evidence;
|
||||
the full effective configuration is not a fixture or a deploy payload.
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"name": "nodedc-device-plane",
|
||||
"networks": {
|
||||
"default": {
|
||||
"name": "nodedc-device-plane_default",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
},
|
||||
"egress": {
|
||||
"name": "nodedc-device-plane_egress",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
},
|
||||
"private": {
|
||||
"name": "nodedc-device-plane_private",
|
||||
"ipam": {},
|
||||
"external": false,
|
||||
"internal": true
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"device-control-core": {
|
||||
"command": null,
|
||||
"entrypoint": null,
|
||||
"environment": {
|
||||
"EXISTING": "synthetic-preserved"
|
||||
},
|
||||
"image": "nodedc/device-control-core:local",
|
||||
"networks": {
|
||||
"egress": {},
|
||||
"private": {
|
||||
"priority": 100
|
||||
}
|
||||
},
|
||||
"volumes": [
|
||||
{
|
||||
"type": "bind",
|
||||
"source": "/synthetic/existing-secret-reference",
|
||||
"target": "/run/existing-secret-reference",
|
||||
"read_only": true,
|
||||
"bind": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
"device-postgres": {
|
||||
"command": null,
|
||||
"entrypoint": null,
|
||||
"image": "postgres:16",
|
||||
"networks": {
|
||||
"default": null
|
||||
},
|
||||
"volumes": [
|
||||
{
|
||||
"type": "volume",
|
||||
"source": "existing-data",
|
||||
"target": "/var/lib/postgresql/data"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"volumes": {
|
||||
"existing-data": {
|
||||
"name": "nodedc-device-plane_existing-data",
|
||||
"external": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
services:
|
||||
device-control-core:
|
||||
image: nodedc/device-control-core:local
|
||||
environment:
|
||||
EXISTING: synthetic-preserved
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /synthetic/existing-secret-reference
|
||||
target: /run/existing-secret-reference
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
networks:
|
||||
private:
|
||||
priority: 100
|
||||
egress:
|
||||
priority: 0
|
||||
device-postgres:
|
||||
image: postgres:16
|
||||
volumes:
|
||||
- type: volume
|
||||
source: existing-data
|
||||
target: /var/lib/postgresql/data
|
||||
networks:
|
||||
private:
|
||||
internal: true
|
||||
egress: {}
|
||||
volumes:
|
||||
existing-data: {}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "nodedc-device-plane",
|
||||
"networks": {
|
||||
"default": {
|
||||
"name": "nodedc-device-plane_default",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
},
|
||||
"egress": {
|
||||
"name": "nodedc-device-plane_egress",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
},
|
||||
"private": {
|
||||
"name": "nodedc-device-plane_private",
|
||||
"ipam": {},
|
||||
"external": false,
|
||||
"internal": true
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"device-control-core": {
|
||||
"command": null,
|
||||
"entrypoint": null,
|
||||
"environment": {
|
||||
"DEVICE_B2_SECRET_ROOT": "/run/nodedc-b2-connections",
|
||||
"EXISTING": "synthetic-preserved"
|
||||
},
|
||||
"image": "nodedc/device-control-core:local",
|
||||
"networks": {
|
||||
"egress": {},
|
||||
"private": {
|
||||
"priority": 100
|
||||
}
|
||||
},
|
||||
"volumes": [
|
||||
{
|
||||
"type": "bind",
|
||||
"source": "/synthetic/existing-secret-reference",
|
||||
"target": "/run/existing-secret-reference",
|
||||
"read_only": true,
|
||||
"bind": {}
|
||||
},
|
||||
{
|
||||
"type": "bind",
|
||||
"source": "/volume1/docker/nodedc-device-plane/private-b2-connections",
|
||||
"target": "/run/nodedc-b2-connections",
|
||||
"bind": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
"device-postgres": {
|
||||
"command": null,
|
||||
"entrypoint": null,
|
||||
"image": "postgres:16",
|
||||
"networks": {
|
||||
"default": null
|
||||
},
|
||||
"volumes": [
|
||||
{
|
||||
"type": "volume",
|
||||
"source": "existing-data",
|
||||
"target": "/var/lib/postgresql/data"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"volumes": {
|
||||
"existing-data": {
|
||||
"name": "nodedc-device-plane_existing-data",
|
||||
"external": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
services:
|
||||
device-control-core:
|
||||
environment:
|
||||
DEVICE_B2_SECRET_ROOT: /run/nodedc-b2-connections
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /volume1/docker/nodedc-device-plane/private-b2-connections
|
||||
target: /run/nodedc-b2-connections
|
||||
read_only: false
|
||||
bind:
|
||||
create_host_path: false
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"schemaVersion": "nodedc.device-b2-shared-contours.v1",
|
||||
"releaseId": "device-b2-shared-contours-v1-20261001-001",
|
||||
"baselineReleaseId": "device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718",
|
||||
"baselineSha256": "fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe",
|
||||
"files": {
|
||||
"deployment/device-b2-shared-contours-v1.sql": "caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a",
|
||||
"deployment/device-b2-shared-contours-v1.rollback.sql": "f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f"
|
||||
},
|
||||
"transition": "one-contour-many-projects",
|
||||
"services": [],
|
||||
"rollback": "refuse-multiple-projects;preserve-all-rows"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
begin;
|
||||
set local lock_timeout = '5s';
|
||||
set local statement_timeout = '30s';
|
||||
lock table device_b2_contour_links in access exclusive mode;
|
||||
do $$
|
||||
begin
|
||||
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-shared-contours/v1'
|
||||
or (select pg_get_constraintdef(oid) from pg_constraint
|
||||
where conrelid='device_b2_contour_links'::regclass and contype='p')
|
||||
is distinct from 'PRIMARY KEY (source_id, contour_id, project_id)' then
|
||||
raise exception 'device_b2_shared_contours_rollback_predecessor_mismatch';
|
||||
end if;
|
||||
if exists(select 1 from device_b2_contour_links group by source_id,contour_id having count(*)>1) then
|
||||
raise exception 'device_b2_shared_contours_rollback_would_lose_links';
|
||||
end if;
|
||||
end $$;
|
||||
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
|
||||
alter table device_b2_contour_links add primary key (source_id, contour_id);
|
||||
comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1';
|
||||
commit;
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
begin;
|
||||
set local lock_timeout = '5s';
|
||||
set local statement_timeout = '30s';
|
||||
|
||||
-- Separate, versioned foundation transition. Never run from application startup.
|
||||
-- Preserve every assignment; only the identity of an assignment becomes a triple.
|
||||
lock table device_b2_contour_links in access exclusive mode;
|
||||
create temporary table device_b2_links_before on commit drop as
|
||||
select * from device_b2_contour_links;
|
||||
do $$
|
||||
begin
|
||||
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-foundation/v1'
|
||||
or (select pg_get_constraintdef(oid) from pg_constraint
|
||||
where conrelid='device_b2_contour_links'::regclass and contype='p')
|
||||
is distinct from 'PRIMARY KEY (source_id, contour_id)' then
|
||||
raise exception 'device_b2_shared_contours_predecessor_mismatch';
|
||||
end if;
|
||||
end $$;
|
||||
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
|
||||
alter table device_b2_contour_links add primary key (source_id, contour_id, project_id);
|
||||
comment on table device_b2_contour_links is 'nodedc.device-b2-shared-contours/v1';
|
||||
do $$
|
||||
begin
|
||||
if exists(
|
||||
(select * from device_b2_links_before except all select * from device_b2_contour_links)
|
||||
union all
|
||||
(select * from device_b2_contour_links except all select * from device_b2_links_before)
|
||||
) then
|
||||
raise exception 'device_b2_shared_contours_row_preservation_failed';
|
||||
end if;
|
||||
end $$;
|
||||
commit;
|
||||
@@ -0,0 +1,25 @@
|
||||
# Actual Compose 2.20.3 config output
|
||||
|
||||
`base.json` is an isolated synthetic two-service configuration, with no secrets,
|
||||
mounts or published ports. `config.json` contains the full parsed JSON output of
|
||||
the official Darwin ARM64 Compose v2.20.3 binary, SHA256
|
||||
`51cd66bf94923ec8668f1a78c8740abb6cfbe1189da5720a8051a97be527372b`.
|
||||
|
||||
Reproduce without creating containers or contacting Docker Engine:
|
||||
|
||||
```sh
|
||||
COMPOSE=/absolute/path/to/docker-compose-2.20.3
|
||||
FIXTURE=infra/deploy-runner/fixtures/device-core-network-priority-compose220/base.json
|
||||
"$COMPOSE" -p nodedc-ci-null-endpoint-repro -f "$FIXTURE" config --format json
|
||||
"$COMPOSE" -p nodedc-ci-null-endpoint-repro -f "$FIXTURE" \
|
||||
-f infra/device-core-deploy/docker-compose.network-priority.yml config --format json
|
||||
```
|
||||
|
||||
The first output contains `null` for bare attachments. The second contains `{}`
|
||||
for explicit zero-priority endpoints and `{"priority":100}` for private networks.
|
||||
Do not replace nulls with hand-written fixture objects: that omission caused
|
||||
runner014 to reject the initial NAS plan. The fixture regression reproduces
|
||||
`Device Core network priority endpoint is invalid` on014 and passes on015.
|
||||
It compares the full config, preserves raw config hashes and exercises negative
|
||||
endpoint-type/property changes separately. This is synthetic source evidence;
|
||||
it does not claim access to the NAS effective config or its exact Compose version.
|
||||
@@ -0,0 +1 @@
|
||||
{"services": {"device-control-core": {"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920", "pull_policy": "never", "command": ["node", "-e", "setInterval(()=>{},1000)"], "read_only": true, "cap_drop": ["ALL"], "security_opt": ["no-new-privileges:true"], "stop_grace_period": "1s", "mem_limit": "96m", "pids_limit": 32, "networks": ["device-plane-private", "device-plane-egress"]}, "device-manager": {"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920", "pull_policy": "never", "command": ["node", "-e", "setInterval(()=>{},1000)"], "read_only": true, "cap_drop": ["ALL"], "security_opt": ["no-new-privileges:true"], "stop_grace_period": "1s", "mem_limit": "96m", "pids_limit": 32, "networks": ["device-plane-private", "platform-edge"]}}, "networks": {"device-plane-private": {"internal": true}, "device-plane-egress": {}, "platform-edge": {}}}
|
||||
@@ -0,0 +1,148 @@
|
||||
{
|
||||
"base": {
|
||||
"name": "nodedc-ci-null-endpoint-repro",
|
||||
"networks": {
|
||||
"device-plane-egress": {
|
||||
"name": "nodedc-ci-null-endpoint-repro_device-plane-egress",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
},
|
||||
"device-plane-private": {
|
||||
"name": "nodedc-ci-null-endpoint-repro_device-plane-private",
|
||||
"ipam": {},
|
||||
"external": false,
|
||||
"internal": true
|
||||
},
|
||||
"platform-edge": {
|
||||
"name": "nodedc-ci-null-endpoint-repro_platform-edge",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"device-control-core": {
|
||||
"cap_drop": [
|
||||
"ALL"
|
||||
],
|
||||
"command": [
|
||||
"node",
|
||||
"-e",
|
||||
"setInterval(()=>{},1000)"
|
||||
],
|
||||
"entrypoint": null,
|
||||
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
|
||||
"mem_limit": "100663296",
|
||||
"networks": {
|
||||
"device-plane-egress": null,
|
||||
"device-plane-private": null
|
||||
},
|
||||
"pids_limit": 32,
|
||||
"pull_policy": "never",
|
||||
"read_only": true,
|
||||
"security_opt": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"stop_grace_period": "1s"
|
||||
},
|
||||
"device-manager": {
|
||||
"cap_drop": [
|
||||
"ALL"
|
||||
],
|
||||
"command": [
|
||||
"node",
|
||||
"-e",
|
||||
"setInterval(()=>{},1000)"
|
||||
],
|
||||
"entrypoint": null,
|
||||
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
|
||||
"mem_limit": "100663296",
|
||||
"networks": {
|
||||
"device-plane-private": null,
|
||||
"platform-edge": null
|
||||
},
|
||||
"pids_limit": 32,
|
||||
"pull_policy": "never",
|
||||
"read_only": true,
|
||||
"security_opt": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"stop_grace_period": "1s"
|
||||
}
|
||||
}
|
||||
},
|
||||
"candidate": {
|
||||
"name": "nodedc-ci-null-endpoint-repro",
|
||||
"networks": {
|
||||
"device-plane-egress": {
|
||||
"name": "nodedc-ci-null-endpoint-repro_device-plane-egress",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
},
|
||||
"device-plane-private": {
|
||||
"name": "nodedc-ci-null-endpoint-repro_device-plane-private",
|
||||
"ipam": {},
|
||||
"external": false,
|
||||
"internal": true
|
||||
},
|
||||
"platform-edge": {
|
||||
"name": "nodedc-ci-null-endpoint-repro_platform-edge",
|
||||
"ipam": {},
|
||||
"external": false
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"device-control-core": {
|
||||
"cap_drop": [
|
||||
"ALL"
|
||||
],
|
||||
"command": [
|
||||
"node",
|
||||
"-e",
|
||||
"setInterval(()=>{},1000)"
|
||||
],
|
||||
"entrypoint": null,
|
||||
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
|
||||
"mem_limit": "100663296",
|
||||
"networks": {
|
||||
"device-plane-egress": {},
|
||||
"device-plane-private": {
|
||||
"priority": 100
|
||||
}
|
||||
},
|
||||
"pids_limit": 32,
|
||||
"pull_policy": "never",
|
||||
"read_only": true,
|
||||
"security_opt": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"stop_grace_period": "1s"
|
||||
},
|
||||
"device-manager": {
|
||||
"cap_drop": [
|
||||
"ALL"
|
||||
],
|
||||
"command": [
|
||||
"node",
|
||||
"-e",
|
||||
"setInterval(()=>{},1000)"
|
||||
],
|
||||
"entrypoint": null,
|
||||
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
|
||||
"mem_limit": "100663296",
|
||||
"networks": {
|
||||
"device-plane-private": {
|
||||
"priority": 100
|
||||
},
|
||||
"platform-edge": {}
|
||||
},
|
||||
"pids_limit": 32,
|
||||
"pull_policy": "never",
|
||||
"read_only": true,
|
||||
"security_opt": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"stop_grace_period": "1s"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,202 @@
|
||||
"""Additive B2 foundation: exact scope and fail-closed preservation proofs."""
|
||||
import copy
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
loader=importlib.machinery.SourceFileLoader('b2_runner_test',str(Path(__file__).with_name('nodedc-deploy')))
|
||||
spec=importlib.util.spec_from_loader(loader.name,loader);R=importlib.util.module_from_spec(spec);loader.exec_module(R)
|
||||
|
||||
|
||||
def baseline():
|
||||
return {'services':{'device-control-core':{'image':'same','environment':{'EXISTING':'preserved'},
|
||||
'volumes':[{'type':'bind','source':'/private/current','target':'/run/current','read_only':True}],
|
||||
'ports':[]},'device-postgres':{'image':'postgres:existing','volumes':['unchanged']}}}
|
||||
|
||||
|
||||
def candidate():
|
||||
v=baseline();c=v['services']['device-control-core']
|
||||
c['environment']['DEVICE_B2_SECRET_ROOT']=R.DEVICE_B2_DESTINATION
|
||||
c['volumes'].append({'type':'bind','source':str(R.DEVICE_B2_SECRET_ROOT),'target':R.DEVICE_B2_DESTINATION,
|
||||
'read_only':False,'bind':{'create_host_path':False}})
|
||||
return v
|
||||
|
||||
|
||||
FIXTURE = Path(__file__).with_name('fixtures') / 'device-b2-foundation-compose220'
|
||||
|
||||
|
||||
def compose_fixture():
|
||||
return tuple(json.loads((FIXTURE / (name + '.json')).read_text()) for name in ('base', 'candidate'))
|
||||
|
||||
|
||||
class Foundation(unittest.TestCase):
|
||||
def test_source_yaml_and_new_identity_remain_exact(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / 'deployment').mkdir()
|
||||
(root / R.DEVICE_B2_DESCRIPTOR).write_text(json.dumps(R.device_b2_descriptor()))
|
||||
yaml = root / R.DEVICE_B2_OVERRIDE
|
||||
yaml.write_text(R.DEVICE_B2_YAML)
|
||||
# Isolate the YAML/identity guard; no database or SQL execution.
|
||||
with mock.patch.object(R, 'sha256_file', return_value=R.DEVICE_B2_SQL_SHA):
|
||||
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
|
||||
for old_id in ('device-b2-foundation-v1-20260930-001', 'device-b2-foundation-v1-20260930-002'):
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, old_id)
|
||||
for replacement in ('true', 'null', '0'):
|
||||
yaml.write_text(R.DEVICE_B2_YAML.replace('create_host_path: false', 'create_host_path: ' + replacement))
|
||||
with self.subTest(replacement=replacement), self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
|
||||
yaml.write_text(R.DEVICE_B2_YAML.replace(' create_host_path: false\n', ''))
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
|
||||
|
||||
def test_real_compose_2201_output_preserves_raw_inputs_and_digest(self):
|
||||
base, actual = compose_fixture()
|
||||
saved = copy.deepcopy((base, actual))
|
||||
mount = next(v for v in actual['services']['device-control-core']['volumes']
|
||||
if v['target'] == R.DEVICE_B2_DESTINATION)
|
||||
self.assertEqual(mount['bind'], {})
|
||||
self.assertNotIn('read_only', mount)
|
||||
self.assertEqual(R.device_b2_config_proof(base, actual), R.device_release_drift_digest(actual))
|
||||
self.assertEqual((base, actual), saved)
|
||||
self.assertEqual((FIXTURE / 'override.yml').read_text(), R.DEVICE_B2_YAML)
|
||||
|
||||
def test_real_compose_new_mount_accepts_only_false_or_omitted_booleans(self):
|
||||
base, actual = compose_fixture()
|
||||
for read_only in ('omitted', False):
|
||||
for create in ('omitted', False):
|
||||
v = copy.deepcopy(actual)
|
||||
mount = next(m for m in v['services']['device-control-core']['volumes']
|
||||
if m['target'] == R.DEVICE_B2_DESTINATION)
|
||||
if read_only != 'omitted': mount['read_only'] = read_only
|
||||
if create != 'omitted': mount['bind']['create_host_path'] = create
|
||||
with self.subTest(read_only=read_only, create=create):
|
||||
R.device_b2_config_proof(base, v)
|
||||
for key in ('read_only', 'create_host_path'):
|
||||
for value in (True, None, 0, 1, 0.0, 'false', {}, []):
|
||||
v = copy.deepcopy(actual)
|
||||
mount = next(m for m in v['services']['device-control-core']['volumes']
|
||||
if m['target'] == R.DEVICE_B2_DESTINATION)
|
||||
target = mount if key == 'read_only' else mount['bind']
|
||||
target[key] = value
|
||||
with self.subTest(key=key, value=value), self.assertRaises(R.DeployError):
|
||||
R.device_b2_config_proof(base, v)
|
||||
|
||||
def test_real_compose_rejects_other_mount_options_and_unrelated_changes(self):
|
||||
base, actual = compose_fixture()
|
||||
for mutation in ('source', 'type', 'bind-null', 'bind-absent', 'propagation',
|
||||
'existing-bind', 'existing-readonly', 'duplicate', 'env', 'network', 'database'):
|
||||
v = copy.deepcopy(actual)
|
||||
core = v['services']['device-control-core']
|
||||
mount = next(m for m in core['volumes'] if m['target'] == R.DEVICE_B2_DESTINATION)
|
||||
existing = next(m for m in core['volumes'] if m['target'] != R.DEVICE_B2_DESTINATION)
|
||||
if mutation == 'source': mount['source'] = '/other'
|
||||
if mutation == 'type': mount['type'] = 'volume'
|
||||
if mutation == 'bind-null': mount['bind'] = None
|
||||
if mutation == 'bind-absent': mount.pop('bind')
|
||||
if mutation == 'propagation': mount['bind']['propagation'] = 'rshared'
|
||||
if mutation == 'existing-bind': existing['bind']['create_host_path'] = False
|
||||
if mutation == 'existing-readonly': existing['read_only'] = False
|
||||
if mutation == 'duplicate': core['volumes'].append(copy.deepcopy(mount))
|
||||
if mutation == 'env': core['environment']['EXISTING'] = 'changed'
|
||||
if mutation == 'network': core['networks']['private']['priority'] = 0
|
||||
if mutation == 'database': v['services']['device-postgres']['image'] = 'changed'
|
||||
with self.subTest(mutation=mutation), self.assertRaises(R.DeployError):
|
||||
R.device_b2_config_proof(base, v)
|
||||
|
||||
def test_scope_has_only_core_and_no_build(self):
|
||||
self.assertEqual(R.component_services('device-b2-foundation',R.DEVICE_B2_ENTRIES),('device-control-core',))
|
||||
self.assertFalse(R.component_builds('device-b2-foundation',R.DEVICE_B2_ENTRIES))
|
||||
self.assertTrue(R.component_compose_no_deps('device-b2-foundation',R.DEVICE_B2_ENTRIES))
|
||||
for entries in [[],R.DEVICE_B2_ENTRIES[:-1],(*R.DEVICE_B2_ENTRIES,'services/device-postgres')]:
|
||||
with self.assertRaises(R.DeployError):R.component_services('device-b2-foundation',entries)
|
||||
for p in ['.env','secrets/key','deployment/other.sql','services/device-control-core/src/server.mjs','../escape','hooks.sh']:
|
||||
with self.assertRaises(R.DeployError):R.allowed_payload_path('device-b2-foundation',p)
|
||||
|
||||
def test_config_delta_keeps_ports_database_and_other_environment(self):
|
||||
R.device_b2_config_proof(baseline(),candidate())
|
||||
for mutation in ['ports','database','environment','mount','readonly']:
|
||||
v=candidate();c=v['services']['device-control-core']
|
||||
if mutation=='ports':c['ports']=[{'target':42,'published':'42'}]
|
||||
if mutation=='database':v['services']['device-postgres']['image']='different'
|
||||
if mutation=='environment':c['environment']['EXISTING']='changed'
|
||||
if mutation=='mount':c['volumes'][0]['read_only']=False
|
||||
if mutation=='readonly':c['volumes'][-1]['read_only']=True
|
||||
with self.subTest(mutation=mutation),self.assertRaises(R.DeployError):R.device_b2_config_proof(baseline(),v)
|
||||
|
||||
def test_runtime_strip_accepts_only_private_mount_and_env(self):
|
||||
field={'HostConfig':{'Mounts':[{'Type':'bind','Source':str(R.DEVICE_B2_SECRET_ROOT),
|
||||
'Target':R.DEVICE_B2_DESTINATION,'ReadOnly':False}]},
|
||||
'Config':{'Env':['OTHER=one','DEVICE_B2_SECRET_ROOT='+R.DEVICE_B2_DESTINATION]},
|
||||
'Mounts':[{'Type':'bind','Source':str(R.DEVICE_B2_SECRET_ROOT),'Destination':R.DEVICE_B2_DESTINATION,
|
||||
'RW':True,'Propagation':'rprivate'}],'networks':['same']}
|
||||
result=R.device_b2_strip_runtime(field)
|
||||
self.assertEqual(result,{'HostConfig':{'Mounts':[]},'Config':{'Env':['OTHER=one']},'Mounts':[],'networks':['same']})
|
||||
for part,key,value in [('Mounts','RW',False),('Mounts','Propagation','rshared'),('HostConfig','Source','/elsewhere')]:
|
||||
wrong=copy.deepcopy(field)
|
||||
target=wrong[part][0] if part=='Mounts' else wrong[part]['Mounts'][0]
|
||||
target[key]=value
|
||||
with self.assertRaises(R.DeployError):R.device_b2_strip_runtime(wrong)
|
||||
|
||||
def test_recreate_never_pulls_builds_or_selects_dependencies(self):
|
||||
with mock.patch.object(R,'device_b2_base',return_value=['docker','compose']),mock.patch.object(R.subprocess,'run') as run:
|
||||
R.device_b2_recreate(True)
|
||||
cmd=run.call_args.args[0]
|
||||
self.assertEqual(cmd[-1],'device-control-core')
|
||||
self.assertIn('--no-build',cmd);self.assertIn('--no-deps',cmd)
|
||||
self.assertEqual(cmd[cmd.index('--pull')+1],'never')
|
||||
self.assertNotIn('device-postgres',cmd)
|
||||
|
||||
def test_schema_collision_and_unvalidated_constraints_fail(self):
|
||||
with self.assertRaises(R.DeployError):R.validate_device_b2_schema([])
|
||||
rows=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA)
|
||||
R.validate_device_b2_schema(rows)
|
||||
rows[0]['validated']=False
|
||||
with self.assertRaises(R.DeployError):R.validate_device_b2_schema(rows)
|
||||
|
||||
def test_failed_rollback_prevents_activation(self):
|
||||
with mock.patch.object(R,'load_state',return_value=[{'component':'device-b2-foundation','started_apply':True,'rollback_status':'failed:DeployError'}]):
|
||||
with self.assertRaises(R.DeployError):R.device_b2_failed_barrier()
|
||||
|
||||
def test_schema_failure_does_not_mark_or_restart_runtime(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp); (root/'deployment').mkdir()
|
||||
(root/R.DEVICE_B2_SQL).write_text('synthetic migration')
|
||||
mark=mock.Mock()
|
||||
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root),mock.patch.object(R,'device_b2_private_directory'),\
|
||||
mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('schema failed')),\
|
||||
mock.patch.object(R,'device_b2_recreate') as recreate:
|
||||
with self.assertRaises(R.DeployError):R.apply_device_b2({},root,mark)
|
||||
mark.assert_not_called();recreate.assert_not_called()
|
||||
|
||||
def test_normal_releases_check_installed_schema_mount_and_vault(self):
|
||||
with mock.patch.object(R,'device_b2_compose_files',return_value=('accepted-foundation',)),\
|
||||
mock.patch.object(R,'device_b2_private_directory') as directory,\
|
||||
mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA),\
|
||||
mock.patch.object(R,'device_release_drift_sample',return_value={'device-control-core':{'fields':{}}}),\
|
||||
mock.patch.object(R,'device_b2_strip_runtime',side_effect=R.DeployError('lost mount')):
|
||||
with self.assertRaises(R.DeployError):R.validate_installed_device_b2()
|
||||
directory.assert_called_once_with()
|
||||
|
||||
def test_marker_without_ledger_cannot_activate_compose(self):
|
||||
with tempfile.TemporaryDirectory() as tmp,mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)),mock.patch.object(R,'load_state',return_value=[]):
|
||||
(Path(tmp)/R.DEVICE_B2_OVERRIDE).write_text(R.DEVICE_B2_YAML)
|
||||
with self.assertRaises(R.DeployError):R.device_b2_compose_files(())
|
||||
|
||||
def test_rollback_retains_nonempty_private_storage(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp);vault=root/'vault';vault.mkdir();(vault/'credential').write_text('synthetic')
|
||||
with mock.patch.object(R,'DEVICE_B2_SECRET_ROOT',vault),mock.patch.object(R,'restore_platform_overlay'),\
|
||||
mock.patch.object(R,'device_b2_schema',return_value=[]),mock.patch.object(R,'device_b2_private_directory'),\
|
||||
mock.patch.object(R,'device_b2_recreate'),mock.patch.object(R,'accept_device_b2') as accept:
|
||||
with self.assertRaises(OSError):R.rollback_device_b2(root,root,(),'',{},True)
|
||||
accept.assert_not_called()
|
||||
self.assertEqual((vault/'credential').read_text(),'synthetic')
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Readiness convergence and metadata-only reconciliation; no Docker required."""
|
||||
import copy
|
||||
from contextlib import ExitStack, redirect_stdout, redirect_stderr
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from test_device_b2_foundation import R
|
||||
|
||||
spec = importlib.util.spec_from_file_location('b2_reconciliation_builder', Path(__file__).with_name('build_device_b2_reconciliation.py'))
|
||||
B = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(B)
|
||||
|
||||
|
||||
def baseline_fields():
|
||||
return {'HostConfig': {'Mounts': []}, 'Config': {'Env': ['PRESERVED=synthetic']}, 'Mounts': [], 'networks': ['private']}
|
||||
|
||||
|
||||
def snapshot(fields):
|
||||
return {service: {'service': service, 'containerId': service + '-old', 'imageId': 'same-image',
|
||||
'health': 'healthy', 'running': True, 'status': 'running', 'restartCount': 0,
|
||||
'runtimeConfigSha256': R.device_release_drift_digest(fields)}
|
||||
for service in R.DEVICE_RELEASE_INVENTORY}
|
||||
|
||||
|
||||
class Readiness(unittest.TestCase):
|
||||
def accept_with_startup(self, rollback, unhealthy=False, drift=None):
|
||||
fields = baseline_fields()
|
||||
current_fields = copy.deepcopy(fields)
|
||||
if not rollback:
|
||||
current_fields['Config']['Env'].append('DEVICE_B2_SECRET_ROOT=' + R.DEVICE_B2_DESTINATION)
|
||||
current_fields['HostConfig']['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
|
||||
'Target': R.DEVICE_B2_DESTINATION, 'ReadOnly': False})
|
||||
current_fields['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
|
||||
'Destination': R.DEVICE_B2_DESTINATION, 'RW': True, 'Propagation': 'rprivate'})
|
||||
before = {'runtime': snapshot(fields), 'compose': {}, 'otherComposeServices': {}, 'installedFiles': {}}
|
||||
state = {'health': 'starting', 'polls': 0, 'snapshots': 0}
|
||||
|
||||
def inspect(command, **kwargs):
|
||||
self.assertEqual(command[1], 'inspect')
|
||||
service = command[-1]
|
||||
if service == 'device-control-core':
|
||||
state['polls'] += 1
|
||||
state['health'] = 'unhealthy' if unhealthy else ('starting' if state['polls'] == 1 else 'healthy')
|
||||
return SimpleNamespace(stdout=state['health'], stderr='', returncode=0)
|
||||
return SimpleNamespace(stdout='healthy', stderr='', returncode=0)
|
||||
|
||||
def samples():
|
||||
state['snapshots'] += 1
|
||||
result = {service: {'runtime': copy.deepcopy(row), 'fields': copy.deepcopy(fields)}
|
||||
for service, row in before['runtime'].items()}
|
||||
core = result['device-control-core']
|
||||
core['runtime']['containerId'] = 'new-generation'
|
||||
core['runtime']['health'] = state['health']
|
||||
core['fields'] = copy.deepcopy(current_fields)
|
||||
if drift == 'image': core['runtime']['imageId'] = 'changed-image'
|
||||
if drift == 'network': core['fields']['networks'] = ['other']
|
||||
if drift == 'preserved': result['device-postgres']['runtime']['containerId'] = 'unexpected-recreate'
|
||||
return result
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(mock.patch.object(R, 'compose_service_container_id', side_effect=lambda c, s: s))
|
||||
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=inspect))
|
||||
stack.enter_context(mock.patch.object(R.time, 'sleep'))
|
||||
stack.enter_context(mock.patch.object(R, 'healthcheck_url'))
|
||||
stack.enter_context(mock.patch.object(R, 'device_release_drift_sample', side_effect=samples))
|
||||
stack.enter_context(mock.patch.object(R, 'device_release_other_compose_services', return_value={}))
|
||||
stack.enter_context(mock.patch.object(R, 'collect_exact_files', return_value={}))
|
||||
stack.enter_context(mock.patch.object(R, 'device_b2_private_directory'))
|
||||
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=R.DEVICE_B2_EXPECTED_SCHEMA))
|
||||
stack.enter_context(mock.patch.object(R, 'read_strict_json', return_value={'schemaSha256': R.device_release_drift_digest(R.DEVICE_B2_EXPECTED_SCHEMA)}))
|
||||
stack.enter_context(redirect_stdout(io.StringIO()))
|
||||
if unhealthy or drift:
|
||||
with self.assertRaises(R.DeployError): R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
|
||||
else:
|
||||
R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
|
||||
return state
|
||||
|
||||
def test_apply_and_rollback_wait_for_healthy_before_strict_snapshot(self):
|
||||
for rollback in (False, True):
|
||||
with self.subTest(rollback=rollback):
|
||||
state = self.accept_with_startup(rollback)
|
||||
self.assertEqual(state['polls'], 2)
|
||||
self.assertGreater(state['snapshots'], 0)
|
||||
|
||||
def test_persistent_unhealthy_does_not_reach_snapshot_or_accept(self):
|
||||
for rollback in (False, True):
|
||||
state = self.accept_with_startup(rollback, unhealthy=True)
|
||||
self.assertEqual(state['polls'], 60)
|
||||
self.assertEqual(state['snapshots'], 0)
|
||||
|
||||
def test_readiness_never_weakens_image_network_or_preserved_service_guards(self):
|
||||
for rollback in (False, True):
|
||||
for drift in ('image', 'network', 'preserved'):
|
||||
with self.subTest(rollback=rollback, drift=drift):
|
||||
self.accept_with_startup(rollback, drift=drift)
|
||||
|
||||
|
||||
class Reconciliation(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.live = self.root / 'live'
|
||||
self.live.mkdir()
|
||||
self.archive = self.root / 'reconciliation.tgz'
|
||||
B.build(self.archive)
|
||||
self.manifest, self.entries, self.payload = R.load_artifact(self.archive, self.root / 'unpack')
|
||||
|
||||
def test_real_archive_is_deterministic_data_only_and_has_no_runtime_action(self):
|
||||
other = self.root / 'second.tgz'
|
||||
B.build(other)
|
||||
self.assertEqual(self.archive.read_bytes(), other.read_bytes())
|
||||
with self.assertRaises(FileExistsError): B.build(other)
|
||||
self.assertEqual(self.entries, [R.DEVICE_B2_RECON_ENTRY])
|
||||
self.assertEqual(R.component_services(self.manifest['component'], self.entries), ())
|
||||
self.assertFalse(R.component_builds(self.manifest['component'], self.entries))
|
||||
with mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('runtime command forbidden')):
|
||||
R.run_component_runtime(self.manifest['component'], self.entries, ())
|
||||
for p in ('secrets/key', '.env', R.DEVICE_B2_SQL, R.DEVICE_B2_OVERRIDE, 'hooks.sh'):
|
||||
with self.subTest(path=p), self.assertRaises(R.DeployError):
|
||||
R.allowed_payload_path(self.manifest['component'], p)
|
||||
for entries in ([], self.entries + ['services/device-control-core']):
|
||||
with self.assertRaises(R.DeployError): R.component_services(self.manifest['component'], entries)
|
||||
|
||||
def test_descriptor_cannot_select_other_incident_or_commands(self):
|
||||
descriptor = self.payload / R.DEVICE_B2_RECON_ENTRY
|
||||
for key, value in [('failedReleaseId', 'another'), ('backupId', '../escape'), ('mode', 'restart'), ('command', 'sh')]:
|
||||
d = R.device_b2_reconciliation_descriptor()
|
||||
d[key] = value
|
||||
descriptor.write_text(json.dumps(d))
|
||||
with self.subTest(key=key), self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_reconciliation_payload(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
|
||||
|
||||
def proof_context(self, stack, **overrides):
|
||||
applied = [{'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA}]
|
||||
failures = [R.device_b2_002_failed_row()]
|
||||
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live))
|
||||
stack.enter_context(mock.patch.object(R, 'DEVICE_B2_SECRET_ROOT', self.live / 'vault'))
|
||||
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={'proof': 'pinned-backup'}))
|
||||
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=overrides.get('schema', [])))
|
||||
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda path: overrides.get('failed', failures) if path == R.FAILED_STATE_FILE else overrides.get('applied', applied)))
|
||||
return stack.enter_context(mock.patch.object(R, 'accept_device_b2'))
|
||||
|
||||
def test_readonly_proof_rejects_remaining_files_vault_schema_and_other_incident(self):
|
||||
for case in ('good', 'file', 'symlink', 'vault', 'schema', 'newer-release', 'another-failed', 'installed-foundation'):
|
||||
with self.subTest(case=case), ExitStack() as stack:
|
||||
changes = {}
|
||||
target = None
|
||||
if case in ('file', 'symlink'):
|
||||
target = self.live / R.DEVICE_B2_OVERRIDE
|
||||
if case == 'file': target.write_text('retained')
|
||||
else: target.symlink_to(self.live / 'missing')
|
||||
if case == 'vault':
|
||||
target = self.live / 'vault'; target.mkdir()
|
||||
if case == 'schema': changes['schema'] = R.DEVICE_B2_EXPECTED_SCHEMA
|
||||
if case == 'newer-release': changes['applied'] = []
|
||||
if case == 'installed-foundation': changes['applied'] = [{'component': 'device-b2-foundation'}]
|
||||
if case == 'another-failed': changes['failed'] = [R.device_b2_002_failed_row(), {'component': 'device-b2-foundation', 'started_apply': True, 'id': 'another'}]
|
||||
accept = self.proof_context(stack, **changes)
|
||||
stack.enter_context(redirect_stdout(io.StringIO()))
|
||||
if case == 'good':
|
||||
R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
|
||||
accept.assert_called_once()
|
||||
self.assertTrue(accept.call_args.kwargs['rollback'])
|
||||
else:
|
||||
with self.assertRaises(R.DeployError): R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
|
||||
accept.assert_not_called()
|
||||
if target:
|
||||
if target.is_dir(): target.rmdir()
|
||||
else: target.unlink()
|
||||
|
||||
def test_marker_alone_cannot_clear_failure_and_other_failed_rows_never_match(self):
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[]):
|
||||
self.assertFalse(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
|
||||
marker = self.live / R.DEVICE_B2_RECON_ENTRY
|
||||
marker.parent.mkdir()
|
||||
marker.write_text(json.dumps(R.device_b2_reconciliation_descriptor()))
|
||||
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
|
||||
wrong = R.device_b2_002_failed_row(); wrong['sha256'] = '0'*64
|
||||
self.assertFalse(R.device_b2_002_reconciled(wrong))
|
||||
|
||||
def test_failed_foundation_blocks_ordinary_releases_even_without_overlay(self):
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[R.device_b2_002_failed_row()]):
|
||||
with self.assertRaises(R.DeployError): R.device_b2_compose_files(())
|
||||
|
||||
def test_incident_evidence_checks_exact_journal_archive_and_every_backup_file(self):
|
||||
failed_dir = self.root/'incident-failed'; failed_dir.mkdir()
|
||||
backups = self.root/'incident-backups'; backups.mkdir()
|
||||
backup = backups/R.DEVICE_B2_002_BACKUP; backup.mkdir()
|
||||
files = {'device-b2-before.json': b'{"runtime":{}}', 'device-b2-schema.json': b'{}',
|
||||
'manifest.env': b'synthetic', 'files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
|
||||
'existing-files.txt': b'', 'missing-files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
|
||||
'source-before.tgz': b'synthetic-empty-source'}
|
||||
for name, value in files.items(): (backup/name).write_bytes(value)
|
||||
archive = failed_dir/R.device_b2_002_failed_row()['artifact']; archive.write_bytes(b'synthetic-archive')
|
||||
hashes = {name: hashlib.sha256(value).hexdigest() for name, value in files.items()}
|
||||
with ExitStack() as stack:
|
||||
for name, value in [('FAILED_DIR', failed_dir), ('BACKUPS_DIR', backups),
|
||||
('DEVICE_B2_002_SHA', hashlib.sha256(archive.read_bytes()).hexdigest()),
|
||||
('DEVICE_B2_002_BACKUP_HASHES', hashes)]:
|
||||
stack.enter_context(mock.patch.object(R, name, value))
|
||||
failed = [R.device_b2_002_failed_row()]; applied = []
|
||||
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda p: failed if p == R.FAILED_STATE_FILE else applied))
|
||||
self.assertEqual(R.device_b2_002_evidence(), {'runtime': {}})
|
||||
for name, value in files.items():
|
||||
(backup/name).write_bytes(value+b'changed')
|
||||
with self.subTest(file=name), self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
||||
(backup/name).write_bytes(value)
|
||||
archive.write_bytes(b'changed')
|
||||
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
||||
archive.write_bytes(b'synthetic-archive')
|
||||
applied.append({'id': R.DEVICE_B2_002_ID})
|
||||
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
||||
applied.clear()
|
||||
failed[0]['rollback_status'] = 'different'
|
||||
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
|
||||
|
||||
def execute_metadata_apply(self, fail_after_marker=False):
|
||||
for name in ('inbox', 'applied', 'failed', 'backups', 'state', 'tmp'): (self.root / name).mkdir()
|
||||
with ExitStack() as stack:
|
||||
for name, value in [('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/'lock'), ('DEVICE_PLANE_ROOT', self.live),
|
||||
('DEVICE_B2_SECRET_ROOT', self.live/'vault')]:
|
||||
stack.enter_context(mock.patch.object(R, name, value))
|
||||
stack.enter_context(mock.patch.dict(R.COMPONENTS, {'device-b2-foundation-reconciliation': {'payload_root': self.live, 'artifact_only': True, 'services': ()}}))
|
||||
for name in ('require_root', 'ensure_layout', 'validate_artifact_location'):
|
||||
stack.enter_context(mock.patch.object(R, name))
|
||||
for name in ('run_build', 'run_compose', 'prepare_component_runtime'):
|
||||
stack.enter_context(mock.patch.object(R, name, side_effect=AssertionError('runtime mutation forbidden')))
|
||||
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('external commands forbidden')))
|
||||
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={}))
|
||||
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=[]))
|
||||
events = []
|
||||
def accept(*args, **kwargs):
|
||||
installed = (self.live / R.DEVICE_B2_RECON_ENTRY).exists()
|
||||
events.append('post' if installed else 'pre')
|
||||
if fail_after_marker and installed: raise R.DeployError('injected restored runtime drift')
|
||||
stack.enter_context(mock.patch.object(R, 'accept_device_b2', side_effect=accept))
|
||||
R.append_jsonl(R.FAILED_STATE_FILE, R.device_b2_002_failed_row())
|
||||
R.append_jsonl(R.STATE_FILE, {'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA})
|
||||
stack.enter_context(redirect_stdout(io.StringIO())); stack.enter_context(redirect_stderr(io.StringIO()))
|
||||
if fail_after_marker:
|
||||
with self.assertRaises(R.DeployError): R.apply_artifact(self.archive)
|
||||
self.assertFalse((self.live/R.DEVICE_B2_RECON_ENTRY).exists())
|
||||
self.assertEqual(R.load_state(R.FAILED_STATE_FILE)[-1]['rollback_status'], 'ok:device-b2-reconciliation-marker-only')
|
||||
self.assertEqual(len(R.load_state(R.STATE_FILE)), 1)
|
||||
else:
|
||||
R.apply_artifact(self.archive)
|
||||
receipt = R.load_state(R.STATE_FILE)[-1]
|
||||
self.assertEqual(receipt['component'], 'device-b2-foundation-reconciliation')
|
||||
self.assertTrue(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
|
||||
R.device_b2_failed_barrier()
|
||||
self.assertEqual(len(R.load_state(R.FAILED_STATE_FILE)), 1) # Original failure retained.
|
||||
(R.APPLIED_DIR/receipt['artifact']).write_bytes(b'changed archive')
|
||||
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
|
||||
self.assertEqual(events, ['pre', 'post'])
|
||||
|
||||
def test_metadata_apply_uses_real_journal_archive_and_receipt_without_runtime_commands(self):
|
||||
self.execute_metadata_apply()
|
||||
|
||||
def test_metadata_apply_failure_removes_only_new_marker_and_retains_incident(self):
|
||||
self.execute_metadata_apply(fail_after_marker=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Exact schema transition, receipt boundary and data-preserving rollback."""
|
||||
import copy
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
loader = importlib.machinery.SourceFileLoader('shared_runner_test', str(Path(__file__).with_name('nodedc-deploy')))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
R = importlib.util.module_from_spec(spec); loader.exec_module(R)
|
||||
FIXTURE = Path(__file__).with_name('fixtures')/'device-b2-shared-contours'
|
||||
|
||||
|
||||
def archive(path, extra=None):
|
||||
files = {'manifest.env': f'id={R.DEVICE_B2_SHARED_ID}\ncomponent=device-b2-shared-contours\ntype=app-overlay\n'.encode(),
|
||||
'files.txt': ('\n'.join(R.DEVICE_B2_SHARED_ENTRIES)+'\n').encode(),
|
||||
**{'payload/'+p: (FIXTURE/p).read_bytes() for p in R.DEVICE_B2_SHARED_ENTRIES}}
|
||||
files.update(extra or {})
|
||||
with tarfile.open(path, 'w:gz') as target:
|
||||
for name, data in files.items():
|
||||
entry=tarfile.TarInfo(name); entry.size=len(data); entry.mode=0o644
|
||||
target.addfile(entry, io.BytesIO(data))
|
||||
|
||||
|
||||
class SharedContours(unittest.TestCase):
|
||||
def test_exact_archive_load_and_empty_runtime_scope(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path=Path(tmp)/'a.tgz'; archive(path)
|
||||
_, entries, payload=R.load_artifact(path, Path(tmp)/'unpack')
|
||||
R.validate_device_b2_shared_payload(payload, entries, R.DEVICE_B2_SHARED_ID)
|
||||
self.assertEqual(R.component_services('device-b2-shared-contours', entries), ())
|
||||
self.assertEqual(R.component_builds('device-b2-shared-contours', entries), ())
|
||||
self.assertTrue(R.component_artifact_only('device-b2-shared-contours'))
|
||||
self.assertEqual(R.component_root('device-b2-shared-contours'), R.DEVICE_PLANE_ROOT)
|
||||
|
||||
def test_extra_sql_env_hook_runtime_or_traversal_rejected(self):
|
||||
for name in ('.env', 'hooks.sh', 'deployment/other.sql', 'secrets/admin.json', '../escape',
|
||||
'services/device-control-core/src/server.mjs', 'runtime/db.dump'):
|
||||
with self.subTest(name=name), self.assertRaises(R.DeployError):
|
||||
R.allowed_payload_path('device-b2-shared-contours', name)
|
||||
for entries in ((), R.DEVICE_B2_SHARED_ENTRIES[:-1], tuple(reversed(R.DEVICE_B2_SHARED_ENTRIES))):
|
||||
with self.assertRaises(R.DeployError): R.component_services('device-b2-shared-contours', entries)
|
||||
|
||||
def test_modified_sql_descriptor_and_identity_rejected(self):
|
||||
for rel in R.DEVICE_B2_SHARED_ENTRIES:
|
||||
with self.subTest(rel=rel), tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp); shutil.copytree(FIXTURE, root, dirs_exist_ok=True)
|
||||
path=root/rel
|
||||
if rel == R.DEVICE_B2_SHARED_DESCRIPTOR:
|
||||
v=json.loads(path.read_text()); v['services']=['device-postgres']; path.write_text(json.dumps(v))
|
||||
else: path.write_text('drop table device_b2_hosts;')
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_shared_payload(root, R.DEVICE_B2_SHARED_ENTRIES, R.DEVICE_B2_SHARED_ID)
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_shared_payload(FIXTURE, R.DEVICE_B2_SHARED_ENTRIES, 'unreviewed')
|
||||
|
||||
def test_forward_schema_is_exact_and_old_contract_is_unchanged(self):
|
||||
old=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA); new=R.device_b2_shared_schema()
|
||||
R.validate_device_b2_schema(old)
|
||||
with self.assertRaises(R.DeployError): R.validate_device_b2_schema(new)
|
||||
R.validate_device_b2_schema(new, expected=R.device_b2_shared_schema())
|
||||
self.assertEqual(R.DEVICE_B2_EXPECTED_SCHEMA, old)
|
||||
self.assertEqual(old[1:], new[1:])
|
||||
for key in ('constraints', 'fields', 'validated', 'columns'):
|
||||
self.assertEqual(old[0][key], new[0][key])
|
||||
for mutation in ('missing-fk', 'wrong-marker', 'extra-field', 'wrong-pk'):
|
||||
value=copy.deepcopy(new)
|
||||
if mutation=='missing-fk': value[0]['definitions'].pop(1)
|
||||
if mutation=='wrong-marker': value[0]['marker']='other'
|
||||
if mutation=='extra-field': value[0]['fields'].append(['unsafe','text',False])
|
||||
if mutation=='wrong-pk': value[0]['definitions'][-1]='PRIMARY KEY (contour_id)'
|
||||
with self.subTest(mutation=mutation), self.assertRaises(R.DeployError):
|
||||
R.validate_device_b2_schema(value, expected=new)
|
||||
|
||||
def test_failed_mutation_blocks_normal_compose_even_without_overlay(self):
|
||||
row={'component':'device-b2-shared-contours','started_apply':True,'rollback_status':'failed:DeployError'}
|
||||
with mock.patch.object(R, 'load_state', return_value=[row]), self.assertRaises(R.DeployError):
|
||||
R.device_b2_compose_files(())
|
||||
for r in ({**row,'started_apply':False}, {**row,'rollback_status':'ok:device-b2-shared-contours'}):
|
||||
with mock.patch.object(R,'load_state',return_value=[r]): R.device_b2_shared_failed_barrier()
|
||||
|
||||
def test_receipt_requires_all_files_unique_success_and_verified_archive(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp)/'live'; root.mkdir()
|
||||
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'TMP_DIR',Path(tmp)), \
|
||||
mock.patch.object(R,'load_state',return_value=[]):
|
||||
self.assertFalse(R.device_b2_shared_receipt())
|
||||
shutil.copytree(FIXTURE,root,dirs_exist_ok=True)
|
||||
with self.assertRaises(R.DeployError): R.device_b2_shared_receipt()
|
||||
row={'component':'device-b2-shared-contours','id':R.DEVICE_B2_SHARED_ID,'status':'ok'}
|
||||
good=Path(tmp)/'good.tgz'; archive(good)
|
||||
state=lambda path: [row] if path==R.STATE_FILE else []
|
||||
with mock.patch.object(R,'load_state',side_effect=state), \
|
||||
mock.patch.object(R,'device_release_applied_archive',return_value=good) as checked:
|
||||
self.assertTrue(R.device_b2_shared_receipt()); checked.assert_called_once_with(row)
|
||||
for rows in ([row,row],[{**row,'id':'other'}],[{**row,'status':'failed'}]):
|
||||
with mock.patch.object(R,'load_state',side_effect=lambda p:rows if p==R.STATE_FILE else []), self.assertRaises(R.DeployError):
|
||||
R.device_b2_shared_receipt()
|
||||
with mock.patch.object(R,'load_state',side_effect=state), \
|
||||
mock.patch.object(R,'device_release_applied_archive',side_effect=R.DeployError('archive mismatch')), \
|
||||
self.assertRaises(R.DeployError): R.device_b2_shared_receipt()
|
||||
|
||||
def test_preflight_rejects_wrong_live_release_before_database_mutation(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \
|
||||
mock.patch.object(R,'load_state',return_value=[]), mock.patch.object(R,'device_b2_database') as db:
|
||||
with self.assertRaisesRegex(R.DeployError,'r37'):
|
||||
R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID)
|
||||
db.assert_not_called()
|
||||
|
||||
def test_preflight_rejects_missing_foundation_and_wrong_source(self):
|
||||
row={'component':'device-core-release','id':R.DEVICE_B2_SHARED_BASELINE,'sha256':R.DEVICE_B2_SHARED_BASELINE_SHA}
|
||||
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \
|
||||
mock.patch.object(R,'TMP_DIR',Path(tmp)), \
|
||||
mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []), \
|
||||
mock.patch.object(R,'device_release_applied_archive',return_value=Path(tmp)/'release.tgz'), \
|
||||
mock.patch.object(R,'load_artifact',return_value=({'component':'device-core-release'}, R.DEVICE_RELEASE_ENTRIES,Path(tmp))), \
|
||||
mock.patch.object(R,'collect_exact_files',side_effect=[{'a':'one'},{'a':'two'}]), \
|
||||
self.assertRaisesRegex(R.DeployError,'source drift'):
|
||||
R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID)
|
||||
|
||||
def test_rollback_never_restores_old_data_over_new_links(self):
|
||||
with mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \
|
||||
mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('would_lose_links')) as db, \
|
||||
mock.patch.object(R,'restore_platform_overlay') as restore, \
|
||||
mock.patch.object(R,'accept_device_b2_shared') as accept:
|
||||
with self.assertRaisesRegex(R.DeployError,'would_lose_links'):
|
||||
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
|
||||
self.assertIn('rollback_would_lose_links',db.call_args.args[0])
|
||||
restore.assert_not_called(); accept.assert_not_called()
|
||||
|
||||
def test_rollback_after_failed_transaction_restores_only_new_files(self):
|
||||
with mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA), \
|
||||
mock.patch.object(R,'device_b2_database') as db, \
|
||||
mock.patch.object(R,'restore_platform_overlay') as restore, \
|
||||
mock.patch.object(R,'accept_device_b2_shared') as accept:
|
||||
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
|
||||
db.assert_not_called(); restore.assert_called_once(); accept.assert_called_once_with({},Path('/unused'),rollback=True)
|
||||
|
||||
def test_unknown_schema_retained_without_destructive_attempt(self):
|
||||
with mock.patch.object(R,'device_b2_schema',return_value=[]), mock.patch.object(R,'device_b2_database') as db, \
|
||||
mock.patch.object(R,'restore_platform_overlay') as restore, self.assertRaises(R.DeployError):
|
||||
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
|
||||
db.assert_not_called(); restore.assert_not_called()
|
||||
|
||||
def test_private_table_backup_fixed_scope_and_failure_precedes_sql(self):
|
||||
def dump(argv, **kwargs):
|
||||
self.assertEqual(argv[-3:], ['--strict-names', '-t', 'public.device_b2_contour_links'])
|
||||
kwargs['stdout'].write(b'PGDMP-synthetic-fixture')
|
||||
return mock.Mock(returncode=0, stderr=b'')
|
||||
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \
|
||||
mock.patch.object(R.subprocess,'run',side_effect=dump), mock.patch.object(R,'device_b2_database') as sql:
|
||||
root=Path(tmp)
|
||||
R.backup_device_b2_shared(root,{'runtime':{}})
|
||||
self.assertEqual((root/'device-b2-contour-links.dump').stat().st_mode & 0o777,0o600)
|
||||
self.assertEqual((root/'device-b2-contour-links.dump.sha256').read_text().strip(),R.sha256_file(root/'device-b2-contour-links.dump'))
|
||||
sql.assert_not_called()
|
||||
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \
|
||||
mock.patch.object(R.subprocess,'run',return_value=mock.Mock(returncode=1,stderr=b'failed')), self.assertRaises(R.DeployError):
|
||||
R.backup_device_b2_shared(Path(tmp),{})
|
||||
|
||||
def test_acceptance_checks_schema_backup_and_preserved_runtime_before_success(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp); shutil.copytree(FIXTURE,root,dirs_exist_ok=True)
|
||||
dump=root/'device-b2-contour-links.dump'; dump.write_bytes(b'PGDMP-fixture'); dump.chmod(0o600)
|
||||
(root/'device-b2-contour-links.dump.sha256').write_text(R.sha256_file(dump)+'\n')
|
||||
before={'runtime':{'postgres':'same','core':'same'},'otherComposeServices':{},'compose':{},'installedFiles':{}}
|
||||
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \
|
||||
mock.patch.object(R,'device_b2_private_directory'), mock.patch.object(R,'run_healthchecks') as health, \
|
||||
mock.patch.object(R,'device_release_runtime_snapshot_v2',return_value=before['runtime']) as runtime, \
|
||||
mock.patch.object(R,'device_release_other_compose_services',return_value={}), \
|
||||
mock.patch.object(R,'collect_exact_files',return_value={}):
|
||||
R.accept_device_b2_shared(before,root)
|
||||
health.assert_called_once_with('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
|
||||
runtime.return_value={'postgres':'recreated','core':'same'}
|
||||
with self.assertRaisesRegex(R.DeployError,'preserved service'): R.accept_device_b2_shared(before,root)
|
||||
runtime.return_value=before['runtime']; dump.write_bytes(b'changed')
|
||||
with self.assertRaisesRegex(R.DeployError,'backup changed'): R.accept_device_b2_shared(before,root)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,359 @@
|
||||
"""Exact metadata transition, effective-config proof and unchanged runtime guards."""
|
||||
import copy
|
||||
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from test_device_core_release import R, runtime, fixture, archive
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / 'device-core-deploy'
|
||||
spec = importlib.util.spec_from_file_location('priority_builder', SOURCE / 'build_network_priority.py')
|
||||
BUILDER = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(BUILDER)
|
||||
|
||||
|
||||
def effective():
|
||||
return {'name': 'nodedc-device-plane', 'services': {
|
||||
'device-control-core': {'image': 'nodedc/device-control-core:local', 'networks': {
|
||||
'device-plane-private': {}, 'device-plane-egress': {}}},
|
||||
'device-manager': {'image': 'nodedc/device-manager:local', 'environment': {'TOKEN': 'synthetic-secret'},
|
||||
'networks': {'device-plane-private': {}, 'platform-edge': {}}},
|
||||
'device-postgres': {'image': 'postgres:17', 'networks': {'device-plane-private': {}}}},
|
||||
'networks': {'device-plane-private': {'internal': True}, 'device-plane-egress': {},
|
||||
'platform-edge': {'external': True}}}
|
||||
|
||||
|
||||
def prioritized():
|
||||
value = effective()
|
||||
for service in ('device-control-core', 'device-manager'):
|
||||
value['services'][service]['networks']['device-plane-private']['priority'] = 100
|
||||
return value
|
||||
|
||||
|
||||
class PriorityTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.live = self.root / 'live'
|
||||
self.live.mkdir()
|
||||
identity, data = BUILDER.bundle()
|
||||
self.artifact = self.root / ('nodedc-' + identity + '.tgz')
|
||||
self.artifact.write_bytes(data)
|
||||
work = self.root / 'unpack'
|
||||
work.mkdir()
|
||||
self.manifest, self.entries, self.payload = R.load_artifact(self.artifact, work)
|
||||
|
||||
def install_files(self):
|
||||
for entry in self.entries:
|
||||
path = self.live / entry
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes((self.payload / entry).read_bytes())
|
||||
|
||||
def test_deterministic_data_bundle_has_no_runtime_action(self):
|
||||
self.assertEqual(BUILDER.bundle()[1], self.artifact.read_bytes())
|
||||
self.assertEqual(self.manifest['component'], 'device-core-network-priority')
|
||||
self.assertEqual(tuple(self.entries), R.DEVICE_PRIORITY_ENTRIES)
|
||||
self.assertEqual((self.payload / self.entries[0]).read_bytes(), R.DEVICE_PRIORITY_YAML.encode())
|
||||
self.assertEqual(R.component_services(self.manifest['component'], self.entries), ())
|
||||
self.assertEqual(R.component_builds(self.manifest['component'], self.entries), ())
|
||||
self.assertTrue(R.component_artifact_only(self.manifest['component']))
|
||||
|
||||
def test_path_and_service_scope_cannot_grow(self):
|
||||
for entry in ('docker-compose.device-plane.yml', 'services/device-manager/a.py',
|
||||
'deployment/other.json', 'secrets/token', 'data/db', '../escape'):
|
||||
with self.subTest(entry=entry), self.assertRaises(R.DeployError):
|
||||
R.allowed_payload_path('device-core-network-priority', entry)
|
||||
for entries in ([], self.entries[:1], [*self.entries, 'services/device-postgres']):
|
||||
with self.subTest(entries=entries), self.assertRaises(R.DeployError):
|
||||
R.component_services('device-core-network-priority', entries)
|
||||
|
||||
def test_payload_rejects_identity_descriptor_and_yaml_changes(self):
|
||||
for identity in ('arbitrary-id', 'device-core-network-priority-v1-20260930-001'):
|
||||
with self.subTest(identity=identity), self.assertRaises(R.DeployError):
|
||||
R.validate_device_priority_payload(self.payload, self.entries, identity)
|
||||
descriptor = self.payload / R.DEVICE_PRIORITY_ENTRY
|
||||
original = descriptor.read_bytes()
|
||||
changed = json.loads(original)
|
||||
changed['primaryPriority'] = 200
|
||||
descriptor.write_text(json.dumps(changed))
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.validate_device_priority_payload(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
descriptor.write_bytes(original)
|
||||
path = self.payload / R.DEVICE_PRIORITY_COMPOSE
|
||||
path.write_text(path.read_text().replace('priority: 100', 'priority: 0'))
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.validate_device_priority_payload(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
|
||||
def test_effective_config_proves_only_two_priority_changes_without_leaking_values(self):
|
||||
base = effective()
|
||||
candidate = prioritized()
|
||||
saved = copy.deepcopy((base, candidate))
|
||||
proof = R.device_priority_config_proof(base, candidate)
|
||||
self.assertEqual((base, candidate), saved)
|
||||
self.assertNotIn('synthetic-secret', json.dumps(proof))
|
||||
self.assertEqual(len(proof['baseConfigSha256']), 64)
|
||||
candidate['services']['device-manager']['networks']['platform-edge']['priority'] = 0
|
||||
R.device_priority_config_proof(base, candidate)
|
||||
|
||||
def test_real_compose220_config_with_null_endpoints_passes_without_changing_raw_digests(self):
|
||||
fixture = Path(__file__).parent / 'fixtures/device-core-network-priority-compose220/config.json'
|
||||
value = json.loads(fixture.read_text())
|
||||
before = copy.deepcopy(value)
|
||||
self.assertIsNone(value['base']['services']['device-manager']['networks']['platform-edge'])
|
||||
proof = R.device_priority_config_proof(value['base'], value['candidate'])
|
||||
self.assertEqual(value, before)
|
||||
self.assertEqual(proof['baseConfigSha256'], R.device_release_drift_digest(before['base']))
|
||||
self.assertEqual(proof['candidateConfigSha256'], R.device_release_drift_digest(before['candidate']))
|
||||
|
||||
def test_null_endpoint_support_does_not_accept_other_types_or_missing_primary_priority(self):
|
||||
for value in (False, True, 0, '', [], 'null', {'priority': None}, {'priority': 0.0}, {'priority': False}):
|
||||
for side in ('base', 'candidate'):
|
||||
base, candidate = effective(), prioritized()
|
||||
config = base if side == 'base' else candidate
|
||||
config['services']['device-manager']['networks']['platform-edge'] = value
|
||||
with self.subTest(side=side, endpoint=value), self.assertRaises(R.DeployError):
|
||||
R.device_priority_config_proof(base, candidate)
|
||||
candidate = prioritized()
|
||||
candidate['services']['device-manager']['networks']['device-plane-private'] = None
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.device_priority_config_proof(effective(), candidate)
|
||||
|
||||
def test_null_equivalence_is_local_and_preserves_endpoint_options(self):
|
||||
base, candidate = effective(), prioritized()
|
||||
base['services']['device-manager']['networks']['platform-edge'] = None
|
||||
candidate['services']['device-manager']['networks']['platform-edge'] = {'aliases': ['foreign']}
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.device_priority_config_proof(base, candidate)
|
||||
base, candidate = effective(), prioritized()
|
||||
candidate['services']['device-postgres']['networks']['device-plane-private'] = None
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.device_priority_config_proof(base, candidate)
|
||||
base, candidate = effective(), prioritized()
|
||||
for config in (base, candidate):
|
||||
config['services']['device-manager']['networks']['platform-edge'] = {'aliases': ['unchanged']}
|
||||
R.device_priority_config_proof(base, candidate)
|
||||
|
||||
def test_network_and_nonnetwork_changes_remain_rejected(self):
|
||||
mutations = (
|
||||
lambda c: c['services']['device-manager'].update(ports=['8080:80']),
|
||||
lambda c: c['services']['device-manager']['environment'].update(TOKEN='different'),
|
||||
lambda c: c['networks']['device-plane-private'].update(internal=False),
|
||||
lambda c: c['services']['device-postgres'].update(image='other'),
|
||||
lambda c: c['services']['device-manager']['networks'].update(other={}),
|
||||
lambda c: c['services']['device-manager']['networks']['platform-edge'].update(priority=100),
|
||||
lambda c: c['services']['device-manager']['networks']['device-plane-private'].update(priority=True),
|
||||
lambda c: c['services']['device-manager']['networks']['device-plane-private'].update(aliases=['foreign']),
|
||||
)
|
||||
for mutate in mutations:
|
||||
c = prioritized()
|
||||
mutate(c)
|
||||
with self.subTest(candidate=c), self.assertRaises(R.DeployError):
|
||||
R.device_priority_config_proof(effective(), c)
|
||||
with self.assertRaises(R.DeployError):
|
||||
R.device_priority_config_proof(prioritized(), prioritized())
|
||||
|
||||
def test_config_reader_never_returns_command_stderr(self):
|
||||
result = mock.Mock(returncode=1, stdout='', stderr='SECRET=do-not-log')
|
||||
with mock.patch.object(R, 'compose_base_cmd', return_value=['docker', 'compose']), \
|
||||
mock.patch.object(R.subprocess, 'run', return_value=result), \
|
||||
self.assertRaises(R.DeployError) as caught:
|
||||
R.device_priority_config(self.payload / R.DEVICE_PRIORITY_COMPOSE)
|
||||
self.assertNotIn('SECRET', str(caught.exception))
|
||||
|
||||
def test_activation_needs_both_files_and_unique_matching_archive_receipt(self):
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
|
||||
mock.patch.object(R, 'APPLIED_DIR', self.root), mock.patch.object(R, 'load_state', return_value=[]):
|
||||
self.assertEqual(R.device_priority_compose_files(('base.yml',)), ('base.yml',))
|
||||
self.install_files()
|
||||
with self.assertRaisesRegex(R.DeployError, 'unique canonical receipt'):
|
||||
R.device_priority_compose_files(('base.yml',))
|
||||
row = {'id': R.DEVICE_PRIORITY_ID, 'component': 'device-core-network-priority', 'status': 'ok',
|
||||
'sha256': R.sha256_file(self.artifact), 'artifact': self.artifact.name}
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
|
||||
mock.patch.object(R, 'APPLIED_DIR', self.root), \
|
||||
mock.patch.object(R, 'load_state', side_effect=lambda p: [row] if p == R.STATE_FILE else []):
|
||||
self.assertEqual(R.device_priority_compose_files(('base.yml',)),
|
||||
('base.yml', self.live / R.DEVICE_PRIORITY_COMPOSE))
|
||||
(self.live / R.DEVICE_PRIORITY_ENTRY).unlink()
|
||||
with self.assertRaisesRegex(R.DeployError, 'incomplete'):
|
||||
R.device_priority_compose_files(('base.yml',))
|
||||
|
||||
def test_uncertain_priority_rollback_blocks_later_release_even_without_marker(self):
|
||||
row = {'component': 'device-core-network-priority', 'started_apply': True, 'rollback_status': 'failed:DeployError'}
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), \
|
||||
mock.patch.object(R, 'load_state', return_value=[row]), \
|
||||
self.assertRaisesRegex(R.DeployError, 'reconciliation'):
|
||||
R.device_priority_compose_files(('base.yml',))
|
||||
|
||||
def test_activation_rejects_duplicate_or_failed_receipt_and_altered_archive(self):
|
||||
self.install_files()
|
||||
row = {'id': R.DEVICE_PRIORITY_ID, 'component': 'device-core-network-priority', 'status': 'ok',
|
||||
'sha256': R.sha256_file(self.artifact), 'artifact': self.artifact.name}
|
||||
for rows in ([row, row], [{**row, 'status': 'failed'}], [{**row, 'sha256': '0' * 64}]):
|
||||
with self.subTest(rows=rows), mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), \
|
||||
mock.patch.object(R, 'TMP_DIR', self.root), mock.patch.object(R, 'APPLIED_DIR', self.root), \
|
||||
mock.patch.object(R, 'load_state', side_effect=lambda p: rows if p == R.STATE_FILE else []), \
|
||||
self.assertRaises(R.DeployError):
|
||||
R.device_priority_compose_files(('base.yml',))
|
||||
|
||||
def test_normal_release_executor_uses_accepted_override_without_expanding_scope(self):
|
||||
self.install_files()
|
||||
row = {'id': R.DEVICE_PRIORITY_ID, 'component': 'device-core-network-priority', 'status': 'ok',
|
||||
'sha256': R.sha256_file(self.artifact), 'artifact': self.artifact.name}
|
||||
original = R.component_compose_files
|
||||
def files(component, **kwargs):
|
||||
if component == 'device-plane':
|
||||
return (self.live / 'base.yml',)
|
||||
return original(component, **kwargs)
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
|
||||
mock.patch.object(R, 'APPLIED_DIR', self.root), mock.patch.object(R, 'component_compose_files', side_effect=files), \
|
||||
mock.patch.object(R, 'load_state', side_effect=lambda p: [row] if p == R.STATE_FILE else []), \
|
||||
mock.patch.object(R.subprocess, 'run') as command:
|
||||
R.run_device_release_compose(R.DEVICE_RELEASE_SERVICES, R.DEVICE_RELEASE_ENTRIES)
|
||||
calls = command.call_args_list
|
||||
self.assertEqual(len(calls), 2)
|
||||
up = calls[0].args[0]
|
||||
index = up.index('up')
|
||||
self.assertEqual(up[index:], ['up', '-d', '--force-recreate', '--pull', 'never', '--no-build', '--no-deps',
|
||||
*R.DEVICE_RELEASE_SERVICES])
|
||||
self.assertEqual(up[index - 2:index], ['-f', str(self.live / R.DEVICE_PRIORITY_COMPOSE)])
|
||||
self.assertEqual(calls[1].args[0], [*up[:index], 'ps'])
|
||||
|
||||
def test_baseline_proves_archive_receipt_and_live_tree(self):
|
||||
d = fixture(self.live, number=12, sha='b2660df9e26afe977bfa62efd35a8397eac4898b')
|
||||
a = self.root / 'baseline.tgz'
|
||||
archive(self.live, a, d)
|
||||
sha = R.sha256_file(a)
|
||||
row = {'id': R.DEVICE_PRIORITY_BASELINE, 'component': 'device-core-release',
|
||||
'status': 'ok', 'sha256': sha, 'artifact': a.name}
|
||||
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
|
||||
mock.patch.object(R, 'DEVICE_PRIORITY_BASELINE_SHA', sha), mock.patch.object(R, 'APPLIED_DIR', self.root), \
|
||||
mock.patch.object(R, 'load_state', side_effect=lambda p: [row] if p == R.STATE_FILE else []):
|
||||
expected = R.device_priority_baseline()
|
||||
self.assertIn(R.DEVICE_RELEASE_ENTRY, expected)
|
||||
(self.live / 'services/device-manager/server/app.mjs').write_text('changed')
|
||||
with self.assertRaisesRegex(R.DeployError, 'source drift'):
|
||||
R.device_priority_baseline()
|
||||
|
||||
def prepare_preflight(self, stack):
|
||||
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live))
|
||||
stack.enter_context(mock.patch.object(R, 'device_priority_baseline', return_value={'app': 'hash'}))
|
||||
stack.enter_context(mock.patch.object(R, 'run_healthchecks'))
|
||||
stack.enter_context(mock.patch.object(R, 'validate_device_manager_control_plane_runtime'))
|
||||
stack.enter_context(mock.patch.object(R, 'device_release_runtime_snapshot_v2', return_value=runtime()))
|
||||
digests = {s: {'HostConfig.NetworkMode': R.device_release_drift_digest('nodedc-device-plane-private')}
|
||||
for s in R.DEVICE_RELEASE_SERVICES}
|
||||
digests['device-control-core']['networks'] = R.device_release_drift_digest(['nodedc-device-plane-egress', 'nodedc-device-plane-private'])
|
||||
digests['device-manager']['networks'] = R.device_release_drift_digest(['nodedc-device-plane-private', 'nodedc-platform_edge'])
|
||||
fields = stack.enter_context(mock.patch.object(R, 'device_release_capture_field_digests', return_value=digests))
|
||||
stack.enter_context(mock.patch.object(R, 'device_priority_config', side_effect=lambda override=None: prioritized() if override else effective()))
|
||||
stack.enter_context(mock.patch.object(R, 'component_compose_files', return_value=()))
|
||||
stack.enter_context(mock.patch.object(R, 'device_release_other_compose_services', return_value={}))
|
||||
stack.enter_context(mock.patch.object(R.subprocess, 'run', return_value=mock.Mock(stdout='2.20.3\n')))
|
||||
return fields
|
||||
|
||||
def test_preflight_refuses_primary_switch_and_already_installed_transition(self):
|
||||
with ExitStack() as stack:
|
||||
fields = self.prepare_preflight(stack)
|
||||
before = R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
self.assertEqual(before['composeVersion'], '2.20.3')
|
||||
fields.return_value['device-manager']['HostConfig.NetworkMode'] = R.device_release_drift_digest('nodedc-platform_edge')
|
||||
with self.assertRaisesRegex(R.DeployError, 'existing private primary'):
|
||||
R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
self.install_files()
|
||||
with self.assertRaisesRegex(R.DeployError, 'initial-only'):
|
||||
R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
|
||||
def test_acceptance_requires_unchanged_runtime_and_exact_candidate(self):
|
||||
with ExitStack() as stack:
|
||||
self.prepare_preflight(stack)
|
||||
before = R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
self.install_files()
|
||||
with redirect_stdout(io.StringIO()):
|
||||
R.accept_device_priority(before)
|
||||
changed = runtime()
|
||||
changed['device-manager']['containerId'] = 'changed'
|
||||
with mock.patch.object(R, 'device_release_runtime_snapshot_v2', return_value=changed), \
|
||||
self.assertRaisesRegex(R.DeployError, 'preserved source/runtime'):
|
||||
R.accept_device_priority(before)
|
||||
with self.assertRaisesRegex(R.DeployError, 'left activation files'):
|
||||
R.accept_device_priority(before, rollback=True)
|
||||
for entry in self.entries:
|
||||
(self.live / entry).unlink()
|
||||
with redirect_stdout(io.StringIO()):
|
||||
R.accept_device_priority(before, rollback=True)
|
||||
|
||||
def test_preflight_refuses_an_extra_attached_network(self):
|
||||
with ExitStack() as stack:
|
||||
fields = self.prepare_preflight(stack)
|
||||
fields.return_value['device-manager']['networks'] = R.device_release_drift_digest(
|
||||
['nodedc-device-plane-private', 'nodedc-platform_edge', 'foreign'])
|
||||
with self.assertRaisesRegex(R.DeployError, 'network set mismatch'):
|
||||
R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
|
||||
|
||||
def execute(self, fail=False, rollback_fail=False):
|
||||
config = {**R.COMPONENTS['device-core-network-priority'], 'payload_root': self.live}
|
||||
for name in ('inbox', 'applied', 'failed', 'backups', 'state', 'tmp'):
|
||||
(self.root / name).mkdir()
|
||||
events = []
|
||||
before = {'runtime': runtime(), 'baseConfigSha256': 'a' * 64}
|
||||
with ExitStack() as stack:
|
||||
for name, value in [('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 / 'lock'), ('DEVICE_PLANE_ROOT', self.live)]:
|
||||
stack.enter_context(mock.patch.object(R, name, value))
|
||||
stack.enter_context(mock.patch.dict(R.COMPONENTS, {'device-core-network-priority': config}))
|
||||
for name in ('require_root', 'ensure_layout', 'validate_artifact_location'):
|
||||
stack.enter_context(mock.patch.object(R, name))
|
||||
stack.enter_context(mock.patch.object(R, 'preflight_device_priority', return_value=before))
|
||||
commands = stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('no external runtime commands')))
|
||||
build = stack.enter_context(mock.patch.object(R, 'run_build', side_effect=AssertionError('no build')))
|
||||
def accept(value, rollback=False):
|
||||
events.append('rollback' if rollback else 'accept')
|
||||
self.assertEqual(value, before)
|
||||
for entry in self.entries:
|
||||
self.assertEqual((self.live / entry).exists(), not rollback)
|
||||
if (fail and not rollback) or (rollback_fail and rollback):
|
||||
raise R.DeployError('injected acceptance failure')
|
||||
stack.enter_context(mock.patch.object(R, 'accept_device_priority', side_effect=accept))
|
||||
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)
|
||||
else:
|
||||
R.apply_artifact(self.artifact)
|
||||
commands.assert_not_called()
|
||||
build.assert_not_called()
|
||||
applied, failed = R.load_state(R.STATE_FILE), R.load_state(R.FAILED_STATE_FILE)
|
||||
return events, applied, failed
|
||||
|
||||
def test_real_apply_dispatch_is_metadata_only_and_journals_after_acceptance(self):
|
||||
events, applied, failed = self.execute()
|
||||
self.assertEqual(events, ['accept'])
|
||||
self.assertEqual(len(applied), 1)
|
||||
self.assertFalse(failed)
|
||||
self.assertFalse(self.artifact.exists())
|
||||
|
||||
def test_real_apply_dispatch_rolls_back_only_new_files(self):
|
||||
events, applied, failed = self.execute(fail=True)
|
||||
self.assertEqual(events, ['accept', 'rollback'])
|
||||
self.assertFalse(applied)
|
||||
self.assertEqual(failed[0]['rollback_status'], 'ok:device-core-network-priority-metadata-only')
|
||||
|
||||
def test_real_apply_dispatch_retains_failed_rollback(self):
|
||||
_, applied, failed = self.execute(fail=True, rollback_fail=True)
|
||||
self.assertFalse(applied)
|
||||
self.assertEqual(failed[0]['rollback_status'], 'failed:DeployError')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,15 +1,25 @@
|
||||
# Device Core automatic deployment acceptance
|
||||
|
||||
Date: 2026-09-29. First automatic release accepted; the second was rejected by runtime
|
||||
acceptance and successfully rolled back. Ordered-release acceptance remains open. This report concerns Device Core only. B2 multi-client contours are
|
||||
Evidence dates: 2026-09-29/30. Automatic releases r11/r12 and subsequently
|
||||
r13/r14 were accepted in sequence without manual NAS commands. The latter pair
|
||||
used accepted network-priority002 under root runner015; see
|
||||
[the full production acceptance register](NETWORK_PRIORITY_20260930.md). Earlier r9 was rejected by runtime
|
||||
acceptance and successfully rolled back; its exact cause remains unresolved.
|
||||
This report concerns Device Core only. B2 multi-client contours are
|
||||
a separate implementation in `NODEDC_MISSION_CORE_ARNAVI-VPS`.
|
||||
|
||||
## Installed authority
|
||||
|
||||
Platform source: `f7416bc59a19a9ac53c4f4591eaf50a7f4a41641`.
|
||||
Current installed Platform source: `50dc3b1a2cb1191484f5b90de2d2702b14127425`.
|
||||
Root runner SHA-256:
|
||||
`c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`.
|
||||
The operator's promotion returned `verify-install-ok`, Python3.8.15.
|
||||
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`.
|
||||
The operator's promotion on 2026-09-30 returned `verify-install-ok`, Python3.8.15.
|
||||
This is runner015. Its metadata002 acceptance and subsequent automatic releases
|
||||
are recorded in [the network-priority report](NETWORK_PRIORITY_20260930.md).
|
||||
The runner013 details below describe the earlier instrumentation checkpoint.
|
||||
Bootstrap and runs8/9 used preceding runner012, SHA
|
||||
`c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`,
|
||||
from Platform `f7416bc59a19a9ac53c4f4591eaf50a7f4a41641`.
|
||||
|
||||
Controller artifact:
|
||||
`nodedc-device-core-autodeploy-v1-20260929-001.tgz`, SHA-256
|
||||
@@ -102,4 +112,87 @@ Validation:75 Device Core release/bootstrap/recovery tests;75 registry tests
|
||||
(1 historical skip);170 Device Core artifact tests (17 historical skips);
|
||||
Python3.8 syntax and diff checks. Runner candidate SHA-256:
|
||||
`3eefc75591bb08339d79c6a484912d7d6a8881fe8729e966b6f0bf32da21da80`.
|
||||
It is prepared, not installed. No new release has been submitted after run9.
|
||||
Its installation is now confirmed by the operator's exact verify-install receipt.
|
||||
|
||||
## Remaining acceptance and handoff
|
||||
|
||||
- [x] Controller bootstrap accepted by the canonical installer.
|
||||
- [x] Run8 passed CI and automatically reached an accepted production release.
|
||||
- [x] An observed Gitea interruption recovered without operator intervention.
|
||||
- [x] Run9 failed runtime acceptance and automatically restored accepted run8.
|
||||
- [x] Candidate013 retains redacted field-level evidence and passed its source tests.
|
||||
- [x] Install candidate013 through the separate root runner promotion gate.
|
||||
- [ ] Obtain exact evidence for the Manager mismatch and qualify its correction.
|
||||
- [x] Accept two ordered automatic application releases with the installed diagnostics (r11, r12).
|
||||
|
||||
Candidate013 source is Platform
|
||||
`d1c5401f52f32cdc4bc4c6db5df8f8d5d6fc7045`, with staged candidate name
|
||||
`nodedc-deploy.device-core-runtime-evidence-20260929-013`. Its byte count is
|
||||
1785138 and its digest is recorded above. It preserves the installed runner's
|
||||
acceptance and rollback rules; it is instrumentation, not a proven incident fix.
|
||||
The next Device Core release was submitted only after this promotion was
|
||||
confirmed. Neither the successful bootstrap/run8 nor terminal failed run9 is replayed.
|
||||
|
||||
At the 2026-09-30 documentation pass, the Mac's `/Volumes/docker` share was
|
||||
disconnected. Historical receipts and artifact hashes remain available locally;
|
||||
this report does not claim a new live NAS inspection at that time. Reconnect the
|
||||
share, check for newer terminal receipts and verify the staged candidate before
|
||||
giving the operator the prepared Synology promotion command. The share was then
|
||||
reconnected: fresh lifecycle inspection confirmed the same387applied/79failed
|
||||
receipts, run8/run9 archive hashes and backups, no warnings, and the staged
|
||||
candidate digest. The operator subsequently completed promotion013.
|
||||
|
||||
Worker006 is not part of Device Core CI/CD. Its Windows installation and any
|
||||
unverified Linux guest are irrelevant to this acceptance. A later isolated B2
|
||||
fleet test is separate work and does not block finishing Synology deployment.
|
||||
|
||||
## Qualification continuation on 2026-09-30
|
||||
|
||||
Run10, source `893cb6490c1d37df1f9bca19d5c058c304091b87`, pinned the installed
|
||||
Platform source. It failed in design-install at05:22:29Z with npm ECONNRESET,
|
||||
before any deploy artifact was produced. Production remained on accepted run8.
|
||||
This transport failure is distinct from the unexplained run9 Manager mismatch.
|
||||
|
||||
Source `70065fb74c449c16094dd4bc05356a8174ec4524` adds at most three frozen
|
||||
dependency-install attempts for explicit ECONNRESET/ETIMEDOUT/EAI_AGAIN only.
|
||||
Integrity/auth/lockfile/unclassified/mixed errors and build/test failures still
|
||||
fail immediately.25local CI tests cover recovery, exhaustion, no false report,
|
||||
and rejection of non-network failures.
|
||||
|
||||
Run11 passed265application/25CI/170artifact tests (17historical skips) and was
|
||||
automatically accepted at2026-09-30T05:36:45Z, canonical applied ledger388.
|
||||
Artifact SHA-256 is
|
||||
`a1c9d201b2f129413b041fb56f2d35f0a05d3936f7ea46116b32929eab343418`;
|
||||
backup is
|
||||
`device-core-release-device-core-release-v1-r11-70065fb74c449c16094dd4bc05356a8174ec4524-20260930-083337`.
|
||||
CI receipt, applied archive hash and backup were independently verified;
|
||||
lifecycle is terminal_success with no warnings or failed receipt. Only
|
||||
manifest/release metadata differ from r8's application payload. The new before
|
||||
snapshot retained per-field hashes and Manager NetworkMode
|
||||
`nodedc-device-plane-private`. The mismatch did not recur in this attempt.
|
||||
Public health returned200 and the authenticated UI retained DC SUDO, DCTOUCH and
|
||||
Robot2B — Moscow Trike Delivery. No user data was changed during the UI check.
|
||||
|
||||
Run12/source `b2660df9e26afe977bfa62efd35a8397eac4898b` is the subsequent
|
||||
documentation push. Its dependency install really
|
||||
encountered ECONNRESET at05:39:41Z, then retried after five seconds and recovered
|
||||
without operator action; qualification proceeded to265application/25CI tests,
|
||||
UI build and artifact contracts. This independently verifies the live transport
|
||||
recovery path added after run10. It does not establish the cause of run9.
|
||||
|
||||
Run12 passed the same265application/25CI/170artifact checks and was automatically
|
||||
accepted at2026-09-30T05:49:19Z, canonical ledger389. Artifact SHA-256:
|
||||
`44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c`.
|
||||
Backup:
|
||||
`device-core-release-device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b-20260930-084605`.
|
||||
Its before snapshot identifies r11 as the predecessor. CI receipt, archive hash,
|
||||
backup and unique journal row agree; lifecycle is terminal_success, with no
|
||||
failed receipt or warnings. Public health returned200 with ok/authRequired/
|
||||
deviceCoreConfigured true after the update. Neither r11 nor r12 needs any
|
||||
operator replay. Current production source at this checkpoint is b2660df.
|
||||
|
||||
These two successful updates establish the automatic delivery path and observed
|
||||
transport recovery. They do not prove the old intermittent Manager mismatch
|
||||
fixed. Guards and rollback remain enabled; the installed diagnostics retain the
|
||||
actual differing fields if it recurs. No topology/normalization workaround was
|
||||
introduced based on the unproven NetworkMode hypothesis.
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
# Stable primary network for recurring Device Core releases
|
||||
|
||||
Status: root runner015 and metadata002 were accepted on 2026-09-30.
|
||||
Two subsequent normal releases, r13 and r14, passed CI, automatic canonical
|
||||
installation and separate UI/health acceptance. Both used the accepted override
|
||||
with strict runtime fingerprint v2 and no manual NAS plan/apply.
|
||||
DCPLATFORM-21 owns this exact registry addition; DCPLATFORM-37 tracks acceptance.
|
||||
|
||||
## Reproduced defect and evidence limits
|
||||
|
||||
Docker Compose 2.20.3 chooses `HostConfig.NetworkMode` from the first result of
|
||||
`NetworksByPriority`. Its compose-go 1.18.1 dependency builds that result from a
|
||||
Go map and sorts only by priority. Equal priorities have no deterministic tie
|
||||
breaker. Reordering YAML keys is therefore insufficient.
|
||||
|
||||
Primary sources:
|
||||
- [Compose 2.20.3 create.go](https://github.com/docker/compose/blob/v2.20.3/pkg/compose/create.go)
|
||||
- [Compose dependency pin](https://github.com/docker/compose/blob/v2.20.3/go.mod)
|
||||
- [compose-go network ordering](https://github.com/compose-spec/compose-go/blob/v1.18.1/types/types.go)
|
||||
|
||||
The official Darwin ARM64 Compose 2.20.3 binary was independently checksum
|
||||
verified as `51cd66bf94923ec8668f1a78c8740abb6cfbe1189da5720a8051a97be527372b`.
|
||||
Tests used local Docker Desktop Engine29.1.3 through API1.44, an existing pinned
|
||||
Node image and isolated synthetic services. They used no NAS access, ports,
|
||||
host mounts, credentials or production data. All test containers/networks were
|
||||
removed by their exact project after each test; cleanup inventories are empty.
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Equal priorities, 32 fresh creates | Private primary28; secondary primary4 |
|
||||
| Explicit private100 / secondary0, 32 fresh creates | Private primary32 |
|
||||
| Exact candidate override, 16 Core+Manager recreations | All32 containers kept private primary and both attached networks |
|
||||
| Original private-primary baseline to exact override, 8 Core+Manager recreations | All16 containers retained every canonical v2 configuration field digest |
|
||||
|
||||
Local reports and executable reproductions are retained under
|
||||
`outputs/device-core-stability-20260930/compose-reproducer/` in the NODEDC
|
||||
workspace: `result.json`, `rollout-result.json`, `fingerprint-result.json` and
|
||||
their corresponding Python scripts. These are test evidence, never NAS payload.
|
||||
|
||||
The accepted NAS plan002 identified Compose `2.20.1-6047-g6817716`. The local Engine is newer
|
||||
than NAS Docker24.0.2, so these checks do not replace NAS acceptance.
|
||||
|
||||
The old r9 receipt retained only an aggregate Manager configuration hash, and
|
||||
rollback removed the rejected container. This reproduces a real defect capable
|
||||
of causing that class of rejection; it does not prove which field differed in r9.
|
||||
The existing r9 failure record remains unresolved historical evidence, not a
|
||||
reason to replay r9 or waive configuration acceptance.
|
||||
|
||||
## Exact registered transition
|
||||
|
||||
Component: `device-core-network-priority`, type `app-overlay`, fixed identity
|
||||
`device-core-network-priority-v1-20260930-002`. Both live and Compose roots are
|
||||
`/volume1/docker/nodedc-device-plane`. The package permits exactly:
|
||||
|
||||
1. `docker-compose.device-release-network-priority.yml`
|
||||
2. `deployment/device-core-network-priority-v1.json`
|
||||
|
||||
The existing base Compose files are unchanged. The new override specifies
|
||||
private-network priority100 and secondary-network priority0 for Core and Manager.
|
||||
It does not add/remove a network, change network properties, control the default
|
||||
gateway or change endpoint settings. In particular, `priority` is not a
|
||||
`gw_priority` substitute. The first installed primary must already be
|
||||
`nodedc-device-plane-private` for both services.
|
||||
|
||||
This initial installation writes metadata only: no build, pull, restart,
|
||||
recreation, database change, network creation or secret repair; services are
|
||||
empty. No new ports, listeners or runtime dependencies are introduced.
|
||||
|
||||
Required predecessor is the exact accepted r12 source
|
||||
`b2660df9e26afe977bfa62efd35a8397eac4898b`, release identity
|
||||
`device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b`, archive SHA
|
||||
`44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c`.
|
||||
Preflight proves journal/archive identity and every installed release file,
|
||||
rejects unresolved rollback failures, requires both new paths absent, checks
|
||||
health and existing secret/mount/network boundaries, then captures all five
|
||||
Device Plane services and other persistent Compose services.
|
||||
|
||||
Canonical `docker compose config --format json` is read before and with the
|
||||
candidate override. An in-memory comparison proves that ONLY the two primary
|
||||
priority values change. Environment values and complete config never enter
|
||||
logs or receipts. Only config hashes, version, file hashes and runtime evidence
|
||||
are saved in `device-network-priority-before.json` with mode0600.
|
||||
|
||||
Runner014/plan001 uncovered a missing parser case: the real Compose2.20.3
|
||||
`config --format json` output represents bare network attachments as `null`,
|
||||
and explicit zero-priority attachments as `{}`. Earlier fixture-based config
|
||||
proof tests used `{}` in both places; actual container tests exercised network
|
||||
selection/fingerprints but did not call the new effective-config validator.
|
||||
This was a test coverage gap, not a production topology change.
|
||||
|
||||
The corrected proof accepts null as an empty object only at the four known
|
||||
service/network endpoints in its private comparison copies. Raw before/after
|
||||
config hashes remain exact. Scalars, arrays, boolean/float/null priority values,
|
||||
missing primary priority, added networks and changed endpoint properties are
|
||||
still rejected. Other services and configuration sections are not normalized.
|
||||
The complete generated config fixture and reproduction commands are committed
|
||||
under `infra/deploy-runner/fixtures/device-core-network-priority-compose220`.
|
||||
The fixture test fails on014 with the same message and passes on015.
|
||||
|
||||
001 remained staged with no applied/failed receipt or backup. It is superseded
|
||||
and must not be applied;002 has a new immutable identity and archive digest.
|
||||
015 rejects001 rather than silently giving that old identity new semantics.
|
||||
|
||||
Apply verifies the copied files, effective configuration, original Compose/source,
|
||||
health and exactly unchanged container identities/images/configuration for all
|
||||
five services and other Compose projects. It emits `deploy-ok` only after those
|
||||
checks. Failure removes/restores only the two new metadata paths, verifies the
|
||||
original config and runtime again, and records the rollback result. An uncertain
|
||||
rollback blocks further application releases even when marker files are absent.
|
||||
|
||||
## Future normal releases and rollback
|
||||
|
||||
Only the recurring `device-core-release` domain appends this override to its
|
||||
effective Compose files. Activation requires both exact files plus a unique
|
||||
successful canonical receipt and its checked immutable archive; copying a marker
|
||||
does not activate it. Generic/Engine executors and historical Device Plane
|
||||
transitions are unchanged.
|
||||
|
||||
Normal release acceptance now hashes the complete effective Compose set,
|
||||
including the accepted override. Build policy, service selection and
|
||||
`--no-deps --no-build --pull never` remain unchanged. Normal activation and
|
||||
automatic rollback call the same domain executor, so both receive the override.
|
||||
Rollback still restores exact prior image IDs without rebuilding.
|
||||
|
||||
The runtime fingerprint stays v2: only complete uniquely addressed mount objects
|
||||
are order-normalized. `HostConfig.NetworkMode`, all its other fields, environment,
|
||||
mount options and attached network names remain strict. There is no retry-until-
|
||||
accepted loop and no acceptance of a switched primary network.
|
||||
|
||||
## Reproducible qualification and operator sequence
|
||||
|
||||
Source checks:
|
||||
```sh
|
||||
python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'
|
||||
python3 -m unittest discover -s infra/device-core-deploy -p 'test_*.py'
|
||||
```
|
||||
Also run the Platform/Device Plane registry suites and the Device Core
|
||||
repository's artifact/real HTTP-health tests against this candidate runner.
|
||||
Twenty focused network-priority tests cover exact payload, deterministic
|
||||
packaging, configuration-diff boundaries, initial predecessor, secret redaction,
|
||||
receipt/archive activation, actual release command construction, no-runtime
|
||||
metadata application and rollback failure. Python3.8 syntax is required.
|
||||
|
||||
Promote the reviewed root runner through the separate atomic SHA-pinned gate,
|
||||
then require its `verify-install`. Build with the committed canonical builder:
|
||||
```sh
|
||||
python3 infra/device-core-deploy/build_network_priority.py --output-dir /tmp/device-network-priority
|
||||
```
|
||||
Audit and stage the resulting immutable TGZ through SMB, inspect lifecycle,
|
||||
then review a fresh NAS `plan`. Only the matching new plan authorizes the
|
||||
already-requested `apply`. No raw Docker/diagnostic shell acceptance follows
|
||||
`deploy-ok`: the runner owns that gate.
|
||||
|
||||
The completed acceptance sequence was: metadata002 → Device Core Platform pin
|
||||
update in `33cd08c7ab4b1ee87e8c943fca4a30f38c782aae` → automatic r13 →
|
||||
documentation commit `6ca6738bab22d0fdef714b90c68959363106ee5b` → automatic r14.
|
||||
For each release, verify CI, canonical receipt/archive/backup, runtime evidence
|
||||
and separate authenticated UI/public health. On another installation, never
|
||||
advance main before its exact metadata predecessor transition is accepted.
|
||||
|
||||
## Production acceptance register
|
||||
|
||||
Installed root runner015 SHA:
|
||||
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`,
|
||||
Python3.8.15, exact operator `verify-install-ok`. Published source:
|
||||
`50dc3b1a2cb1191484f5b90de2d2702b14127425` on
|
||||
`fix/device-core-network-priority-20260930`; Device Core pins the full commit.
|
||||
|
||||
Metadata002 was accepted at2026-09-30T09:12:12Z, applied journal390,
|
||||
archive SHA `5ee23f440ef4a5ef7593c5c35b27b17d93d556453df69e152caee1ddd41e8c7b`.
|
||||
Backup:
|
||||
`device-core-network-priority-device-core-network-priority-v1-20260930-002-20260930-121204`.
|
||||
Independent SMB lifecycle inspection found one applied receipt, matching archive,
|
||||
existing backup, no failed receipt/warnings and expected absence from inbox.
|
||||
This proves the registered metadata acceptance; it is not an application release.
|
||||
Do not restage/replay002 or the superseded001.
|
||||
|
||||
Live application acceptance below must follow CI → controller → canonical
|
||||
archive/ledger/backup → authenticated Device Core UI/public GET health.
|
||||
No manual NAS commands or shell acceptance are needed after `deploy-ok`.
|
||||
|
||||
First release after002: r13/source `33cd08c7ab4b1ee87e8c943fca4a30f38c782aae`.
|
||||
CI passed265application/25CI/170artifact cases (17historical skips). Canonical
|
||||
acceptance at09:25:33Z, ledger391, archive SHA
|
||||
`5fa322be2619ddfe2ad91f9e7d2c9d2cd1b3f8d91d34b7a2e5650eb9b617fc98`, backup
|
||||
`device-core-release-device-core-release-v1-r13-33cd08c7ab4b1ee87e8c943fca4a30f38c782aae-20260930-122207`.
|
||||
The before snapshot identifies r12, both private primary networks and accepted
|
||||
override SHA `01cd551b23ac56eee2577e60f9e1e4ecdcc252cd09c122d73583e3c39c9f2644`.
|
||||
All77 regular artifact files were compared with r12: only manifest and release
|
||||
descriptor differ. This qualifies delivery/recreation, not a schema migration.
|
||||
Independent CI receipt, archive digest, unique canonical record and backup agree;
|
||||
lifecycle terminal_success without warnings/failed record. Public GET health200,
|
||||
all three health flags true; authenticated reload retained DC SUDO, DCTOUCH and
|
||||
Robot2B — Moscow Trike Delivery, with no user/device-data mutation.
|
||||
|
||||
Second source `6ca6738bab22d0fdef714b90c68959363106ee5b` records r13 acceptance
|
||||
and triggers r14 through the ordinary main push path. It changes only the
|
||||
Device Core deployment documentation. No second root command is involved.
|
||||
|
||||
A Mac observation issue occurred after r13: the existing SMB read initially
|
||||
returned465 zero bytes for the appended row although the controller reported
|
||||
deployed. Read-only macOS F_NOCACHE/F_RDAHEAD returned the complete391st JSON
|
||||
record, after which the canonical lifecycle inspector passed. The NAS journal
|
||||
was not edited and the release was not replayed. The local observer now reads
|
||||
journals without the client data cache and still rejects malformed rows. A
|
||||
controller status alone must never substitute for journal/archive/backup proof.
|
||||
|
||||
Second release r14 was accepted at2026-09-30T09:38:00Z, ledger392, archive SHA
|
||||
`385c2fec8fce300cb80a93edfbcb0d537e34755b0ccc35294c0102b3c4a7f724`, backup
|
||||
`device-core-release-device-core-release-v1-r14-6ca6738bab22d0fdef714b90c68959363106ee5b-20260930-123508`.
|
||||
CI passed the same265application/25CI/170artifact cases (17historical skips).
|
||||
The independently downloaded CI receipt/archive agree with the unique canonical
|
||||
record and existing backup. Lifecycle is terminal_success, with no failed
|
||||
record/warnings. Its before snapshot identifies r13; effective Compose file
|
||||
hashes and all diagnostic field hashes equal the r13 before snapshot, including
|
||||
both private primary networks. Canonical acceptance also checks the recreated
|
||||
services against those strict before fingerprints before reporting success.
|
||||
Artifact payload comparison r13/r14 again differs only in manifest and release
|
||||
descriptor. Public GET health200 and authenticated Devices UI retained DC SUDO,
|
||||
DCTOUCH and Robot2B — Moscow Trike Delivery after reload.
|
||||
|
||||
The two-release gate is complete. No manual source staging, plan/apply, SSH
|
||||
session or Mac-side deploy authority was used. Mac tools only observed Gitea/SMB
|
||||
and product health/UI; the independent NAS controller performed installation.
|
||||
This is measured acceptance of the Device Core delivery path and the reproduced
|
||||
network-selection correction, not proof of the lost historical r9 field, fleet
|
||||
load capacity, universal multi-repo onboarding or every possible outage.
|
||||
|
||||
Local evidence: `outputs/device-core-stability-20260930/automatic-acceptance/`
|
||||
contains per-source CI receipts/packages, journal/archive lifecycle checks,
|
||||
redacted runtime evidence, product checks and cross-release payload/field-digest
|
||||
comparisons. Platform documentation is published separately from Device Core
|
||||
main, so recording r14 does not cause an endless chain of documentation releases.
|
||||
@@ -1,11 +1,20 @@
|
||||
# Device Core recurring deployment
|
||||
|
||||
Status: 2026-09-29. The build runner is installed and push-to-main qualification
|
||||
works. Release r7 (`edf69068ec64e3d105d5324d39b8eaeface21215`) is accepted
|
||||
in canonical ledger 385. The outbound production controller was activated by
|
||||
`device-core-autodeploy-v1-20260929-001` in ledger 386 at18:35:52Z on2026-09-29.
|
||||
Run8 deployed automatically; run9 failed Manager runtime configuration acceptance
|
||||
and rolled back successfully. Full ordered-release acceptance remains open.
|
||||
Status: 2026-09-30. Push-to-main qualification and automatic installation work on
|
||||
Synology. The outbound controller bootstrap is recorded in ledger386.
|
||||
Runs11 and12 were accepted automatically in sequence (ledgers388/389), followed
|
||||
by runs13 and14 (ledgers391/392). Current accepted application source is
|
||||
`6ca6738bab22d0fdef714b90c68959363106ee5b`. A real npm
|
||||
ECONNRESET during run12 recovered through the bounded CI install retry.
|
||||
Earlier run9 failed Manager runtime configuration acceptance and rolled back;
|
||||
its exact cause remains unresolved. The installed runner retains per-field
|
||||
diagnostics without weakening acceptance. See [the evidence report](ACCEPTANCE_20260929.md).
|
||||
An independently reproduced equal-priority Compose network-selection defect now
|
||||
has a tested correction. Runner014's first metadata plan exposed
|
||||
a null-endpoint parser case. Corrected runner015 and metadata002 are now accepted;
|
||||
two subsequent automatic application releases, r13 and r14, passed canonical
|
||||
installation and separate authenticated UI/public-health acceptance.
|
||||
See [the exact network-priority transition](NETWORK_PRIORITY_20260930.md).
|
||||
DCPLATFORM-21 owns the deployment contract; DCPLATFORM-37 tracks acceptance.
|
||||
|
||||
## Release domain
|
||||
@@ -109,12 +118,18 @@ canon. Device Core uses its own exact Core+Manager Compose entry with unchanged
|
||||
|
||||
- Runner012 was promoted and verified as
|
||||
`c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`.
|
||||
- Runner013 subsequently passed operator verify-install as
|
||||
`3eefc75591bb08339d79c6a484912d7d6a8881fe8729e966b6f0bf32da21da80`.
|
||||
- Current runner015 passed operator verify-install as
|
||||
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`.
|
||||
Metadata002 was accepted at2026-09-30T09:12:12Z, canonical journal390.
|
||||
See the network-priority report for its immutable artifact and backup identity.
|
||||
- The data-only bootstrap built by `build_autodeploy.py` passed fresh plan/apply;
|
||||
artifact SHA is `fe9298baa5f41a35c2705ee9946b730ff2de7d5b5c9b2b8eb1b4cca0bc8ed12b`.
|
||||
- NAS imported its root-private credential and removed enrollment staging. The
|
||||
temporary Mac credential was removed after acceptance. Neither a Mac nor SMB
|
||||
needs to remain connected for recurring delivery.
|
||||
- Ordered automatic releases are being verified against their CI receipts,
|
||||
- Ordered automatic releases r11/r12 and then r13/r14 were verified against their CI receipts,
|
||||
archive digests, unique canonical journal rows and backups. Failed-check and
|
||||
crash/reconciliation tests are source qualification, not a claim that the NAS
|
||||
was deliberately crashed during production acceptance.
|
||||
@@ -129,15 +144,14 @@ successfully to run8. Its failed archive must not be replayed. The initial
|
||||
snapshots retained only an aggregate configuration hash, so the specific field
|
||||
was not available after rollback removed the failed container.
|
||||
|
||||
The next runner candidate adds diagnostic field hashes to new before snapshots.
|
||||
It binds each observation to the checked container/image/configuration identity.
|
||||
Diagnostics introduced in runner013 add field hashes to new before snapshots.
|
||||
Each observation is bound to the checked container/image/configuration identity.
|
||||
On a mismatch, the canonical failed receipt retains changed field names and
|
||||
their hashes before the failed generation is removed. Raw environment values,
|
||||
inspect payloads and external exception text are not included. The v2 comparison,
|
||||
network/mount semantics, selected services and rollback checks are unchanged.
|
||||
Old snapshots still use their original aggregate hash. This instrumentation is
|
||||
not a fix for an as-yet-unidentified configuration difference and is not installed
|
||||
until the separate root promotion succeeds.
|
||||
not by itself a fix for an as-yet-unidentified configuration difference.
|
||||
|
||||
See [live acceptance and the run9 incident](ACCEPTANCE_20260929.md).
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the exact data-only Device Core primary-network contract."""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
ENTRIES = ('docker-compose.device-release-network-priority.yml',
|
||||
'deployment/device-core-network-priority-v1.json')
|
||||
|
||||
|
||||
def bundle():
|
||||
descriptor = (ROOT / 'network-priority-v1.json').read_bytes()
|
||||
identity = json.loads(descriptor)['releaseId']
|
||||
members = {
|
||||
'manifest.env': ('id=' + identity + '\ncomponent=device-core-network-priority\ntype=app-overlay\n').encode(),
|
||||
'files.txt': ('\n'.join(ENTRIES) + '\n').encode(),
|
||||
'payload/' + ENTRIES[0]: (ROOT / 'docker-compose.network-priority.yml').read_bytes(),
|
||||
'payload/' + ENTRIES[1]: descriptor,
|
||||
}
|
||||
output = io.BytesIO()
|
||||
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
|
||||
with tarfile.open(fileobj=compressed, mode='w') as archive:
|
||||
for name, data in sorted(members.items()):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.mode = 0o644
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return identity, output.getvalue()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output-dir', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
identity, data = bundle()
|
||||
path = args.output_dir / ('nodedc-' + identity + '.tgz')
|
||||
with path.open('xb') as stream:
|
||||
stream.write(data)
|
||||
print(json.dumps({'artifact': str(path), 'sha256': hashlib.sha256(data).hexdigest(), 'id': identity}))
|
||||
@@ -0,0 +1,13 @@
|
||||
services:
|
||||
device-control-core:
|
||||
networks:
|
||||
device-plane-private:
|
||||
priority: 100
|
||||
device-plane-egress:
|
||||
priority: 0
|
||||
device-manager:
|
||||
networks:
|
||||
device-plane-private:
|
||||
priority: 100
|
||||
platform-edge:
|
||||
priority: 0
|
||||
@@ -0,0 +1 @@
|
||||
{"schemaVersion":"nodedc.device-core.network-priority.v1","releaseId":"device-core-network-priority-v1-20260930-002","baselineReleaseId":"device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b","baselineSha256":"44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c","mode":"metadata-only-existing-primary-network","primaryPriority":100,"secondaryPriority":0}
|
||||
@@ -0,0 +1,39 @@
|
||||
# Optional delegated Core egress
|
||||
|
||||
Prepared 17 November 2026; **not deployed on NAS**. The legacy AMD path remains
|
||||
active when no delegation is supplied. McHost's relay is installed, but Cesium
|
||||
country-blocks its public egress IP; Mission Core has therefore not selected it.
|
||||
|
||||
`src/egress.mjs` admits a request-scoped `nodedc.map-egress/v1` binding only with a
|
||||
separate HMAC signature over schema, method, path and payload. A browser or trusted
|
||||
subject header alone cannot set the route. The key is derived from Gateway's
|
||||
existing administrative secret with the domain `nodedc.map-egress.core/v1`; Core
|
||||
would receive only the derived key in private `services/cesium-ion/egress-signing.key`
|
||||
(64 hexadecimal characters). No key has been provisioned in this rollout. Keep
|
||||
the key, binding and provider credentials out of logs, responses and Git.
|
||||
|
||||
The binding expires within 30 seconds and supplies a pinned relay endpoint,
|
||||
credential and Cesium profile. TLS 1.3 certificate verification by exact fingerprint
|
||||
precedes HTTP credentials. Destination checks forbid private addresses and arbitrary
|
||||
provider hosts. The relay allows only GET/HEAD; range and conditional headers are
|
||||
forwarded. Cancellation closes the stream. Concurrent relay requests are bounded
|
||||
at 16; handshake and body idle timeouts are 8 and 30 seconds.
|
||||
|
||||
Cache lookup is unchanged and occurs before external fetch. Delegation affects
|
||||
only a miss/refresh fetch: it does not change canonical URLs, object keys, index
|
||||
format, credential scoping, atomic fills or the physical cache root. Warm hits
|
||||
need neither AMD nor VPS. Do not rebuild, copy, clear or reindex tiles for this
|
||||
transport change. The health contract advertises `egressContract` after deployment;
|
||||
Core requires this contract and its signing key before admitting a cached route.
|
||||
|
||||
Three delegation tests passed, including real TLS pin/header/cancellation cases.
|
||||
Existing smoke checks passed for no-browser-credentials, live-cache-fallback and
|
||||
streaming-cache-fill (unchanged warm-hit writes, conditional responses, bounded
|
||||
singleflight and partial-object privacy). These are local checks, not proof of a
|
||||
deployed Gateway or live NAS-to-VPS acceptance.
|
||||
|
||||
Before activation: qualify a reachable provider exit; build and deploy only with
|
||||
the canonical NODE.DC artifact/runner plan/apply workflow; provision the derived
|
||||
private key; verify bounded warm hits, cold fills and NAS outage/recovery. Preserve
|
||||
the existing AMD route as rollback. No NAS deployment artifact was staged during
|
||||
the blocked McHost qualification.
|
||||
@@ -0,0 +1,103 @@
|
||||
// Delegated Core egress is authenticated separately from map-read admission.
|
||||
// A browser/trusted-subject header alone cannot redirect provider credentials.
|
||||
import {AsyncLocalStorage} from 'node:async_hooks';
|
||||
import {createHash, createHmac, timingSafeEqual} from 'node:crypto';
|
||||
import {lookup} from 'node:dns/promises';
|
||||
import {Agent, request as httpRequest} from 'node:http';
|
||||
import {isIP} from 'node:net';
|
||||
import {Readable} from 'node:stream';
|
||||
import {connect} from 'node:tls';
|
||||
|
||||
export const egressContext = new AsyncLocalStorage();
|
||||
const contract = 'nodedc.map-egress/v1';
|
||||
const hosts = new Set(['api.cesium.com', 'assets.ion.cesium.com', 'assets.cesium.com',
|
||||
'dev.virtualearth.net', 'ecn.tiles.virtualearth.net',
|
||||
...[0,1,2,3].map(n=>`ecn.t${n}.tiles.virtualearth.net`)]);
|
||||
function denied(code='map_egress_request_rejected', statusCode=403) {
|
||||
return Object.assign(new Error(code), {statusCode});
|
||||
}
|
||||
export function signingKey(adminSecret) {
|
||||
return createHmac('sha256', adminSecret).update('nodedc.map-egress.core/v1').digest();
|
||||
}
|
||||
export function authorizeEgress(request, adminSecret, path, now=Date.now()) {
|
||||
const payload=request.headers['x-nodedc-map-egress'];
|
||||
const signature=request.headers['x-nodedc-map-egress-signature'];
|
||||
if (!payload && !signature) return null;
|
||||
if (!adminSecret || typeof payload!=='string' || payload.length>4096 || !/^[A-Za-z0-9_-]+$/.test(payload)
|
||||
|| typeof signature!=='string' || !/^[a-f0-9]{64}$/.test(signature)) throw denied();
|
||||
const expected=createHmac('sha256',signingKey(adminSecret))
|
||||
.update(`${contract}\n${request.method}\n${path}\n${payload}`).digest();
|
||||
if (!timingSafeEqual(expected,Buffer.from(signature,'hex'))) throw denied();
|
||||
let value;
|
||||
try {value=JSON.parse(Buffer.from(payload,'base64url'));} catch {throw denied();}
|
||||
if (!value || Object.keys(value).sort().join(',')!=='endpoint,fingerprint,profile,schema,timestamp,token'
|
||||
|| value.schema!==contract || value.profile!=='cesium' || !Number.isSafeInteger(value.timestamp)
|
||||
|| Math.abs(now/1000-value.timestamp)>30 || !/^[a-f0-9]{64}$/.test(value.fingerprint)
|
||||
|| !/^[A-Za-z0-9_-]{43}$/.test(value.token)) throw denied();
|
||||
validateEndpoint(value.endpoint);
|
||||
return value;
|
||||
}
|
||||
export function publicIPv4(address) {
|
||||
if(isIP(address)!==4) return false;
|
||||
const [a,b,c]=address.split('.').map(Number);
|
||||
return !(a===0||a===10||a===127||a>=224||(a===100&&b>=64&&b<=127)
|
||||
||(a===169&&b===254)||(a===172&&b>=16&&b<=31)||(a===192&&(b===168||b===0||b===2))
|
||||
||(a===198&&(b===18||b===19||(b===51&&c===100)))||(a===203&&b===0&&c===113));
|
||||
}
|
||||
function validateEndpoint(endpoint) {
|
||||
let url;
|
||||
try {url=new URL(endpoint);} catch {throw denied();}
|
||||
if(url.protocol!=='https:'||url.username||url.password||url.search||url.hash||url.pathname!=='/'
|
||||
|| !url.port || Number(url.port)<1024 || Number(url.port)>65535) throw denied();
|
||||
return url;
|
||||
}
|
||||
let active=0;
|
||||
export async function relayFetch(binding,target,options={},dependencies={}) {
|
||||
const provider=new URL(target);
|
||||
if(provider.protocol!=='https:'||!hosts.has(provider.hostname)||provider.username||provider.password
|
||||
||provider.hash||(provider.port&&provider.port!=='443')||!['GET','HEAD'].includes(options.method||'GET')) throw denied();
|
||||
const endpoint=validateEndpoint(binding.endpoint);
|
||||
if(active>=16) throw denied('map_egress_capacity_reached',503);
|
||||
active++;
|
||||
let socket,agent,released=false;
|
||||
const release=()=>{if(!released){released=true;active--;agent?.destroy();socket?.destroy();}};
|
||||
try {
|
||||
const addresses=await (dependencies.lookup||lookup)(endpoint.hostname,{all:true,family:4});
|
||||
if(!addresses.length||addresses.some(item=>!publicIPv4(item.address))) throw denied();
|
||||
options.signal?.throwIfAborted();
|
||||
socket=await new Promise((resolve,reject)=>{
|
||||
const candidate=(dependencies.connect||connect)({host:addresses[0].address,port:Number(endpoint.port),servername:isIP(endpoint.hostname)?undefined:endpoint.hostname,
|
||||
rejectUnauthorized:false,minVersion:'TLSv1.3'});
|
||||
const timer=setTimeout(()=>candidate.destroy(new Error('relay_timeout')),8000);
|
||||
const abort=()=>candidate.destroy(new Error('relay_cancelled'));
|
||||
options.signal?.addEventListener('abort',abort,{once:true});
|
||||
candidate.once('error',error=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);reject(error);});
|
||||
candidate.once('secureConnect',()=>{
|
||||
clearTimeout(timer);options.signal?.removeEventListener('abort',abort);
|
||||
const actual=createHash('sha256').update(candidate.getPeerCertificate().raw||Buffer.alloc(0)).digest('hex');
|
||||
if(actual!==binding.fingerprint){candidate.destroy();reject(denied('map_egress_identity_changed',502));}
|
||||
else resolve(candidate); // No HTTP bytes/credentials sent before this point.
|
||||
});
|
||||
});
|
||||
const input=new Headers(options.headers||{}), headers={Authorization:`Bearer ${binding.token}`};
|
||||
for(const name of ['accept','range','if-none-match','if-modified-since']) if(input.has(name)) headers[name]=input.get(name);
|
||||
if(input.has('authorization')) headers['X-Nodedc-Upstream-Authorization']=input.get('authorization');
|
||||
if(input.has('referer')) headers['X-Nodedc-Upstream-Referer']=input.get('referer');
|
||||
agent=new Agent({keepAlive:false});
|
||||
agent.createConnection=()=>socket;
|
||||
const response=await new Promise((resolve,reject)=>{
|
||||
const req=httpRequest({host:endpoint.hostname,port:Number(endpoint.port),agent,method:options.method||'GET',
|
||||
path:'/v1/fetch/cesium?'+new URLSearchParams({url:provider.href}),headers,signal:options.signal},resolve);
|
||||
req.setTimeout(30000,()=>req.destroy(new Error('relay_timeout')));
|
||||
req.once('error',reject);req.end();
|
||||
});
|
||||
response.once('close',release);
|
||||
const responseHeaders=new Headers();
|
||||
for(const [key,value] of Object.entries(response.headers)) if(value!==undefined&&!['transfer-encoding','connection','set-cookie'].includes(key))
|
||||
responseHeaders.set(key,Array.isArray(value)?value.join(', '):value);
|
||||
if(options.method==='HEAD'||[204,205,304].includes(response.statusCode)) {
|
||||
response.resume();return new Response(null,{status:response.statusCode,headers:responseHeaders});
|
||||
}
|
||||
return new Response(Readable.toWeb(response),{status:response.statusCode,headers:responseHeaders});
|
||||
} catch(error) {release();throw error?.statusCode?error:denied('map_egress_unavailable',502);}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
TRANSPORT_STATION_PROFILE_ID,
|
||||
createReferenceStationSource,
|
||||
} from "./reference-station-source.mjs";
|
||||
import {authorizeEgress, egressContext, relayFetch} from "./egress.mjs";
|
||||
import { loadZoneSourceProfile } from "./zone-source-snapshot.mjs";
|
||||
|
||||
const canonicalCesiumAssetIds = ["1", "2", "96188"];
|
||||
@@ -21,6 +22,8 @@ const cesiumVerificationTransportVersion = 4;
|
||||
const canonicalCesiumEgressHosts = new Set([
|
||||
"api.cesium.com",
|
||||
"assets.ion.cesium.com",
|
||||
"assets.cesium.com",
|
||||
"ecn.tiles.virtualearth.net",
|
||||
"dev.virtualearth.net",
|
||||
"ecn.t0.tiles.virtualearth.net",
|
||||
"ecn.t1.tiles.virtualearth.net",
|
||||
@@ -63,7 +66,7 @@ let activeCesiumIonToken = (await readStoredCesiumIonToken()) || config.bootstra
|
||||
let ionTokenWriteQueue = Promise.resolve();
|
||||
let ionTokenGeneration = 0;
|
||||
|
||||
const server = createServer(async (request, response) => {
|
||||
const server = createServer((request, response) => egressContext.run(null, async () => {
|
||||
applyCors(request, response);
|
||||
if (request.method === "OPTIONS") return response.writeHead(204).end();
|
||||
let requestPath = "unknown";
|
||||
@@ -82,6 +85,7 @@ const server = createServer(async (request, response) => {
|
||||
return serveZoneSourceGeneration(request, response);
|
||||
}
|
||||
if (!isAllowedRequest(request)) return writeJson(response, 401, { ok: false, error: "map_gateway_auth_required" });
|
||||
egressContext.enterWith(authorizeEgress(request, config.mapGatewayAdminSecret, requestUrl.pathname));
|
||||
|
||||
if (requestUrl.pathname === `/api/map/reference-sources/v1/profiles/${TRANSPORT_STATION_PROFILE_ID}/current`
|
||||
&& ["GET", "HEAD"].includes(request.method || "")) {
|
||||
@@ -96,6 +100,7 @@ const server = createServer(async (request, response) => {
|
||||
return writeJson(response, 200, {
|
||||
ok: true,
|
||||
service: "nodedc-map-gateway",
|
||||
egressContract: "nodedc.map-egress/v1",
|
||||
cache: await cacheStats(liveCache),
|
||||
offlineSnapshot: offlineSnapshot ? await cacheStats(offlineSnapshot) : null,
|
||||
diagnostics: gatewayDiagnostics.status(),
|
||||
@@ -144,7 +149,7 @@ const server = createServer(async (request, response) => {
|
||||
error: errorCode,
|
||||
});
|
||||
}
|
||||
});
|
||||
}));
|
||||
|
||||
server.listen(config.port, "0.0.0.0", () => {
|
||||
console.log(`NODE.DC Map Gateway listening on http://0.0.0.0:${config.port}`);
|
||||
@@ -1356,16 +1361,20 @@ function throughCesiumEgress(target, options = {}) {
|
||||
async function fetchWithTimeout(target, options = {}, diagnostic = {}) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), config.upstreamTimeoutMs);
|
||||
const viaEgress = shouldUseCesiumEgress(target);
|
||||
const binding = egressContext.getStore();
|
||||
const viaRelay = Boolean(binding && canonicalCesiumEgressHosts.has(new URL(String(target)).hostname));
|
||||
const viaEgress = viaRelay || shouldUseCesiumEgress(target);
|
||||
const provider = safeProviderName(target);
|
||||
const operation = safeProviderOperation(diagnostic.operation);
|
||||
const assetId = /^\d{1,20}$/.test(String(diagnostic.assetId || "")) ? String(diagnostic.assetId) : undefined;
|
||||
const request = viaEgress
|
||||
const request = viaEgress && !viaRelay
|
||||
? throughCesiumEgress(target, options)
|
||||
: { target, options };
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const response = await fetch(request.target, { ...request.options, signal: controller.signal, redirect: "follow" });
|
||||
const response = viaRelay
|
||||
? await relayFetch(binding, target, {...options, signal: controller.signal})
|
||||
: await fetch(request.target, { ...request.options, signal: controller.signal, redirect: "follow" });
|
||||
const egressError = safeEgressErrorCode(response.headers.get("x-nodedc-egress-error"));
|
||||
// The restricted egress emits a short code instead of a target URL or a
|
||||
// secret. Preserve it through Map Gateway so the operator can distinguish
|
||||
@@ -1498,7 +1507,8 @@ function createGatewayDiagnostics(slowUpstreamMs) {
|
||||
|
||||
function safeEgressErrorCode(value) {
|
||||
const code = String(value || "").trim();
|
||||
return /^amd_[a-z0-9_.:-]{1,100}$/.test(code) ? code : "";
|
||||
const relay = new Set(["upstream_region_denied", "upstream_unavailable", "capacity_reached", "access_rejected", "request_rejected"]);
|
||||
return /^amd_[a-z0-9_.:-]{1,100}$/.test(code) || relay.has(code) ? code : "";
|
||||
}
|
||||
|
||||
function safeDiagnosticCode(value) {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createHash,createHmac,X509Certificate} from 'node:crypto';
|
||||
import {createServer} from 'node:https';
|
||||
import {connect} from 'node:tls';
|
||||
import {execFileSync} from 'node:child_process';
|
||||
import {mkdtemp,readFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {authorizeEgress,publicIPv4,relayFetch,signingKey} from '../src/egress.mjs';
|
||||
|
||||
const secret='a'.repeat(64);
|
||||
function signed(overrides={}) {
|
||||
const value={schema:'nodedc.map-egress/v1',timestamp:1000,profile:'cesium',
|
||||
endpoint:'https://1.1.1.1:19446',fingerprint:'b'.repeat(64),token:'c'.repeat(43),...overrides};
|
||||
const payload=Buffer.from(JSON.stringify(value)).toString('base64url');
|
||||
const signature=createHmac('sha256',signingKey(secret)).update(`nodedc.map-egress/v1\nGET\n/api/map/cache\n${payload}`).digest('hex');
|
||||
return {method:'GET',headers:{'x-nodedc-map-egress':payload,'x-nodedc-map-egress-signature':signature}};
|
||||
}
|
||||
test('signed admission rejects tampering, expiry and a subject without delegation',()=>{
|
||||
assert.equal(authorizeEgress(signed(),secret,'/api/map/cache',1000000).profile,'cesium');
|
||||
assert.throws(()=>authorizeEgress(signed(),secret,'/api/map/ion',1000000));
|
||||
assert.throws(()=>authorizeEgress(signed(),secret,'/api/map/cache',1031000));
|
||||
assert.throws(()=>authorizeEgress(signed(),'wrong','/api/map/cache',1000000));
|
||||
assert.throws(()=>authorizeEgress(signed({profile:'arbitrary'}),secret,'/api/map/cache',1000000));
|
||||
assert.equal(authorizeEgress({headers:{'x-nodedc-user-id':'operator'}},secret,'/api/map/cache'),null);
|
||||
});
|
||||
test('public relay destination excludes private and special address ranges',()=>{
|
||||
for(const address of ['127.0.0.1','0.0.0.0','10.1.1.1','100.64.0.1','169.254.169.254','172.22.0.1','192.168.1.2','198.18.0.1','203.0.113.1','224.0.0.1','::1']) assert.equal(publicIPv4(address),false,address);
|
||||
assert.equal(publicIPv4('1.1.1.1'),true);
|
||||
});
|
||||
test('TLS pin checked before secrets; range and cancellation preserve transport boundaries',async()=>{
|
||||
const folder=await mkdtemp(join(tmpdir(),'egress-test-'));
|
||||
let server;
|
||||
try {
|
||||
execFileSync('openssl',['req','-x509','-newkey','ed25519','-nodes','-days','1','-subj','/CN=test','-keyout',join(folder,'key'),'-out',join(folder,'cert')],{stdio:'ignore'});
|
||||
const cert=await readFile(join(folder,'cert')),key=await readFile(join(folder,'key'));
|
||||
const fingerprint=createHash('sha256').update(new X509Certificate(cert).raw).digest('hex');
|
||||
const received=[];
|
||||
server=createServer({cert,key,minVersion:'TLSv1.3'},(req,res)=>{
|
||||
received.push({url:req.url,headers:req.headers});
|
||||
res.writeHead(206,{'content-type':'application/octet-stream','content-range':'bytes 1-3/4','set-cookie':'secret'});res.end('abc');
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const dependencies={lookup:async()=>[{address:'1.1.1.1'}],connect:options=>connect({...options,host:'127.0.0.1',port:server.address().port})};
|
||||
const binding={endpoint:'https://1.1.1.1:19446',token:'c'.repeat(43),fingerprint};
|
||||
await assert.rejects(relayFetch({...binding,fingerprint:'0'.repeat(64)},'https://assets.ion.cesium.com/a',{},dependencies),/identity_changed/);
|
||||
assert.equal(received.length,0);
|
||||
const response=await relayFetch(binding,'https://assets.ion.cesium.com/a',{headers:{authorization:'Bearer provider-secret',range:'bytes=1-3',cookie:'no'}},dependencies);
|
||||
assert.equal(response.status,206);assert.equal(await response.text(),'abc');
|
||||
assert.equal(response.headers.get('content-range'),'bytes 1-3/4');assert.equal(response.headers.get('set-cookie'),null);
|
||||
assert.equal(received[0].headers.authorization,'Bearer '+binding.token);
|
||||
assert.equal(received[0].headers['x-nodedc-upstream-authorization'],'Bearer provider-secret');
|
||||
assert.equal(received[0].headers.cookie,undefined);
|
||||
const cancelled=new AbortController();cancelled.abort();
|
||||
await assert.rejects(relayFetch(binding,'https://assets.ion.cesium.com/a',{signal:cancelled.signal},dependencies));
|
||||
assert.equal(received.length,1,'A cancelled request must not send credentials');
|
||||
await assert.rejects(relayFetch(binding,'https://private.example/',{},dependencies));
|
||||
} finally {if(server)await new Promise(resolve=>server.close(resolve));await rm(folder,{recursive:true,force:true});}
|
||||
});
|
||||
Reference in New Issue
Block a user