139 lines
8.7 KiB
Python
139 lines
8.7 KiB
Python
# 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
|