Register additive Device B2 private storage foundation
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
# 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.
|
||||
|
||||
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.
|
||||
@@ -2962,6 +2962,11 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
|
||||
)
|
||||
|
||||
COMPONENTS = {
|
||||
"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 +4988,10 @@ def denied_payload_path(component, rel):
|
||||
|
||||
def allowed_payload_path(component, rel):
|
||||
validate_posix_path(rel)
|
||||
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 +11624,8 @@ 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-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 +22484,10 @@ def is_platform_provider_catalog_only(entries):
|
||||
|
||||
|
||||
def component_services(component, entries=None):
|
||||
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 +22833,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 +33207,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 +33253,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 +33321,11 @@ 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-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 +39517,10 @@ 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-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 +40655,7 @@ def apply_artifact(artifact):
|
||||
gitea_actions_before = None
|
||||
device_autodeploy_before = None
|
||||
device_priority_before = None
|
||||
device_b2_before = None
|
||||
current_stamp = stamp()
|
||||
|
||||
with DeployLock():
|
||||
@@ -40671,6 +40700,8 @@ 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-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 +41241,10 @@ 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-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 +41351,12 @@ def apply_artifact(artifact):
|
||||
elif component == "device-core-autodeploy":
|
||||
runtime_started = True
|
||||
apply_device_autodeploy(device_autodeploy_before)
|
||||
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 +41398,8 @@ def apply_artifact(artifact):
|
||||
):
|
||||
die("Engine L2 closed-loop app generation was not recreated")
|
||||
run_healthchecks(component, entries, services)
|
||||
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 +41480,13 @@ 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-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)
|
||||
@@ -42755,6 +42804,303 @@ def main(argv):
|
||||
return 2
|
||||
|
||||
|
||||
# Additive external VPS management foundation. The payload never contains keys.
|
||||
DEVICE_B2_ID = 'device-b2-foundation-v1-20260930-001'
|
||||
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'):
|
||||
die('Device B2 foundation requires failed-state reconciliation')
|
||||
|
||||
|
||||
def device_b2_compose_files(files):
|
||||
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):
|
||||
if schema != DEVICE_B2_EXPECTED_SCHEMA:
|
||||
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 versions can explicitly serialize read_only:false or omit it.
|
||||
for value in (expected, actual):
|
||||
volumes = value['services']['device-control-core'].get('volumes', [])
|
||||
for v in volumes:
|
||||
if v.get('target') == DEVICE_B2_DESTINATION and v.get('read_only') is False:
|
||||
v.pop('read_only')
|
||||
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()
|
||||
validate_device_b2_schema(device_b2_schema())
|
||||
device_b2_strip_runtime(device_release_drift_sample()['device-control-core']['fields'])
|
||||
|
||||
|
||||
def accept_device_b2(before, backup_dir, rollback=False):
|
||||
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')
|
||||
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
|
||||
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)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""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
|
||||
|
||||
|
||||
class Foundation(unittest.TestCase):
|
||||
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()
|
||||
Reference in New Issue
Block a user