Files
mtusi2026lab7/tests/lifecycle.py
T

46 lines
2.5 KiB
Python

"""Host operator: renewal, expired worker leaf, sealed Bao, automatic recovery."""
import json,subprocess,sys,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
from pki import PRIVATE,issue
from bao_operator import call
from client import Client
def compose(*args):return subprocess.check_output(['./scripts/compose.sh',*args],text=True,stderr=subprocess.DEVNULL)
def status(role):return json.loads(compose('exec','-T',role,'cat','/tmp/agent-status.json'))
def until(fn,timeout=90):
start=time.monotonic()
while time.monotonic()-start<timeout:
if fn():return round(time.monotonic()-start,3)
time.sleep(1)
raise AssertionError('bounded lifecycle transition timed out')
c=Client(ca_file=str(PRIVATE/'ca.crt'),timeout=10)
# Existing agent should have renewed at least once; wait if fresh start.
until(lambda:status('worker')['renewals']>=1)
renew=status('worker');assert renew['child_running']
alice,bob,eve,chat=c.bootstrap()
leaf=PRIVATE/'roles/worker';saved={n:(leaf/n).read_bytes() for n in ('service.crt','service.key','service.pem')}
try:
issue('worker',replace=True,expired=True)
expired_stop=until(lambda:not status('worker')['child_running'],35)
att,payload=c.attachment(alice,chat)
assert c.call('GET','/api/v1/attachments/'+att['id'],actor=alice,schema='Attachment')['json']['status']=='queued'
finally:
for n,data in saved.items():(leaf/n).write_bytes(data)
start=time.monotonic();c.wait_ready(alice,att,wait_seconds=90);expiry_recovery=round(time.monotonic()-start,3)
assert c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==payload
try:
call('sys/seal',{})
sealed_stop=until(lambda:not status('worker')['child_running'] and not status('api')['child_running'],40)
blocked=status('worker');assert blocked['blocked_events']>0
finally:
creds=json.loads((PRIVATE/'bao-operator.json').read_text());call('sys/unseal',{'key':creds['keys'][0]},token=False)
start=time.monotonic()
def ready():
try:return c.call('GET','/health/ready',schema='Health')['status']==200
except Exception:return False
until(ready,120);sealed_recovery=round(time.monotonic()-start,3)
c.message(alice,chat,'after operator unseal')
print(json.dumps({'status':'PASS','renewal_status':renew,'expired_leaf_stop_seconds':expired_stop,'expiry_task_preserved':True,'expiry_recovery_seconds':expiry_recovery,'sealed_stop_seconds':sealed_stop,'sealed_recovery_seconds':sealed_recovery,'plaintext_fallback':False},indent=2))