#!/usr/bin/env python3 """Runs public tests unchanged, checks hook scope and restores stopped replicas.""" import argparse,json,os,subprocess,time from pathlib import Path from resilience_hooks import ROOT,DC,command,wait_ready def main(): p=argparse.ArgumentParser();p.add_argument('--mode',choices=['persistence','failover','all'],default='all');p.add_argument('--base-url',default=os.environ.get('BASE_URL','https://localhost:8443'));args=p.parse_args() os.environ['BASE_URL']=args.base_url # Fail before changing the stack if the host cannot run the delivered hardening. command([str(ROOT/'scripts/check-docker-hardening.sh')],timeout=15) command([str(ROOT/'scripts/bootstrap-openbao.sh')],timeout=100) up = DC+['up','-d','--no-build','--wait','--wait-timeout','90'] try: command(up,timeout=100) except RuntimeError: # After unseal, previously failing workloads can still be in restart backoff. container_ids = command(DC+['ps','--all','--quiet','api','api2','worker']).split() if not container_ids: raise fmt = '{{index .Config.Labels "com.docker.compose.service"}} {{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' states = command([str(ROOT/'scripts/docker.sh'),'inspect','--format',fmt,*container_ids]) stale = [] for line in states.splitlines(): service, status, health = line.split() if status in ('restarting','exited') or health=='unhealthy': stale.append(service) if not stale: raise command(DC+['up','-d','--no-build','--no-deps','--force-recreate',*stale],timeout=90) command(up,timeout=100) wait_ready() modes=['persistence','failover'] if args.mode=='all' else [args.mode] summary={'base_url':args.base_url,'hardening':'main compose, NoNewPrivs=1 probe passed','tests':[]} try: for index,mode in enumerate(modes): if index: print('Waiting 61s for a fresh shared login limiter window.',flush=True) for _ in range(61):time.sleep(1) hook=ROOT/'evidence'/('resilience-'+mode+'-hook.json') previous_hook_mtime=hook.stat().st_mtime_ns if hook.exists() else None started=time.monotonic() result=subprocess.run(['python3',str(ROOT/'tests/resilience.py'),'--mode',mode,'--action-script',str(ROOT/'scripts'/('restart.sh' if mode=='persistence' else 'stop-one.sh')),'--base-url',args.base_url,'--ca-file',str(ROOT/'certs/ca.crt')],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=220) # Public tests keep bearer tokens in memory and print only aggregate results. print(result.stdout,flush=True) entry={'mode':mode,'status':'PASS' if result.returncode==0 else 'FAIL','elapsed_seconds':round(time.monotonic()-started,3)} for line in result.stdout.splitlines(): if line.startswith('{'): values=json.loads(line) entry['public_metrics']={k:values[k] for k in ['observed_instances_before','successful_writes','failed_attempts','first_recovery_seconds'] if k in values} if hook.exists() and hook.stat().st_mtime_ns!=previous_hook_mtime: entry['hook']=json.loads(hook.read_text()) if entry.get('hook',{}).get('status')!='PASS': entry['status']='FAIL' summary['tests'].append(entry) if result.returncode: raise RuntimeError(f'Public {mode} test failed (exit {result.returncode})') if entry['status']!='PASS': raise RuntimeError(f'Missing or failed hook evidence for {mode}') print('PASS: '+mode+' data/session check AND real process/mount scope',flush=True) finally: # Restore even when failover assertions fail; never remove volumes. command(DC+['up','-d','--no-deps','--wait','--wait-timeout','60','api','api2'],timeout=70) (ROOT/'evidence/resilience-results.json').write_text(json.dumps(summary,indent=2,ensure_ascii=False)+'\n') if __name__=='__main__':main()