import base64 from concurrent.futures import ThreadPoolExecutor import json import os from pathlib import Path import socket import ssl import statistics import sys import time from urllib.error import HTTPError, URLError from urllib.request import Request sys.path.insert(0,str(Path(__file__).resolve().parents[1])) from scripts import lab, provision as p from scripts.observability_checks import arguments, probe def denied(function, allowed=(400,403)): try: function() except HTTPError as error: status=error.code;error.close() if status not in allowed:raise RuntimeError('Unexpected deny status: '+str(status)) return status raise RuntimeError('Forbidden operation was permitted') def tls(args): p.negative_certificates() c=lab.client(args) c.call('GET','/health/live',schema='Health') results=probe(args,{'op':'tls'}) for server in ('api1','api2'): for identity in ('None','wrong-role','foreign','expired'): if results[server+':'+identity]:raise RuntimeError('Unauthorized TLS identity reached API') if not results[server+':lb'] or results[server+':plaintext']: raise RuntimeError('mTLS positive/plaintext boundary failed') for name in ('untrusted-ca','wrong-hostname'): context=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) if name=='untrusted-ca' else ssl.create_default_context(cafile=lab.environment(args)['CA_FILE']) try: with socket.create_connection(('127.0.0.1',args.port),timeout=5) as raw: with context.wrap_socket(raw,server_hostname='localhost' if name=='untrusted-ca' else 'wrong.lab'):pass except ssl.SSLCertVerificationError: results[name]='CERTIFICATE_VERIFY_FAILED' else:raise RuntimeError('Bad external TLS trust accepted') lab.evidence('tls.json',{'status':'PASS','checks':results}) lab.say('PASS: external CA/hostname, both mTLS identities, foreign CA, expiry and no plaintext bypass') return results def policies(args): result={} result['wrong_certificate_role']=denied(lambda:p.bao_request('auth/cert/login',{'name':'api1'},identity='wrong-role')) result['local_boundaries']=probe(args,{'op':'audit'}) if not all(result['local_boundaries'].values()):raise RuntimeError('Unexpected plaintext/admin listener exposed') for identity,role in [('api1','api'),('api2','api'),('worker','worker'),('cleanup','cleanup')]: auth=p.bao_request('auth/cert/login',{'name':identity},identity=identity)['auth'] token=auth['client_token'] own=p.bao_request('secret/data/'+role,token=token,identity=identity)['data']['data'] result[identity]={'own_secret':True,'ttl_seconds':auth['lease_duration']} other='api' if role!='api' else 'worker' result[identity]['other_secret']=denied(lambda:p.bao_request('secret/data/'+other,token=token,identity=identity)) result[identity]['write_policy']=denied(lambda:p.bao_request('sys/policies/acl/forbidden',{'policy':''},token,identity,method='PUT')) p.bao_request('auth/token/revoke-self',{},token,identity) result[identity]['revoked_token']=denied(lambda:p.bao_request('secret/data/'+role,token=token,identity=identity)) if role!='api' and ('cursor_key' in own or 'api' in own['database_url'].split('@')[0]): raise RuntimeError('Wrong secret bundle') result['database']=probe(args,{'op':'database'}) if not all(result['database'].values()):raise RuntimeError('Database role check failed') result['dependencies']=probe(args,{'op':'rights'}) if not all(result['dependencies'].values()):raise RuntimeError('Dependency ACL check failed') for name, state in lab.states(args).items(): if name in ('api1','api2','worker') and state['user']!='messenger': raise RuntimeError('Application user is not non-root') if 'root_token' in p.operator_load():raise RuntimeError('Initial root token not revoked') lab.evidence('policies.json',{'status':'PASS','results':result}) lab.say('PASS: scoped OpenBao policies, revoked tokens, DB/S3/broker/telemetry permissions') return result def limits(args): c=lab.client(args) c.call('POST','/api/v1/users',413,raw=b' '*65537,headers={'Content-Type':'application/json'}) def chunks(): for _ in range(17):yield b' '*4096 c.call('POST','/api/v1/users',413,raw=chunks(),headers={'Content-Type':'application/json'}) authorization='Basic '+base64.b64encode(b'unknown:wrong-password').decode() def login(_): return c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':authorization}) with ThreadPoolExecutor(max_workers=12) as pool: replies=list(pool.map(login,range(60))) rejected=[r for r in replies if r['status']==429] if not rejected or not all(r['headers'].get('Retry-After') for r in rejected): raise RuntimeError('No valid login rate limit observed') time.sleep(2) actor=c.user('after_rate_limit') c.call('GET','/api/v1/users/me',actor=actor) measured=probe(args,{'op':'argon2'}) timings=measured['timings'] result={'status':'PASS','json_limit_bytes':65536,'chunked_limit':'PASS','login_429':len(rejected), 'retry_after':'PASS','recovered_login':201,'measurement_context':measured['context'],'argon2id':{'memory_kib':19456,'t':2,'p':1,'timings':timings}} lab.evidence('limits.json',result) lab.say('PASS: JSON/chunked limits, login 429/Retry-After, Argon2id measurements') return result def bao_expiry(args): import argparse test=argparse.Namespace(project=args.project+'-bao-ttl',port=args.test_port,ttl=3600, test_port=args.test_port,grafana_port=3311,action='start') try: lab.setup(test) lab.start(test) lab.run(test,[lab.interpreter(),'-X','utf8','scripts/security_checks.py','bao-expiry']) finally: lab.compose(test,'down','--timeout','10') def sealed_case(args): c=lab.client(args) actor=c.user('bao_expiry') c.call('GET','/api/v1/users/me',actor=actor) auth=p.bao_request('auth/cert/login',{'name':'operator'})['auth'] try: p.bao_request('sys/seal',{},auth['client_token']) time.sleep(5) c.call('GET','/health/live',schema='Health') c.call('GET','/health/ready',503) c.call('GET','/api/v1/users/me',503,actor=actor) finally: p.unseal() lab.wait_ready(args) c.call('GET','/api/v1/users/me',actor=actor) result={'status':'PASS','service_token_ttl':2,'while_sealed':{'live':200,'ready':503,'business':503}, 'after_unseal':200,'old_session_preserved':True,'operator_unseal_outside_containers':True} lab.evidence('bao-expiry.json',result) lab.say('PASS: sealed OpenBao, bounded credential cache and recovery with old session') if __name__=='__main__': args=arguments() if sys.argv[1] in ('tls-check','security-check'):tls(args) if sys.argv[1] in ('policy-check','security-check'):policies(args) if sys.argv[1]=='security-check':limits(args) if sys.argv[1]=='bao-check':bao_expiry(args) if sys.argv[1]=='bao-expiry':sealed_case(args)