#!/usr/bin/env python3 """Passive Windows auto-WSS→HTTPS with two exact authenticated rejections. Reuses the qualified Windows preservation primitive and existing dev/test server fault. No job, direct approval, new identity or guest reboot exists here. """ import argparse import datetime as dt import hashlib import json import os from pathlib import Path import time import uuid import transport_acceptance as base import cloud_transport_acceptance as fault cloud = base.cloud require = base.require STATE = base.cb.EVIDENCE/'auto-transport' PRIOR_CASE = '697b19ba-e7ff-4ebf-8a45-f5a0b0514fea' def server_state(payload): """Only fixed nonsecret flags and known file hashes; no complete env.""" root = Path('/opt/rust-discovery'); compose = root/'deploy/server.compose.yaml' selected = root/'devstate/root-policy/transport-fault.json' require(not compose.is_symlink() and not selected.is_symlink(), 'fixed transport metadata paths') command = ['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(compose)] flags = ('RMM_PROFILE','RMM_DEV_AUTH','RMM_DEV_TRANSPORT_FAULTS','RMM_DEV_TRANSPORT_FAULT_FILE') roles = {} for role in ('api','gateway'): identifier = subprocess.run(command+['ps','-q',role],capture_output=True,check=True,timeout=10).stdout.decode().strip() require(len(identifier) == 64 and all(c in '0123456789abcdef' for c in identifier), 'one running application role') values = {} for flag in flags: response = subprocess.run(['docker','exec',identifier,'printenv',flag],capture_output=True,timeout=10) require(response.returncode in (0,1) and len(response.stdout) <= 1024, 'bounded explicit nonsecret flag') values[flag] = response.stdout.decode().strip() if response.returncode == 0 else None roles[role] = values policy = root/'devstate/root-policy/policy.json' require(not policy.is_symlink(), 'known Root policy path') return dict(compose_sha256=hashlib.sha256(compose.read_bytes()).hexdigest(), fault_config_sha256=hashlib.sha256(selected.read_bytes()).hexdigest() if selected.exists() else None, root_policy_sha256=hashlib.sha256(policy.read_bytes()).hexdigest(),roles=roles) def flags_disabled(value): return len(value['roles']) == 2 and all( role['RMM_PROFILE'] == 'development' and role['RMM_DEV_AUTH'] == 'true' and role['RMM_DEV_TRANSPORT_FAULTS'] in (None,'false') and role['RMM_DEV_TRANSPORT_FAULT_FILE'] is None for role in value['roles'].values()) def flags_enabled(value): return len(value['roles']) == 2 and all( role['RMM_PROFILE'] == 'development' and role['RMM_DEV_AUTH'] == 'true' and role['RMM_DEV_TRANSPORT_FAULTS'] == 'true' and role['RMM_DEV_TRANSPORT_FAULT_FILE'] == '/root-policy/transport-fault.json' for role in value['roles'].values()) def scopes(): linux = base.cb.contract.protected_json(cloud.ROOT/'devstate/cloud-mvp-final-closeout.json') require(linux['verified'] is True, 'qualified Linux target witness') return dict(windows=base.gate(),linux=cloud.bootstrap.rpc('server.conf',cloud.server, dict(kind='gate',tenant_id=linux['target']['tenant_id'],agent_id=linux['target']['agent_id']))) def status(): return cloud.bootstrap.rpc('server.conf',server_state,{}) def observe(ident): return cloud.bootstrap.rpc('server.conf',fault.server_evidence, dict(tenant_id=cloud.TENANT,agent_id=base.AGENT,fault_id=ident)) def validate_receipts(value, config, config_sha, baseline): receipts = value['receipts']; device = value['device'] require(len(receipts) == 2 and {r['data']['slot'] for r in receipts} == {1,2} and len({r['data']['handshake_id'] for r in receipts}) == 2, 'two distinct actual authenticated WSS rejections') require(all(r['data']['status'] == 503 and r['data']['agent_id'] == base.AGENT and r['data']['tenant_id'] == cloud.TENANT and r['data']['fault_id'] == config['fault_id'] and r['data']['config_sha256'] == config_sha and r['data']['testsimulation'] is True and r['data']['certificate_sha256'] == baseline['certificate_sha256'] for r in receipts), 'same exact dev/test fault, original authenticated device and configuration') require(all(device[k] == baseline[k] for k in ('agent_id','asset_id','enrollment_generation','assignment_version','certificate_sha256')), 'same retained Windows identity and assignment') require(device['transport'] == 'https' and device['last_contact_at'] and base.cb.contract.timestamp(device['last_contact_at']) > max(base.cb.contract.timestamp(r['created_at']) for r in receipts), 'actual HTTPS heartbeat after both WSS rejections') def wait_fallback(ident, config, digest, baseline): deadline = time.monotonic()+150; first = None while True: observed = observe(ident) device = observed.get('device') or {} if (len(observed['receipts']) == 2 and device.get('transport') == 'https' and device.get('last_contact_at') and base.cb.contract.timestamp(device['last_contact_at']) > max(base.cb.contract.timestamp(r['created_at']) for r in observed['receipts'])): validate_receipts(observed,config,digest,baseline) if first is None: first = observed elif first['device']['last_contact_at'] != observed['device']['last_contact_at']: return dict(first=first,second=observed) require(time.monotonic() < deadline, 'two actual WSS503 and two fresh HTTPS heartbeats not proven') time.sleep(2) def prior_hash(): folder = cloud.ROOT/'devstate/cloud-transport'/PRIOR_CASE complete = base.cb.contract.protected_json(folder/'completion.json') previous = base.cb.contract.protected_json(folder/'checkpoint.json') require(complete['verified'] is True and previous['id'] == PRIOR_CASE and previous['disabled']['deployed'] and previous['disabled']['enabled'] is False, 'actual closed historical Linux fault witness') raw = json.dumps(previous['config'],separators=(',',':')).encode() digest = hashlib.sha256(raw).hexdigest() require(digest == previous['disabled']['config_sha256'] == previous['enabled']['config_sha256'], 'independently known original fault configuration; never adopt a host hash') return digest def cleanup(folder, intent, before): ident = intent['id']; current = status() require(current['compose_sha256'] == before['server']['compose_sha256'] and current['root_policy_sha256'] == before['server']['root_policy_sha256'], 'application config and closed Root policy unchanged') if (folder/'enable-intent.json').exists(): base.fixed_intent(folder,'disable-intent.json',dict(id=ident,known_hashes=[intent['config_sha256'],before['server']['fault_config_sha256']])) if not flags_disabled(current): closed = cloud.bootstrap.rpc('server.conf',fault.configure_server,dict( id=str(uuid.uuid4()),enabled=False,tenant_id=cloud.TENANT,agent_id=base.AGENT, compose_sha256=intent['compose_sha256'], expected_config_sha256=[intent['config_sha256'],before['server']['fault_config_sha256']])) base.save(folder,'disabled-'+str(uuid.uuid4())+'.json',closed) require(closed['deployed'], 'server fault disable must finish') actual = status() require(flags_disabled(actual) and actual['fault_config_sha256'] in (intent['config_sha256'],before['server']['fault_config_sha256']), 'both actual application fault hooks disabled') base.save(folder,'disabled-readback-'+str(uuid.uuid4())+'.json',actual) base.fixed_intent(folder,'restore-intent.json',dict(id=ident,expected_original_config_sha256=base.ORIGINAL_CONFIG)) native = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']) base.preserved(before['native'],native) if not (native['transport'] == 'wss' and native['config_sha256'] == base.ORIGINAL_CONFIG and native['config_acl_sha256'] == before['native']['config_acl_sha256'] and native['service_state'] == 'Running'): restored = base.remote(ident,'restore',mode='auto',source_sha256=intent['source_sha256']) else: restored = dict(restored_by_readback=True,snapshot=native,no_jobs=True,no_reboot=True) base.save(folder,'restored-'+str(uuid.uuid4())+'.json',restored) def finish(ident): folder = STATE/str(uuid.UUID(ident)); intent = base.cb.contract.protected_json(folder/'intent.json') before = base.cb.contract.protected_json(folder/'before.json') require(intent['id'] == ident and intent['case'] == 'automatic_fallback' and intent['source_sha256'] == hashlib.sha256(base.SCRIPT.encode()).hexdigest(), 'same qualified passive Windows case') require(not (folder/'result.json').exists(), 'retain completed original acceptance') accepted = folder/'https-accepted.json' try: if not accepted.exists(): native = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']) base.preserved(before['native'],native) require(native['transport'] == 'auto', 'automatic mode must have been selected before fault') if not (folder/'enable-intent.json').exists(): initial = base.wait_mode(ident,'wss',base.cb.contract.timestamp(intent['started_at']),before['central']['device']) base.save(folder,'initial-auto-wss.json',initial) require(base.cb.contract.now() < base.cb.contract.timestamp(intent['config']['expires_at']), 'fixed bounded fault lease') call = dict(id=ident,enabled=True,tenant_id=cloud.TENANT,agent_id=base.AGENT, compose_sha256=intent['compose_sha256'],expected_config_sha256=before['server']['fault_config_sha256'],config=intent['config']) base.save(folder,'enable-intent.json',call) enabled = cloud.bootstrap.rpc('server.conf',fault.configure_server,call) base.save(folder,'enabled.json',enabled);require(enabled['deployed'], 'bounded server fault activation incomplete') else: actual = status() require(flags_enabled(actual) and actual['fault_config_sha256'] == intent['config_sha256'], 'resume only an already active exact fault; never repeat activation') online = wait_fallback(ident,intent['config'],intent['config_sha256'],before['central']['device']) native = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']);base.preserved(before['native'],native) require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > before['native']['journal']['sequence'] and native['service_state'] == 'Running' and native['process_owner_sid'] == 'S-1-5-19', 'actual ACK, monotone journal and LocalService') inventory = base.read_device(); denied = base.foreign_denied() require(scopes() == before['counts'], 'no new jobs/grants on Windows or permanent Linux target') base.save(folder,'https-accepted.json',dict(verified=True,online=online,native=native,inventory=inventory,foreign_denied=denied)) else: require(base.cb.contract.protected_json(accepted)['verified'] is True, 'retained actual fallback proof') finally: cleanup(folder,intent,before) restored = base.wait_mode(ident,'wss',base.cb.contract.now(),before['central']['device']) native = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']);base.preserved(before['native'],native) require(native['config_sha256'] == base.ORIGINAL_CONFIG and native['config_acl_sha256'] == before['native']['config_acl_sha256'] and native['journal']['pending_inventory_events'] == 0 and scopes() == before['counts'], 'restored exact WSS config/ACL/ACK and both targets unchanged') final = status();require(flags_disabled(final), 'no active transport hook remains') base.save(folder,'result.json',dict(verified=True,id=ident,case='automatic_fallback',https=base.cb.contract.protected_json(accepted), restored_wss=restored,final_native=native,server=final,counts=before['counts'],no_jobs_or_approvals=True,no_reboot=True, automatic_switchback_claimed=False)) print('PASS native Windows auto WSS→HTTPS: two authenticated503, fresh HTTPS heartbeats/ACK, same identity, both hooks disabled, original WSS config/ACL restored, zero new jobs') def start(https_case): os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True) prerequisite = base.STATE/str(uuid.UUID(https_case))/'result.json' report = base.cb.contract.protected_json(prerequisite) require(report['verified'] is True and report['case'] == 'explicit_https' and report['no_jobs_or_approvals'] is True and report['final_native']['agent_id'] == base.AGENT, 'native HTTPS acceptance must be finished first') ident = str(uuid.uuid4());folder = STATE/ident;folder.mkdir(mode=0o700) source = base.stage_script();issued = base.cb.contract.now() config = dict(schema_version=1,fault_id=ident,tenant_id=cloud.TENANT,agent_id=base.AGENT, issued_at=issued.isoformat(),expires_at=(issued+dt.timedelta(minutes=10)).isoformat()) digest = hashlib.sha256(json.dumps(config,separators=(',',':')).encode()).hexdigest() intent = dict(id=ident,case='automatic_fallback',started_at=issued.isoformat(),source_sha256=source,config=config,config_sha256=digest, compose_sha256=hashlib.sha256((cloud.ROOT/'deploy/server.compose.yaml').read_bytes()).hexdigest(), https_prerequisite=dict(path=str(prerequisite),sha256=hashlib.sha256(prerequisite.read_bytes()).hexdigest()),no_jobs=True,no_reboot=True) base.save(folder,'intent.json',intent) native = base.remote(ident,'state',mode='auto',source_sha256=source);central = observe(ident);server = status();counts = scopes() base.preserved(report['final_native'],native) require(native['transport'] == 'wss' and native['config_sha256'] == base.ORIGINAL_CONFIG and native['journal']['pending_inventory_events'] == 0 and flags_disabled(server) and server['compose_sha256'] == intent['compose_sha256'] and server['fault_config_sha256'] == prior_hash() and counts['windows'] == dict(jobs=0,outbox=0,permits=0,unresolved=0) and counts['linux']['unresolved'] == 0, 'independent original config hashes and settled targets') base.save(folder,'before.json',dict(native=native,central=central,server=server,counts=counts)) base.save(folder,'enter-intent.json',base.payload(ident,'enter','auto')) try: entered = base.remote(ident,'enter',mode='auto',source_sha256=source) base.save(folder,'entered.json',entered) except Exception as error: base.save(folder,'enter-failure.json',dict(error_class=type(error).__name__,phase='native_enter',same_case_preserved=True)) cleanup(folder,intent,base.cb.contract.protected_json(folder/'before.json')) raise print('Entered existing Windows automatic-fallback case '+ident,flush=True) finish(ident) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('action',choices=('start','finish','restore')) parser.add_argument('--https-case');parser.add_argument('--id') args = parser.parse_args() if args.action == 'start': require(args.https_case and not args.id, 'one actual finished HTTPS case required') start(args.https_case) else: require(args.id and not args.https_case, 'same existing fallback case required') if args.action == 'finish':finish(args.id) else: folder = STATE/str(uuid.UUID(args.id));intent = base.cb.contract.protected_json(folder/'intent.json') before = base.cb.contract.protected_json(folder/'before.json');cleanup(folder,intent,before) print('Closed only existing Windows fallback case '+args.id) if __name__ == '__main__': try: main() except Exception as error: message = str(error) print('WINDOWS_AUTO_TRANSPORT_INCOMPLETE:'+(message if isinstance(error,base.cb.contract.GuardError) else type(error).__name__)) raise SystemExit(2) from None