Files
rust-discovery/deploy/cloud_noop_preflight_evidence.py
2026-11-13 20:08:52 +01:00

130 lines
9.9 KiB
Python

#!/usr/bin/env python3
"""Read only the exact failed b7fbd NoOp and retained native12 history.
No package scan/command, service operation, API/DB write, execution retry,
grant or approval. A saved report does not authorize a future attempt.
"""
import hashlib
import json
import os
from pathlib import Path
import uuid
import cloud_mvp_acceptance as cloud
STATE=cloud.ROOT/'devstate/cloud-apt-recovery/configured-reconcile-runtime'
GRANT='b7fbd250-c382-4d2f-950d-ae6001e4c48e'
NATIVE='6b68c65b-8c0c-4cab-964d-e12a2d7f0626'
ACCEPTANCE='a88d6b10bbf6c36eaa8dee87eb1a381f2becc36297db8df2b4189791b9165506'
PARTIAL='dc3bf3870ea77c12f9291bac712c53ae72194eaec980a8646155a7fb5c0dbe21'
CONFIGURED_PROOF='27f784e135eeaf1403bdfa7f86374dc32ae7ebb9d7e92ca2405e8440a0172b56'
def stored(payload):
import sqlite3
import stat
grant='b7fbd250-c382-4d2f-950d-ae6001e4c48e'
native='6b68c65b-8c0c-4cab-964d-e12a2d7f0626'
base=Path('/var/lib/rmm-apt-transaction')
def read(path,limit=1024*1024):
for parent in path.parents:
metadata=parent.lstat();require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid==0 and metadata.st_mode&0o022==0,'trusted root witness parents')
fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
with os.fdopen(fd,'rb') as stream:
metadata=os.fstat(stream.fileno());require(stat.S_ISREG(metadata.st_mode) and metadata.st_uid==0 and metadata.st_mode&0o022==0
and metadata.st_size<=limit,'bounded retained root witness')
return stream.read()
def witness(path):
require(not path.is_symlink(),'witness symlink')
if not path.exists():return dict(exists=False)
raw=read(path);metadata=path.stat()
return dict(exists=True,sha256=hashlib.sha256(raw).hexdigest(),size=len(raw),inode=metadata.st_ino)
root=Path('/var/lib/rmm-helper/consumption.sqlite')
with sqlite3.connect(root.as_uri()+'?mode=ro',uri=True) as db:
require(db.execute('PRAGMA integrity_check').fetchone()[0]=='ok','retained ledger integrity')
row=db.execute('SELECT c.rowid,c.agent,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?',(grant,)).fetchone()
require(row is not None,'exact existing NoOp row')
rowid,agent,job,attempt,finished,start,outcome=row
require(job==payload['job_id'] and attempt==payload['attempt_id'] and agent==payload['agent_id'],'fixed old NoOp attempt')
saved=json.loads(start);request=saved['request'];permit=json.loads(bytes(request['permit_bytes']))
action=json.loads(bytes(request['job_bytes']))
binding=bool(permit['grant_id']==grant and permit['job_id']==job and permit['attempt_id']==attempt
and request['plan_hash']==payload['plan_sha256'] and action['job_id']==job and action['attempt_id']==attempt
and action['action']['action']=='ensure_package' and action['execution_identity']=='root'
and hashlib.sha256(bytes(request['job_bytes'])).hexdigest()==payload['job_payload_sha256'])
result=json.loads(finished) if finished else None;last=json.loads(outcome) if outcome else None
failed=bool(result==last and result and result['state']=='failed' and result['error_code']=='STATUS_FINGERPRINT'
and result['evidence']['postconditions_passed'] is False
and result['evidence']['effect_armed_ledger_id']=='apt-'+grant+'-'+str(rowid))
ledger=dict(consumed=db.execute('SELECT count(*) FROM consumed').fetchone()[0],unresolved=db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0],
faults=db.execute('SELECT count(*) FROM helper_sync_meta WHERE fault IS NOT NULL').fetchone()[0])
partial=[dict(grant_id=g,proof_sha256=h,proof_hash_valid=hashlib.sha256(raw).hexdigest()==h)
for g,h,raw in db.execute('SELECT grant_id,proof_sha256,proof FROM apt_partial_reconciliations')]
effect=[]
for g,h,raw,oldhash,old in db.execute('SELECT grant_id,proof_sha256,proof,previous_outcome_sha256,previous_outcome FROM apt_effect_reconciliations'):
previous=json.loads(old)
effect.append(dict(grant_id=g,proof_sha256=h,proof_hash_valid=hashlib.sha256(raw).hexdigest()==h,
previous_unknown_hash_valid=hashlib.sha256(old).hexdigest()==oldhash,previous_state=previous['state'],previous_code=previous['error_code']))
native_row=db.execute('SELECT c.rowid,c.job,c.attempt,c.result,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?',(native,)).fetchone()
native_result=json.loads(native_row[3]) if native_row and native_row[3] else None
native_status=dict(rowid=native_row[0],job_id=native_row[1],attempt_id=native_row[2],result=native_result,
result_equals_outcome=bool(native_row[3] and native_row[3]==native_row[4])) if native_row else None
names=('context.json','signed-action.json','expectation.json','baseline.json','launch.json','hook-armed.json',
'native-prechecks.json','sandbox-ready.json','sandbox-result.json','host-reboot-before.json','host-namespaces.json')
locations={};raw_contexts={}
for name,path in (('active',base/'active'),('target_history',base/'history'/grant),('native_history',base/'history'/native)):
require(not path.is_symlink(),'history symlink')
if not path.exists():locations[name]=dict(exists=False);continue
context=json.loads(read(path/'context.json'));raw_contexts[name]=context
files={n:witness(path/n) for n in names}
locations[name]=dict(exists=True,grant_id=context['grant_id'],job_id=context['job_id'],attempt_id=context['attempt_id'],files=files)
targets=[name for name,context in raw_contexts.items() if context['grant_id']==grant]
no_child=bool(binding and failed and targets)
for name in targets:
context=raw_contexts[name];files=locations[name]['files']
no_child=bool(no_child and context['job_id']==job and context['attempt_id']==attempt
and context['job_payload_sha256']==payload['job_payload_sha256'] and context['plan_sha256']==payload['plan_sha256']
and all(not files[n]['exists'] for n in ('launch.json','hook-armed.json','native-prechecks.json','sandbox-ready.json','sandbox-result.json','host-reboot-before.json','host-namespaces.json')))
acceptance=witness(base/'acceptance-rmm-apt-fixture-update-1.1.json')
# Verify that recorded hashes/ownership did not change during this read.
for name,location in locations.items():
if not location['exists']:continue
path=base/'active' if name=='active' else base/'history'/(grant if name=='target_history' else native)
require({n:witness(path/n) for n in names}==location['files'],'retained witness changed during evidence read')
require(witness(base/'acceptance-rmm-apt-fixture-update-1.1.json')==acceptance,'native acceptance changed during evidence read')
return dict(schema_version=1,grant_id=grant,target_binding_verified=binding,root_rowid=rowid,stored_result=result,stored_outcome=last,
result_bytes_equal_outcome=finished==outcome,definitive_status_fingerprint_failure=failed,ledger=ledger,locations=locations,
target_context_locations=targets,verified_no_apt_child_launch=no_child,
active_still_original_native=raw_contexts.get('active',{}).get('grant_id')==native,native12=native_status,
native_acceptance=acceptance,partial_rows=partial,effect_rows=effect,
evidence_kind='retained files and readonly SQLite only; no live package scan')
def main():
os.umask(0o077)
checkpoint=cloud.contract.protected_json(STATE/'cases/ensure_package/checkpoint.json')
job=checkpoint['plan']['jobs'][0];identity=cloud.contract.protected_json(cloud.ROOT/'devstate/remote-vm.json')['identity']
report=cloud.bootstrap.rpc('linux-vm.conf',stored,dict(agent_id=identity['agent_id'],job_id=job['job_id'],attempt_id=job['payload']['attempt_id'],
plan_sha256=checkpoint['plan']['plan_hash'],job_payload_sha256=job['job_payload_hash']))
counts=cloud.bootstrap.rpc('server.conf',cloud.server,dict(kind='gate',tenant_id=cloud.TENANT,agent_id=identity['agent_id']))
result=cloud.Backend().call('jobs.get',dict(tenant_id=cloud.TENANT,job_id=job['job_id']))
path=STATE/('noop-preflight-'+uuid.uuid4().hex+'.json')
cloud.contract.write_private(path,dict(native=report,central_counts=counts,central=result))
cloud.contract.require(report['target_binding_verified'] and report['definitive_status_fingerprint_failure'] and report['root_rowid']==13
and report['result_bytes_equal_outcome'] and report['verified_no_apt_child_launch'] and report['ledger']==dict(consumed=13,unresolved=0,faults=0)
and report['native_acceptance'].get('sha256')==ACCEPTANCE and report['native12']['result']['state']=='succeeded'
and report['native12']['result_equals_outcome'] and report['partial_rows']==[dict(grant_id='31ef5e5e-5dbd-4428-a9a1-cbd15de2f5a0',proof_sha256=PARTIAL,proof_hash_valid=True)]
and report['effect_rows']==[dict(grant_id='33775478-15b0-46ec-b059-44f500dbb0b6',proof_sha256=CONFIGURED_PROOF,proof_hash_valid=True,previous_unknown_hash_valid=True,
previous_state='unknown',previous_code='FIXTURE_UNEXPECTED_REBOOT_REQUIRED')]
and counts['unresolved']==0 and result['state']=='failed' and result['result']['error_code']=='STATUS_FINGERPRINT',
'same failed attempt no-child and retained history not proven; no automatic retry')
print('PASS old b7fbd failed STATUS_FINGERPRINT, Root13/0/fault0, no targetAPTchild launch, native12 acceptance and old31/337 proofs preserved; new UI plan still required')
print('protected_report='+str(path.relative_to(cloud.ROOT)))
if __name__=='__main__':
try:main()
except Exception as error:
print('NOOP_PREFLIGHT_INCOMPLETE:'+(str(error) if isinstance(error,cloud.contract.GuardError) else type(error).__name__))
raise SystemExit(2) from None