diff --git a/infra/cms-deploy/R39_RUNTIME_RECONCILIATION.md b/infra/cms-deploy/R39_RUNTIME_RECONCILIATION.md new file mode 100644 index 0000000..b412153 --- /dev/null +++ b/infra/cms-deploy/R39_RUNTIME_RECONCILIATION.md @@ -0,0 +1,72 @@ +# CMS r39: runtime representation and exact recovery + +The first qualified CMS application release failed runtime acceptance and rollback +verification. The original failed journal, archive and six backup files remain +immutable. Availability alone was not treated as proof of recovery. + +The installed plan-only diagnostic reported stable samples, the original image, +unchanged source, foundation, NAS metadata, project/site data, other containers, +running image source and healthy authenticated CMS. Its limited bind-order search +did not recover the original fingerprint because three DNS fields also differed. + +## Exact evidence + +The current runtime was reconstructed locally from the diagnostic's per-field +hashes, unchanged Compose source and unchanged environment file. Environment +values were retained only in memory. The complete reconstructed current digest +matched the NAS diagnostic, not merely selected field hashes. Changing exactly +these four representations then reproduced the complete saved predecessor digest: + +| Field | Saved predecessor | Current | +| --- | --- | --- | +| `HostConfig.Binds` | projects, website | website, projects | +| `HostConfig.Dns` | `[]` | `null` | +| `HostConfig.DnsOptions` | `[]` | `null` | +| `HostConfig.DnsSearch` | `[]` | `null` | + +Both bind strings, including source, destination and `rw`, are unchanged. +All environment values, ports, network names, mount options, resource settings +and security flags are included in the complete digest proof. + +- Legacy predecessor: `e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f`. +- Current legacy digest: `00d5d3aa50519a923cc6cd2a6478c313e2c8433b4d089b214192da201fc599fd`. +- Shared version-2 digest: `5d656cf19d63800ca3c9d6f797dd5f71f86be0dfe55899ccb80a8935a937bbce`. + +Docker 24.0.2 checks `len(...) > 0` for these three DNS settings in +[`daemon/container_operations.go`](https://github.com/moby/moby/blob/v24.0.2/daemon/container_operations.go). +Empty lists and null therefore select the same DNS fallback. Nonempty DNS lists +and their ordering are never discarded by the version-2 fingerprint. + +## Registered transition + +Component `dc-cms-runtime-reconciliation` has fixed root +`/volume1/docker/dc-cms/source`, no service/build/Compose selection, and only +`deployment/dc-cms-r39-runtime-reconciliation-v2.json` as payload. Its immutable +identity is `dc-cms-r39-runtime-reconciliation-v2-20261104-001`. +The descriptor pins the failed release, original backup hashes and legacy digest. + +Fresh plan and apply recheck the exact original failed row/archive/backup. Three +identical live samples must have the original image and produce the saved digest +by enumerating only two observed bind strings and empty DNS representations +(at most 16 candidates). Existing source, data, metadata, foundation, dependency +and health acceptance then runs against the proven version-2 baseline. + +Apply copies only the descriptor and rechecks the proof after the copy. Failure +removes only that new marker; no application service, secret, database, volume, +queue or failed historical receipt is changed by this metadata transition. + +The automatic controller acknowledges r39 only after matching the successful +canonical recovery receipt, archived artifact and installed marker while retaining +the original incident evidence. Its separate exact `blocked -> failed` queue +transition is pinned to run 39, number 1, source/artifact digest and prior receipt. +The old release never becomes ready again; only a new qualified run may proceed. + +New CMS releases record `runtimeFingerprintVersion=2` and per-field hashes for +future diagnostics. Version 1 remains strict for old evidence and the original +audit. Version 2 sorts only complete, unambiguous bind strings and normalizes +only null/empty DNS lists; real changes still fail acceptance. Device Core and +the accepted CMS bootstrap remain unchanged. + +Build the data artifact with `build_runtime_reconciliation.py` only after the +reviewed root runner has been promoted and verified. A prepared candidate or +successful local proof does not establish production reconciliation. diff --git a/infra/cms-deploy/README.md b/infra/cms-deploy/README.md index ab53af6..0c34baf 100644 --- a/infra/cms-deploy/README.md +++ b/infra/cms-deploy/README.md @@ -52,3 +52,10 @@ be a separately reviewed transition after its actual runtime findings. After diagnostic runner promotion, build its fixed data bundle with `python3 infra/cms-deploy/build_runtime_audit.py --output-dir ` and use only the canonical `plan` operation for the audit artifact. + +The r39 audit confirmed the old image and all source/data/dependency checks. +Offline reconstruction matched the complete current fingerprint and the complete +saved predecessor fingerprint: only bind-string order and three empty DNS list +representations differ. See [the incident proof and recovery contract](R39_RUNTIME_RECONCILIATION.md). +The separate `dc-cms-runtime-reconciliation` marker transition re-proves that +exact legacy hash on NAS before releasing the r39 barrier. It never retries r39. diff --git a/infra/cms-deploy/autodeploy_runtime.py b/infra/cms-deploy/autodeploy_runtime.py index 5610cc7..294e37f 100644 --- a/infra/cms-deploy/autodeploy_runtime.py +++ b/infra/cms-deploy/autodeploy_runtime.py @@ -284,6 +284,8 @@ class CmsAutodeployInstaller: return 'ambiguous', 'canonical-archive-or-backup-mismatch' if applied and record.get('status') == 'ok': outcome = 'deployed' + elif failed and cms_r39_reconciled(record): + return 'rolled-back', 'canonical-reconciled:' + CMS_RECON_ID elif failed and record.get('rollback_status') == 'ok:dc-cms-release': outcome = 'rolled-back' else: diff --git a/infra/cms-deploy/build_runtime_reconciliation.py b/infra/cms-deploy/build_runtime_reconciliation.py new file mode 100644 index 0000000..1f8e027 --- /dev/null +++ b/infra/cms-deploy/build_runtime_reconciliation.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Build the fixed, data-only CMS r39 runtime reconciliation descriptor.""" +import argparse +import gzip +import hashlib +import io +import json +from pathlib import Path +import tarfile +ROOT=Path(__file__).resolve().parent +ENTRY='deployment/dc-cms-r39-runtime-reconciliation-v2.json' + + +def bundle(): + descriptor=(ROOT/'runtime-reconciliation-v2.json').read_bytes() + identity=json.loads(descriptor)['releaseId'] + members={'manifest.env':f'id={identity}\ncomponent=dc-cms-runtime-reconciliation\ntype=app-overlay\n'.encode(), + 'files.txt':(ENTRY+'\n').encode(),'payload/'+ENTRY:descriptor} + output=io.BytesIO() + with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed: + with tarfile.open(fileobj=compressed,mode='w') as archive: + for name,value in sorted(members.items()): + info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value) + archive.addfile(info,io.BytesIO(value)) + return identity,output.getvalue() + + +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',type=Path,required=True) + args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True) + identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz') + with path.open('xb') as stream:stream.write(data) + print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity})) diff --git a/infra/cms-deploy/controller.py b/infra/cms-deploy/controller.py index 61e436c..89b044d 100644 --- a/infra/cms-deploy/controller.py +++ b/infra/cms-deploy/controller.py @@ -8,6 +8,13 @@ class Controller: def reconcile(self): for row in self.queue.snapshot(): + if row['phase'] == 'blocked': + outcome, receipt = self.installer.receipt(row) + if outcome == 'rolled-back': + self.queue.reconcile_r39(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt) + elif outcome != 'ambiguous': + raise QueueError('blocked_run_requires_exact_recovery') + continue if row['phase'] != 'deploying': continue outcome, receipt = self.installer.receipt(row) diff --git a/infra/cms-deploy/deployment_queue.py b/infra/cms-deploy/deployment_queue.py index 6612ff3..132183b 100644 --- a/infra/cms-deploy/deployment_queue.py +++ b/infra/cms-deploy/deployment_queue.py @@ -174,5 +174,29 @@ class DeploymentQueue: self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.transaction(apply) + def reconcile_r39(self, identity, *, digest, artifact, receipt): + """Exact terminal blocked -> failed recovery after canonical proof. + + This never makes the failed artifact ready again. The caller verifies + the immutable failed evidence and the separate successful recovery. + """ + sha = 'c9d8f0ae59211ce3443300acfea311907508261a' + expected_receipt = 'canonical-reconciled:dc-cms-r39-runtime-reconciliation-v2-20261104-001' + if (type(identity) is not int or identity != 39 + or digest != '3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029' + or artifact != 'nodedc-dc-cms-release-v1-r39-'+sha+'.tgz' + or receipt != expected_receipt): + raise QueueError('r39_reconciliation_identity_mismatch') + def apply(): + row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone() + if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (1,sha,'push','master',WORKFLOW,digest,artifact): + raise QueueError('r39_reconciliation_row_mismatch') + if row['phase'] == 'failed' and row['receipt'] == receipt: + return + if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed': + raise QueueError('r39_reconciliation_predecessor_mismatch') + self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity)) + self.transaction(apply) + def snapshot(self): return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] diff --git a/infra/cms-deploy/embed_runtime.py b/infra/cms-deploy/embed_runtime.py index 419da81..f78a05d 100644 --- a/infra/cms-deploy/embed_runtime.py +++ b/infra/cms-deploy/embed_runtime.py @@ -16,7 +16,8 @@ def section(): library+='\n'.join(' '+line if line else '' for line in lines)+'\n\n' library+=' return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)\n' audit=(ROOT/'audit_runtime.py').read_text() - return START+release+'\n'+ci+'\n'+auto+'\n'+audit+'\n'+library+END + reconciliation=(ROOT/'reconciliation_runtime.py').read_text() + return START+release+'\n'+ci+'\n'+auto+'\n'+audit+'\n'+reconciliation+'\n'+library+END if __name__=='__main__': before,rest=RUNNER.read_text().split(START,1);_,after=rest.split(END,1) diff --git a/infra/cms-deploy/reconciliation_runtime.py b/infra/cms-deploy/reconciliation_runtime.py new file mode 100644 index 0000000..7a1f7e4 --- /dev/null +++ b/infra/cms-deploy/reconciliation_runtime.py @@ -0,0 +1,141 @@ +# Exact r39 reconciliation; this code is embedded in the root-owned runner. +CMS_RECON_ID = 'dc-cms-r39-runtime-reconciliation-v2-20261104-001' +CMS_RECON_ENTRY = 'deployment/dc-cms-r39-runtime-reconciliation-v2.json' +CMS_RECON_LEGACY_SHA = 'e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f' +CMS_DNS_FIELDS = ('Dns','DnsOptions','DnsSearch') + + +def cms_reconciliation_descriptor(): + return {'schemaVersion':'nodedc.dc-cms.runtime-reconciliation.v2','releaseId':CMS_RECON_ID, + 'failedReleaseId':CMS_AUDIT_FAILED_ID,'failedSha256':CMS_AUDIT_FAILED_SHA, + 'backupId':CMS_AUDIT_BACKUP,'backupSha256':CMS_AUDIT_BACKUP_SHA, + 'legacyRuntimeSha256':CMS_RECON_LEGACY_SHA,'runtimeFingerprintVersion':2, + 'mode':'prove-restored-baseline-bind-order-empty-dns-only'} + + +def validate_cms_reconciliation_payload(payload, entries, identity): + if tuple(entries or ())!=(CMS_RECON_ENTRY,) or identity!=CMS_RECON_ID: + die('CMS reconciliation identity/entry mismatch') + marker=payload/CMS_RECON_ENTRY + if marker.is_symlink() or not marker.is_file():die('CMS reconciliation marker is unsafe') + expected=(json.dumps(cms_reconciliation_descriptor(),sort_keys=True,indent=2)+'\n').encode() + if marker.read_bytes()!=expected:die('CMS reconciliation descriptor mismatch') + + +def cms_runtime_fields_v2(fields): + result=json.loads(json.dumps(fields));host=result['host'] + binds=host.get('Binds') + if not isinstance(binds,list) or not 1<=len(binds)<=8: + die('CMS v2 bind list is missing or outside bounds') + targets=[] + for bind in binds: + if not isinstance(bind,str) or '\0' in bind:die('CMS v2 bind is malformed') + parts=bind.split(':') + if len(parts) not in (2,3):die('CMS v2 bind is ambiguous') + for path in parts[:2]: + if not path.startswith('/') or str(PurePosixPath(path))!=path or '..' in PurePosixPath(path).parts: + die('CMS v2 bind path is not canonical') + if len(parts)==3 and not parts[2]:die('CMS v2 bind options are ambiguous') + targets.append(parts[1]) + if len(set(targets))!=len(targets):die('CMS v2 duplicate bind target') + host['Binds']=sorted(binds) + # Docker 24 uses len(...) > 0 for these three settings. Nonempty lists and + # their order are untouched; every other HostConfig field remains exact. + for key in CMS_DNS_FIELDS: + if key not in host:die('CMS v2 DNS field is missing') + value=host[key] + if value is None:host[key]=[] + elif not isinstance(value,list) or any(not isinstance(v,str) for v in value): + die('CMS v2 DNS field is malformed') + return result + + +def cms_runtime_v2_from_sample(sample): + fields=cms_runtime_fields_v2(sample['fields']) + digests={section+'.'+key:cms_audit_digest(value) for section in ('host','config') + for key,value in fields[section].items()} + digests.update({key:cms_audit_digest(fields[key]) for key in ('mounts','networks')}) + return {**sample['runtime'],'configSha256':cms_audit_digest(fields),'fieldSha256':digests} + + +def cms_runtime_snapshot_v2(): + return cms_runtime_v2_from_sample(cms_audit_sample()) + + +def cms_r39_representation_proof(fields, expected): + cms_runtime_fields_v2(fields) # Validate paths and types before enumeration. + if not isinstance(expected,str) or not re.fullmatch('[a-f0-9]{64}',expected): + die('CMS reconciliation predecessor digest is invalid') + if len(fields['host']['Binds'])!=2 or any(fields['host'][k] not in (None,[]) for k in CMS_DNS_FIELDS): + die('CMS r39 proof requires exactly two binds and empty DNS settings') + work=json.loads(json.dumps(fields));checked=0 + for binds in itertools.permutations(fields['host']['Binds']): + work['host']['Binds']=list(binds) + for dns in itertools.product((None,[]),repeat=3): + for key,value in zip(CMS_DNS_FIELDS,dns):work['host'][key]=value + checked+=1 + if cms_audit_digest(work)==expected:return checked + die('CMS runtime differs beyond bind order and empty DNS representation') + + +def cms_r39_failed_row(): + return {'artifact':'nodedc-'+CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125', + 'backup_id':CMS_AUDIT_BACKUP,'component':'dc-cms-release', + 'failed_at':'2026-11-04T19:34:46+00:00','id':CMS_AUDIT_FAILED_ID, + 'message':'CMS environment, mounts, ports or network topology changed', + 'rollback_status':'failed:DeployError','sha256':CMS_AUDIT_FAILED_SHA, + 'started_apply':True,'status':'failed'} + + +def cms_r39_evidence(): + rows=[r for r in load_state(FAILED_STATE_FILE) if r.get('id')==CMS_AUDIT_FAILED_ID or r.get('sha256')==CMS_AUDIT_FAILED_SHA] + if rows!=[cms_r39_failed_row()]:die('CMS reconciliation failed receipt mismatch') + before=cms_audit_evidence() + if before['runtime']['configSha256']!=CMS_RECON_LEGACY_SHA: + die('CMS reconciliation saved runtime digest differs') + return before + + +def cms_r39_restored_baseline(before): + samples=[cms_audit_sample() for _ in range(3)] + if any(sample!=samples[0] for sample in samples):die('CMS runtime changed during reconciliation') + sample=samples[0];old=before['runtime'];runtime=sample['runtime'] + if runtime['imageId']!=old['imageId'] or runtime['imageRef']!=old['imageRef']: + die('CMS reconciliation original image mismatch') + checked=cms_r39_representation_proof(sample['fields'],old['configSha256']) + result=json.loads(json.dumps(before));result['runtimeFingerprintVersion']=2 + result['runtime']=cms_runtime_v2_from_sample(sample) + print('cms_reconciliation_proof=exact-legacy-sha;changed-representation=bind-order,empty-dns;' + 'samples=3;candidates='+str(checked)+';fingerprint=v2') + return result + + +def preflight_cms_reconciliation(payload, entries, identity, *, marker_installed=False): + require_root();validate_cms_reconciliation_payload(payload,entries,identity) + marker=CMS_ROOT/CMS_RECON_ENTRY + if not marker_installed and (marker.exists() or marker.is_symlink()): + die('CMS reconciliation marker already exists') + before=cms_r39_restored_baseline(cms_r39_evidence()) + accept_cms_release(before,rollback=True) + print('cms_reconciliation_accept=restored-baseline-proven;services=none;build=none;runtime-mutation=none') + return before + + +def cms_r39_reconciled(row): + if row!=cms_r39_failed_row():return False + marker=CMS_ROOT/CMS_RECON_ENTRY + records=[r for r in load_state(STATE_FILE) if r.get('id')==CMS_RECON_ID] + if not records: + # During canonical apply the marker may precede its success receipt. + # Neither marker presence nor an in-progress apply grants queue release. + return False + if len(records)!=1 or records[0].get('component')!='dc-cms-runtime-reconciliation' or records[0].get('status')!='ok': + die('CMS reconciliation applied receipt mismatch') + validate_cms_reconciliation_payload(CMS_ROOT,(CMS_RECON_ENTRY,),CMS_RECON_ID) + with tempfile.TemporaryDirectory(prefix='cms-r39-marker-',dir=TMP_DIR) as tmp: + manifest,entries,payload=load_artifact(device_release_applied_archive(records[0]),Path(tmp)) + if manifest.get('component')!='dc-cms-runtime-reconciliation' or manifest.get('id')!=CMS_RECON_ID: + die('CMS reconciliation applied archive identity mismatch') + if sha256_file(payload/CMS_RECON_ENTRY)!=sha256_file(marker):die('CMS reconciliation marker drift') + cms_r39_evidence() + return True diff --git a/infra/cms-deploy/release_runtime.py b/infra/cms-deploy/release_runtime.py index 02d0c1a..f680571 100644 --- a/infra/cms-deploy/release_runtime.py +++ b/infra/cms-deploy/release_runtime.py @@ -92,7 +92,8 @@ def cms_application_inventory(): def cms_installed_release(): for row in load_state(FAILED_STATE_FILE): - if row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') and not str(row.get('rollback_status','')).startswith('ok:'): + if (row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') + and not str(row.get('rollback_status','')).startswith('ok:') and not cms_r39_reconciled(row)): die('CMS deployment requires failed-rollback reconciliation') rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'dc-cms-release'] if rows: @@ -172,7 +173,7 @@ def preflight_cms_release(payload, entries, identity): if not set(installed) <= set(entries):die('CMS v1 release cannot remove existing application files') cms_healthchecks() return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'], - 'runtime':cms_runtime_snapshot(),'otherServices':cms_other_services(), + 'runtimeFingerprintVersion':2,'runtime':cms_runtime_snapshot_v2(),'otherServices':cms_other_services(), 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata} @@ -211,9 +212,16 @@ for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){ def accept_cms_release(before, *, rollback=False): cms_healthchecks() - current=cms_runtime_snapshot();old=before['runtime'] + version=before.get('runtimeFingerprintVersion',1) + if type(version) is not int or version not in (1,2):die('CMS runtime fingerprint version mismatch') + current=cms_runtime_snapshot_v2() if version==2 else cms_runtime_snapshot();old=before['runtime'] if current['configSha256'] != old['configSha256'] or current['imageRef'] != old['imageRef']: - die('CMS environment, mounts, ports or network topology changed') + detail='' + if version==2: + previous=old.get('fieldSha256') or {};actual=current.get('fieldSha256') or {} + changed=sorted(k for k in set(previous)|set(actual) if previous.get(k)!=actual.get(k)) + detail='; fields='+','.join(changed) + die('CMS environment, mounts, ports or network topology changed'+detail) expected_image=old['imageId'] if rollback else before['builtImageId'] if current['imageId'] != expected_image or (not rollback and current['id']==old['id']): die('CMS selected service image/generation mismatch') diff --git a/infra/cms-deploy/runtime-reconciliation-v2.json b/infra/cms-deploy/runtime-reconciliation-v2.json new file mode 100644 index 0000000..513fa44 --- /dev/null +++ b/infra/cms-deploy/runtime-reconciliation-v2.json @@ -0,0 +1,18 @@ +{ + "backupId": "dc-cms-release-dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a-20261104-223125", + "backupSha256": { + "cms-runtime-before.json": "e14634fc1ef03da8b8a7751d9418b74c52da65dfe6dea82ad9c14ef04634263b", + "existing-files.txt": "46fa370124d7ed95362666e84372188bdf9d0c2b4c2e0e3d9dbeed42ad571762", + "files.txt": "4a696155703c6aa15daf777331847a37cd5e8345e2bb0a6b1fc98515e27988d8", + "manifest.env": "ce246952d0ef6cee1f4b22b770108d5c92d671cc7984dc83e136d61f2e607f22", + "missing-files.txt": "c31852f6da115fed68880fcf0aa8a7b4c0d2a7a9cfdae095907e95863bdb2409", + "source-before.tgz": "cd35cb27dd4875e13cdf7202ab57c24e7db0a43c473454675fe122ebf23090b1" + }, + "failedReleaseId": "dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a", + "failedSha256": "3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029", + "legacyRuntimeSha256": "e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f", + "mode": "prove-restored-baseline-bind-order-empty-dns-only", + "releaseId": "dc-cms-r39-runtime-reconciliation-v2-20261104-001", + "runtimeFingerprintVersion": 2, + "schemaVersion": "nodedc.dc-cms.runtime-reconciliation.v2" +} diff --git a/infra/cms-deploy/test_reconciliation.py b/infra/cms-deploy/test_reconciliation.py new file mode 100644 index 0000000..57289d3 --- /dev/null +++ b/infra/cms-deploy/test_reconciliation.py @@ -0,0 +1,246 @@ +import copy +from contextlib import ExitStack, redirect_stdout, redirect_stderr +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch +from test_runner import r +from build_runtime_reconciliation import bundle +from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID, WORKFLOW +from controller import Controller + + +def old_fields(): + return {'host':{'Binds':['/source/a:/a:rw','/source/b:/b:rw'], + 'Dns':[],'DnsOptions':[],'DnsSearch':[], 'NetworkMode':'cms-edge', + 'ReadonlyRootfs':False,'PortBindings':{}}, + 'config':{'Env':['TOKEN=fixture-never-print'],'Cmd':['npm','run','admin']}, + 'mounts':[{'Source':'/source/a','Destination':'/a','RW':True}], 'networks':['cms-edge']} + + +def sample(fields=None, identity='new'): + fields=copy.deepcopy(fields or old_fields()) + return {'fields':fields,'runtime':{'id':identity,'imageId':'old-image','imageRef':'dc-cms-cms-app', + 'configSha256':r.cms_audit_digest(fields)}} + + +def incident(): + return {'runtime':sample(identity='old')['runtime'],'installedFiles':{'server/app.mjs':'sha'}, + 'installedMetadata':{},'foundation':{},'data':{},'otherServices':{}} + + +def changed_sample(): + fields=old_fields();fields['host']['Binds'].reverse() + for key in r.CMS_DNS_FIELDS:fields['host'][key]=None + return sample(fields) + + +class ReconciliationTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.root=Path(self.tmp.name) + self.artifact=self.root/'candidate.tgz';self.artifact.write_bytes(bundle()[1]) + unpack=self.root/'unpack';unpack.mkdir() + self.manifest,self.entries,self.payload=r.load_artifact(self.artifact,unpack) + + def acceptance(self,stack): + before=incident() + for name,value in [('cms_healthchecks',None),('cms_foundation',{}),('cms_preserved_data',{}), + ('cms_other_services',{}),('cms_application_inventory',(before['installedFiles'],{})), + ('cms_image_files',before['installedFiles']),('cms_r39_evidence',before), + ('cms_audit_sample',changed_sample())]: + stack.enter_context(patch.object(r,name,return_value=value)) + return before + + def test_fixed_data_only_artifact_and_no_service_or_build_authority(self): + self.assertEqual(self.artifact.read_bytes(),bundle()[1]) + self.assertEqual(self.entries,[r.CMS_RECON_ENTRY]) + self.assertEqual(self.manifest['id'],r.CMS_RECON_ID) + self.assertEqual(r.component_services(self.manifest['component'],self.entries),()) + self.assertEqual(r.component_builds(self.manifest['component'],self.entries),()) + self.assertEqual(r.component_compose_files(self.manifest['component']),()) + for path in ['server/app.mjs','deployment/other.json','.env','projects/nodedc.json']: + with self.assertRaises(r.DeployError):r.allowed_payload_path(self.manifest['component'],path) + for key,value in [('runtimeFingerprintVersion',1),('mode','restart'),('failedSha256','a'*64),('extra',True)]: + descriptor=r.cms_reconciliation_descriptor();descriptor[key]=value + (self.payload/r.CMS_RECON_ENTRY).write_text(json.dumps(descriptor)) + with self.assertRaises(r.DeployError):r.validate_cms_reconciliation_payload(self.payload,self.entries,r.CMS_RECON_ID) + + def test_only_evidenced_representation_changes_are_equal(self): + old=old_fields();new=changed_sample()['fields'];saved=copy.deepcopy(new) + self.assertNotEqual(r.cms_audit_digest(old),r.cms_audit_digest(new)) + self.assertEqual(r.cms_runtime_fields_v2(old),r.cms_runtime_fields_v2(new)) + self.assertLessEqual(r.cms_r39_representation_proof(new,r.cms_audit_digest(old)),16) + self.assertEqual(new,saved) + + def test_real_dns_env_mount_port_network_and_security_drift_remain_rejected(self): + old=old_fields();variants=[] + for section,key,value in [('config','Env',['TOKEN=changed']),('config','Cmd',['other']), + ('host','Dns',['1.1.1.1']),('host','DnsOptions',['ndots:2']), + ('host','DnsSearch',['internal']),('host','NetworkMode','other'), + ('host','ReadonlyRootfs',True),('host','PortBindings',{'80/tcp':[]}), + ('host','Binds',['/different:/a:rw','/source/b:/b:rw'])]: + fields=changed_sample()['fields'];fields[section][key]=value;variants.append(fields) + fields=changed_sample()['fields'];fields['mounts'][0]['RW']=False;variants.append(fields) + fields=changed_sample()['fields'];fields['networks'].append('other');variants.append(fields) + for fields in variants: + self.assertNotEqual(r.cms_runtime_fields_v2(old),r.cms_runtime_fields_v2(fields)) + with self.assertRaises(r.DeployError):r.cms_r39_representation_proof(fields,r.cms_audit_digest(old)) + fields=old_fields();fields['host']['Dns']=['1.1.1.1','8.8.8.8'] + reversed_fields=copy.deepcopy(fields);reversed_fields['host']['Dns'].reverse() + self.assertNotEqual(r.cms_runtime_fields_v2(fields),r.cms_runtime_fields_v2(reversed_fields)) + + def test_ambiguous_binds_and_missing_or_malformed_dns_fail_closed(self): + for binds in [[],None,['a:/a:rw'],['/a:/a:'],['/a:/a:rw','/b:/a:rw'],['/a:/a/../b:rw'],['/a:/a:rw\0']]: + fields=old_fields();fields['host']['Binds']=binds + with self.assertRaises(r.DeployError):r.cms_runtime_fields_v2(fields) + for value in ['',{},False,0,['valid',1]]: + fields=old_fields();fields['host']['Dns']=value + with self.assertRaises(r.DeployError):r.cms_runtime_fields_v2(fields) + fields=old_fields();del fields['host']['Dns'] + with self.assertRaises(r.DeployError):r.cms_runtime_fields_v2(fields) + + def test_three_stable_samples_prove_old_image_and_preserve_original_evidence(self): + before=incident();saved=copy.deepcopy(before) + with patch.object(r,'cms_audit_sample',return_value=changed_sample()),redirect_stdout(io.StringIO()) as output: + result=r.cms_r39_restored_baseline(before) + self.assertEqual(before,saved);self.assertEqual(result['runtimeFingerprintVersion'],2) + self.assertEqual(result['runtime']['configSha256'],r.cms_audit_digest(r.cms_runtime_fields_v2(old_fields()))) + self.assertIn('config.Env',result['runtime']['fieldSha256']) + self.assertNotIn('fixture-never-print',output.getvalue()+json.dumps(result['runtime'])) + for key,value in [('imageId','wrong-image'),('imageRef','wrong-ref')]: + changed=changed_sample();changed['runtime'][key]=value + with patch.object(r,'cms_audit_sample',return_value=changed),self.assertRaises(r.DeployError):r.cms_r39_restored_baseline(before) + other=changed_sample();other['runtime']['id']='another-generation' + with patch.object(r,'cms_audit_sample',side_effect=[changed_sample(),other,changed_sample()]),self.assertRaisesRegex(r.DeployError,'changed during'): + r.cms_r39_restored_baseline(before) + + def test_legacy_acceptance_stays_strict_new_acceptance_uses_version_two(self): + with ExitStack() as stack: + before=self.acceptance(stack) + stack.enter_context(patch.object(r,'cms_runtime_snapshot',return_value=changed_sample()['runtime'])) + with self.assertRaisesRegex(r.DeployError,'environment'):r.accept_cms_release(before,rollback=True) + stack.enter_context(redirect_stdout(io.StringIO())) + restored=r.cms_r39_restored_baseline(before) + r.accept_cms_release(restored,rollback=True) + for version in [True,0,3,'2']: + with self.assertRaisesRegex(r.DeployError,'version mismatch'):r.accept_cms_release({**restored,'runtimeFingerprintVersion':version},rollback=True) + newer=changed_sample();newer['fields']['config']['Env']=['TOKEN=changed'] + with patch.object(r,'cms_audit_sample',return_value=newer),self.assertRaisesRegex(r.DeployError,'config.Env') as error: + r.accept_cms_release(restored,rollback=True) + self.assertNotIn('TOKEN',str(error.exception)) + + def test_preflight_for_new_release_captures_versioned_field_hashes(self): + with ExitStack() as stack: + for name,value in [('require_root',None),('validate_cms_release_payload',{'sourceCommit':'new','runNumber':2}), + ('cms_installed_release',{'sourceCommit':'old','runNumber':0}), + ('cms_application_inventory',({'app':'sha'},{})),('cms_healthchecks',None), + ('cms_foundation',{}),('cms_preserved_data',{}),('cms_other_services',{}), + ('cms_runtime_snapshot_v2',{'fieldSha256':{'config.Env':'sha'}})]: + stack.enter_context(patch.object(r,name,return_value=value)) + legacy=stack.enter_context(patch.object(r,'cms_runtime_snapshot')) + result=r.preflight_cms_release(self.payload,['app'],'new') + self.assertEqual(result['runtimeFingerprintVersion'],2);legacy.assert_not_called() + self.assertEqual(result['runtime']['fieldSha256'],{'config.Env':'sha'}) + + def test_failed_receipt_is_exact_and_cannot_be_relabelled(self): + row=r.cms_r39_failed_row() + with patch.object(r,'load_state',return_value=[row]),patch.object(r,'cms_audit_evidence',return_value={'runtime':{'configSha256':r.CMS_RECON_LEGACY_SHA}}): + self.assertEqual(r.cms_r39_evidence()['runtime']['configSha256'],r.CMS_RECON_LEGACY_SHA) + row['rollback_status']='ok:dc-cms-release' + with self.assertRaises(r.DeployError):r.cms_r39_evidence() + with patch.object(r,'load_state',return_value=[]),patch.object(r,'CMS_ROOT',self.payload): + self.assertFalse(r.cms_r39_reconciled(r.cms_r39_failed_row())) + self.assertFalse(r.cms_r39_reconciled({**r.cms_r39_failed_row(),'id':'other'})) + + def test_source_barrier_requires_separate_canonical_reconciliation(self): + expected={**r.CMS_BASELINE['filesSha256'],**{p:r.CMS_BASELINE['foundationSha256'][p] for p in r.CMS_DEPENDENCY_FILES}} + with ExitStack() as stack: + stack.enter_context(patch.object(r,'load_state',side_effect=lambda path:[r.cms_r39_failed_row()] if path==r.FAILED_STATE_FILE else [])) + stack.enter_context(patch.object(r,'cms_application_inventory',return_value=(expected,{}))) + stack.enter_context(patch.object(r,'cms_foundation')) + proof=stack.enter_context(patch.object(r,'cms_r39_reconciled',return_value=False)) + with self.assertRaisesRegex(r.DeployError,'reconciliation'):r.cms_installed_release() + proof.return_value=True + self.assertEqual(r.cms_installed_release()['sourceCommit'],r.CMS_BASELINE['sourceCommit']) + proof.assert_called_with(r.cms_r39_failed_row()) + + def execute_apply(self, fail=False): + live=self.root/'live';live.mkdir() + for name in ('inbox','applied','failed','backups','state','tmp'):(self.root/name).mkdir() + with ExitStack() as stack: + self.acceptance(stack) + for name,value in [('CMS_ROOT',live),('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'), + ('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'), + ('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'), + ('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'), + ('LOCK_DIR',self.root/'state/deploy.lock')]:stack.enter_context(patch.object(r,name,value)) + stack.enter_context(patch.dict(r.COMPONENTS,{self.manifest['component']:{**r.COMPONENTS[self.manifest['component']],'payload_root':live}})) + for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name)) + def health(): + if fail and (live/r.CMS_RECON_ENTRY).exists():raise r.DeployError('injected post-copy health failure') + stack.enter_context(patch.object(r,'cms_healthchecks',side_effect=health)) + command=stack.enter_context(patch.object(r.subprocess,'run')) + stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO())) + if fail: + with self.assertRaises(r.DeployError):r.apply_artifact(self.artifact) + self.assertFalse((live/r.CMS_RECON_ENTRY).exists()) + self.assertFalse(r.load_state(r.STATE_FILE)) + self.assertEqual(r.load_state(r.FAILED_STATE_FILE)[0]['rollback_status'],'ok:dc-cms-runtime-reconciliation-marker-only') + else: + r.apply_artifact(self.artifact) + self.assertTrue(r.cms_r39_reconciled(r.cms_r39_failed_row())) + row=r.load_state(r.STATE_FILE)[0];archive=r.APPLIED_DIR/row['artifact'] + archive.write_bytes(archive.read_bytes()+b'changed') + with self.assertRaises(r.DeployError):r.cms_r39_reconciled(r.cms_r39_failed_row()) + command.assert_not_called() + + def test_full_apply_proves_restoration_and_requires_archive_receipt_marker(self):self.execute_apply() + def test_failed_apply_rolls_back_marker_without_runtime_mutation(self):self.execute_apply(fail=True) + + +class ReconciledQueueTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.q=DeploymentQueue(Path(self.tmp.name)/'queue.db',first_run_number=1);self.addCleanup(self.q.close) + self.sha='c9d8f0ae59211ce3443300acfea311907508261a' + self.run={'id':39,'run_number':1,'head_sha':self.sha,'run_attempt':1,'status':'completed','conclusion':'success','event':'push','head_branch':'master','path':WORKFLOW} + self.q.observe([self.run],repository=REPOSITORY,repository_id=REPOSITORY_ID) + self.artifact='nodedc-'+r.CMS_AUDIT_FAILED_ID+'.tgz' + self.q.reserve(39,digest=r.CMS_AUDIT_FAILED_SHA,artifact=self.artifact) + self.q.reconcile(39,digest=r.CMS_AUDIT_FAILED_SHA,artifact=self.artifact,outcome='ambiguous',receipt='canonical-rollback-unconfirmed') + self.kw={'digest':r.CMS_AUDIT_FAILED_SHA,'artifact':self.artifact,'receipt':'canonical-reconciled:'+r.CMS_RECON_ID} + + def test_exact_recovery_is_terminal_idempotent_and_not_replayed_on_observe(self): + self.q.reconcile_r39(39,**self.kw);self.q.reconcile_r39(39,**self.kw) + self.assertEqual(self.q.snapshot()[0]['phase'],'failed') + self.q.observe([self.run],repository=REPOSITORY,repository_id=REPOSITORY_ID) + self.assertIsNone(self.q.next_ready()) + with self.assertRaises(QueueError):self.q.reserve(39,digest=r.CMS_AUDIT_FAILED_SHA,artifact=self.artifact) + following={**self.run,'id':40,'run_number':2,'head_sha':'a'*40} + self.q.observe([self.run,following],repository=REPOSITORY,repository_id=REPOSITORY_ID) + self.assertEqual(self.q.next_ready()['id'],40) + self.assertEqual(self.q.snapshot()[0]['phase'],'failed') + + def test_missing_or_wrong_proof_cannot_release_blocked_row(self): + for key,value in [('receipt','canonical-reconciled:other'),('digest','a'*64),('artifact','other.tgz')]: + with self.assertRaises(QueueError):self.q.reconcile_r39(39,**{**self.kw,key:value}) + self.assertEqual(self.q.snapshot()[0]['phase'],'blocked') + with self.assertRaises(QueueError):self.q.reconcile_r39(40,**self.kw) + self.q.db.execute("UPDATE runs SET receipt='different' WHERE id=39") + with self.assertRaises(QueueError):self.q.reconcile_r39(39,**self.kw) + + def test_controller_waits_for_canonical_receipt_then_never_applies_old_release(self): + source=Mock();source.discover.return_value=[self.run] + installer=Mock();installer.receipt.return_value=('ambiguous','canonical-rollback-unconfirmed') + controller=Controller(self.q,source,installer) + with self.assertRaisesRegex(QueueError,'reconciliation_required'):controller.tick() + installer.receipt.return_value=('rolled-back',self.kw['receipt']) + self.assertEqual(controller.tick(),{'status':'waiting'}) + self.assertEqual(self.q.snapshot()[0]['phase'],'failed') + installer.apply.assert_not_called();installer.stage.assert_not_called() + + +if __name__=='__main__':unittest.main() diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index c69cb43..78665cb 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -2962,6 +2962,10 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple( ) COMPONENTS = { + "dc-cms-runtime-reconciliation": { + "payload_root": Path("/volume1/docker/dc-cms/source"), + "artifact_only": True, "services": (), + }, "dc-cms-runtime-audit": { "payload_root": Path("/volume1/docker/dc-cms/source"), "artifact_only": True, "services": (), @@ -5012,6 +5016,9 @@ def denied_payload_path(component, rel): def allowed_payload_path(component, rel): + if component == "dc-cms-runtime-reconciliation": + if rel in ("deployment", CMS_RECON_ENTRY): return True + die("CMS reconciliation accepts only its fixed descriptor") if component == "dc-cms-runtime-audit": if rel in ("deployment", CMS_AUDIT_ENTRY): return True die("CMS runtime audit accepts only its fixed descriptor") @@ -11675,6 +11682,8 @@ def load_artifact(artifact, work_dir): validate_device_priority_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "dc-cms-release": validate_cms_release_payload(payload_dir, entries, manifest["id"]) + if manifest["component"] == "dc-cms-runtime-reconciliation": + validate_cms_reconciliation_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "dc-cms-runtime-audit": validate_cms_audit_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "dc-cms-autodeploy": @@ -22535,6 +22544,9 @@ def is_platform_provider_catalog_only(entries): def component_services(component, entries=None): + if component == "dc-cms-runtime-reconciliation": + if tuple(entries or ()) != (CMS_RECON_ENTRY,): die("CMS reconciliation requires its exact descriptor") + return () if component == "dc-cms-runtime-audit": if tuple(entries or ()) != (CMS_AUDIT_ENTRY,): die("CMS runtime audit requires its exact descriptor") return () @@ -33407,6 +33419,8 @@ def plan_artifact(artifact): print("device_network_priority_delta=core-private:100,manager-private:100;secondary:0") print("device_network_priority_source=accepted-r12;services=none;build=none;runtime-mutation=none") print("device_network_priority_preserved=all-runtime,databases,volumes,ports,secrets;rollback=two-new-files-only") + if manifest["component"] == "dc-cms-runtime-reconciliation": + preflight_cms_reconciliation(payload_dir, entries, manifest["id"]) if manifest["component"] == "dc-cms-runtime-audit": cms_runtime_audit(payload_dir, entries, manifest["id"]) return @@ -39604,6 +39618,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 == "dc-cms-runtime-reconciliation": + if tuple(services or ()) != (): die("CMS reconciliation cannot select services") + preflight_cms_reconciliation(CMS_ROOT, entries, CMS_RECON_ID, marker_installed=True) + return if component in ("dc-cms-release", "dc-cms-autodeploy"): if tuple(services or ()) != component_services(component, entries): die("CMS health service scope mismatch") if component == "dc-cms-release": cms_healthchecks() @@ -40823,6 +40841,8 @@ def apply_artifact(artifact): preflight_device_release_reconciliation(payload_dir, entries, patch_id) if component == "device-core-release": device_release_before = preflight_device_release(payload_dir, entries, patch_id) + if component == "dc-cms-runtime-reconciliation": + preflight_cms_reconciliation(payload_dir, entries, patch_id) if component == "dc-cms-release": cms_release_before = preflight_cms_release(payload_dir, entries, patch_id) if component == "dc-cms-autodeploy": @@ -41633,6 +41653,14 @@ def apply_artifact(artifact): rollback_status = "ok:device-core-network-priority-metadata-only" except Exception as rollback_exc: rollback_status = "failed:" + type(rollback_exc).__name__ + elif component == "dc-cms-runtime-reconciliation": + try: + restore_platform_overlay(root, backup_dir, entries, current_stamp) + if any((root / entry).exists() or (root / entry).is_symlink() for entry in entries): + die("CMS reconciliation rollback left a marker") + rollback_status = "ok:dc-cms-runtime-reconciliation-marker-only" + except Exception as rollback_exc: + rollback_status = "failed:" + type(rollback_exc).__name__ elif component == "dc-cms-release": try: rollback_cms_release(root, backup_dir, entries, current_stamp, cms_release_before, runtime_started) @@ -43023,7 +43051,8 @@ def cms_application_inventory(): def cms_installed_release(): for row in load_state(FAILED_STATE_FILE): - if row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') and not str(row.get('rollback_status','')).startswith('ok:'): + if (row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') + and not str(row.get('rollback_status','')).startswith('ok:') and not cms_r39_reconciled(row)): die('CMS deployment requires failed-rollback reconciliation') rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'dc-cms-release'] if rows: @@ -43103,7 +43132,7 @@ def preflight_cms_release(payload, entries, identity): if not set(installed) <= set(entries):die('CMS v1 release cannot remove existing application files') cms_healthchecks() return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'], - 'runtime':cms_runtime_snapshot(),'otherServices':cms_other_services(), + 'runtimeFingerprintVersion':2,'runtime':cms_runtime_snapshot_v2(),'otherServices':cms_other_services(), 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata} @@ -43142,9 +43171,16 @@ for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){ def accept_cms_release(before, *, rollback=False): cms_healthchecks() - current=cms_runtime_snapshot();old=before['runtime'] + version=before.get('runtimeFingerprintVersion',1) + if type(version) is not int or version not in (1,2):die('CMS runtime fingerprint version mismatch') + current=cms_runtime_snapshot_v2() if version==2 else cms_runtime_snapshot();old=before['runtime'] if current['configSha256'] != old['configSha256'] or current['imageRef'] != old['imageRef']: - die('CMS environment, mounts, ports or network topology changed') + detail='' + if version==2: + previous=old.get('fieldSha256') or {};actual=current.get('fieldSha256') or {} + changed=sorted(k for k in set(previous)|set(actual) if previous.get(k)!=actual.get(k)) + detail='; fields='+','.join(changed) + die('CMS environment, mounts, ports or network topology changed'+detail) expected_image=old['imageId'] if rollback else before['builtImageId'] if current['imageId'] != expected_image or (not rollback and current['id']==old['id']): die('CMS selected service image/generation mismatch') @@ -43798,6 +43834,8 @@ class CmsAutodeployInstaller: return 'ambiguous', 'canonical-archive-or-backup-mismatch' if applied and record.get('status') == 'ok': outcome = 'deployed' + elif failed and cms_r39_reconciled(record): + return 'rolled-back', 'canonical-reconciled:' + CMS_RECON_ID elif failed and record.get('rollback_status') == 'ok:dc-cms-release': outcome = 'rolled-back' else: @@ -44003,6 +44041,148 @@ def cms_runtime_audit(payload, entries, identity): print('cms_runtime_audit_result=diagnostic-only;apply=forbidden;acceptance-barriers=unchanged') return report +# Exact r39 reconciliation; this code is embedded in the root-owned runner. +CMS_RECON_ID = 'dc-cms-r39-runtime-reconciliation-v2-20261104-001' +CMS_RECON_ENTRY = 'deployment/dc-cms-r39-runtime-reconciliation-v2.json' +CMS_RECON_LEGACY_SHA = 'e50d894ff1292c8250b5c1a8eb97d5e4f7f8522a0157fac393b5cf82ced5aa1f' +CMS_DNS_FIELDS = ('Dns','DnsOptions','DnsSearch') + + +def cms_reconciliation_descriptor(): + return {'schemaVersion':'nodedc.dc-cms.runtime-reconciliation.v2','releaseId':CMS_RECON_ID, + 'failedReleaseId':CMS_AUDIT_FAILED_ID,'failedSha256':CMS_AUDIT_FAILED_SHA, + 'backupId':CMS_AUDIT_BACKUP,'backupSha256':CMS_AUDIT_BACKUP_SHA, + 'legacyRuntimeSha256':CMS_RECON_LEGACY_SHA,'runtimeFingerprintVersion':2, + 'mode':'prove-restored-baseline-bind-order-empty-dns-only'} + + +def validate_cms_reconciliation_payload(payload, entries, identity): + if tuple(entries or ())!=(CMS_RECON_ENTRY,) or identity!=CMS_RECON_ID: + die('CMS reconciliation identity/entry mismatch') + marker=payload/CMS_RECON_ENTRY + if marker.is_symlink() or not marker.is_file():die('CMS reconciliation marker is unsafe') + expected=(json.dumps(cms_reconciliation_descriptor(),sort_keys=True,indent=2)+'\n').encode() + if marker.read_bytes()!=expected:die('CMS reconciliation descriptor mismatch') + + +def cms_runtime_fields_v2(fields): + result=json.loads(json.dumps(fields));host=result['host'] + binds=host.get('Binds') + if not isinstance(binds,list) or not 1<=len(binds)<=8: + die('CMS v2 bind list is missing or outside bounds') + targets=[] + for bind in binds: + if not isinstance(bind,str) or '\0' in bind:die('CMS v2 bind is malformed') + parts=bind.split(':') + if len(parts) not in (2,3):die('CMS v2 bind is ambiguous') + for path in parts[:2]: + if not path.startswith('/') or str(PurePosixPath(path))!=path or '..' in PurePosixPath(path).parts: + die('CMS v2 bind path is not canonical') + if len(parts)==3 and not parts[2]:die('CMS v2 bind options are ambiguous') + targets.append(parts[1]) + if len(set(targets))!=len(targets):die('CMS v2 duplicate bind target') + host['Binds']=sorted(binds) + # Docker 24 uses len(...) > 0 for these three settings. Nonempty lists and + # their order are untouched; every other HostConfig field remains exact. + for key in CMS_DNS_FIELDS: + if key not in host:die('CMS v2 DNS field is missing') + value=host[key] + if value is None:host[key]=[] + elif not isinstance(value,list) or any(not isinstance(v,str) for v in value): + die('CMS v2 DNS field is malformed') + return result + + +def cms_runtime_v2_from_sample(sample): + fields=cms_runtime_fields_v2(sample['fields']) + digests={section+'.'+key:cms_audit_digest(value) for section in ('host','config') + for key,value in fields[section].items()} + digests.update({key:cms_audit_digest(fields[key]) for key in ('mounts','networks')}) + return {**sample['runtime'],'configSha256':cms_audit_digest(fields),'fieldSha256':digests} + + +def cms_runtime_snapshot_v2(): + return cms_runtime_v2_from_sample(cms_audit_sample()) + + +def cms_r39_representation_proof(fields, expected): + cms_runtime_fields_v2(fields) # Validate paths and types before enumeration. + if not isinstance(expected,str) or not re.fullmatch('[a-f0-9]{64}',expected): + die('CMS reconciliation predecessor digest is invalid') + if len(fields['host']['Binds'])!=2 or any(fields['host'][k] not in (None,[]) for k in CMS_DNS_FIELDS): + die('CMS r39 proof requires exactly two binds and empty DNS settings') + work=json.loads(json.dumps(fields));checked=0 + for binds in itertools.permutations(fields['host']['Binds']): + work['host']['Binds']=list(binds) + for dns in itertools.product((None,[]),repeat=3): + for key,value in zip(CMS_DNS_FIELDS,dns):work['host'][key]=value + checked+=1 + if cms_audit_digest(work)==expected:return checked + die('CMS runtime differs beyond bind order and empty DNS representation') + + +def cms_r39_failed_row(): + return {'artifact':'nodedc-'+CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125', + 'backup_id':CMS_AUDIT_BACKUP,'component':'dc-cms-release', + 'failed_at':'2026-11-04T19:34:46+00:00','id':CMS_AUDIT_FAILED_ID, + 'message':'CMS environment, mounts, ports or network topology changed', + 'rollback_status':'failed:DeployError','sha256':CMS_AUDIT_FAILED_SHA, + 'started_apply':True,'status':'failed'} + + +def cms_r39_evidence(): + rows=[r for r in load_state(FAILED_STATE_FILE) if r.get('id')==CMS_AUDIT_FAILED_ID or r.get('sha256')==CMS_AUDIT_FAILED_SHA] + if rows!=[cms_r39_failed_row()]:die('CMS reconciliation failed receipt mismatch') + before=cms_audit_evidence() + if before['runtime']['configSha256']!=CMS_RECON_LEGACY_SHA: + die('CMS reconciliation saved runtime digest differs') + return before + + +def cms_r39_restored_baseline(before): + samples=[cms_audit_sample() for _ in range(3)] + if any(sample!=samples[0] for sample in samples):die('CMS runtime changed during reconciliation') + sample=samples[0];old=before['runtime'];runtime=sample['runtime'] + if runtime['imageId']!=old['imageId'] or runtime['imageRef']!=old['imageRef']: + die('CMS reconciliation original image mismatch') + checked=cms_r39_representation_proof(sample['fields'],old['configSha256']) + result=json.loads(json.dumps(before));result['runtimeFingerprintVersion']=2 + result['runtime']=cms_runtime_v2_from_sample(sample) + print('cms_reconciliation_proof=exact-legacy-sha;changed-representation=bind-order,empty-dns;' + 'samples=3;candidates='+str(checked)+';fingerprint=v2') + return result + + +def preflight_cms_reconciliation(payload, entries, identity, *, marker_installed=False): + require_root();validate_cms_reconciliation_payload(payload,entries,identity) + marker=CMS_ROOT/CMS_RECON_ENTRY + if not marker_installed and (marker.exists() or marker.is_symlink()): + die('CMS reconciliation marker already exists') + before=cms_r39_restored_baseline(cms_r39_evidence()) + accept_cms_release(before,rollback=True) + print('cms_reconciliation_accept=restored-baseline-proven;services=none;build=none;runtime-mutation=none') + return before + + +def cms_r39_reconciled(row): + if row!=cms_r39_failed_row():return False + marker=CMS_ROOT/CMS_RECON_ENTRY + records=[r for r in load_state(STATE_FILE) if r.get('id')==CMS_RECON_ID] + if not records: + # During canonical apply the marker may precede its success receipt. + # Neither marker presence nor an in-progress apply grants queue release. + return False + if len(records)!=1 or records[0].get('component')!='dc-cms-runtime-reconciliation' or records[0].get('status')!='ok': + die('CMS reconciliation applied receipt mismatch') + validate_cms_reconciliation_payload(CMS_ROOT,(CMS_RECON_ENTRY,),CMS_RECON_ID) + with tempfile.TemporaryDirectory(prefix='cms-r39-marker-',dir=TMP_DIR) as tmp: + manifest,entries,payload=load_artifact(device_release_applied_archive(records[0]),Path(tmp)) + if manifest.get('component')!='dc-cms-runtime-reconciliation' or manifest.get('id')!=CMS_RECON_ID: + die('CMS reconciliation applied archive identity mismatch') + if sha256_file(payload/CMS_RECON_ENTRY)!=sha256_file(marker):die('CMS reconciliation marker drift') + cms_r39_evidence() + return True + def cms_autodeploy_library(): """Durable release ordering. Pure state policy; no network or runtime authority. @@ -44180,6 +44360,30 @@ def cms_autodeploy_library(): self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.transaction(apply) + def reconcile_r39(self, identity, *, digest, artifact, receipt): + """Exact terminal blocked -> failed recovery after canonical proof. + + This never makes the failed artifact ready again. The caller verifies + the immutable failed evidence and the separate successful recovery. + """ + sha = 'c9d8f0ae59211ce3443300acfea311907508261a' + expected_receipt = 'canonical-reconciled:dc-cms-r39-runtime-reconciliation-v2-20261104-001' + if (type(identity) is not int or identity != 39 + or digest != '3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029' + or artifact != 'nodedc-dc-cms-release-v1-r39-'+sha+'.tgz' + or receipt != expected_receipt): + raise QueueError('r39_reconciliation_identity_mismatch') + def apply(): + row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone() + if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (1,sha,'push','master',WORKFLOW,digest,artifact): + raise QueueError('r39_reconciliation_row_mismatch') + if row['phase'] == 'failed' and row['receipt'] == receipt: + return + if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed': + raise QueueError('r39_reconciliation_predecessor_mismatch') + self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity)) + self.transaction(apply) + def snapshot(self): return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] @@ -44455,6 +44659,13 @@ def cms_autodeploy_library(): def reconcile(self): for row in self.queue.snapshot(): + if row['phase'] == 'blocked': + outcome, receipt = self.installer.receipt(row) + if outcome == 'rolled-back': + self.queue.reconcile_r39(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt) + elif outcome != 'ambiguous': + raise QueueError('blocked_run_requires_exact_recovery') + continue if row['phase'] != 'deploying': continue outcome, receipt = self.installer.receipt(row)