#!/usr/bin/env python3 """Bounded cached authorization during sealed Bao, restart, expiry and recovery.""" import importlib.util,json,ssl,subprocess,sys,time,urllib.error,urllib.request from pathlib import Path ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'));from client import Client,check s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec);op=sec.op s=importlib.util.spec_from_file_location('boot',ROOT/'scripts/bootstrap.py');boot=importlib.util.module_from_spec(s);s.loader.exec_module(boot) def main(): boot.issue('expired-worker',force=True,identity='worker',days=0);time.sleep(1) expired=sec.probe(Kind='redis',Role='worker',Cert='expired-worker',Command=['PING']);assert not expired['ok'] and expired.get('error_category')=='tls_handshake_denied',expired c=Client(sec.BASE,ca_file=sec.CA);a,b,o,chat=c.bootstrap();message=c.message(a,chat,'Synthetic persisted across sealed Bao')['json'];attachment,data=c.attachment(a,chat);c.wait_ready(a,attachment) root=json.loads((op.OP/'init.json').read_text())['root_token'];ctx=ssl.create_default_context(cafile=sec.CA) def status(): req=urllib.request.Request(sec.BASE+'/api/v1/users/me',headers={'Authorization':'Bearer '+a['token']}) try: with urllib.request.urlopen(req,context=ctx,timeout=3) as r:return r.status except urllib.error.HTTPError as e:return e.code start=time.monotonic();rows=[] try: op.request('PUT','sys/seal',{},root) first=sec.dc('ps','-q','api').splitlines()[0];subprocess.run(['docker','restart',first],check=True,stdout=subprocess.DEVNULL) while time.monotonic()-start<80: rows.append({'seconds':round(time.monotonic()-start,3),'http_status':status()}) if rows[-1]['http_status']==503 and time.monotonic()-start>65:break time.sleep(2) assert rows[-1]['http_status']==503,'authorization cache continued beyond bounded TTL' finally:op.init_unseal() restored=time.monotonic() while time.monotonic()-restored<30: if status()==200:break time.sleep(1) else:raise AssertionError('service did not recover after explicit operator unseal') c.call('GET','/api/v1/chats/'+chat['id'],actor=a,schema='Chat');download=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=a);check(download['bytes']==data,'confirmed original lost during seal/restart') result={'expired_correct_identity_leaf':expired,'sealed_timeline':rows,'authorization_ttl_seconds':60,'poll_seconds':5,'observation_step_seconds':2,'restarted_one_api_while_sealed':True,'restart_had_no_static_secret_fallback':True,'all_api_unavailable_observed_seconds':next(r['seconds'] for r in rows if r['http_status']==503),'recovery_seconds_after_unseal':round(time.monotonic()-restored,3),'same_user_token_valid':True,'original_identical':True,'limits':'successful secret-read authorization cached until60s, refresh attempt timeout<=3s and loop5s; external TLS remains required; local single Bao fails closed after bounded cache'} (ROOT/'evidence/sealed-expiry.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: expired correct-SAN leaf rejected; sealed Bao bounds authorization, restarted API has no fallback, operator unseal restores same session/file',flush=True) if __name__=='__main__':main()