Files
rust-discovery/deploy/cloud_reboot_acceptance.py
T
2026-11-13 19:49:12 +01:00

274 lines
27 KiB
Python

#!/usr/bin/env python3
"""LAST Linux-MVP gate: one fixed WebUI-approved Cloud-VM reboot.
Bootstrap changes only the existing General policy/pin and an expiring central
reboot-only scope. Bootstrap never requests a reboot. Unknown means stop, never
retry; finish reads the same job and close restores the original policy/pin.
"""
import argparse
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
import cloud_apt_recovery as apt
cloud=apt.cloud
require=cloud.contract.require
STATE=cloud.ROOT/'devstate/cloud-reboot'
REASON='Explicit final Linux VM dev/test acceptance; reconnect within 180 seconds of the central start reservation'
GATES=('apt_native_update','ensure_package','apply_updates','offline_wait','expired_offline','revoked_before_start','agent_crash','transport_fallback','mcp')
def vm_state(payload):
import sqlite3
root=Path('/var/lib/rmm-agent-remote');helper=Path('/var/lib/rmm-helper')
require(json.loads((root/'identity.json').read_text())['agent_id']==payload['agent_id'],'permanent Cloud identity')
for path,key in ((Path('/usr/local/libexec/rmm-agent-remote'),'agent_sha256'),(Path('/usr/local/libexec/rmm-privileged-helper'),'helper_sha256')):
require(not path.is_symlink() and hashlib.sha256(path.read_bytes()).hexdigest()==payload[key],'qualified current binaries')
require(hashlib.sha256(Path('/etc/systemd/system/rmm-helper-cloud.service').read_bytes()).hexdigest()==payload['general_unit_sha256'],'reviewed General D-Bus service profile with direct reboot syscalls denied')
services={}
for unit in ('rmm-agent-remote.service','rmm-helper-cloud.service','rmm-apt-helper.service'):
raw=subprocess.run(['systemctl','show',unit,'-p','ActiveState','-p','MainPID','-p','UnitFileState'],capture_output=True,check=True,timeout=10).stdout.decode()
services[unit]=dict(line.split('=',1) for line in raw.splitlines())
dropin=Path('/etc/systemd/system/rmm-agent-remote.service.d/30-cloud-root.conf')
require(not dropin.is_symlink() and 'RMM_APT_HELPER_' not in dropin.read_text() and services['rmm-apt-helper.service']['ActiveState']=='inactive','close APT endpoint before final reboot gate')
result=dict(boot_id=Path('/proc/sys/kernel/random/boot_id').read_text().strip(),services=services,root_rows={},database_inodes={})
for path in (root/'journal.sqlite',root/'consumption.sqlite',helper/'consumption.sqlite'):
s=path.stat();result['database_inodes'][str(path)]=[s.st_dev,s.st_ino]
with sqlite3.connect(path.as_uri()+'?mode=ro',uri=True) as db:
require(db.execute('PRAGMA integrity_check').fetchone()[0]=='ok','preserved database integrity')
if path==helper/'consumption.sqlite':
rows=db.execute('SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) ORDER BY grant_id').fetchall()
for row in rows:
serial=[dict(sha256=hashlib.sha256(v).hexdigest(),size=len(v)) if isinstance(v,bytes) else v for v in row]
result['root_rows'][row[0]]=hashlib.sha256(json.dumps(serial,separators=(',',':')).encode()).hexdigest()
result['root_unresolved']=sum(row[5] is None for row in rows)
require(db.execute('SELECT count(*) FROM helper_sync_meta WHERE fault IS NOT NULL').fetchone()[0]==0,'no helper fault')
if payload.get('job_id'):
selected=[r for r in rows if r[3]==payload['job_id'] and r[4]==payload['attempt_id']]
result['selected_root_grants']=[r[0] for r in selected]
row=db.execute('SELECT response FROM helper_sync_decisions WHERE decision_id=(SELECT last_decision FROM helper_sync_meta WHERE id=1)').fetchone()
signed=json.loads(row[0]);decision=json.loads(bytes(signed['decision_bytes']))
result['signed_sync']=dict(decision_id=decision['decision_id'],ready=decision['ready'],helper_ready=decision['helper_ready'],boot_id=decision['boot_id'],
selected=[a for a in decision['attempts'] if a['job_id']==payload['job_id'] and a['attempt_id']==payload['attempt_id']])
elif path==root/'journal.sqlite':
require(db.execute('SELECT count(*) FROM reconcile_meta WHERE fault IS NOT NULL').fetchone()[0]==0,'no agent fault')
result['agent_last_decision']=db.execute('SELECT last_decision FROM reconcile_meta WHERE id=1').fetchone()[0]
if payload.get('job_id'):
result['other_unresolved']=db.execute("SELECT count(*) FROM job_attempts WHERE NOT(job=? AND attempt=?) AND state NOT IN ('succeeded','failed','cancelled','expired')",(payload['job_id'],payload['attempt_id'])).fetchone()[0]
else:result['other_unresolved']=db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0]
config=Path('/etc/rmm-remote/helper-general.json');pin=Path('/etc/rmm-remote/general-helper-proof.json')
result.update(config_sha256=hashlib.sha256(config.read_bytes()).hexdigest(),pin_sha256=hashlib.sha256(pin.read_bytes()).hexdigest(),general_pin=json.loads(pin.read_text()))
return result
def vm_policy(payload):
import fcntl
import sqlite3
os.umask(0o077)
state=Path('/var/lib/rmm-agent-remote');helper=Path('/var/lib/rmm-helper');config=Path('/etc/rmm-remote/helper-general.json');pin=Path('/etc/rmm-remote/general-helper-proof.json')
binary=Path('/usr/local/libexec/rmm-privileged-helper');agent=Path('/usr/local/libexec/rmm-agent-remote')
require(hashlib.sha256(binary.read_bytes()).hexdigest()==payload['helper_sha256'] and hashlib.sha256(agent.read_bytes()).hexdigest()==payload['agent_sha256'],'same qualified runtime')
require(json.loads((state/'identity.json').read_text())['agent_id']==payload['agent_id'],'same permanent identity')
require(not config.is_symlink() and not pin.is_symlink() and hashlib.sha256(config.read_bytes()).hexdigest()==payload['config_sha256'] and hashlib.sha256(pin.read_bytes()).hexdigest()==payload['pin_sha256'],'exact General policy/pin required')
enabled=payload['enabled'];require(type(enabled) is bool,'fixed policy direction')
current=json.loads(config.read_text());require(current['allow_reboot'] is (not enabled),'only one explicit policy transition')
backup=Path('/var/lib/rmm-bootstrap-history')/('cloud-reboot-'+str(uuid.UUID(payload['id']))+('-enable' if enabled else '-restore'));backup.mkdir(mode=0o700)
def create(path,raw,mode=0o600,gid=0):
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
with os.fdopen(fd,'wb') as f:f.write(raw);f.flush();os.fchown(f.fileno(),0,gid);os.fchmod(f.fileno(),mode);os.fsync(f.fileno())
def manifest(path):
result={}
for p in [path,*sorted(path.rglob('*'))]:
s=p.lstat();require(not p.is_symlink() and (p.is_file() or p.is_dir()),'preserved state must be regular')
result[str(p.relative_to(path))]=[s.st_dev,s.st_ino,hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else None]
return result
subprocess.run(['systemctl','stop','rmm-agent-remote.service','rmm-helper-cloud.service'],capture_output=True,check=True,timeout=30)
lock=os.open(helper/'executor.lock',os.O_RDWR|os.O_NOFOLLOW);fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
try:
with sqlite3.connect((helper/'consumption.sqlite').as_uri()+'?mode=ro',uri=True) as db:
require(db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0]==0 and db.execute('SELECT count(*) FROM helper_sync_meta WHERE fault IS NOT NULL').fetchone()[0]==0,'all Root effects closed')
preserved={str(p):manifest(p) for p in (state,helper,Path('/var/lib/rmm-apt-transaction'))}
old_config=config.read_bytes();old_pin=pin.read_bytes()
if enabled:
next_config=dict(current,allow_reboot=True)
else:
original=Path(payload['original_backup'])
require(original.parent==backup.parent and original.name=='cloud-reboot-'+payload['id']+'-enable','same versioned policy origin')
original_raw=(original/'general-before.json').read_bytes();next_config=json.loads(original_raw)
require(next_config==dict(current,allow_reboot=False),'restore only the exact original policy')
for p,name in ((config,'general-before.json'),(pin,'pin-before.json')):
require(p.stat().st_dev==backup.stat().st_dev,'same-filesystem versioned original')
os.rename(p,backup/name)
create(config,json.dumps(next_config).encode() if enabled else original_raw)
output=subprocess.run([str(binary),'--inspect-general-profile'],capture_output=True,check=True,timeout=15,env=dict(os.environ,RMM_HELPER_CONFIG=str(config))).stdout
new_pin=json.loads(output)
require(new_pin['identity']==json.loads(old_pin)['identity'],'helper identity unchanged')
if not enabled:require(new_pin==json.loads((Path(payload['original_backup'])/'pin-before.json').read_text()),'original pin restored')
create(pin,json.dumps(new_pin).encode() if enabled else (Path(payload['original_backup'])/'pin-before.json').read_bytes(),0o640,984)
require(all(manifest(Path(p))==v for p,v in preserved.items()),'journal/ledger/fixture/history bytes and inodes preserved before restart')
report=dict(enabled=enabled,backup=str(backup),preserved_state=True,config_sha256=hashlib.sha256(config.read_bytes()).hexdigest(),pin_sha256=hashlib.sha256(pin.read_bytes()).hexdigest(),general_pin=new_pin,reboot_requested=False)
create(backup/'report.json',json.dumps(report).encode())
finally:fcntl.flock(lock,fcntl.LOCK_UN);os.close(lock)
subprocess.run(['systemctl','start','rmm-helper-cloud.service','rmm-agent-remote.service'],capture_output=True,check=True,timeout=30)
return report
def server_policy(payload):
import datetime as dt
root=Path('/opt/rust-discovery');path=root/'devstate/root-policy/policy.json'
compose=['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml')]
require(subprocess.run(compose+['exec','-T','gateway','printenv','RMM_PROFILE','RMM_DEV_AUTH'],capture_output=True,check=True,timeout=15).stdout.splitlines()==[b'development',b'true'],'actual development gateway only')
raw=path.read_bytes();policy=json.loads(raw);digest=hashlib.sha256(raw).hexdigest()
require(not path.is_symlink() and path.stat().st_uid==10001 and path.stat().st_mode&0o777==0o600,'private root policy')
if payload['action']=='state':return dict(policy_sha256=digest,closed=dt.datetime.fromisoformat(policy['expires_at'])<=dt.datetime.now(dt.timezone.utc))
require(digest==payload['previous_sha256'],'Root policy drift')
if payload['action']=='enable':
require(dt.datetime.fromisoformat(policy['expires_at'])<=dt.datetime.now(dt.timezone.utc),'previous policy must be closed')
updated=payload['policy'];require(len(updated['scopes'])==1,'one final Cloud VM scope')
scope=updated['scopes'][0]
now=dt.datetime.now(dt.timezone.utc)
require(updated['schema_version']==1 and updated['profile']=='development' and now<dt.datetime.fromisoformat(updated['expires_at'])<=now+dt.timedelta(minutes=31),'short development-only reboot policy')
require(set(scope)==set('tenant_id asset_id agent_id enrollment_generation assignment_version principals helper_policy_sha256 acceptance_evidence_id allowed_services allow_root_scripts allow_reboot'.split()),'no extra Root/APT/log scope')
require(scope['allow_reboot'] is True and scope['allow_root_scripts'] is False and scope['allowed_services']==[] and 'apt' not in scope and scope['principals']==['simulated-testprincipal-a'],'reboot only; no script/APT/service authority')
else:
require(payload['action']=='close','fixed policy action');updated=dict(policy,expires_at=dt.datetime.now(dt.timezone.utc).isoformat())
folder=root/'devstate'/('root-policy-bootstrap-reboot-'+str(uuid.UUID(payload['id']))+'-'+payload['action']);folder.mkdir(mode=0o700)
def create(p,data,uid):
fd=os.open(p,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fchown(f.fileno(),uid,uid);os.fsync(f.fileno())
create(folder/'previous-policy.json',raw,0);next_path=path.with_suffix('.reboot-next');create(next_path,json.dumps(updated).encode(),10001);os.replace(next_path,path)
return dict(policy_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),backup=str(folder),closed=payload['action']=='close',approvals_created=False)
def server_boot_evidence(payload):
root=Path('/opt/rust-discovery');tenant=str(uuid.UUID(payload['tenant_id']));agent=str(uuid.UUID(payload['agent_id']))
job=str(uuid.UUID(payload['job_id']));receipt=str(uuid.UUID(payload['inventory_message_id']))
query=("SELECT json_build_object('new_boot_id',a.connection_boot_id,'generation',a.connection_generation,'sync_ready',a.sync_ready,'helper_ready',a.helper_sync_ready,"
"'restore_blocked',a.restore_blocked,'last_authenticated_at',a.last_authenticated_at,'grant_id',p.grant_id,'reserved_at',p.created_at,"
"'original_boot_id',(SELECT data->>'boot_id' FROM audit_events WHERE tenant_id=a.tenant_id AND event_type='start_reserved' AND data->>'job_id'='"+job+"' AND data->>'grant_id'=p.grant_id::text),"
"'inventory_message_id',o.message_id,'inventory_boot_id',o.boot_id,'inventory_received_at',o.received_at) FROM agent_installations a "
"JOIN execution_permits p ON p.tenant_id=a.tenant_id AND p.job_id='"+job+"' JOIN observations o ON o.tenant_id=a.tenant_id AND o.agent_id=a.agent_id AND o.message_id='"+receipt+"' "
"WHERE a.tenant_id='"+tenant+"' AND a.agent_id='"+agent+"';")
cmd=['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml'),'exec','-T','postgres','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm']
raw=subprocess.run(cmd,input=query.encode(),capture_output=True,check=True,timeout=15).stdout.strip();require(raw,'bound authenticated reboot/inventory evidence required')
return json.loads(raw)
def prerequisites(path,target):
m=cloud.contract;manifest=m.protected_json(Path(path));require(manifest['schema_version']==1 and manifest['target']==target and set(manifest['checks'])==set(GATES),'all earlier MVP gates for this permanent target')
selected={}
for name,item in manifest['checks'].items():
p=Path(item['path']).resolve();require(p.is_relative_to(cloud.ROOT/'devstate') and hashlib.sha256(p.read_bytes()).hexdigest()==item['sha256'],'exact protected native gate witness')
data=m.protected_json(p);require(data.get('verified') is True,'native gate not verified');selected[name]=data
for name in ('apt_native_update','ensure_package','apply_updates'):
result=selected[name]['result'];proof=result['result']['evidence']['apt']
require(result['state']=='succeeded' and proof['packages']==[dict(name='rmm-mvp-test',architecture='all',version='1.1')] and proof['fixture_payload_sha256']==hashlib.sha256(b'1.1\n').hexdigest(),'earlier approved stored fixture1.1 postcondition; no SSH package scan')
return dict(path=str(Path(path).resolve()),sha256=hashlib.sha256(Path(path).read_bytes()).hexdigest(),checks=manifest['checks'])
def fixed():
installed=cloud.contract.protected_json(cloud.ROOT/'devstate/remote-vm.json');runtime,_=apt.runtime_session()
return dict(tenant_id=cloud.TENANT,**installed['identity']),dict(agent_id=installed['identity']['agent_id'],agent_sha256=installed['binary_sha256'],helper_sha256=runtime['helper_sha256'],general_unit_sha256=hashlib.sha256((cloud.ROOT/'deploy/linux/rmm-helper-cloud.service').read_bytes()).hexdigest())
def evidence(target,kind,**extra):return cloud.bootstrap.rpc('server.conf',cloud.server,dict(kind=kind,tenant_id=target['tenant_id'],agent_id=target['agent_id'],**extra))
def browser(path):
cloud.prepare_browser();result=subprocess.run(['node',str(cloud.ROOT/'deploy/browser/cloud_reboot_acceptance.cjs'),str(path)],capture_output=True,timeout=120)
require(result.returncode==0,'actual reboot UI incomplete; retain fixed checkpoint, never repeat approval')
def enable(path):
m=cloud.contract;target,pins=fixed();gates=prerequisites(path,target)
require(evidence(target,'gate')['unresolved']==0,'no earlier unresolved work')
old=cloud.bootstrap.rpc('server.conf',server_policy,dict(action='state'));require(old['closed'],'all earlier Root scopes must be closed')
before=cloud.bootstrap.rpc('linux-vm.conf',vm_state,pins)
require(before['root_unresolved']==before['other_unresolved']==0,'healthy fully reconciled runtime')
for name in ('rmm-agent-remote.service','rmm-helper-cloud.service'):
require(before['services'][name]['ActiveState']=='active' and before['services'][name]['UnitFileState']=='enabled','agent and General helper must already autostart after boot')
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
session=dict(id=ident,target=target,pins=pins,prerequisites=gates,before=before,old_boot_id=before['boot_id'])
m.write_private(folder/'before.json',session)
changed=cloud.bootstrap.rpc('linux-vm.conf',vm_policy,dict(pins,id=ident,enabled=True,config_sha256=before['config_sha256'],pin_sha256=before['pin_sha256']))
m.write_private(folder/'helper-enabled.json',changed)
scope={k:changed['general_pin']['identity'][k] for k in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')}
scope.update(principals=['simulated-testprincipal-a'],helper_policy_sha256=changed['general_pin']['policy_sha256'],acceptance_evidence_id='final-cloud-reboot:'+ident,allowed_services=[],allow_root_scripts=False,allow_reboot=True)
policy=dict(schema_version=1,profile='development',expires_at=(m.now()+dt.timedelta(minutes=30)).isoformat(),scopes=[scope])
opened=cloud.bootstrap.rpc('server.conf',server_policy,dict(id=ident,action='enable',previous_sha256=old['policy_sha256'],policy=policy))
m.write_private(folder/'policy-open.json',dict(opened,policy=policy));print(dict(id=ident,reboot_requested=False,reboot_only_limits_enabled=True))
def accept(ident):
m=cloud.contract;folder=STATE/str(uuid.UUID(ident));session=m.protected_json(folder/'before.json');target=session['target'];pins=session['pins']
prerequisites(session['prerequisites']['path'],target)
require(not (folder/'prepare.json').exists() and evidence(target,'gate')['unresolved']==0,'one new fixed attempt only')
deadline=time.monotonic()+100
while True:
device=cloud.Backend().call('inventory.get_device',{k:target[k] for k in ('tenant_id','asset_id')})
if device['presence']=='online' and {'reboot','root:reboot'}<=set(device['capabilities']):break
require(time.monotonic()<deadline,'fresh measured reboot capability unavailable');time.sleep(2)
current=cloud.bootstrap.rpc('linux-vm.conf',vm_state,pins);require(current['boot_id']==session['old_boot_id'] and current['root_unresolved']==0,'preapproval originalboot and closedeffects')
start=dt.datetime.fromtimestamp((int(time.time())//60+1)*60,dt.timezone.utc)
request=dict(tenant_id=target['tenant_id'],action='reboot',targets=dict(asset_ids=[target['asset_id']]),parameters=dict(reason=REASON,dependency_group='single-test-vm',reconnect_timeout_seconds=180,execution_identity='root',timeout_seconds=240,max_output_bytes=65536),schedule=m.schedule(start,start+dt.timedelta(minutes=10)),rollout=dict(max_parallel=1,halt_after_failures=1),reason=REASON)
common=dict(profile='dev/test',case='reboot_last',expected_principal='simulated-testprincipal-a',**target,id=ident,old_boot_id=session['old_boot_id'])
m.write_private(folder/'prepare.json',dict(common,phase='prepare',request=request,output_file=str(folder/'prepared.json')));browser(folder/'prepare.json')
prepared=m.protected_json(folder/'prepared.json');plan=prepared['plan'];operation=prepared['operation'];require(len(plan['jobs'])==1 and hashlib.sha256(bytes(plan['plan_payload_bytes'])).hexdigest()==plan['plan_hash'],'immutable single reboot plan')
job=plan['jobs'][0];stored=cloud.Backend().call('jobs.get',dict(tenant_id=target['tenant_id'],operation_id=operation['operation_id']));counts=evidence(target,'gate',job_id=job['job_id'])
require(stored['approval_state']=='pending_approval' and stored['job_count']==0 and stored['execution_state'] is None and all(counts[k]==0 for k in ('jobs','outbox','permits')),'real pending0/0/0')
checkpoint=dict(common,plan=plan,job=job,request=request,operation_id=operation['operation_id'],preapproval=counts,stage='pending_approval');m.write_private(folder/'checkpoint.json',checkpoint)
now=cloud.bootstrap.rpc('linux-vm.conf',vm_state,pins);enabled=m.protected_json(folder/'helper-enabled.json')
require(now['boot_id']==session['old_boot_id'] and now['root_unresolved']==0 and now['root_rows']==session['before']['root_rows'] and now['config_sha256']==enabled['config_sha256'] and now['pin_sha256']==enabled['pin_sha256'],'no boot/effect/policy change before actual UI approval')
m.write_private(folder/'approve.json',dict(checkpoint,phase='approve'));browser(folder/'approve.json');finish(ident)
def finish(ident):
m=cloud.contract;folder=STATE/str(uuid.UUID(ident));session=m.protected_json(folder/'before.json');checkpoint=m.protected_json(folder/'checkpoint.json');target=session['target'];job=checkpoint['job'];deadline=time.monotonic()+420
while True:
result=cloud.Backend().call('jobs.get',dict(tenant_id=target['tenant_id'],job_id=job['job_id']))
if result['state'] in m.TERMINAL:break
# awaiting_reboot / unknown remain fenced while the SAME attempt's
# normal outgoing reconnect/inventory/signed Sync can prove completion.
require(time.monotonic()<deadline,'reboot unproven; preserve unknown and do not repeat');time.sleep(3)
require(result['state']=='succeeded','single reboot did not prove success; no retry')
post=result['result']['evidence'];require(post['postconditions_passed'] is True and post['reconciled_after_reboot'] is True and post['new_boot_id']!=session['old_boot_id'],'actual newboot postcondition')
central=cloud.bootstrap.rpc('server.conf',server_boot_evidence,dict(target,job_id=job['job_id'],inventory_message_id=post['inventory_message_id']))
require(central['new_boot_id']==central['inventory_boot_id']==post['new_boot_id'] and central['original_boot_id']==session['old_boot_id'] and central['sync_ready'] and central['helper_ready'] and not central['restore_blocked'],'actual outgoing authenticated currentboot, persisted inventory and fresh signed Sync')
reserved=m.timestamp(central['reserved_at']);received=m.timestamp(central['inventory_received_at'])
require(reserved<received<=reserved+dt.timedelta(seconds=180) and m.timestamp(post['reboot_reserved_at'])==reserved and m.timestamp(post['reconnect_deadline'])==reserved+dt.timedelta(seconds=180),'original central deadline and timely independent receipt')
native=cloud.bootstrap.rpc('linux-vm.conf',vm_state,dict(session['pins'],job_id=job['job_id'],attempt_id=job['attempt_id']))
sync=native['signed_sync'];require(native['boot_id']==post['new_boot_id'] and native['root_unresolved']==native['other_unresolved']==0 and native['database_inodes']==session['before']['database_inodes'] and len(native['root_rows'])==len(session['before']['root_rows'])+1 and all(native['root_rows'].get(k)==v for k,v in session['before']['root_rows'].items()),'preserved oldledgers/inodes and closedexactreboot')
require(sync['ready'] and sync['helper_ready'] and sync['boot_id']==post['new_boot_id'] and native['agent_last_decision']==sync['decision_id'] and len(native['selected_root_grants'])==1 and native['selected_root_grants']==[result['result']['grant_id']],'same consumed grant and applied normal signed Sync')
require(len(sync['selected'])==1 and sync['selected'][0]['grant_id']==result['result']['grant_id'] and sync['selected'][0]['outcome_state']=='succeeded','same signed reboot result')
counts=evidence(target,'gate',job_id=job['job_id']);audit=evidence(target,'audit',operation_id=checkpoint['operation_id'])
require([counts[k] for k in ('jobs','outbox','permits')]==[1,1,1] and audit==dict(origin='dev_test_browser_simulation',simulation=True,principal='simulated-testprincipal-a',plan_hash=checkpoint['plan']['plan_hash']),'one actual simulated UI approval and one job/outbox/grant')
m.write_private(folder/'result.json',dict(verified=True,result=result,central=central,native=native,postapproval=counts,audit=audit));print(dict(verified=True,single_native_reboot=True,new_boot_proven=True,old_state_preserved=True,id=ident))
def close(ident):
m=cloud.contract;folder=STATE/str(uuid.UUID(ident));require(m.protected_json(folder/'result.json')['verified'],'normal verified reconnect required before rollback')
session=m.protected_json(folder/'before.json');target=session['target'];opened=m.protected_json(folder/'policy-open.json');enabled=m.protected_json(folder/'helper-enabled.json')
require(evidence(target,'gate')['unresolved']==0,'all effects closed')
closed=cloud.bootstrap.rpc('server.conf',server_policy,dict(id=ident,action='close',previous_sha256=opened['policy_sha256']))
m.write_private(folder/'policy-closed.json',closed)
restored=cloud.bootstrap.rpc('linux-vm.conf',vm_policy,dict(session['pins'],id=ident,enabled=False,config_sha256=enabled['config_sha256'],pin_sha256=enabled['pin_sha256'],original_backup=enabled['backup']))
require(restored['general_pin']==session['before']['general_pin'] and restored['config_sha256']==session['before']['config_sha256'] and restored['pin_sha256']==session['before']['pin_sha256'] and restored['preserved_state'] and not restored['reboot_requested'],'original non-reboot policy/pin bytes restored without another reboot')
m.write_private(folder/'closed.json',dict(verified=True,policy=closed,helper=restored));print('Final reboot limits closed; exact original General policy/pin restored; no second reboot')
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('enable','accept','finish','close'));parser.add_argument('--id');parser.add_argument('--prerequisites');args=parser.parse_args();os.umask(0o077)
if args.action=='enable':require(args.prerequisites,'explicit completed native prerequisite manifest required');enable(args.prerequisites)
else:require(args.id,'one existing bound reboot session required');{'accept':accept,'finish':finish,'close':close}[args.action](args.id)
if __name__=='__main__':
try:main()
except Exception as error:
message=str(error);print(message if message.startswith('remote bootstrap incomplete: ') else 'CLOUD_REBOOT_INCOMPLETE:'+type(error).__name__)
raise SystemExit(2) from None