Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b984de10a | ||
|
|
27c155276a | ||
|
|
39a2239563 | ||
|
|
1e191868be | ||
|
|
9dcd520503 |
@@ -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;
|
||||
@@ -2962,6 +2962,17 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
|
||||
)
|
||||
|
||||
COMPONENTS = {
|
||||
"device-b2-shared-contours": {
|
||||
"payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, "services": (),
|
||||
},
|
||||
"device-b2-foundation-reconciliation": {
|
||||
"payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, "services": (),
|
||||
},
|
||||
"device-b2-foundation": {
|
||||
"payload_root": DEVICE_PLANE_ROOT, "compose_root": DEVICE_PLANE_ROOT,
|
||||
"compose_project": "nodedc-device-plane", "compose_no_deps": True,
|
||||
"services": ("device-control-core",),
|
||||
},
|
||||
"device-core-network-priority": {
|
||||
"payload_root": DEVICE_PLANE_ROOT,
|
||||
"artifact_only": True, "services": (),
|
||||
@@ -4983,6 +4994,18 @@ def denied_payload_path(component, rel):
|
||||
|
||||
def allowed_payload_path(component, rel):
|
||||
validate_posix_path(rel)
|
||||
if component == "device-b2-shared-contours":
|
||||
if rel in ("deployment", *DEVICE_B2_SHARED_ENTRIES):
|
||||
return True
|
||||
die("Device B2 shared contours accepts only its three fixed files")
|
||||
if component == "device-b2-foundation-reconciliation":
|
||||
if rel in ("deployment", DEVICE_B2_RECON_ENTRY):
|
||||
return True
|
||||
die("Device B2 reconciliation accepts only its fixed descriptor")
|
||||
if component == "device-b2-foundation":
|
||||
if rel in ("deployment", *DEVICE_B2_ENTRIES):
|
||||
return True
|
||||
die("Device B2 foundation accepts only three fixed files")
|
||||
if component == "device-core-network-priority":
|
||||
if rel in ("deployment", *DEVICE_PRIORITY_ENTRIES):
|
||||
return True
|
||||
@@ -11615,6 +11638,12 @@ def load_artifact(artifact, work_dir):
|
||||
die(f"files.txt entry missing in payload: {rel}")
|
||||
|
||||
validate_payload_tree(manifest["component"], payload_dir, entries)
|
||||
if manifest["component"] == "device-b2-shared-contours":
|
||||
validate_device_b2_shared_payload(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-b2-foundation-reconciliation":
|
||||
validate_device_b2_reconciliation_payload(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-b2-foundation":
|
||||
validate_device_b2_payload(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-core-network-priority":
|
||||
validate_device_priority_payload(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-core-autodeploy":
|
||||
@@ -22473,6 +22502,18 @@ def is_platform_provider_catalog_only(entries):
|
||||
|
||||
|
||||
def component_services(component, entries=None):
|
||||
if component == "device-b2-shared-contours":
|
||||
if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES:
|
||||
die("Device B2 shared contours requires all three exact entries")
|
||||
return ()
|
||||
if component == "device-b2-foundation-reconciliation":
|
||||
if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,):
|
||||
die("Device B2 reconciliation requires the exact descriptor entry")
|
||||
return ()
|
||||
if component == "device-b2-foundation":
|
||||
if tuple(entries or ()) != DEVICE_B2_ENTRIES:
|
||||
die("Device B2 foundation requires all three exact entries")
|
||||
return ("device-control-core",)
|
||||
if component == "device-core-network-priority":
|
||||
if tuple(entries or ()) != DEVICE_PRIORITY_ENTRIES:
|
||||
die("Device Core network priority requires exact entries")
|
||||
@@ -22818,6 +22859,8 @@ def component_compose_files(
|
||||
expected_node_intelligence_gateway_sha256=None,
|
||||
):
|
||||
if component == "device-core-release":
|
||||
return device_b2_compose_files(device_priority_compose_files(component_compose_files("device-plane")))
|
||||
if component == "device-b2-foundation":
|
||||
return device_priority_compose_files(component_compose_files("device-plane"))
|
||||
if component == "engine":
|
||||
root = component_root(component)
|
||||
@@ -33190,6 +33233,7 @@ def preflight_device_release(payload, entries, patch_id):
|
||||
run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES)
|
||||
before = device_release_runtime_snapshot_v2()
|
||||
field_digests = device_release_capture_field_digests(before)
|
||||
validate_installed_device_b2()
|
||||
compose = {str(p): sha256_file(p) for p in component_compose_files("device-core-release")}
|
||||
return {"runtimeFingerprintVersion": 2, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4",
|
||||
"runtime": before, "runtimeFieldDigests": field_digests,
|
||||
@@ -33235,6 +33279,7 @@ def accept_device_release(before, *, rollback=False):
|
||||
else:
|
||||
d = before["descriptor"]
|
||||
validate_device_release_payload(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, d["releaseId"])
|
||||
validate_installed_device_b2()
|
||||
print("device_release_accept=" + ("rollback" if rollback else before["descriptor"]["sourceCommit"]) + ";database-volumes-and-topology=preserved")
|
||||
|
||||
|
||||
@@ -33302,6 +33347,18 @@ def plan_artifact(artifact):
|
||||
gitea_salvage_preflight = None
|
||||
with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp:
|
||||
manifest, entries, payload_dir = load_artifact(artifact, Path(tmp))
|
||||
if manifest["component"] == "device-b2-shared-contours":
|
||||
preflight_device_b2_shared(payload_dir, entries, manifest["id"])
|
||||
print("device_b2_shared_scope=one-table-primary-key;services=none;build=none;ports=preserved")
|
||||
print("device_b2_shared_preserved=all-links,applications,keys,volumes,containers,compose")
|
||||
print("device_b2_shared_backup=private-table-dump;rollback=lossless-schema-only;multi-links-refused")
|
||||
if manifest["component"] == "device-b2-foundation-reconciliation":
|
||||
preflight_device_b2_reconciliation(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-b2-foundation":
|
||||
preflight_device_b2(payload_dir, entries, manifest["id"])
|
||||
print("device_b2_scope=core-only;same-image;build=none;new-ports=none")
|
||||
print("device_b2_state=private-directory0700;three-new-tables;existing-data-preserved")
|
||||
print("device_b2_rollback=restore-runtime;remove-only-empty-new-schema-and-directory")
|
||||
if manifest["component"] == "device-core-network-priority":
|
||||
priority_before = preflight_device_priority(payload_dir, entries, manifest["id"])
|
||||
print("device_network_priority_compose=" + priority_before["composeVersion"])
|
||||
@@ -39493,6 +39550,19 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
|
||||
|
||||
|
||||
def run_healthchecks(component, entries=None, services=None):
|
||||
if component == "device-b2-shared-contours":
|
||||
if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES or tuple(services or ()) != ():
|
||||
die("Device B2 shared contours health scope mismatch")
|
||||
return # Exact schema/runtime/product checks run in accept_device_b2_shared.
|
||||
if component == "device-b2-foundation-reconciliation":
|
||||
if tuple(services or ()) != ():
|
||||
die("Device B2 reconciliation cannot select services")
|
||||
preflight_device_b2_reconciliation(DEVICE_PLANE_ROOT, entries, DEVICE_B2_RECON_ID, marker_installed=True)
|
||||
return
|
||||
if component == "device-b2-foundation":
|
||||
if tuple(entries or ()) != DEVICE_B2_ENTRIES or tuple(services or ()) != ("device-control-core",):
|
||||
die("Device B2 foundation health scope mismatch")
|
||||
return # Exact before/after checks run in accept_device_b2.
|
||||
if component == "device-core-network-priority":
|
||||
if tuple(entries or ()) != DEVICE_PRIORITY_ENTRIES or tuple(services or ()) != ():
|
||||
die("Device Core network priority health scope mismatch")
|
||||
@@ -40627,6 +40697,8 @@ def apply_artifact(artifact):
|
||||
gitea_actions_before = None
|
||||
device_autodeploy_before = None
|
||||
device_priority_before = None
|
||||
device_b2_before = None
|
||||
device_b2_shared_before = None
|
||||
current_stamp = stamp()
|
||||
|
||||
with DeployLock():
|
||||
@@ -40671,6 +40743,12 @@ def apply_artifact(artifact):
|
||||
compose_root = component_compose_root(component)
|
||||
bootstrap_root = bool(COMPONENTS[component].get("bootstrap_root"))
|
||||
services = component_services(component, entries)
|
||||
if component == "device-b2-shared-contours":
|
||||
device_b2_shared_before = preflight_device_b2_shared(payload_dir, entries, patch_id)
|
||||
if component == "device-b2-foundation-reconciliation":
|
||||
preflight_device_b2_reconciliation(payload_dir, entries, patch_id)
|
||||
if component == "device-b2-foundation":
|
||||
device_b2_before = preflight_device_b2(payload_dir, entries, patch_id)
|
||||
if component == "device-core-network-priority":
|
||||
device_priority_before = preflight_device_priority(payload_dir, entries, patch_id)
|
||||
if component == "mission-core-map-access":
|
||||
@@ -41210,6 +41288,12 @@ def apply_artifact(artifact):
|
||||
|
||||
include_nginx_html = component == "engine" and component_publish_dist(component, entries)
|
||||
create_backup(root, backup_dir, entries, include_nginx_html)
|
||||
if component == "device-b2-shared-contours":
|
||||
backup_device_b2_shared(backup_dir, device_b2_shared_before)
|
||||
if component == "device-b2-foundation":
|
||||
proof = backup_dir / "device-b2-before.json"
|
||||
proof.write_text(json.dumps(device_b2_before, sort_keys=True) + "\n")
|
||||
proof.chmod(0o600)
|
||||
if component == "device-core-network-priority":
|
||||
proof = backup_dir / "device-network-priority-before.json"
|
||||
proof.write_text(json.dumps(device_priority_before, sort_keys=True) + "\n", encoding="utf-8")
|
||||
@@ -41316,6 +41400,14 @@ def apply_artifact(artifact):
|
||||
elif component == "device-core-autodeploy":
|
||||
runtime_started = True
|
||||
apply_device_autodeploy(device_autodeploy_before)
|
||||
elif component == "device-b2-shared-contours":
|
||||
device_b2_database((DEVICE_PLANE_ROOT / DEVICE_B2_SHARED_SQL).read_text())
|
||||
elif component == "device-b2-foundation":
|
||||
def mark_device_b2_runtime_started():
|
||||
nonlocal runtime_started
|
||||
runtime_started = True
|
||||
|
||||
apply_device_b2(device_b2_before, backup_dir, mark_device_b2_runtime_started)
|
||||
elif component == "device-core-network-priority":
|
||||
pass # Metadata only: never build, pull, restart or recreate.
|
||||
elif component == "gitea-actions-config":
|
||||
@@ -41357,6 +41449,10 @@ def apply_artifact(artifact):
|
||||
):
|
||||
die("Engine L2 closed-loop app generation was not recreated")
|
||||
run_healthchecks(component, entries, services)
|
||||
if component == "device-b2-shared-contours":
|
||||
accept_device_b2_shared(device_b2_shared_before, backup_dir)
|
||||
if component == "device-b2-foundation":
|
||||
accept_device_b2(device_b2_before, backup_dir)
|
||||
if component == "device-core-network-priority":
|
||||
accept_device_priority(device_priority_before)
|
||||
if component == "device-core-autodeploy":
|
||||
@@ -41437,7 +41533,19 @@ def apply_artifact(artifact):
|
||||
and backup_dir is not None
|
||||
and root is not None
|
||||
):
|
||||
if component == "device-core-network-priority":
|
||||
if component == "device-b2-shared-contours":
|
||||
try:
|
||||
rollback_device_b2_shared(root, backup_dir, entries, current_stamp, device_b2_shared_before)
|
||||
rollback_status = "ok:device-b2-shared-contours"
|
||||
except Exception as rollback_exc:
|
||||
rollback_status = "failed:" + type(rollback_exc).__name__
|
||||
elif component == "device-b2-foundation":
|
||||
try:
|
||||
rollback_device_b2(root, backup_dir, entries, current_stamp, device_b2_before, runtime_started)
|
||||
rollback_status = "ok:device-b2-foundation"
|
||||
except Exception as rollback_exc:
|
||||
rollback_status = "failed:" + type(rollback_exc).__name__
|
||||
elif component == "device-core-network-priority":
|
||||
try:
|
||||
restore_platform_overlay(root, backup_dir, entries, current_stamp)
|
||||
accept_device_priority(device_priority_before, rollback=True)
|
||||
@@ -41450,6 +41558,12 @@ def apply_artifact(artifact):
|
||||
rollback_status = "ok:device-core-autodeploy-bootstrap"
|
||||
except Exception as rollback_exc:
|
||||
rollback_status = "failed:" + type(rollback_exc).__name__
|
||||
elif component == "device-b2-foundation-reconciliation":
|
||||
try:
|
||||
rollback_device_b2_reconciliation(root, backup_dir, entries, current_stamp)
|
||||
rollback_status = "ok:device-b2-reconciliation-marker-only"
|
||||
except Exception as rollback_exc:
|
||||
rollback_status = "failed:" + type(rollback_exc).__name__
|
||||
elif component == "device-core-release-reconciliation":
|
||||
try:
|
||||
restore_platform_overlay(root, backup_dir, entries, current_stamp)
|
||||
@@ -42755,6 +42869,602 @@ def main(argv):
|
||||
return 2
|
||||
|
||||
|
||||
# Additive external VPS management foundation. The payload never contains keys.
|
||||
DEVICE_B2_ID = 'device-b2-foundation-v1-20260930-003'
|
||||
DEVICE_B2_DESCRIPTOR = 'deployment/device-b2-foundation-v1.json'
|
||||
DEVICE_B2_SQL = 'deployment/device-b2-foundation-v1.sql'
|
||||
DEVICE_B2_OVERRIDE = 'docker-compose.device-b2-foundation.yml'
|
||||
DEVICE_B2_ENTRIES = (DEVICE_B2_OVERRIDE, DEVICE_B2_SQL, DEVICE_B2_DESCRIPTOR)
|
||||
DEVICE_B2_SQL_SHA = 'dc5608eccb8f628aab49390d245e6758505bb8a459a49705c375c3ca59b3e03b'
|
||||
DEVICE_B2_SECRET_ROOT = Path('/volume1/docker/nodedc-device-plane/private-b2-connections')
|
||||
DEVICE_B2_DESTINATION = '/run/nodedc-b2-connections'
|
||||
DEVICE_B2_BASELINE_ID = 'device-core-release-v1-r14-6ca6738bab22d0fdef714b90c68959363106ee5b'
|
||||
DEVICE_B2_BASELINE_SHA = '385c2fec8fce300cb80a93edfbcb0d537e34755b0ccc35294c0102b3c4a7f724'
|
||||
DEVICE_B2_EXPECTED_SCHEMA = json.loads('[{"columns":6,"constraints":4,"definitions":["CHECK ((contour_id ~ \'^[a-f0-9]{32}$\'::text))","FOREIGN KEY (project_id, owner_scope_id) REFERENCES device_projects(id, owner_scope_id)","FOREIGN KEY (source_id, owner_scope_id) REFERENCES device_b2_hosts(id, owner_scope_id)","PRIMARY KEY (source_id, contour_id)"],"fields":[["source_id","uuid",true],["contour_id","text",true],["project_id","uuid",true],["owner_scope_id","uuid",true],["created_by_ref","text",true],["created_at","timestamp with time zone",true]],"marker":"nodedc.device-b2-foundation/v1","name":"device_b2_contour_links","validated":true},{"columns":4,"constraints":3,"definitions":["FOREIGN KEY (host_id, project_id, owner_scope_id) REFERENCES device_infrastructure_hosts(id, project_id, owner_scope_id)","FOREIGN KEY (source_id, owner_scope_id) REFERENCES device_b2_hosts(id, owner_scope_id)","PRIMARY KEY (host_id)"],"fields":[["host_id","uuid",true],["project_id","uuid",true],["owner_scope_id","uuid",true],["source_id","uuid",true]],"marker":"nodedc.device-b2-foundation/v1","name":"device_b2_host_views","validated":true},{"columns":11,"constraints":7,"definitions":["CHECK ((authority = ANY (ARRAY[\'host\'::text, \'contours\'::text])))","CHECK ((fingerprint ~ \'^[a-f0-9]{64}$\'::text))","CHECK ((integration_id ~ \'^[a-f0-9]{32}$\'::text))","FOREIGN KEY (owner_scope_id) REFERENCES device_owner_scopes(id)","PRIMARY KEY (id)","UNIQUE (id, owner_scope_id)","UNIQUE (owner_scope_id, remote_host_id)"],"fields":[["id","uuid",true],["owner_scope_id","uuid",true],["remote_host_id","text",true],["endpoint","text",true],["fingerprint","text",true],["integration_id","text",true],["authority","text",true],["secret_ref","text",true],["revision","bigint",true],["created_at","timestamp with time zone",true],["updated_at","timestamp with time zone",true]],"marker":"nodedc.device-b2-foundation/v1","name":"device_b2_hosts","validated":true}]')
|
||||
DEVICE_B2_TABLES = ('device_b2_contour_links', 'device_b2_host_views', 'device_b2_hosts')
|
||||
DEVICE_B2_YAML = '''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
|
||||
'''
|
||||
|
||||
|
||||
def device_b2_descriptor():
|
||||
return {'schemaVersion': 'nodedc.device-b2-foundation.v1', 'releaseId': DEVICE_B2_ID,
|
||||
'baselineReleaseId': DEVICE_B2_BASELINE_ID, 'baselineSha256': DEVICE_B2_BASELINE_SHA,
|
||||
'sqlSha256': DEVICE_B2_SQL_SHA, 'transition': 'add-private-vault-and-three-tables',
|
||||
'runtime': 'same-image-core-only', 'newPorts': False}
|
||||
|
||||
|
||||
def validate_device_b2_payload(root, entries, identity):
|
||||
if tuple(entries or ()) != DEVICE_B2_ENTRIES or identity != DEVICE_B2_ID:
|
||||
die('Device B2 foundation identity/entries mismatch')
|
||||
if read_strict_json(root / DEVICE_B2_DESCRIPTOR, 'Device B2 foundation') != device_b2_descriptor():
|
||||
die('Device B2 foundation descriptor mismatch')
|
||||
if (root / DEVICE_B2_OVERRIDE).read_bytes() != DEVICE_B2_YAML.encode() or sha256_file(root / DEVICE_B2_SQL) != DEVICE_B2_SQL_SHA:
|
||||
die('Device B2 foundation fixed Compose/SQL mismatch')
|
||||
|
||||
|
||||
def device_b2_failed_barrier():
|
||||
for row in load_state(FAILED_STATE_FILE):
|
||||
if (row.get('component') == 'device-b2-foundation' and row.get('started_apply')
|
||||
and row.get('rollback_status') != 'ok:device-b2-foundation'
|
||||
and not device_b2_002_reconciled(row)):
|
||||
die('Device B2 foundation requires failed-state reconciliation')
|
||||
|
||||
|
||||
def device_b2_compose_files(files):
|
||||
device_b2_shared_failed_barrier()
|
||||
# A failed foundation rollback blocks ordinary releases too, even when the
|
||||
# old source files were already restored and no overlay remains.
|
||||
device_b2_failed_barrier()
|
||||
present = [(DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in DEVICE_B2_ENTRIES]
|
||||
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-b2-foundation']
|
||||
if not any(present) and not rows:
|
||||
return files
|
||||
if not all(present) or len(rows) != 1 or rows[0].get('id') != DEVICE_B2_ID:
|
||||
die('Device B2 foundation has no unique complete applied receipt')
|
||||
validate_device_b2_payload(DEVICE_PLANE_ROOT, DEVICE_B2_ENTRIES, DEVICE_B2_ID)
|
||||
with tempfile.TemporaryDirectory(prefix='device-b2-receipt-', dir=TMP_DIR) as tmp:
|
||||
manifest, entries, payload = load_artifact(device_release_applied_archive(rows[0]), Path(tmp))
|
||||
if manifest['component'] != 'device-b2-foundation':
|
||||
die('Device B2 foundation archive owner mismatch')
|
||||
validate_device_b2_payload(payload, entries, manifest['id'])
|
||||
return (*files, DEVICE_PLANE_ROOT / DEVICE_B2_OVERRIDE)
|
||||
|
||||
|
||||
def device_b2_database(sql):
|
||||
ids = device_plane_service_container_ids('device-postgres')
|
||||
if len(ids) != 1:
|
||||
die('Device B2 foundation requires the existing PostgreSQL container')
|
||||
result = subprocess.run([str(DOCKER), 'exec', '-i', ids[0], 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'device_plane', '-d', 'device_plane'], input=sql, text=True,
|
||||
capture_output=True, timeout=45, check=False)
|
||||
if result.returncode or result.stderr.strip() or len(result.stdout) > 65536:
|
||||
die('Device B2 foundation database contract failed')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def device_b2_schema():
|
||||
# Fixed object scope; row data and secrets are never selected.
|
||||
return json.loads(device_b2_database("""select coalesce(json_agg(x order by x.name),'[]'::json) from (
|
||||
select c.relname as name, obj_description(c.oid) as marker,
|
||||
(select count(*) from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as columns,
|
||||
(select count(*) from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as constraints,
|
||||
(select bool_and(k.convalidated) from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as validated,
|
||||
(select json_agg(json_build_array(a.attname,format_type(a.atttypid,a.atttypmod),a.attnotnull)
|
||||
order by a.attnum) from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as fields,
|
||||
(select json_agg(pg_get_constraintdef(k.oid) order by pg_get_constraintdef(k.oid))
|
||||
from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as definitions
|
||||
from pg_class c join pg_namespace n on n.oid=c.relnamespace
|
||||
where n.nspname='public' and c.relname in
|
||||
('device_b2_hosts','device_b2_host_views','device_b2_contour_links')
|
||||
) x;"""))
|
||||
|
||||
|
||||
def validate_device_b2_schema(schema, *, expected=None):
|
||||
if schema != (DEVICE_B2_EXPECTED_SCHEMA if expected is None else expected):
|
||||
die('Device B2 foundation exact schema fields/constraints mismatch')
|
||||
return device_release_drift_digest(schema)
|
||||
|
||||
|
||||
def device_b2_private_directory(create=False):
|
||||
root = DEVICE_B2_SECRET_ROOT
|
||||
if create:
|
||||
root.mkdir(mode=0o700, exist_ok=False)
|
||||
os.chown(root, 1000, 1000)
|
||||
root.chmod(0o700)
|
||||
info = root.lstat()
|
||||
if (not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != 1000
|
||||
or info.st_gid != 1000 or stat.S_IMODE(info.st_mode) != 0o700):
|
||||
die('Device B2 foundation private directory metadata mismatch')
|
||||
|
||||
|
||||
def device_b2_base():
|
||||
# The foundation is added explicitly only by this transition until its
|
||||
# applied receipt exists. Normal application releases use the receipt gate.
|
||||
cmd = compose_base_cmd('device-plane')
|
||||
files = device_priority_compose_files(())
|
||||
for file in files:
|
||||
cmd.extend(['-f', str(file)])
|
||||
return cmd
|
||||
|
||||
|
||||
def device_b2_effective(override=None):
|
||||
cmd = device_b2_base()
|
||||
if override:
|
||||
cmd.extend(['-f', str(override)])
|
||||
result = subprocess.run([*cmd, 'config', '--format', 'json'], capture_output=True, text=True,
|
||||
cwd=str(DEVICE_PLANE_ROOT), timeout=45, check=True)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def device_b2_config_proof(base, candidate):
|
||||
expected = json.loads(json.dumps(base))
|
||||
core = expected['services']['device-control-core']
|
||||
if 'DEVICE_B2_SECRET_ROOT' in core.get('environment', {}):
|
||||
die('Device B2 foundation is initial-only')
|
||||
if any(v.get('target') == DEVICE_B2_DESTINATION for v in core.get('volumes', [])):
|
||||
die('Device B2 foundation mount already exists')
|
||||
core['environment']['DEVICE_B2_SECRET_ROOT'] = DEVICE_B2_DESTINATION
|
||||
core.setdefault('volumes', []).append({'type': 'bind', 'source': str(DEVICE_B2_SECRET_ROOT),
|
||||
'target': DEVICE_B2_DESTINATION, 'bind': {'create_host_path': False}})
|
||||
actual = json.loads(json.dumps(candidate))
|
||||
# Compose 2.20.1 omits false booleans, including create_host_path inside
|
||||
# bind:{}. Normalize only the approved new mount in comparison copies.
|
||||
# The fixed source YAML still requires create_host_path:false. True, null,
|
||||
# non-booleans, other bind options and all existing mounts stay exact.
|
||||
for value in (expected, actual):
|
||||
volumes = value['services']['device-control-core'].get('volumes', [])
|
||||
for v in volumes:
|
||||
if v.get('target') == DEVICE_B2_DESTINATION:
|
||||
if v.get('read_only') is False:
|
||||
v.pop('read_only')
|
||||
bind = v.get('bind')
|
||||
if isinstance(bind, dict) and bind.get('create_host_path') is False:
|
||||
bind.pop('create_host_path')
|
||||
volumes.sort(key=lambda v: v['target'])
|
||||
if expected != actual:
|
||||
die('Device B2 foundation changes more than its one private mount/environment entry')
|
||||
return device_release_drift_digest(candidate)
|
||||
|
||||
|
||||
def preflight_device_b2(payload, entries, identity):
|
||||
validate_device_b2_payload(payload, entries, identity)
|
||||
device_b2_failed_barrier()
|
||||
if any((DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in entries):
|
||||
die('Device B2 foundation is initial-only')
|
||||
if DEVICE_B2_SECRET_ROOT.exists() or DEVICE_B2_SECRET_ROOT.is_symlink():
|
||||
die('Device B2 foundation private directory conflict')
|
||||
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-core-release']
|
||||
if not rows or rows[-1].get('id') != DEVICE_B2_BASELINE_ID or rows[-1].get('sha256') != DEVICE_B2_BASELINE_SHA:
|
||||
die('Device B2 foundation requires exact accepted r14 baseline')
|
||||
with tempfile.TemporaryDirectory(prefix='device-b2-baseline-', dir=TMP_DIR) as tmp:
|
||||
manifest, release_entries, source = load_artifact(device_release_applied_archive(rows[-1]), Path(tmp))
|
||||
if manifest['component'] != 'device-core-release':
|
||||
die('Device B2 foundation baseline owner mismatch')
|
||||
expected = collect_exact_files(source, release_entries, 'Device B2 baseline')
|
||||
if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, 'Device B2 installed source') != expected:
|
||||
die('Device B2 foundation installed source drift')
|
||||
if device_b2_schema():
|
||||
die('Device B2 foundation schema collision')
|
||||
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
|
||||
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode='private-egress', require_persistent_data=True, read_only=True)
|
||||
before = device_release_runtime_snapshot_v2()
|
||||
core = inspect_device_plane_container(before['device-control-core']['containerId'])
|
||||
if (core.get('Config') or {}).get('User') not in ('node', '1000', '1000:1000'):
|
||||
die('Device B2 foundation Core runtime user mismatch')
|
||||
# Pin the already running image before Compose can choose a mutable local tag.
|
||||
tagged = docker_json(['image','inspect','nodedc/device-control-core:local'], 'Device B2 existing image')
|
||||
if len(tagged) != 1 or tagged[0].get('Id') != before['device-control-core']['imageId']:
|
||||
die('Device B2 foundation local image tag differs from running image')
|
||||
proof = device_b2_config_proof(device_b2_effective(), device_b2_effective(payload / DEVICE_B2_OVERRIDE))
|
||||
return {'runtime':before, 'otherComposeServices':device_release_other_compose_services(),
|
||||
'installedFiles':expected, 'candidateConfigSha256':proof,
|
||||
'compose':{str(p):sha256_file(p) for p in component_compose_files('device-core-release')}}
|
||||
|
||||
|
||||
def device_b2_recreate(override):
|
||||
cmd = device_b2_base()
|
||||
if override:
|
||||
cmd.extend(['-f', str(DEVICE_PLANE_ROOT / DEVICE_B2_OVERRIDE)])
|
||||
subprocess.run([*cmd,'up','-d','--force-recreate','--pull','never','--no-build','--no-deps','device-control-core'],
|
||||
cwd=str(DEVICE_PLANE_ROOT),check=True)
|
||||
|
||||
|
||||
def apply_device_b2(before, backup_dir, mark_runtime_started):
|
||||
device_b2_private_directory(create=True)
|
||||
device_b2_database((DEVICE_PLANE_ROOT / DEVICE_B2_SQL).read_text())
|
||||
schema_sha = validate_device_b2_schema(device_b2_schema())
|
||||
receipt = backup_dir / 'device-b2-schema.json'
|
||||
receipt.write_text(json.dumps({'sqlSha256':DEVICE_B2_SQL_SHA,'schemaSha256':schema_sha})+'\n')
|
||||
receipt.chmod(0o600)
|
||||
if device_release_drift_digest(device_b2_effective(DEVICE_PLANE_ROOT / DEVICE_B2_OVERRIDE)) != before['candidateConfigSha256']:
|
||||
die('Device B2 foundation effective configuration changed before recreation')
|
||||
mark_runtime_started()
|
||||
device_b2_recreate(True)
|
||||
|
||||
|
||||
def device_b2_strip_runtime(fields):
|
||||
value = json.loads(json.dumps(fields))
|
||||
env = value['Config']['Env']
|
||||
entry = 'DEVICE_B2_SECRET_ROOT=' + DEVICE_B2_DESTINATION
|
||||
if env.count(entry) != 1:
|
||||
die('Device B2 foundation runtime environment delta mismatch')
|
||||
env.remove(entry)
|
||||
hm = value['HostConfig'].get('Mounts', [])
|
||||
found = [m for m in hm if m.get('Target') == DEVICE_B2_DESTINATION]
|
||||
if (len(found) != 1 or found[0].get('Type') != 'bind' or found[0].get('Source') != str(DEVICE_B2_SECRET_ROOT)
|
||||
or found[0].get('ReadOnly',False) is not False):
|
||||
die('Device B2 foundation HostConfig mount mismatch')
|
||||
value['HostConfig']['Mounts'] = [m for m in hm if m not in found]
|
||||
found = [m for m in value['Mounts'] if m.get('Destination') == DEVICE_B2_DESTINATION]
|
||||
if (len(found) != 1 or found[0].get('Type') != 'bind' or found[0].get('Source') != str(DEVICE_B2_SECRET_ROOT)
|
||||
or found[0].get('RW') is not True or found[0].get('Propagation') != 'rprivate'):
|
||||
die('Device B2 foundation runtime private mount mismatch')
|
||||
value['Mounts'] = [m for m in value['Mounts'] if m not in found]
|
||||
return device_release_mounts_v2(value)
|
||||
|
||||
|
||||
def validate_installed_device_b2():
|
||||
# Normal app updates must retain a previously accepted foundation, including
|
||||
# its real mount and private directory. A source marker alone is not enough.
|
||||
if not device_b2_compose_files(()):
|
||||
return
|
||||
device_b2_private_directory()
|
||||
expected = device_b2_shared_schema() if device_b2_shared_receipt() else DEVICE_B2_EXPECTED_SCHEMA
|
||||
validate_device_b2_schema(device_b2_schema(), expected=expected)
|
||||
device_b2_strip_runtime(device_release_drift_sample()['device-control-core']['fields'])
|
||||
|
||||
|
||||
def accept_device_b2(before, backup_dir, rollback=False):
|
||||
# Compose "Started" is not readiness. Both the candidate and a restored
|
||||
# generation must pass the existing bounded grace + HTTP checks first.
|
||||
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
|
||||
current = device_release_runtime_snapshot_v2()
|
||||
for service, old in before['runtime'].items():
|
||||
new = current[service]
|
||||
if service != 'device-control-core':
|
||||
if new != old: die('Device B2 foundation changed preserved service: '+service)
|
||||
elif new['imageId'] != old['imageId']:
|
||||
die('Device B2 foundation replaced the existing Core image')
|
||||
elif rollback:
|
||||
if new['runtimeConfigSha256'] != old['runtimeConfigSha256']:
|
||||
die('Device B2 foundation rollback runtime mismatch')
|
||||
else:
|
||||
if new['containerId'] == old['containerId']:
|
||||
die('Device B2 foundation did not recreate Core')
|
||||
sample = device_release_drift_sample()['device-control-core']['fields']
|
||||
if device_release_drift_digest(device_b2_strip_runtime(sample)) != old['runtimeConfigSha256']:
|
||||
die('Device B2 foundation changed an unapproved Core runtime field')
|
||||
if device_release_other_compose_services() != before['otherComposeServices']:
|
||||
die('Device B2 foundation changed unrelated services')
|
||||
if any(sha256_file(Path(p)) != digest for p,digest in before['compose'].items()):
|
||||
die('Device B2 foundation changed existing Compose files')
|
||||
if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, 'Device B2 source') != before['installedFiles']:
|
||||
die('Device B2 foundation changed application source')
|
||||
if not rollback:
|
||||
device_b2_private_directory()
|
||||
receipt = read_strict_json(backup_dir / 'device-b2-schema.json','Device B2 schema receipt')
|
||||
if validate_device_b2_schema(device_b2_schema()) != receipt['schemaSha256']:
|
||||
die('Device B2 foundation schema changed after migration')
|
||||
print('device_b2_accept='+('rollback' if rollback else 'private-vault+three-tables')+';ports=preserved;image=preserved;scope=core-only')
|
||||
|
||||
|
||||
def rollback_device_b2(root, backup_dir, entries, stamp, before, runtime_started):
|
||||
restore_platform_overlay(root,backup_dir,entries,stamp)
|
||||
if runtime_started:
|
||||
device_b2_recreate(False)
|
||||
schema=device_b2_schema()
|
||||
if schema:
|
||||
# Only our exact complete empty schema can be removed. Never delete
|
||||
# user-created rows, keys, an unrelated table or an ambiguous mutation.
|
||||
receipt=read_strict_json(backup_dir/'device-b2-schema.json','Device B2 rollback schema')
|
||||
if validate_device_b2_schema(schema) != receipt['schemaSha256']:
|
||||
die('Device B2 rollback retains unexpected additive schema for reconciliation')
|
||||
device_b2_database("""begin; lock table device_b2_hosts,device_b2_host_views,device_b2_contour_links in access exclusive mode;
|
||||
do $$ begin if exists(select 1 from device_b2_hosts) or exists(select 1 from device_b2_host_views)
|
||||
or exists(select 1 from device_b2_contour_links) then raise exception 'retained nonempty schema'; end if; end $$;
|
||||
drop table device_b2_contour_links,device_b2_host_views,device_b2_hosts; commit;""")
|
||||
if DEVICE_B2_SECRET_ROOT.exists():
|
||||
device_b2_private_directory()
|
||||
DEVICE_B2_SECRET_ROOT.rmdir() # Fails closed if even one key was written.
|
||||
accept_device_b2(before,backup_dir,rollback=True)
|
||||
|
||||
|
||||
# Additive schema transition. SQL is fixed by reviewed hashes, never commands
|
||||
# selected by a manifest. All data and running service generations are preserved.
|
||||
DEVICE_B2_SHARED_ID = 'device-b2-shared-contours-v1-20261001-001'
|
||||
DEVICE_B2_SHARED_DESCRIPTOR = 'deployment/device-b2-shared-contours-v1.json'
|
||||
DEVICE_B2_SHARED_SQL = 'deployment/device-b2-shared-contours-v1.sql'
|
||||
DEVICE_B2_SHARED_REVERSE = 'deployment/device-b2-shared-contours-v1.rollback.sql'
|
||||
DEVICE_B2_SHARED_ENTRIES = (DEVICE_B2_SHARED_DESCRIPTOR, DEVICE_B2_SHARED_SQL, DEVICE_B2_SHARED_REVERSE)
|
||||
DEVICE_B2_SHARED_HASHES = {
|
||||
DEVICE_B2_SHARED_SQL: 'caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a',
|
||||
DEVICE_B2_SHARED_REVERSE: 'f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f',
|
||||
}
|
||||
DEVICE_B2_SHARED_BASELINE = 'device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718'
|
||||
DEVICE_B2_SHARED_BASELINE_SHA = 'fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe'
|
||||
|
||||
|
||||
def device_b2_shared_descriptor():
|
||||
return {'schemaVersion': 'nodedc.device-b2-shared-contours.v1', 'releaseId': DEVICE_B2_SHARED_ID,
|
||||
'baselineReleaseId': DEVICE_B2_SHARED_BASELINE, 'baselineSha256': DEVICE_B2_SHARED_BASELINE_SHA,
|
||||
'files': DEVICE_B2_SHARED_HASHES, 'transition': 'one-contour-many-projects',
|
||||
'services': [], 'rollback': 'refuse-multiple-projects;preserve-all-rows'}
|
||||
|
||||
|
||||
def validate_device_b2_shared_payload(root, entries, identity):
|
||||
if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES or identity != DEVICE_B2_SHARED_ID:
|
||||
die('Device B2 shared contours exact identity/entries mismatch')
|
||||
for rel in DEVICE_B2_SHARED_ENTRIES:
|
||||
path = root / rel
|
||||
if path.is_symlink() or not path.is_file():
|
||||
die('Device B2 shared contours missing/unsafe payload')
|
||||
if read_strict_json(root / DEVICE_B2_SHARED_DESCRIPTOR, 'Device B2 shared contours') != device_b2_shared_descriptor():
|
||||
die('Device B2 shared contours descriptor mismatch')
|
||||
if any(sha256_file(root / rel) != digest for rel, digest in DEVICE_B2_SHARED_HASHES.items()):
|
||||
die('Device B2 shared contours SQL digest mismatch')
|
||||
|
||||
|
||||
def device_b2_shared_schema():
|
||||
result = json.loads(json.dumps(DEVICE_B2_EXPECTED_SCHEMA))
|
||||
links = result[0]
|
||||
assert links['name'] == 'device_b2_contour_links'
|
||||
links['marker'] = 'nodedc.device-b2-shared-contours/v1'
|
||||
links['definitions'] = [
|
||||
'PRIMARY KEY (source_id, contour_id, project_id)' if v == 'PRIMARY KEY (source_id, contour_id)' else v
|
||||
for v in links['definitions']]
|
||||
return result
|
||||
|
||||
|
||||
def device_b2_shared_failed_barrier():
|
||||
if any(r.get('component') == 'device-b2-shared-contours' and r.get('started_apply')
|
||||
and r.get('rollback_status') != 'ok:device-b2-shared-contours' for r in load_state(FAILED_STATE_FILE)):
|
||||
die('Device B2 shared contours requires failed-state reconciliation')
|
||||
|
||||
|
||||
def device_b2_shared_receipt():
|
||||
device_b2_shared_failed_barrier()
|
||||
present = [(DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink()
|
||||
for p in DEVICE_B2_SHARED_ENTRIES]
|
||||
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-b2-shared-contours']
|
||||
if not any(present) and not rows:
|
||||
return False
|
||||
if not all(present) or len(rows) != 1 or rows[0].get('id') != DEVICE_B2_SHARED_ID or rows[0].get('status') != 'ok':
|
||||
die('Device B2 shared contours has no unique complete applied receipt')
|
||||
validate_device_b2_shared_payload(DEVICE_PLANE_ROOT, DEVICE_B2_SHARED_ENTRIES, DEVICE_B2_SHARED_ID)
|
||||
with tempfile.TemporaryDirectory(prefix='device-b2-shared-receipt-', dir=TMP_DIR) as tmp:
|
||||
manifest, entries, payload = load_artifact(device_release_applied_archive(rows[0]), Path(tmp))
|
||||
if manifest['component'] != 'device-b2-shared-contours':
|
||||
die('Device B2 shared contours archive owner mismatch')
|
||||
validate_device_b2_shared_payload(payload, entries, manifest['id'])
|
||||
return True
|
||||
|
||||
|
||||
def preflight_device_b2_shared(payload, entries, identity):
|
||||
validate_device_b2_shared_payload(payload, entries, identity)
|
||||
device_b2_shared_failed_barrier()
|
||||
if any((DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in entries):
|
||||
die('Device B2 shared contours is initial-only')
|
||||
if any(r.get('component') == 'device-b2-shared-contours' for r in load_state(STATE_FILE)):
|
||||
die('Device B2 shared contours already has an applied receipt')
|
||||
rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-core-release']
|
||||
if not rows or rows[-1].get('id') != DEVICE_B2_SHARED_BASELINE or rows[-1].get('sha256') != DEVICE_B2_SHARED_BASELINE_SHA:
|
||||
die('Device B2 shared contours requires exact accepted r37 baseline')
|
||||
with tempfile.TemporaryDirectory(prefix='device-b2-shared-baseline-', dir=TMP_DIR) as tmp:
|
||||
manifest, release_entries, source = load_artifact(device_release_applied_archive(rows[-1]), Path(tmp))
|
||||
if manifest['component'] != 'device-core-release' or tuple(release_entries) != DEVICE_RELEASE_ENTRIES:
|
||||
die('Device B2 shared contours baseline owner/entries mismatch')
|
||||
expected = collect_exact_files(source, release_entries, 'Device B2 shared contours baseline')
|
||||
if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, 'Device B2 shared contours installed source') != expected:
|
||||
die('Device B2 shared contours installed source drift')
|
||||
validate_installed_device_b2()
|
||||
if not device_b2_compose_files(()):
|
||||
die('Device B2 shared contours requires accepted B2 foundation')
|
||||
validate_device_b2_schema(device_b2_schema())
|
||||
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
|
||||
return {'runtime': device_release_runtime_snapshot_v2(),
|
||||
'otherComposeServices': device_release_other_compose_services(), 'installedFiles': expected,
|
||||
'compose': {str(p): sha256_file(p) for p in component_compose_files('device-core-release')}}
|
||||
|
||||
|
||||
def backup_device_b2_shared(backup_dir, before):
|
||||
proof = backup_dir / 'device-b2-shared-before.json'
|
||||
with proof.open('x') as output:
|
||||
os.fchmod(output.fileno(), 0o600)
|
||||
output.write(json.dumps(before, sort_keys=True) + '\n')
|
||||
output.flush(); os.fsync(output.fileno())
|
||||
ids = device_plane_service_container_ids('device-postgres')
|
||||
if len(ids) != 1:
|
||||
die('Device B2 shared contours requires the existing PostgreSQL container')
|
||||
path = backup_dir / 'device-b2-contour-links.dump'
|
||||
with path.open('xb') as output:
|
||||
os.fchmod(output.fileno(), 0o600)
|
||||
result = subprocess.run([str(DOCKER), 'exec', ids[0], 'pg_dump', '-U', 'device_plane', '-d', 'device_plane',
|
||||
'-Fc', '--strict-names', '-t', 'public.device_b2_contour_links'],
|
||||
stdout=output, stderr=subprocess.PIPE, timeout=45, check=False)
|
||||
output.flush(); os.fsync(output.fileno())
|
||||
with path.open('rb') as saved:
|
||||
signature = saved.read(5)
|
||||
if result.returncode or result.stderr or signature != b'PGDMP':
|
||||
die('Device B2 shared contours private table backup failed')
|
||||
digest = backup_dir / 'device-b2-contour-links.dump.sha256'
|
||||
with digest.open('x') as output:
|
||||
os.fchmod(output.fileno(), 0o600)
|
||||
output.write(sha256_file(path) + '\n')
|
||||
output.flush(); os.fsync(output.fileno())
|
||||
|
||||
|
||||
def accept_device_b2_shared(before, backup_dir, rollback=False):
|
||||
dump = backup_dir / 'device-b2-contour-links.dump'
|
||||
if dump.is_symlink() or not dump.is_file() or stat.S_IMODE(dump.stat().st_mode) != 0o600:
|
||||
die('Device B2 shared contours backup is missing or unsafe')
|
||||
if sha256_file(dump) != (backup_dir / 'device-b2-contour-links.dump.sha256').read_text().strip():
|
||||
die('Device B2 shared contours backup changed')
|
||||
if not rollback:
|
||||
validate_device_b2_shared_payload(DEVICE_PLANE_ROOT, DEVICE_B2_SHARED_ENTRIES, DEVICE_B2_SHARED_ID)
|
||||
expected = DEVICE_B2_EXPECTED_SCHEMA if rollback else device_b2_shared_schema()
|
||||
validate_device_b2_schema(device_b2_schema(), expected=expected)
|
||||
device_b2_private_directory()
|
||||
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
|
||||
if device_release_runtime_snapshot_v2() != before['runtime']:
|
||||
die('Device B2 shared contours changed a preserved service generation/runtime')
|
||||
if device_release_other_compose_services() != before['otherComposeServices']:
|
||||
die('Device B2 shared contours changed unrelated services')
|
||||
if any(sha256_file(Path(p)) != digest for p, digest in before['compose'].items()):
|
||||
die('Device B2 shared contours changed existing Compose files')
|
||||
if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, 'Device B2 shared contours source') != before['installedFiles']:
|
||||
die('Device B2 shared contours changed application source')
|
||||
print('device_b2_shared_accept=' + ('rollback' if rollback else 'shared-projects')
|
||||
+ ';rows=preserved;runtime=unchanged;backup=verified')
|
||||
|
||||
|
||||
def rollback_device_b2_shared(root, backup_dir, entries, stamp, before):
|
||||
schema = device_b2_schema()
|
||||
if schema == device_b2_shared_schema():
|
||||
validate_device_b2_shared_payload(root, entries, DEVICE_B2_SHARED_ID)
|
||||
device_b2_database((root / DEVICE_B2_SHARED_REVERSE).read_text())
|
||||
elif schema != DEVICE_B2_EXPECTED_SCHEMA:
|
||||
die('Device B2 shared contours rollback retains unexpected schema for reconciliation')
|
||||
restore_platform_overlay(root, backup_dir, entries, stamp)
|
||||
accept_device_b2_shared(before, backup_dir, rollback=True)
|
||||
|
||||
|
||||
DEVICE_B2_RECON_ID = 'device-b2-foundation-reconciliation-v1-20260930-001'
|
||||
DEVICE_B2_RECON_ENTRY = 'deployment/device-b2-foundation-reconciliation-v1.json'
|
||||
DEVICE_B2_002_ID = 'device-b2-foundation-v1-20260930-002'
|
||||
DEVICE_B2_002_SHA = 'da1c97fb0fd2ed9f50acf198c0492b27a5d7273009c0a85b9231fd8c60a70222'
|
||||
DEVICE_B2_002_BACKUP = 'device-b2-foundation-device-b2-foundation-v1-20260930-002-20260930-164433'
|
||||
DEVICE_B2_002_BACKUP_HASHES = {
|
||||
'device-b2-before.json': '70ba33a7917c75593586758a93ea9c83fb4c0d958544d1bf4d024e7449f684cb',
|
||||
'device-b2-schema.json': '144b3fb60b46ead20570869452d21dd91871fc7049045b3ee969beb9ad9ac34e',
|
||||
'manifest.env': '74917c5b06429307d7b875c01971a7e8e01a52d890ea11ba634357821c96cebf',
|
||||
'files.txt': '83ec615f1fcc5443d7afe89c23b3dcf068f928874d62bc8bfbbc55f04d74bf23',
|
||||
'existing-files.txt': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
|
||||
'missing-files.txt': '83ec615f1fcc5443d7afe89c23b3dcf068f928874d62bc8bfbbc55f04d74bf23',
|
||||
'source-before.tgz': '8d10ddfcb56c0b9e7b3cc4bf39cfcd7623594bbe8d68d1e13bc8115c5796991e',
|
||||
}
|
||||
|
||||
|
||||
def device_b2_002_failed_row():
|
||||
return {'artifact': 'nodedc-' + DEVICE_B2_002_ID + '.tgz.20260930-164433',
|
||||
'backup_id': DEVICE_B2_002_BACKUP, 'component': 'device-b2-foundation',
|
||||
'failed_at': '2026-09-30T13:45:49+00:00', 'id': DEVICE_B2_002_ID,
|
||||
'message': 'Device Core predecessor service is not healthy: device-control-core',
|
||||
'rollback_status': 'failed:DeployError', 'sha256': DEVICE_B2_002_SHA,
|
||||
'started_apply': True, 'status': 'failed'}
|
||||
|
||||
|
||||
def device_b2_reconciliation_descriptor():
|
||||
return {'schemaVersion': 'nodedc.device-b2-foundation-reconciliation.v1',
|
||||
'releaseId': DEVICE_B2_RECON_ID, 'failedReleaseId': DEVICE_B2_002_ID,
|
||||
'failedSha256': DEVICE_B2_002_SHA, 'backupId': DEVICE_B2_002_BACKUP,
|
||||
'mode': 'prove-restored-r14;metadata-only;no-runtime-mutation'}
|
||||
|
||||
|
||||
def validate_device_b2_reconciliation_payload(payload, entries, identity):
|
||||
if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,) or identity != DEVICE_B2_RECON_ID:
|
||||
die('Device B2 reconciliation identity/entry mismatch')
|
||||
if read_strict_json(payload / DEVICE_B2_RECON_ENTRY, 'Device B2 reconciliation') != device_b2_reconciliation_descriptor():
|
||||
die('Device B2 reconciliation descriptor mismatch')
|
||||
|
||||
|
||||
def device_b2_002_evidence():
|
||||
expected = device_b2_002_failed_row()
|
||||
failures = load_state(FAILED_STATE_FILE)
|
||||
matching = [r for r in failures if r.get('id') == DEVICE_B2_002_ID or r.get('sha256') == DEVICE_B2_002_SHA]
|
||||
if matching != [expected]:
|
||||
die('Device B2 reconciliation failed journal mismatch')
|
||||
if any(r.get('id') == DEVICE_B2_002_ID or r.get('sha256') == DEVICE_B2_002_SHA for r in load_state(STATE_FILE)):
|
||||
die('Device B2 failed foundation conflicts with applied journal')
|
||||
archive = FAILED_DIR / expected['artifact']
|
||||
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != DEVICE_B2_002_SHA:
|
||||
die('Device B2 reconciliation failed archive mismatch')
|
||||
backup = BACKUPS_DIR / DEVICE_B2_002_BACKUP
|
||||
if backup.is_symlink() or not backup.is_dir():
|
||||
die('Device B2 reconciliation backup is missing or unsafe')
|
||||
for name, digest in DEVICE_B2_002_BACKUP_HASHES.items():
|
||||
path = backup / name
|
||||
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
|
||||
die('Device B2 reconciliation backup digest mismatch: ' + name)
|
||||
existing = read_backup_path_list(backup / 'existing-files.txt')
|
||||
missing = read_backup_path_list(backup / 'missing-files.txt')
|
||||
validate_backup_partition(DEVICE_B2_ENTRIES, existing, missing, 'Device B2 reconciliation')
|
||||
if existing or set(missing) != set(DEVICE_B2_ENTRIES):
|
||||
die('Device B2 reconciliation backup partition mismatch')
|
||||
return read_strict_json(backup / 'device-b2-before.json', 'Device B2 incident baseline', max_bytes=256*1024)
|
||||
|
||||
|
||||
def preflight_device_b2_reconciliation(payload, entries, identity, *, marker_installed=False):
|
||||
validate_device_b2_reconciliation_payload(payload, entries, identity)
|
||||
marker = DEVICE_PLANE_ROOT / DEVICE_B2_RECON_ENTRY
|
||||
if not marker_installed and (marker.exists() or marker.is_symlink()):
|
||||
die('Device B2 reconciliation marker already exists')
|
||||
if marker_installed and (marker.is_symlink() or not marker.is_file()):
|
||||
die('Device B2 reconciliation installed marker is unsafe')
|
||||
before = device_b2_002_evidence()
|
||||
# Reconciliation cannot mask a different incomplete transition.
|
||||
for row in load_state(FAILED_STATE_FILE):
|
||||
if (row.get('component') == 'device-b2-foundation' and row.get('started_apply')
|
||||
and row.get('rollback_status') != 'ok:device-b2-foundation'
|
||||
and row != device_b2_002_failed_row()):
|
||||
die('Device B2 reconciliation found another unresolved foundation')
|
||||
applied = load_state(STATE_FILE)
|
||||
releases = [r for r in applied if r.get('component') == 'device-core-release']
|
||||
if (not releases or releases[-1].get('id') != DEVICE_B2_BASELINE_ID
|
||||
or releases[-1].get('sha256') != DEVICE_B2_BASELINE_SHA
|
||||
or any(r.get('component') == 'device-b2-foundation' for r in applied)):
|
||||
die('Device B2 reconciliation requires the exact restored r14 baseline')
|
||||
if any((DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in DEVICE_B2_ENTRIES):
|
||||
die('Device B2 reconciliation retains unexpected foundation files')
|
||||
if DEVICE_B2_SECRET_ROOT.exists() or DEVICE_B2_SECRET_ROOT.is_symlink():
|
||||
die('Device B2 reconciliation retains unexpected private storage')
|
||||
if device_b2_schema():
|
||||
die('Device B2 reconciliation retains unexpected schema; no mutation allowed')
|
||||
accept_device_b2(before, BACKUPS_DIR / DEVICE_B2_002_BACKUP, rollback=True)
|
||||
print('device_b2_reconciliation=restored-r14-proven;services=none;build=none;runtime-mutation=none;schema=absent;vault=absent')
|
||||
return before
|
||||
|
||||
|
||||
def rollback_device_b2_reconciliation(root, backup_dir, entries, stamp):
|
||||
if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,):
|
||||
die('Device B2 reconciliation rollback scope mismatch')
|
||||
restore_platform_overlay(root, backup_dir, entries, stamp)
|
||||
if (root / DEVICE_B2_RECON_ENTRY).exists() or (root / DEVICE_B2_RECON_ENTRY).is_symlink():
|
||||
die('Device B2 reconciliation rollback left a marker')
|
||||
|
||||
|
||||
def device_b2_002_reconciled(row):
|
||||
if row != device_b2_002_failed_row():
|
||||
return False
|
||||
marker = DEVICE_PLANE_ROOT / DEVICE_B2_RECON_ENTRY
|
||||
if not marker.exists() and not marker.is_symlink():
|
||||
return False
|
||||
if marker.is_symlink() or not marker.is_file():
|
||||
die('Device B2 reconciliation marker is unsafe')
|
||||
validate_device_b2_reconciliation_payload(DEVICE_PLANE_ROOT, (DEVICE_B2_RECON_ENTRY,), DEVICE_B2_RECON_ID)
|
||||
records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_B2_RECON_ID]
|
||||
if len(records) != 1 or records[0].get('component') != 'device-b2-foundation-reconciliation':
|
||||
die('Device B2 reconciliation marker lacks its unique applied receipt')
|
||||
with tempfile.TemporaryDirectory(prefix='device-b2-reconciled-', dir=TMP_DIR) as tmp:
|
||||
manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp))
|
||||
if manifest['component'] != 'device-b2-foundation-reconciliation' or manifest['id'] != DEVICE_B2_RECON_ID:
|
||||
die('Device B2 reconciliation archive owner mismatch')
|
||||
if sha256_file(payload / DEVICE_B2_RECON_ENTRY) != sha256_file(marker):
|
||||
die('Device B2 reconciliation installed marker drift')
|
||||
device_b2_002_evidence() # Historical evidence remains immutable after acknowledgement.
|
||||
return True
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
|
||||
@@ -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,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