diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 880899e..a7490f9 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -11,6 +11,7 @@ import io import itertools import json import os +import posixpath import pwd import re import secrets @@ -4979,7 +4980,7 @@ def allowed_payload_path(component, rel): return True die("Device Core drift audit accepts only its exact descriptor") if component == "device-core-release-reconciliation": - if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY): + if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY, DEVICE_RELEASE_RECONCILIATION_V2_ENTRY): return True die("Device Core reconciliation accepts only its exact descriptor") if component == "device-core-release": @@ -22457,7 +22458,7 @@ def component_services(component, entries=None): die("Device Core drift audit requires the exact descriptor entry") return () if component == "device-core-release-reconciliation": - if tuple(entries or ()) != (DEVICE_RELEASE_RECONCILIATION_ENTRY,): + if tuple(entries or ()) not in ((DEVICE_RELEASE_RECONCILIATION_ENTRY,), (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,)): die("Device Core reconciliation requires the exact descriptor entry") return () if component == "device-core-release": @@ -32505,6 +32506,8 @@ DEVICE_RELEASE_R5_SHA = "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad913 DEVICE_RELEASE_R5_BACKUP = "device-core-release-" + DEVICE_RELEASE_R5_ID + "-20260929-190019" DEVICE_RELEASE_RECONCILIATION_ID = "device-core-release-r5-reconciliation-v1-20260929-001" DEVICE_RELEASE_RECONCILIATION_ENTRY = "deployment/device-core-release-r5-reconciliation-v1.json" +DEVICE_RELEASE_RECONCILIATION_V2_ID = "device-core-release-r5-reconciliation-v2-20260929-002" +DEVICE_RELEASE_RECONCILIATION_V2_ENTRY = "deployment/device-core-release-r5-reconciliation-v2.json" DEVICE_RELEASE_R5_BACKUP_HASHES = { "device-release-before.json": "0e30ebd1a1e511da5e8026afbba9b761c5edb2fcc151b23ecc79bbae8af0b739", "source-before.tgz": "d597d1cd1dcb1eeaf79836c40523258ae1a9aa1b6e3333a94238f40f078accb5", @@ -32557,7 +32560,20 @@ def device_release_reconciliation_descriptor(): "backupId": DEVICE_RELEASE_R5_BACKUP, "mode": "prove-restored-baseline-only"} +def device_release_reconciliation_v2_descriptor(): + return {"schemaVersion": "nodedc.device-core.release-reconciliation.v2", + "releaseId": DEVICE_RELEASE_RECONCILIATION_V2_ID, + "failedReleaseId": DEVICE_RELEASE_R5_ID, "failedSha256": DEVICE_RELEASE_R5_SHA, + "backupId": DEVICE_RELEASE_R5_BACKUP, + "mode": "prove-restored-baseline-mount-order-only", "runtimeFingerprintVersion": 2} + + def validate_device_release_reconciliation_payload(payload, entries, patch_id): + if tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,): + if (patch_id != DEVICE_RELEASE_RECONCILIATION_V2_ID or + read_strict_json(payload / DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, "Device Core reconciliation v2") != device_release_reconciliation_v2_descriptor()): + die("Device Core reconciliation v2 identity/descriptor mismatch") + return if tuple(entries) != (DEVICE_RELEASE_RECONCILIATION_ENTRY,) or patch_id != DEVICE_RELEASE_RECONCILIATION_ID: die("Device Core reconciliation identity/entry mismatch") if read_strict_json(payload / DEVICE_RELEASE_RECONCILIATION_ENTRY, "Device Core reconciliation") != device_release_reconciliation_descriptor(): @@ -32606,13 +32622,19 @@ def device_release_r5_evidence(): def preflight_device_release_reconciliation(payload, entries, patch_id, *, marker_installed=False): validate_device_release_reconciliation_payload(payload, entries, patch_id) - marker = DEVICE_PLANE_ROOT / DEVICE_RELEASE_RECONCILIATION_ENTRY + v2 = tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) + marker = DEVICE_PLANE_ROOT / entries[0] + other = DEVICE_PLANE_ROOT / (DEVICE_RELEASE_RECONCILIATION_ENTRY if v2 else DEVICE_RELEASE_RECONCILIATION_V2_ENTRY) + if other.exists() or other.is_symlink(): + die("Device Core reconciliation marker versions conflict") if not marker_installed and (marker.exists() or marker.is_symlink()): die("Device Core reconciliation marker already exists") before = device_release_r5_evidence() # Source, current image IDs, configuration and every preserved dependency # are checked without invoking any build, Compose mutation or secret ensure. run_healthchecks("device-core-release", DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES) + if v2: + before = device_release_r5_mount_order_baseline(before) accept_device_release(before, rollback=True) print("device_release_reconciliation=restored-baseline-proven;services=none;build=none;runtime-mutation=none") return before @@ -32621,18 +32643,27 @@ def preflight_device_release_reconciliation(payload, entries, patch_id, *, marke def device_release_r5_reconciled(row): if row != device_release_r5_failed_row(): return False - marker = DEVICE_PLANE_ROOT / DEVICE_RELEASE_RECONCILIATION_ENTRY - if marker.is_symlink() or not marker.is_file(): + candidates = [(DEVICE_RELEASE_RECONCILIATION_ENTRY, DEVICE_RELEASE_RECONCILIATION_ID), + (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, DEVICE_RELEASE_RECONCILIATION_V2_ID)] + present = [(entry, identity) for entry, identity in candidates + if (DEVICE_PLANE_ROOT / entry).exists() or (DEVICE_PLANE_ROOT / entry).is_symlink()] + if not present: return False - validate_device_release_reconciliation_payload(DEVICE_PLANE_ROOT, (DEVICE_RELEASE_RECONCILIATION_ENTRY,), DEVICE_RELEASE_RECONCILIATION_ID) - records = [r for r in load_state(STATE_FILE) if r.get("id") == DEVICE_RELEASE_RECONCILIATION_ID] + if len(present) != 1: + die("Device Core reconciliation marker versions conflict") + entry, identity = present[0] + marker = DEVICE_PLANE_ROOT / entry + if marker.is_symlink() or not marker.is_file(): + die("Device Core reconciliation marker is unsafe") + validate_device_release_reconciliation_payload(DEVICE_PLANE_ROOT, (entry,), identity) + records = [r for r in load_state(STATE_FILE) if r.get("id") == identity] if len(records) != 1 or records[0].get("component") != "device-core-release-reconciliation": die("Device Core reconciliation marker lacks its canonical applied receipt") with tempfile.TemporaryDirectory(prefix="device-r5-marker-", dir=TMP_DIR) as tmp: manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp)) - if manifest.get("component") != "device-core-release-reconciliation" or manifest.get("id") != DEVICE_RELEASE_RECONCILIATION_ID: + if manifest.get("component") != "device-core-release-reconciliation" or manifest.get("id") != identity: die("Device Core reconciliation applied archive identity mismatch") - if sha256_file(payload / DEVICE_RELEASE_RECONCILIATION_ENTRY) != sha256_file(marker): + if sha256_file(payload / entry) != sha256_file(marker): die("Device Core reconciliation installed marker drift") # Keep original incident evidence immutable after acknowledgement. device_release_r5_evidence() @@ -32792,6 +32823,89 @@ def device_release_drift_audit(payload, entries, patch_id): return report +def device_release_mounts_v2(fields): + """Sort only uniquely addressed mount objects; keep every option and value.""" + result = json.loads(json.dumps(fields)) + host = result["HostConfig"] + mounts = host.get("Mounts") + if mounts is None: + return result + if not isinstance(mounts, list): + die("Device Core mount fingerprint requires a mount list") + targets = set() + for mount in mounts: + target = mount.get("Target") if isinstance(mount, dict) else None + if (not isinstance(target, str) or not target.startswith("/") or "\0" in target + or posixpath.normpath(target) != target or target.startswith("//") + or target in targets): + die("Device Core mount fingerprint requires unique absolute targets") + targets.add(target) + host["Mounts"] = sorted(mounts, key=lambda value: json.dumps(value, sort_keys=True)) + return result + + +def device_release_runtime_snapshot_v2(): + samples = device_release_drift_sample() + result = {} + for service, sample in samples.items(): + row = sample["runtime"] + if not row["running"] or row["health"] not in (None, "healthy"): + die("Device Core predecessor service is not healthy: " + service) + row["runtimeConfigSha256"] = device_release_drift_digest(device_release_mounts_v2(sample["fields"])) + result[service] = row + return result + + +def device_release_mount_order_proof(fields, expected): + # Unlike the diagnostic probe, this CANNOT change Binds or NetworkMode. + # The legacy backup contains only a digest, so prove an exact old preimage. + device_release_mounts_v2(fields) + if not isinstance(expected, str) or not re.fullmatch(r"[a-f0-9]{64}", expected): + die("Device Core mount order proof requires an exact saved digest") + mounts = fields["HostConfig"].get("Mounts") + if mounts is not None and len(mounts) > 7: + die("Device Core r5 mount order proof exceeds seven-mount bound") + if device_release_drift_digest(fields) == expected: + return 1 + candidate = json.loads(json.dumps(fields)) + checked = 1 + for order in (() if mounts is None else itertools.permutations(mounts)): + candidate["HostConfig"]["Mounts"] = list(order) + checked += 1 + if device_release_drift_digest(candidate) == expected: + return checked + die("Device Core r5 configuration differs beyond HostConfig.Mounts order") + + +def device_release_r5_mount_order_baseline(before): + """Derive v2 hashes only after exact legacy proof, preserving original evidence.""" + if "runtimeFingerprintVersion" in before or set(before["runtime"]) != set(DEVICE_RELEASE_INVENTORY): + die("Device Core r5 legacy baseline mismatch") + observations = [device_release_drift_sample() for _ in range(3)] + baseline = json.loads(json.dumps(before)) + baseline["runtimeFingerprintVersion"] = 2 + report = {} + for service in DEVICE_RELEASE_INVENTORY: + old = before["runtime"][service] + samples = [observation[service] for observation in observations] + if any(sample != samples[0] for sample in samples): + die("Device Core r5 runtime changed during mount order proof: " + service) + sample = samples[0] + row, fields = sample["runtime"], sample["fields"] + if (not row["running"] or row["health"] not in (None, "healthy") or row["imageId"] != old["imageId"] + or row["runtimeConfigSha256"] != device_release_drift_digest(fields)): + die("Device Core r5 service image/health/evidence mismatch: " + service) + if service not in DEVICE_RELEASE_SERVICES and row != old: + die("Device Core r5 preserved service differs: " + service) + checked = device_release_mount_order_proof(fields, old["runtimeConfigSha256"]) + digest = device_release_drift_digest(device_release_mounts_v2(fields)) + baseline["runtime"][service]["runtimeConfigSha256"] = digest + report[service] = {"exactLegacyProof": True, "sampleCount": 3, + "candidatesChecked": checked, "runtimeFingerprintV2": digest} + print("device_release_mount_order_proof=" + json.dumps(report, sort_keys=True, separators=(",", ":"))) + return baseline + + def preflight_device_release(payload, entries, patch_id): d = validate_device_release_payload(payload, entries, patch_id) predecessor = device_release_predecessor(d) @@ -32802,15 +32916,18 @@ def preflight_device_release(payload, entries, patch_id): die("Device Core release changes the immutable database/build foundation") validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True) run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES) - before = device_release_runtime_snapshot() + before = device_release_runtime_snapshot_v2() compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")} - return {"descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", + return {"runtimeFingerprintVersion": 2, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", "runtime": before, "compose": compose, "otherComposeServices": device_release_other_compose_services(), "installedFiles": collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES if predecessor else DEVICE_RELEASE_ENTRIES[:-1], "Device Core rollback baseline")} def accept_device_release(before, *, rollback=False): - current = device_release_runtime_snapshot() + version = before.get("runtimeFingerprintVersion", 1) + if type(version) is not int or version not in (1, 2): + die("Device Core release runtime fingerprint version mismatch") + current = device_release_runtime_snapshot_v2() if version == 2 else device_release_runtime_snapshot() for service, old in before["runtime"].items(): new = current[service] if service not in DEVICE_RELEASE_SERVICES: @@ -32920,6 +33037,7 @@ def plan_artifact(artifact): release_before = preflight_device_release(payload_dir, entries, manifest["id"]) print("device_release_source=" + release_before["descriptor"]["sourceCommit"]) print("device_release_predecessor=" + release_before["predecessor"]) + print("device_release_runtime_fingerprint=v2;normalized=HostConfig.Mounts-order-only") print("device_release_scope=core,manager;database-volumes-topology-secrets=preserved;rollback=exact-image-ids") if is_gitea_fresh_install_slice(manifest["component"], entries): validate_gitea_compose_schema(payload_dir / GITEA_COMPOSE_REL) @@ -39081,7 +39199,8 @@ def run_healthchecks(component, entries=None, services=None): if component == "device-core-release-reconciliation": if tuple(services or ()) != (): die("Device Core reconciliation must not select services") - preflight_device_release_reconciliation(DEVICE_PLANE_ROOT, entries, DEVICE_RELEASE_RECONCILIATION_ID, marker_installed=True) + identity = DEVICE_RELEASE_RECONCILIATION_V2_ID if tuple(entries or ()) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) else DEVICE_RELEASE_RECONCILIATION_ID + preflight_device_release_reconciliation(DEVICE_PLANE_ROOT, entries, identity, marker_installed=True) return if component == "device-core-release": if tuple(services or ()) != DEVICE_RELEASE_SERVICES or tuple(entries or ()) != DEVICE_RELEASE_ENTRIES: @@ -40997,7 +41116,7 @@ def apply_artifact(artifact): if component == "device-core-release-reconciliation": try: restore_platform_overlay(root, backup_dir, entries, current_stamp) - if (root / DEVICE_RELEASE_RECONCILIATION_ENTRY).exists(): + if any((root / entry).exists() or (root / entry).is_symlink() for entry in entries): die("Device Core reconciliation rollback left a marker") rollback_status = "ok:device-core-release-reconciliation-marker-only" except Exception as rollback_exc: diff --git a/infra/deploy-runner/test_device_core_mount_order.py b/infra/deploy-runner/test_device_core_mount_order.py new file mode 100644 index 0000000..0677988 --- /dev/null +++ b/infra/deploy-runner/test_device_core_mount_order.py @@ -0,0 +1,223 @@ +"""Order-only recovery must prove the legacy digest without relaxing values.""" +import copy +from contextlib import ExitStack, redirect_stdout, redirect_stderr +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from test_device_core_release import R, runtime, put +from test_device_core_reconciliation import B +from test_device_core_drift_audit import inspect_fixture + + +def samples_fixture(): + samples = {} + for service, row in runtime().items(): + fields = R.device_release_drift_fields(inspect_fixture()) + fields['HostConfig']['Binds'] = None + count = 7 if service == 'device-control-core' else 3 + fields['HostConfig']['Mounts'] = [ + {'Type': 'bind', 'Source': '/host/'+str(i), 'Target': '/target/'+str(i), + 'ReadOnly': True, 'BindOptions': {'Propagation': 'rprivate'}} for i in range(count)] + row['runtimeConfigSha256'] = R.device_release_drift_digest(fields) + samples[service] = {'runtime': row, 'fields': fields} + return samples + + +def evidence_fixture(samples): + return {'runtime': {s:copy.deepcopy(v['runtime']) for s,v in samples.items()}, + 'compose': {}, 'otherComposeServices': {}, 'installedFiles': {}} + + +def reorder(samples): + new = copy.deepcopy(samples) + for s in R.DEVICE_RELEASE_SERVICES: + new[s]['fields']['HostConfig']['Mounts'].reverse() + new[s]['runtime']['runtimeConfigSha256'] = R.device_release_drift_digest(new[s]['fields']) + new[s]['runtime']['containerId'] = 'a'*64 + return new + + +class MountOrderTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.artifact = self.root/'proof-v2.tgz';self.artifact.write_bytes(B.bundle(2)[1]) + work = self.root/'work';work.mkdir() + self.manifest,self.entries,self.payload = R.load_artifact(self.artifact,work) + + def test_v2_bundle_fixed_data_only_and_v1_bytes_unchanged(self): + self.assertEqual(self.artifact.read_bytes(),B.bundle(2)[1]) + self.assertEqual(tuple(self.entries),(R.DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,)) + self.assertEqual(self.manifest['id'],R.DEVICE_RELEASE_RECONCILIATION_V2_ID) + self.assertEqual(__import__('hashlib').sha256(B.bundle(1)[1]).hexdigest(),'68de2806a57253269bf9efb9d508cffbd1942fcca4cf9fc94b82d12fff0f322c') + for func in [R.component_services,R.component_builds]: + self.assertEqual(func(self.manifest['component'],self.entries),()) + self.assertEqual(R.component_compose_files(self.manifest['component']),()) + with self.assertRaises(R.DeployError): + R.component_services(self.manifest['component'],[R.DEVICE_RELEASE_RECONCILIATION_ENTRY,*self.entries]) + for key,value in [('runtimeFingerprintVersion',1),('mode','restart'),('failedSha256','f'*64),('extra',True)]: + d = R.device_release_reconciliation_v2_descriptor();d[key] = value + (self.payload/self.entries[0]).write_text(json.dumps(d)) + with self.subTest(key=key),self.assertRaises(R.DeployError): + R.validate_device_release_reconciliation_payload(self.payload,self.entries,self.manifest['id']) + + def test_permutations_preserve_every_option_without_mutating_input(self): + a = samples_fixture()['device-control-core']['fields'];original = copy.deepcopy(a) + b = copy.deepcopy(a);b['HostConfig']['Mounts'].reverse() + self.assertNotEqual(R.device_release_drift_digest(a),R.device_release_drift_digest(b)) + self.assertEqual(R.device_release_mounts_v2(a),R.device_release_mounts_v2(b)) + self.assertEqual(R.device_release_mount_order_proof(b,R.device_release_drift_digest(a)),5041) + self.assertEqual(a,original) + + def test_real_changes_and_binds_order_cannot_use_mount_order_proof(self): + fields = samples_fixture()['device-manager']['fields'] + fields['HostConfig']['Binds'] = ['/host/a:/a:ro','/host/b:/b:ro'] + digest = R.device_release_drift_digest(fields) + variants = [] + for key,value in [('Source','/different'),('Target','/different'),('ReadOnly',False),('Type','volume'),('BindOptions',{'Propagation':'rshared'}),('VolumeOptions',{'NoCopy':True})]: + d = copy.deepcopy(fields);d['HostConfig']['Mounts'][0][key] = value;variants.append(d) + for section,key,value in [('HostConfig','NetworkMode','egress'),('HostConfig','Binds',list(reversed(fields['HostConfig']['Binds']))),('HostConfig','PortBindings',{'1/tcp':[{'HostPort':'1234'}]}),('HostConfig','ReadonlyRootfs',False),('Config','Env',['CHANGED=1']),('Config','Cmd',['other'])]: + d = copy.deepcopy(fields);d[section][key] = value;variants.append(d) + for i,d in enumerate(variants): + with self.subTest(variant=i): + self.assertNotEqual(R.device_release_mounts_v2(fields),R.device_release_mounts_v2(d)) + with self.assertRaisesRegex(R.DeployError,'beyond HostConfig.Mounts order'): + R.device_release_mount_order_proof(d,digest) + + def test_duplicate_or_ambiguous_targets_and_oversized_proof_fail_closed(self): + fields = samples_fixture()['device-manager']['fields'] + for target in ['/target/1','relative','/a/../target','//target','/a/','/a\0b',None]: + d = copy.deepcopy(fields);d['HostConfig']['Mounts'][0]['Target'] = target + with self.subTest(target=target),self.assertRaises(R.DeployError):R.device_release_mounts_v2(d) + for value in ['invalid',[None],[{}]]: + d = copy.deepcopy(fields);d['HostConfig']['Mounts'] = value + with self.assertRaises(R.DeployError):R.device_release_mounts_v2(d) + d = copy.deepcopy(fields);d['HostConfig']['Mounts'] = [{'Target':'/t/'+str(i)} for i in range(8)] + with self.assertRaisesRegex(R.DeployError,'seven-mount'):R.device_release_mount_order_proof(d,R.device_release_drift_digest(d)) + + def test_none_absent_and_empty_mounts_remain_distinct(self): + fields = samples_fixture()['device-manager']['fields'] + for mounts in [None,[]]: + d = copy.deepcopy(fields);d['HostConfig']['Mounts'] = mounts + self.assertEqual(d,R.device_release_mounts_v2(d)) + d['HostConfig'].pop('Mounts');self.assertEqual(d,R.device_release_mounts_v2(d)) + + def test_three_samples_prove_exact_old_hashes_and_preserve_original_evidence(self): + original = samples_fixture();before = evidence_fixture(original);saved = copy.deepcopy(before) + current = reorder(original) + with mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current)),redirect_stdout(io.StringIO()) as output: + new = R.device_release_r5_mount_order_baseline(before) + self.assertEqual(before,saved);self.assertEqual(new['runtimeFingerprintVersion'],2) + for service in R.DEVICE_RELEASE_INVENTORY: + self.assertEqual(new['runtime'][service]['runtimeConfigSha256'],R.device_release_drift_digest(R.device_release_mounts_v2(original[service]['fields']))) + self.assertNotIn('SECRET=',output.getvalue());self.assertNotIn('/host/',output.getvalue()) + + def test_bad_image_unhealthy_preserved_recreation_and_unstable_sample_block_proof(self): + old = samples_fixture();before = evidence_fixture(old);current = reorder(old) + for service,key,value in [('device-manager','imageId','sha256:'+'f'*64),('device-control-core','running',False),('device-postgres','containerId','b'*64)]: + d = copy.deepcopy(current);d[service]['runtime'][key] = value + with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_drift_sample',return_value=d),self.assertRaises(R.DeployError): + R.device_release_r5_mount_order_baseline(before) + d = copy.deepcopy(current);d['device-manager']['runtime']['restartCount'] += 1 + with mock.patch.object(R,'device_release_drift_sample',side_effect=[current,d,current]),self.assertRaisesRegex(R.DeployError,'changed during'):R.device_release_r5_mount_order_baseline(before) + + def test_snapshot_v2_is_stable_and_rejects_unhealthy_services(self): + current = samples_fixture();changed = reorder(current) + with mock.patch.object(R,'device_release_drift_sample',return_value=copy.deepcopy(current)):a = R.device_release_runtime_snapshot_v2() + with mock.patch.object(R,'device_release_drift_sample',return_value=copy.deepcopy(changed)):b = R.device_release_runtime_snapshot_v2() + self.assertEqual([r['runtimeConfigSha256'] for r in a.values()],[r['runtimeConfigSha256'] for r in b.values()]) + changed['device-postgres']['runtime']['health'] = 'unhealthy' + with mock.patch.object(R,'device_release_drift_sample',return_value=changed),self.assertRaises(R.DeployError):R.device_release_runtime_snapshot_v2() + + def acceptance_stack(self,stack): + for name,value in [('device_release_other_compose_services',{}),('component_compose_files',()),('collect_exact_files',{})]: + stack.enter_context(mock.patch.object(R,name,return_value=value)) + stack.enter_context(mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'live')) + stack.enter_context(mock.patch.object(R,'validate_device_manager_control_plane_runtime')) + stack.enter_context(mock.patch.object(R,'validate_device_release_payload')) + + def test_normal_release_and_rollback_use_versioned_hash_and_legacy_stays_strict(self): + original = samples_fixture();before = evidence_fixture(original);current = reorder(original) + with ExitStack() as stack: + self.acceptance_stack(stack) + stack.enter_context(mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current))) + stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot',return_value={s:v['runtime'] for s,v in current.items()})) + with self.assertRaisesRegex(R.DeployError,'configuration drift'):R.accept_device_release(before,rollback=True) + with redirect_stdout(io.StringIO()):new = R.device_release_r5_mount_order_baseline(before) + with redirect_stdout(io.StringIO()):R.accept_device_release(new,rollback=True) + new['descriptor'] = {'releaseId':'fixture','sourceCommit':'a'*40} + stack.enter_context(mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':new['runtime'][args[-1].split('/')[1].split(':')[0]]['imageId']}])) + with redirect_stdout(io.StringIO()):R.accept_device_release(new) + for version in [True,0,3,'2']: + with self.subTest(version=version),self.assertRaisesRegex(R.DeployError,'version mismatch'):R.accept_device_release({**before,'runtimeFingerprintVersion':version}) + + def test_preflight_records_v2_for_new_normal_release(self): + with ExitStack() as stack: + for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v2',runtime())]: + stack.enter_context(mock.patch.object(R,name,return_value=value)) + for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']: + stack.enter_context(mock.patch.object(R,name)) + legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot')) + before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id') + self.assertEqual(before['runtimeFingerprintVersion'],2);legacy.assert_not_called() + + def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self): + old = samples_fixture();before = evidence_fixture(old);current = reorder(old) + with ExitStack() as stack: + self.acceptance_stack(stack) + stack.enter_context(mock.patch.object(R,'device_release_r5_evidence',return_value=before)) + stack.enter_context(mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current))) + stack.enter_context(mock.patch.object(R,'healthcheck_compose_service_with_grace')) + stack.enter_context(mock.patch.object(R,'healthcheck_url')) + command = stack.enter_context(mock.patch.object(R.subprocess,'run')) + with redirect_stdout(io.StringIO()):new = R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id']) + self.assertEqual(new['runtimeFingerprintVersion'],2) + # Post-copy acceptance reads the installed v2 descriptor and same real guards. + stack.enter_context(mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload)) + with redirect_stdout(io.StringIO()):R.run_healthchecks(self.manifest['component'],self.entries,()) + command.assert_not_called() + put(self.payload,R.DEVICE_RELEASE_RECONCILIATION_ENTRY,b'conflict') + with self.assertRaisesRegex(R.DeployError,'versions conflict'): + R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'],marker_installed=True) + + def execute_apply(self,fail=False): + live = self.root/'live';live.mkdir() + for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir() + original = samples_fixture();before = evidence_fixture(original);current = reorder(original) + with ExitStack() as stack: + self.acceptance_stack(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',live)]: + stack.enter_context(mock.patch.object(R,name,value)) + config = {**R.COMPONENTS[self.manifest['component']],'payload_root':live} + stack.enter_context(mock.patch.dict(R.COMPONENTS,{self.manifest['component']:config})) + for name in ['require_root','ensure_layout','validate_artifact_location','healthcheck_compose_service_with_grace']: + stack.enter_context(mock.patch.object(R,name)) + stack.enter_context(mock.patch.object(R,'device_release_r5_evidence',return_value=before)) + stack.enter_context(mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current))) + def http(check): + if fail and (live/self.entries[0]).exists():raise R.DeployError('injected post-copy health failure') + stack.enter_context(mock.patch.object(R,'healthcheck_url',side_effect=http)) + command = stack.enter_context(mock.patch.object(R.subprocess,'run')) + stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO())) + if fail: + with self.assertRaises(R.DeployError):R.apply_artifact(self.artifact) + self.assertFalse((live/self.entries[0]).exists()) + self.assertFalse(R.load_state(R.STATE_FILE)) + self.assertEqual(R.load_state(R.FAILED_STATE_FILE)[0]['rollback_status'],'ok:device-core-release-reconciliation-marker-only') + else: + R.apply_artifact(self.artifact) + self.assertTrue(R.device_release_r5_reconciled(R.device_release_r5_failed_row())) + row = R.load_state(R.STATE_FILE)[0] + archive = R.APPLIED_DIR/row['artifact'];archive.write_bytes(archive.read_bytes()+b'tamper') + with self.assertRaises(R.DeployError):R.device_release_r5_reconciled(R.device_release_r5_failed_row()) + command.assert_not_called() + + def test_full_v2_apply_rechecks_proof_then_receipt_and_archive_unblock_only_r5(self):self.execute_apply() + def test_full_v2_failed_apply_removes_marker_without_touching_services(self):self.execute_apply(fail=True) + + +if __name__=='__main__':unittest.main() diff --git a/infra/device-core-deploy/README.md b/infra/device-core-deploy/README.md index 8485c2e..9f55764 100644 --- a/infra/device-core-deploy/README.md +++ b/infra/device-core-deploy/README.md @@ -94,9 +94,10 @@ successful CI run become the next normal-release candidate. ## Read-only diagnosis after rejected reconciliation Reconciliation001 stopped in plan on the saved Core runtime configuration hash. -No apply ran. This does not prove either harmless ordering or actual drift. The -original backup stores only an aggregate hash, and the legacy snapshot retains -HostConfig.Binds/Mounts order. Existing acceptance is deliberately unchanged. +No apply ran. The initial rejection alone did not prove harmless ordering or +actual drift. The original backup stores only an aggregate hash, and the legacy +snapshot retains HostConfig.Binds/Mounts order. The diagnostic kept acceptance +unchanged. `build_drift_audit.py` creates a separate `device-core-release-drift-audit` bundle. Its only entry is `deployment/device-core-release-r5-drift-audit-v1.json`. @@ -113,3 +114,43 @@ NetworkMode is reported as a difference, never accepted as harmless. Exhaustion, changing samples or no match remains unresolved. No diagnostic result creates a reconciliation marker or bypasses the original acceptance barriers. A subsequent recovery decision requires the actual NAS report. + + +## Proven mount-order recovery and runtime fingerprint v2 + +The NAS audit on 2026-09-29 found an exact old hash preimage for Core and Manager +by reordering only `HostConfig.Mounts` (7 and 3 entries). All three observations +were stable; image IDs, source, topology, health, runtime boundaries and preserved +services matched. The audit output SHA is +`cf687c8bf550fa8c7d1125a3297e04c3d0d81a704b1d6ad17dbddc66470a1189`. +This evidence does not itself create a canonical recovery receipt. + +The recurring release domain now records `runtimeFingerprintVersion: 2` in new +before snapshots. Version 2 sorts complete `HostConfig.Mounts` objects, requiring +unique absolute normalized Target paths, and preserves every value and option. +Binds and NetworkMode are unchanged. Old snapshots without a version retain the +legacy comparison; generic Compose and historical transition guards are unchanged. +Docker 24.0.2 registers mount points by unique destination, independently of this +input list order: . + +Build the NEW data-only recovery package with: + +```sh +python3 infra/device-core-deploy/build_reconciliation.py --version 2 --output-dir /tmp/recovery-v2 +``` + +The fixed identity is `device-core-release-r5-reconciliation-v2-20260929-002`, with +only `deployment/device-core-release-r5-reconciliation-v2.json`. Version 1 remains +strict and byte-identical. V2 proves the old digest with at most 5,041 candidates +per service by permuting only existing HostConfig.Mounts (at most seven); it never +uses the broader diagnostic probe. Three identical observations, old images and +exact preserved service rows are required. After proving equivalence it derives a +v2 baseline and rechecks every existing acceptance guard. Plan, locked preflight +and post-copy acceptance all repeat this proof. Conflicting v1/v2 markers fail. + +Apply only writes the marker, backup and canonical journal. Original incident +files and the failed receipt remain unchanged. Marker plus unique applied receipt, +archive digest/identity and original evidence are required to acknowledge r5. +A failure removes only the marker. This package performs no application deployment +and does not activate automatic deployment. Live plan/apply are still required; +the old r5 artifact and the rejected v1 reconciliation must not be replayed. diff --git a/infra/device-core-deploy/build_reconciliation.py b/infra/device-core-deploy/build_reconciliation.py index ea4c7e6..2221ff7 100644 --- a/infra/device-core-deploy/build_reconciliation.py +++ b/infra/device-core-deploy/build_reconciliation.py @@ -12,13 +12,16 @@ ROOT = Path(__file__).resolve().parent ENTRY = 'deployment/device-core-release-r5-reconciliation-v1.json' -def bundle(): - descriptor = (ROOT / 'r5-reconciliation-v1.json').read_bytes() +def bundle(version=1): + if version not in (1, 2): + raise ValueError("unsupported reconciliation version") + entry = ENTRY if version == 1 else ENTRY.replace("-v1.json", "-v2.json") + descriptor = (ROOT / ('r5-reconciliation-v'+str(version)+'.json')).read_bytes() identity = json.loads(descriptor)['releaseId'] members = { 'manifest.env': ('id='+identity+'\ncomponent=device-core-release-reconciliation\ntype=app-overlay\n').encode(), - 'files.txt': (ENTRY+'\n').encode(), - 'payload/'+ENTRY: descriptor, + 'files.txt': (entry+'\n').encode(), + 'payload/'+entry: descriptor, } output=io.BytesIO() with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed: @@ -31,8 +34,9 @@ def bundle(): if __name__=='__main__': parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--version', type=int, choices=(1, 2), default=1) parser.add_argument('--output-dir',required=True,type=Path) args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True) - identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz') + identity,data=bundle(args.version);path=args.output_dir/('nodedc-'+identity+'.tgz') with path.open('xb') as stream:stream.write(data) print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity})) diff --git a/infra/device-core-deploy/r5-reconciliation-v2.json b/infra/device-core-deploy/r5-reconciliation-v2.json new file mode 100644 index 0000000..de958aa --- /dev/null +++ b/infra/device-core-deploy/r5-reconciliation-v2.json @@ -0,0 +1,9 @@ +{ + "backupId": "device-core-release-device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406-20260929-190019", + "failedReleaseId": "device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406", + "failedSha256": "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad9136ccbf9347", + "mode": "prove-restored-baseline-mount-order-only", + "releaseId": "device-core-release-r5-reconciliation-v2-20260929-002", + "runtimeFingerprintVersion": 2, + "schemaVersion": "nodedc.device-core.release-reconciliation.v2" +}