Prove CMS r39 restoration and version runtime fingerprints

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 23:21:52 +03:00
parent 3abfce339d
commit 0998d76428
12 changed files with 779 additions and 9 deletions
+215 -4
View File
@@ -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)