From 3abfce339dd972ec9293534a5d560b79662a135e Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Wed, 4 Nov 2026 22:44:55 +0300 Subject: [PATCH] Register read-only CMS r39 runtime reconciliation audit --- infra/cms-deploy/README.md | 15 +++ infra/cms-deploy/audit_runtime.py | 138 +++++++++++++++++++++ infra/cms-deploy/build_runtime_audit.py | 33 +++++ infra/cms-deploy/embed_runtime.py | 3 +- infra/cms-deploy/runtime-audit-v1.json | 17 +++ infra/cms-deploy/test_runtime_audit.py | 116 ++++++++++++++++++ infra/deploy-runner/nodedc-deploy | 156 ++++++++++++++++++++++++ 7 files changed, 477 insertions(+), 1 deletion(-) create mode 100644 infra/cms-deploy/audit_runtime.py create mode 100644 infra/cms-deploy/build_runtime_audit.py create mode 100644 infra/cms-deploy/runtime-audit-v1.json create mode 100644 infra/cms-deploy/test_runtime_audit.py diff --git a/infra/cms-deploy/README.md b/infra/cms-deploy/README.md index b980160..ab53af6 100644 --- a/infra/cms-deploy/README.md +++ b/infra/cms-deploy/README.md @@ -37,3 +37,18 @@ repository, labels, job, steps, run identity and artifact ownership. Registratio IDs are allocated by Gitea, so no fixed numeric fallback is permitted. This controller correction preserves the accepted bootstrap 002 receipt and private queue; it does not rerun bootstrap or re-register/restart the build daemon. + +Release r39 then reached canonical apply but failed runtime-config acceptance; +its automatic rollback restored the original source and healthy authenticated +CMS, while full runtime equivalence remained unproven. The failed receipt and +controller reconciliation barrier stay intact. `dc-cms-runtime-audit` is a +separate **plan-only** diagnostic domain pinned to that exact incident, archive +and six backup-file hashes. It reads current source/data/image/runtime evidence +and reports a bounded saved-digest preimage search without accepting any drift. +No environment values or raw Docker inspection are printed. `apply` is forbidden; +no application, queue, receipt or service is changed by this audit. Recovery must +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. diff --git a/infra/cms-deploy/audit_runtime.py b/infra/cms-deploy/audit_runtime.py new file mode 100644 index 0000000..4c0dc7d --- /dev/null +++ b/infra/cms-deploy/audit_runtime.py @@ -0,0 +1,138 @@ +# Registered read-only diagnosis. Never normalizes or reconciles production. +CMS_AUDIT_ID = 'dc-cms-r39-runtime-audit-v1-20261104-001' +CMS_AUDIT_ENTRY = 'deployment/dc-cms-r39-runtime-audit-v1.json' +CMS_AUDIT_FAILED_ID = 'dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a' +CMS_AUDIT_FAILED_SHA = '3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029' +CMS_AUDIT_BACKUP = 'dc-cms-release-'+CMS_AUDIT_FAILED_ID+'-20261104-223125' +CMS_AUDIT_BACKUP_SHA = { + 'cms-runtime-before.json':'e14634fc1ef03da8b8a7751d9418b74c52da65dfe6dea82ad9c14ef04634263b', + 'source-before.tgz':'cd35cb27dd4875e13cdf7202ab57c24e7db0a43c473454675fe122ebf23090b1', + 'manifest.env':'ce246952d0ef6cee1f4b22b770108d5c92d671cc7984dc83e136d61f2e607f22', + 'files.txt':'4a696155703c6aa15daf777331847a37cd5e8345e2bb0a6b1fc98515e27988d8', + 'existing-files.txt':'46fa370124d7ed95362666e84372188bdf9d0c2b4c2e0e3d9dbeed42ad571762', + 'missing-files.txt':'c31852f6da115fed68880fcf0aa8a7b4c0d2a7a9cfdae095907e95863bdb2409', +} + + +def cms_audit_descriptor(): + return {'schemaVersion':'nodedc.dc-cms.runtime-audit.v1','auditId':CMS_AUDIT_ID, + 'failedReleaseId':CMS_AUDIT_FAILED_ID,'failedSha256':CMS_AUDIT_FAILED_SHA, + 'backupId':CMS_AUDIT_BACKUP,'backupSha256':CMS_AUDIT_BACKUP_SHA, + 'allowedOperation':'canonical-plan-only','mutation':False} + + +def validate_cms_audit_payload(payload, entries, identity): + if identity!=CMS_AUDIT_ID or tuple(entries)!=(CMS_AUDIT_ENTRY,): + die('CMS runtime audit requires its exact registered identity and descriptor') + expected=(json.dumps(cms_audit_descriptor(),sort_keys=True,indent=2)+'\n').encode() + if (payload/CMS_AUDIT_ENTRY).read_bytes()!=expected: + die('CMS runtime audit descriptor mismatch') + + +def cms_audit_evidence(): + if any(row.get('id')==CMS_AUDIT_FAILED_ID for row in load_state(STATE_FILE)): + die('CMS runtime audit found an unexpected successful receipt') + rows=[row for row in load_state(FAILED_STATE_FILE) if row.get('id')==CMS_AUDIT_FAILED_ID] + if len(rows)!=1:die('CMS runtime audit requires one exact failed receipt') + row=rows[0] + expected={'id':CMS_AUDIT_FAILED_ID,'sha256':CMS_AUDIT_FAILED_SHA,'backup_id':CMS_AUDIT_BACKUP, + 'component':'dc-cms-release','status':'failed','started_apply':True, + 'rollback_status':'failed:DeployError', + 'message':'CMS environment, mounts, ports or network topology changed', + 'artifact':'nodedc-'+CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125'} + if any(row.get(k)!=v for k,v in expected.items()):die('CMS runtime audit incident receipt differs') + archive=FAILED_DIR/expected['artifact'];backup=BACKUPS_DIR/CMS_AUDIT_BACKUP + for path in (archive,backup): + if any(p.is_symlink() for p in (path,*path.parents)):die('CMS runtime audit evidence path is unsafe') + if not archive.is_file() or sha256_file(archive)!=CMS_AUDIT_FAILED_SHA: + die('CMS runtime audit failed archive mismatch') + if collect_exact_files(backup,sorted(CMS_AUDIT_BACKUP_SHA),'CMS runtime audit backup')!=CMS_AUDIT_BACKUP_SHA: + die('CMS runtime audit backup differs') + return read_strict_json(backup/'cms-runtime-before.json','CMS runtime audit predecessor',max_bytes=512*1024) + + +def cms_audit_fields(info): + # Exact preimage of cms_runtime_snapshot; this does not change acceptance. + host=json.loads(json.dumps(info.get('HostConfig') or {})) + for field in ('Mounts','Ulimits'): + if isinstance(host.get(field),list):host[field].sort(key=lambda x:json.dumps(x,sort_keys=True)) + config=info.get('Config') or {} + fields={'host':host,'config':{k:config.get(k) for k in ('Env','User','Cmd','Entrypoint','WorkingDir','ExposedPorts')}, + 'mounts':sorted(info.get('Mounts') or [],key=lambda x:json.dumps(x,sort_keys=True)), + 'networks':sorted((info.get('NetworkSettings') or {}).get('Networks') or {})} + if isinstance(fields['config']['Env'],list):fields['config']['Env'].sort() + return fields + + +def cms_audit_digest(value): + return hashlib.sha256(json.dumps(value,sort_keys=True).encode()).hexdigest() + + +def cms_audit_sample(): + runtime=cms_runtime_snapshot();info=inspect_container(runtime['id']) + fields=cms_audit_fields(info) + if info.get('Image')!=runtime['imageId'] or cms_audit_digest(fields)!=runtime['configSha256']: + die('CMS runtime changed during audit sampling') + return {'runtime':runtime,'fields':fields} + + +def cms_audit_probe(fields, expected, budget=20000): + """Find a saved SHA preimage using observed values only; NEVER accept it.""" + if not isinstance(expected,str) or not re.fullmatch('[a-f0-9]{64}',expected):die('CMS audit expected digest invalid') + current=cms_audit_digest(fields) + result={'expectedSha256':expected,'actualSha256':current,'exactCurrentMatch':current==expected, + 'exactPreimageFound':current==expected,'changedFields':[],'candidatesChecked':1,'searchTruncated':False} + if current==expected:return result + original=json.loads(json.dumps(fields));work=json.loads(json.dumps(fields));lists=[] + for name in ('Binds','Mounts'): + value=original['host'].get(name) + if value is not None: + if not isinstance(value,list) or len(value)>8: + result.update(searchTruncated=True,reason='mount-list-bound');return result + if len({json.dumps(v,sort_keys=True) for v in value})!=len(value): + result.update(searchTruncated=True,reason='duplicate-mounts');return result + lists.append((name,value)) + mode=original['host'].get('NetworkMode') + for alternative in [mode]+[n for n in original['networks'] if n!=mode]: + if alternative!=mode or 'NetworkMode' in original['host']:work['host']['NetworkMode']=alternative + for left in ([None] if lists[0][1] is None else itertools.permutations(lists[0][1])): + if left is not None:work['host'][lists[0][0]]=list(left) + for right in ([None] if lists[1][1] is None else itertools.permutations(lists[1][1])): + if right is not None:work['host'][lists[1][0]]=list(right) + if result['candidatesChecked']>=budget: + result['searchTruncated']=True;return result + result['candidatesChecked']+=1 + if cms_audit_digest(work)==expected: + result['exactPreimageFound']=True + result['changedFields']=['HostConfig.'+k for k in ('Binds','Mounts','NetworkMode') if work['host'].get(k)!=original['host'].get(k)] + if alternative!=mode:result.update(currentNetworkMode=mode,matchingSavedNetworkMode=alternative) + return result + return result + + +def cms_runtime_audit(payload, entries, identity): + require_root();validate_cms_audit_payload(payload,entries,identity);before=cms_audit_evidence() + report={'schemaVersion':'nodedc.dc-cms.runtime-audit-report.v1','mutation':False,'applyAllowed':False, + 'failedReleaseId':CMS_AUDIT_FAILED_ID,'incidentEvidenceExact':True,'checks':{}} + def check(name, fn): + try:report['checks'][name]={'ok':fn() is not False} + except Exception as error:report['checks'][name]={'ok':False,'errorType':type(error).__name__} + check('source',lambda:cms_application_inventory()[0]==before['installedFiles']) + check('metadata',lambda:cms_application_inventory()[1]==before['installedMetadata']) + check('foundation',lambda:cms_foundation()==before['foundation']) + check('siteAndProjectData',lambda:cms_preserved_data()==before['data']) + check('otherServices',lambda:cms_other_services()==before['otherServices']) + check('health',cms_healthchecks) + samples=[cms_audit_sample() for _ in range(3)];sample=samples[0];runtime=sample['runtime'];fields=sample['fields'] + proof=cms_audit_probe(fields,before['runtime']['configSha256']) + proof.update(expectedImageId=before['runtime']['imageId'],actualImageId=runtime['imageId'], + imageMatches=runtime['imageId']==before['runtime']['imageId'], + imageRefMatches=runtime['imageRef']==before['runtime']['imageRef'], + sampleCount=len(samples),samplesStable=all(s==sample for s in samples), + mountCounts={k:len(fields['host'].get(k) or []) for k in ('Binds','Mounts')}, + fieldSha256={section:{k:cms_audit_digest(v) for k,v in fields[section].items()} for section in ('host','config')}) + check('runningImageSource',lambda:cms_image_files(runtime['id'])=={k:v for k,v in before['installedFiles'].items() if k not in CMS_DEPENDENCY_FILES}) + report['runtime']=proof + print('cms_runtime_audit='+json.dumps(report,sort_keys=True,separators=(',',':'))) + print('cms_runtime_audit_result=diagnostic-only;apply=forbidden;acceptance-barriers=unchanged') + return report diff --git a/infra/cms-deploy/build_runtime_audit.py b/infra/cms-deploy/build_runtime_audit.py new file mode 100644 index 0000000..1b52add --- /dev/null +++ b/infra/cms-deploy/build_runtime_audit.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Build the fixed, data-only CMS r39 plan-only audit 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-audit-v1.json' + + +def bundle(): + descriptor=(ROOT/'runtime-audit-v1.json').read_bytes() + identity=json.loads(descriptor)['auditId'] + members={'manifest.env':f'id={identity}\ncomponent=dc-cms-runtime-audit\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/embed_runtime.py b/infra/cms-deploy/embed_runtime.py index 0ed922c..419da81 100644 --- a/infra/cms-deploy/embed_runtime.py +++ b/infra/cms-deploy/embed_runtime.py @@ -15,7 +15,8 @@ def section(): lines=[line for line in (ROOT/file).read_text().splitlines() if not line.startswith('from deployment_queue import ')] library+='\n'.join(' '+line if line else '' for line in lines)+'\n\n' library+=' return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)\n' - return START+release+'\n'+ci+'\n'+auto+'\n'+library+END + audit=(ROOT/'audit_runtime.py').read_text() + return START+release+'\n'+ci+'\n'+auto+'\n'+audit+'\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/runtime-audit-v1.json b/infra/cms-deploy/runtime-audit-v1.json new file mode 100644 index 0000000..f69fcac --- /dev/null +++ b/infra/cms-deploy/runtime-audit-v1.json @@ -0,0 +1,17 @@ +{ + "allowedOperation": "canonical-plan-only", + "auditId": "dc-cms-r39-runtime-audit-v1-20261104-001", + "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", + "mutation": false, + "schemaVersion": "nodedc.dc-cms.runtime-audit.v1" +} diff --git a/infra/cms-deploy/test_runtime_audit.py b/infra/cms-deploy/test_runtime_audit.py new file mode 100644 index 0000000..5843075 --- /dev/null +++ b/infra/cms-deploy/test_runtime_audit.py @@ -0,0 +1,116 @@ +from contextlib import ExitStack,redirect_stdout,redirect_stderr +import copy +import hashlib +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +from test_runner import r +from build_runtime_audit import bundle + + +def fields(): + return {'host':{'Binds':['/host/a:/a:ro','/host/b:/b:rw'],'Mounts':None,'NetworkMode':'cms-edge', + 'PortBindings':{},'ReadonlyRootfs':False}, + 'config':{'Env':['PRIVATE_TOKEN=fixture-never-print'],'Cmd':['npm','run','admin']}, + 'mounts':[],'networks':['cms-edge','other-attached']} + + +class CmsAuditTests(unittest.TestCase): + def test_deterministic_data_only_archive_and_exact_scope(self): + identity,data=bundle();self.assertEqual(data,bundle()[1]) + with tempfile.TemporaryDirectory() as d: + root=Path(d);artifact=root/'audit.tgz';artifact.write_bytes(data);unpack=root/'unpack';unpack.mkdir() + m,e,p=r.load_artifact(artifact,unpack) + self.assertEqual(m['id'],r.CMS_AUDIT_ID);self.assertEqual(tuple(e),(r.CMS_AUDIT_ENTRY,)) + self.assertEqual(r.component_services(m['component'],e),()) + self.assertEqual(r.component_builds(m['component'],e),()) + (p/r.CMS_AUDIT_ENTRY).write_text('{}') + with self.assertRaises(r.DeployError):r.validate_cms_audit_payload(p,e,identity) + for name in ('server/admin-server.mjs','deployment/other.json','.env','deployment/'+r.CMS_AUDIT_ENTRY): + with self.assertRaises(r.DeployError):r.allowed_payload_path('dc-cms-runtime-audit',name) + + def test_apply_refuses_audit_before_any_application_mutation(self): + with tempfile.TemporaryDirectory() as d,ExitStack() as stack: + root=Path(d) + for name in ('inbox','applied','failed','backups','state','tmp'):(root/name).mkdir() + artifact=root/'inbox/audit.tgz';artifact.write_bytes(bundle()[1]) + for key,value in [('INBOX',root/'inbox'),('APPLIED_DIR',root/'applied'),('FAILED_DIR',root/'failed'),('BACKUPS_DIR',root/'backups'),('STATE_DIR',root/'state'),('TMP_DIR',root/'tmp'),('STATE_FILE',root/'state/applied.jsonl'),('FAILED_STATE_FILE',root/'state/failed.jsonl'),('LOCK_DIR',root/'lock')]:stack.enter_context(patch.object(r,key,value)) + for name in ('require_root','ensure_layout','validate_artifact_location'):stack.enter_context(patch.object(r,name)) + changed=stack.enter_context(patch.object(r,'copy_payload_path')) + stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO())) + with self.assertRaisesRegex(r.DeployError,'plan-only'):r.apply_artifact(artifact) + changed.assert_not_called() + + def test_probe_identifies_order_but_does_not_change_or_accept_it(self): + previous=fields();current=copy.deepcopy(previous);current['host']['Binds'].reverse() + original=copy.deepcopy(current);proof=r.cms_audit_probe(current,r.cms_audit_digest(previous)) + self.assertFalse(proof['exactCurrentMatch']);self.assertTrue(proof['exactPreimageFound']) + self.assertEqual(proof['changedFields'],['HostConfig.Binds']);self.assertEqual(current,original) + + def test_probe_reports_attached_network_difference_without_authorizing_it(self): + previous=fields();current=copy.deepcopy(previous);current['host']['NetworkMode']='other-attached' + proof=r.cms_audit_probe(current,r.cms_audit_digest(previous)) + self.assertFalse(proof['exactCurrentMatch']);self.assertTrue(proof['exactPreimageFound']) + self.assertEqual(proof['changedFields'],['HostConfig.NetworkMode']) + + def test_probe_does_not_mask_real_configuration_changes(self): + original=fields() + for section,key,value in [('config','Env',['CHANGED=1']),('config','Cmd',['other']),('host','ReadonlyRootfs',True),('host','PortBindings',{'80/tcp':[{'HostPort':'80'}]})]: + current=copy.deepcopy(original);current[section][key]=value + self.assertFalse(r.cms_audit_probe(current,r.cms_audit_digest(original))['exactPreimageFound']) + + def test_probe_is_bounded(self): + current=fields();current['host']['Binds']=['duplicate','duplicate'] + self.assertTrue(r.cms_audit_probe(current,'a'*64)['searchTruncated']) + current['host']['Binds']=[str(i) for i in range(9)] + self.assertTrue(r.cms_audit_probe(current,'a'*64)['searchTruncated']) + self.assertTrue(r.cms_audit_probe(fields(),'a'*64,budget=1)['searchTruncated']) + + def test_audit_preimage_matches_unchanged_acceptance_fingerprint(self): + info={'Id':'a'*64,'Image':'sha256:old','State':{'Running':True},'HostConfig':{'Binds':['b','a'],'Mounts':[{'Target':'z'},{'Target':'a'}],'Ulimits':[{'Name':'z'},{'Name':'a'}]}, + 'Config':{'Image':'dc-cms-cms-app','Env':['Z=1','A=1'],'Labels':{'com.docker.compose.project':'dc-cms','com.docker.compose.service':'cms-app'}}, + 'Mounts':[],'NetworkSettings':{'Networks':{'cms-edge':{}}}} + with patch.object(r,'compose_service_container_id',return_value=info['Id']),patch.object(r,'inspect_container',return_value=info): + self.assertEqual(r.cms_runtime_snapshot()['configSha256'],r.cms_audit_digest(r.cms_audit_fields(info))) + + def test_report_is_read_only_and_does_not_print_environment_values(self): + runtime={'id':'container','imageId':'old-image','imageRef':'dc-cms-cms-app','configSha256':r.cms_audit_digest(fields())} + sample={'runtime':runtime,'fields':fields()} + before={'runtime':runtime,'installedFiles':{'server/app.mjs':'a'},'installedMetadata':{},'foundation':{},'data':{},'otherServices':{}} + output=io.StringIO() + with ExitStack() as stack: + for name,value in [('require_root',None),('validate_cms_audit_payload',None),('cms_audit_evidence',before),('cms_application_inventory',(before['installedFiles'],{})),('cms_foundation',{}),('cms_preserved_data',{}),('cms_other_services',{}),('cms_healthchecks',None),('cms_audit_sample',sample),('cms_image_files',before['installedFiles'])]:stack.enter_context(patch.object(r,name,return_value=value)) + apply=stack.enter_context(patch.object(r,'copy_payload_path'));run=stack.enter_context(patch.object(r.subprocess,'run')) + stack.enter_context(redirect_stdout(output));report=r.cms_runtime_audit(Path('/unused'),[],r.CMS_AUDIT_ID) + apply.assert_not_called();run.assert_not_called() + self.assertFalse(report['mutation']);self.assertFalse(report['applyAllowed']) + self.assertTrue(all(v['ok'] for v in report['checks'].values())) + self.assertNotIn('fixture-never-print',output.getvalue()) + + def test_incident_evidence_requires_exact_journal_archive_and_backup(self): + with tempfile.TemporaryDirectory() as d,ExitStack() as stack: + root=Path(d).resolve();failed=root/'failed';failed.mkdir();backups=root/'backups';backups.mkdir() + archive=failed/('nodedc-'+r.CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125');archive.write_bytes(b'fixture archive') + digest=hashlib.sha256(archive.read_bytes()).hexdigest();backup=backups/r.CMS_AUDIT_BACKUP;backup.mkdir() + for name in r.CMS_AUDIT_BACKUP_SHA:(backup/name).write_bytes(b'fixture backup') + (backup/'cms-runtime-before.json').write_text('{"fixture": true}') + hashes={name:hashlib.sha256((backup/name).read_bytes()).hexdigest() for name in r.CMS_AUDIT_BACKUP_SHA} + row={'id':r.CMS_AUDIT_FAILED_ID,'sha256':digest,'backup_id':r.CMS_AUDIT_BACKUP,'component':'dc-cms-release', + 'status':'failed','started_apply':True,'rollback_status':'failed:DeployError','artifact':archive.name, + 'message':'CMS environment, mounts, ports or network topology changed'} + for name,value in [('FAILED_DIR',failed),('BACKUPS_DIR',backups),('CMS_AUDIT_FAILED_SHA',digest),('CMS_AUDIT_BACKUP_SHA',hashes)]:stack.enter_context(patch.object(r,name,value)) + stack.enter_context(patch.object(r,'load_state',side_effect=lambda path:[row] if path==r.FAILED_STATE_FILE else [])) + self.assertEqual(r.cms_audit_evidence(),{'fixture':True}) + row['rollback_status']='ok:dc-cms-release' + with self.assertRaisesRegex(r.DeployError,'receipt differs'):r.cms_audit_evidence() + row['rollback_status']='failed:DeployError' + archive.write_bytes(b'changed') + with self.assertRaisesRegex(r.DeployError,'archive mismatch'):r.cms_audit_evidence() + archive.write_bytes(b'fixture archive');(backup/'source-before.tgz').write_bytes(b'changed') + with self.assertRaisesRegex(r.DeployError,'backup differs'):r.cms_audit_evidence() + + +if __name__=='__main__':unittest.main() diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 3656a03..c69cb43 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-audit": { + "payload_root": Path("/volume1/docker/dc-cms/source"), + "artifact_only": True, "services": (), + }, "dc-cms-release": { "payload_root": Path("/volume1/docker/dc-cms/source"), "compose_root": Path("/volume1/docker/dc-cms/source/infra"), @@ -5008,6 +5012,9 @@ def denied_payload_path(component, rel): def allowed_payload_path(component, rel): + if component == "dc-cms-runtime-audit": + if rel in ("deployment", CMS_AUDIT_ENTRY): return True + die("CMS runtime audit accepts only its fixed descriptor") if component == "dc-cms-release": return cms_release_path(rel, directory=True) if component == "dc-cms-autodeploy": @@ -11668,6 +11675,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-audit": + validate_cms_audit_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "dc-cms-autodeploy": validate_cms_autodeploy_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-core-autodeploy": @@ -22526,6 +22535,9 @@ def is_platform_provider_catalog_only(entries): def component_services(component, entries=None): + if component == "dc-cms-runtime-audit": + if tuple(entries or ()) != (CMS_AUDIT_ENTRY,): die("CMS runtime audit requires its exact descriptor") + return () if component == "dc-cms-release": cms_release_entries(entries) return CMS_RELEASE_SERVICES @@ -33395,6 +33407,9 @@ 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-audit": + cms_runtime_audit(payload_dir, entries, manifest["id"]) + return if manifest["component"] == "dc-cms-release": cms_before = preflight_cms_release(payload_dir, entries, manifest["id"]) print("cms_release_source=" + cms_before["descriptor"]["sourceCommit"]) @@ -40751,6 +40766,8 @@ def apply_artifact(artifact): with tempfile.TemporaryDirectory(prefix=f"apply-{current_stamp}-", dir=TMP_DIR) as tmp: work = Path(tmp) manifest, entries, payload_dir = load_artifact(artifact, work) + if manifest["component"] == "dc-cms-runtime-audit": + die("CMS runtime audit is plan-only; apply is forbidden") if manifest["component"] == "device-core-release-drift-audit": die("Device Core drift audit is plan-only; apply is forbidden") if is_gitea_fresh_install_slice( @@ -43847,6 +43864,145 @@ def cms_autodeploy_tick(): +# Registered read-only diagnosis. Never normalizes or reconciles production. +CMS_AUDIT_ID = 'dc-cms-r39-runtime-audit-v1-20261104-001' +CMS_AUDIT_ENTRY = 'deployment/dc-cms-r39-runtime-audit-v1.json' +CMS_AUDIT_FAILED_ID = 'dc-cms-release-v1-r39-c9d8f0ae59211ce3443300acfea311907508261a' +CMS_AUDIT_FAILED_SHA = '3d3ca8ced21aa694d18bbbcf62c93058f2660b3e84aed3292f7e6f21b9d03029' +CMS_AUDIT_BACKUP = 'dc-cms-release-'+CMS_AUDIT_FAILED_ID+'-20261104-223125' +CMS_AUDIT_BACKUP_SHA = { + 'cms-runtime-before.json':'e14634fc1ef03da8b8a7751d9418b74c52da65dfe6dea82ad9c14ef04634263b', + 'source-before.tgz':'cd35cb27dd4875e13cdf7202ab57c24e7db0a43c473454675fe122ebf23090b1', + 'manifest.env':'ce246952d0ef6cee1f4b22b770108d5c92d671cc7984dc83e136d61f2e607f22', + 'files.txt':'4a696155703c6aa15daf777331847a37cd5e8345e2bb0a6b1fc98515e27988d8', + 'existing-files.txt':'46fa370124d7ed95362666e84372188bdf9d0c2b4c2e0e3d9dbeed42ad571762', + 'missing-files.txt':'c31852f6da115fed68880fcf0aa8a7b4c0d2a7a9cfdae095907e95863bdb2409', +} + + +def cms_audit_descriptor(): + return {'schemaVersion':'nodedc.dc-cms.runtime-audit.v1','auditId':CMS_AUDIT_ID, + 'failedReleaseId':CMS_AUDIT_FAILED_ID,'failedSha256':CMS_AUDIT_FAILED_SHA, + 'backupId':CMS_AUDIT_BACKUP,'backupSha256':CMS_AUDIT_BACKUP_SHA, + 'allowedOperation':'canonical-plan-only','mutation':False} + + +def validate_cms_audit_payload(payload, entries, identity): + if identity!=CMS_AUDIT_ID or tuple(entries)!=(CMS_AUDIT_ENTRY,): + die('CMS runtime audit requires its exact registered identity and descriptor') + expected=(json.dumps(cms_audit_descriptor(),sort_keys=True,indent=2)+'\n').encode() + if (payload/CMS_AUDIT_ENTRY).read_bytes()!=expected: + die('CMS runtime audit descriptor mismatch') + + +def cms_audit_evidence(): + if any(row.get('id')==CMS_AUDIT_FAILED_ID for row in load_state(STATE_FILE)): + die('CMS runtime audit found an unexpected successful receipt') + rows=[row for row in load_state(FAILED_STATE_FILE) if row.get('id')==CMS_AUDIT_FAILED_ID] + if len(rows)!=1:die('CMS runtime audit requires one exact failed receipt') + row=rows[0] + expected={'id':CMS_AUDIT_FAILED_ID,'sha256':CMS_AUDIT_FAILED_SHA,'backup_id':CMS_AUDIT_BACKUP, + 'component':'dc-cms-release','status':'failed','started_apply':True, + 'rollback_status':'failed:DeployError', + 'message':'CMS environment, mounts, ports or network topology changed', + 'artifact':'nodedc-'+CMS_AUDIT_FAILED_ID+'.tgz.20261104-223125'} + if any(row.get(k)!=v for k,v in expected.items()):die('CMS runtime audit incident receipt differs') + archive=FAILED_DIR/expected['artifact'];backup=BACKUPS_DIR/CMS_AUDIT_BACKUP + for path in (archive,backup): + if any(p.is_symlink() for p in (path,*path.parents)):die('CMS runtime audit evidence path is unsafe') + if not archive.is_file() or sha256_file(archive)!=CMS_AUDIT_FAILED_SHA: + die('CMS runtime audit failed archive mismatch') + if collect_exact_files(backup,sorted(CMS_AUDIT_BACKUP_SHA),'CMS runtime audit backup')!=CMS_AUDIT_BACKUP_SHA: + die('CMS runtime audit backup differs') + return read_strict_json(backup/'cms-runtime-before.json','CMS runtime audit predecessor',max_bytes=512*1024) + + +def cms_audit_fields(info): + # Exact preimage of cms_runtime_snapshot; this does not change acceptance. + host=json.loads(json.dumps(info.get('HostConfig') or {})) + for field in ('Mounts','Ulimits'): + if isinstance(host.get(field),list):host[field].sort(key=lambda x:json.dumps(x,sort_keys=True)) + config=info.get('Config') or {} + fields={'host':host,'config':{k:config.get(k) for k in ('Env','User','Cmd','Entrypoint','WorkingDir','ExposedPorts')}, + 'mounts':sorted(info.get('Mounts') or [],key=lambda x:json.dumps(x,sort_keys=True)), + 'networks':sorted((info.get('NetworkSettings') or {}).get('Networks') or {})} + if isinstance(fields['config']['Env'],list):fields['config']['Env'].sort() + return fields + + +def cms_audit_digest(value): + return hashlib.sha256(json.dumps(value,sort_keys=True).encode()).hexdigest() + + +def cms_audit_sample(): + runtime=cms_runtime_snapshot();info=inspect_container(runtime['id']) + fields=cms_audit_fields(info) + if info.get('Image')!=runtime['imageId'] or cms_audit_digest(fields)!=runtime['configSha256']: + die('CMS runtime changed during audit sampling') + return {'runtime':runtime,'fields':fields} + + +def cms_audit_probe(fields, expected, budget=20000): + """Find a saved SHA preimage using observed values only; NEVER accept it.""" + if not isinstance(expected,str) or not re.fullmatch('[a-f0-9]{64}',expected):die('CMS audit expected digest invalid') + current=cms_audit_digest(fields) + result={'expectedSha256':expected,'actualSha256':current,'exactCurrentMatch':current==expected, + 'exactPreimageFound':current==expected,'changedFields':[],'candidatesChecked':1,'searchTruncated':False} + if current==expected:return result + original=json.loads(json.dumps(fields));work=json.loads(json.dumps(fields));lists=[] + for name in ('Binds','Mounts'): + value=original['host'].get(name) + if value is not None: + if not isinstance(value,list) or len(value)>8: + result.update(searchTruncated=True,reason='mount-list-bound');return result + if len({json.dumps(v,sort_keys=True) for v in value})!=len(value): + result.update(searchTruncated=True,reason='duplicate-mounts');return result + lists.append((name,value)) + mode=original['host'].get('NetworkMode') + for alternative in [mode]+[n for n in original['networks'] if n!=mode]: + if alternative!=mode or 'NetworkMode' in original['host']:work['host']['NetworkMode']=alternative + for left in ([None] if lists[0][1] is None else itertools.permutations(lists[0][1])): + if left is not None:work['host'][lists[0][0]]=list(left) + for right in ([None] if lists[1][1] is None else itertools.permutations(lists[1][1])): + if right is not None:work['host'][lists[1][0]]=list(right) + if result['candidatesChecked']>=budget: + result['searchTruncated']=True;return result + result['candidatesChecked']+=1 + if cms_audit_digest(work)==expected: + result['exactPreimageFound']=True + result['changedFields']=['HostConfig.'+k for k in ('Binds','Mounts','NetworkMode') if work['host'].get(k)!=original['host'].get(k)] + if alternative!=mode:result.update(currentNetworkMode=mode,matchingSavedNetworkMode=alternative) + return result + return result + + +def cms_runtime_audit(payload, entries, identity): + require_root();validate_cms_audit_payload(payload,entries,identity);before=cms_audit_evidence() + report={'schemaVersion':'nodedc.dc-cms.runtime-audit-report.v1','mutation':False,'applyAllowed':False, + 'failedReleaseId':CMS_AUDIT_FAILED_ID,'incidentEvidenceExact':True,'checks':{}} + def check(name, fn): + try:report['checks'][name]={'ok':fn() is not False} + except Exception as error:report['checks'][name]={'ok':False,'errorType':type(error).__name__} + check('source',lambda:cms_application_inventory()[0]==before['installedFiles']) + check('metadata',lambda:cms_application_inventory()[1]==before['installedMetadata']) + check('foundation',lambda:cms_foundation()==before['foundation']) + check('siteAndProjectData',lambda:cms_preserved_data()==before['data']) + check('otherServices',lambda:cms_other_services()==before['otherServices']) + check('health',cms_healthchecks) + samples=[cms_audit_sample() for _ in range(3)];sample=samples[0];runtime=sample['runtime'];fields=sample['fields'] + proof=cms_audit_probe(fields,before['runtime']['configSha256']) + proof.update(expectedImageId=before['runtime']['imageId'],actualImageId=runtime['imageId'], + imageMatches=runtime['imageId']==before['runtime']['imageId'], + imageRefMatches=runtime['imageRef']==before['runtime']['imageRef'], + sampleCount=len(samples),samplesStable=all(s==sample for s in samples), + mountCounts={k:len(fields['host'].get(k) or []) for k in ('Binds','Mounts')}, + fieldSha256={section:{k:cms_audit_digest(v) for k,v in fields[section].items()} for section in ('host','config')}) + check('runningImageSource',lambda:cms_image_files(runtime['id'])=={k:v for k,v in before['installedFiles'].items() if k not in CMS_DEPENDENCY_FILES}) + report['runtime']=proof + print('cms_runtime_audit='+json.dumps(report,sort_keys=True,separators=(',',':'))) + print('cms_runtime_audit_result=diagnostic-only;apply=forbidden;acceptance-barriers=unchanged') + return report + def cms_autodeploy_library(): """Durable release ordering. Pure state policy; no network or runtime authority.