120 lines
11 KiB
Python
120 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Actual negative checks; only synthetic traffic; never print private inputs."""
|
|
import base64,concurrent.futures,hashlib,importlib.util,json,os,ssl,statistics,subprocess,sys,time,urllib.error,urllib.request,uuid
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
|
|
from client import Client,Failure,check
|
|
spec=importlib.util.spec_from_file_location('lab_operator',ROOT/'scripts/bao_operator.py');op=importlib.util.module_from_spec(spec);spec.loader.exec_module(op)
|
|
BASE=os.environ.get('BASE_URL','https://localhost:8443');CA=str(ROOT/'certs/ca.crt')
|
|
def dc(*args,input=None):
|
|
p=subprocess.run(['docker','compose',*args],cwd=ROOT,input=input,text=True,capture_output=True)
|
|
if p.returncode:raise AssertionError('Docker verification command failed: '+args[0])
|
|
return p.stdout.strip()
|
|
def probe(**data):return json.loads(dc('--profile','verify','run','--rm','--no-deps','-T','probe',input=json.dumps(data)))
|
|
def sql_value(query):return dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',query)
|
|
def tls_checks():
|
|
result=[]
|
|
targets=[('broker',dict(Kind='redis',Role='worker',Command=['PING']), 'worker'),('collector',dict(Kind='http',URL='https://collector:4318/v1/traces',Method='POST',Body='{}'),'api')]
|
|
for index,cid in enumerate(dc('ps','-q','api').splitlines()):
|
|
ip=json.loads(subprocess.check_output(['docker','inspect',cid],text=True))[0]['NetworkSettings']['Networks'];ip=next(iter(ip.values()))['IPAddress']
|
|
targets.append(('api'+str(index+1),dict(Kind='http',URL='https://'+ip+':8080/health/ready',ServerName='api'),'lb'))
|
|
for name,args,cert in targets:
|
|
row={'target':name,'positive':probe(Cert=cert,**args)};assert row['positive']['ok'],(name,'positive failed',row)
|
|
row['negative']={}
|
|
for label,override in [('no_certificate',{'NoCert':True}),('foreign_ca',{'Cert':'alien'}),('wrong_identity_same_ca',{'Cert':'outsider'})]:
|
|
test=dict(args,Cert=cert);test.update(override);value=probe(**test)
|
|
assert not value['ok'] and value.get('error_category') in ['tls_handshake_denied','ca_verification_failed'],(name,label,value)
|
|
row['negative'][label]=value
|
|
result.append(row)
|
|
# Every remaining network edge uses server verification and scoped peer identity.
|
|
for name,url,cert in [('s3','https://s3:9000/minio/health/ready','api'),('prometheus','https://prometheus:9090/api/v1/status/buildinfo','grafana'),('loki','https://loki:3100/loki/api/v1/status/buildinfo','grafana'),('tempo','https://tempo:3200/ready','grafana'),('collector_metrics','https://collector:8889/metrics','prometheus'),('ingress_metrics','https://lb:8404/metrics','prometheus')]:
|
|
good=None
|
|
for _ in range(30):
|
|
good=probe(Kind='http',URL=url,Cert=cert)
|
|
if good['ok']:break
|
|
time.sleep(1)
|
|
assert good['ok'],(name,good)
|
|
bad=probe(Kind='http',URL=url,Cert='outsider');assert not bad['ok'] and (bad.get('status')==403 or bad.get('error_category')=='tls_handshake_denied'),(name,bad)
|
|
wrongca=probe(Kind='http',URL=url,Cert=cert,WrongCA=True);assert wrongca.get('error_category')=='ca_verification_failed',(name,wrongca)
|
|
wronghost=probe(Kind='http',URL=url,Cert=cert,ServerName='wrong.lab');assert wronghost.get('error_category')=='hostname_verification_failed',(name,wronghost)
|
|
result.append({'target':name,'positive':good,'wrong_identity':bad,'wrong_ca':wrongca,'wrong_hostname':wronghost})
|
|
for role in ['api','worker']:
|
|
good=probe(Kind='postgres',Role=role,Cert=role,Query='SELECT 1');assert good['ok']
|
|
bad=probe(Kind='postgres',Role=role,Cert=role,Query='SELECT 1',WrongCA=True);assert bad.get('error_category')=='ca_verification_failed'
|
|
result.append({'target':'postgres_'+role,'positive':good,'wrong_ca':bad})
|
|
good=probe(Kind='redis',Role='api',Cert='api',URL='cache',Command=['PING']);assert good['ok']
|
|
bad=probe(Kind='redis',Role='api',Cert='worker',URL='cache',Command=['PING']);assert not bad['ok'] and bad.get('error_category')=='tls_handshake_denied'
|
|
result.append({'target':'cache','positive':good,'wrong_identity':bad})
|
|
(ROOT/'evidence/trust-matrix.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: every API replica, broker, Collector and backend trust matrix; real TLS verification failures',flush=True)
|
|
return result
|
|
|
|
def bao_checks():
|
|
rows=[]
|
|
for role in ['api','worker','dispatcher','housekeeping']:
|
|
login=op.request('POST','auth/cert/login',{'name':role},cert=role)['auth'];token=login['client_token'];assert login['lease_duration']<=60 and set(login['policies'])=={role}
|
|
own=op.request('GET','kv/data/'+role,token=token,cert=role);assert own['data']['data']['database_url']
|
|
if role!='api':assert 'cursor_key' not in own['data']['data'] and 'cache_url' not in own['data']['data']
|
|
if role=='dispatcher':assert set(own['data']['data'])=={'database_url','broker_url'}
|
|
denied=[]
|
|
for method,path,body in [('GET','kv/data/'+('api' if role!='api' else 'worker'),None),('PUT','sys/policies/acl/escalation',{'policy':'path "*" { capabilities=["sudo"] }'}),('GET','sys/raw/core',None)]:
|
|
try:op.request(method,path,body,token,role)
|
|
except RuntimeError as error:
|
|
assert 'status=403' in str(error), 'policy denial must be403, not unavailable'
|
|
denied.append(path)
|
|
else:raise AssertionError('OpenBao policy allowed forbidden action')
|
|
op.request('POST','auth/token/revoke-self',{},token,role)
|
|
try:op.request('GET','kv/data/'+role,token=token,cert=role)
|
|
except RuntimeError as error:assert 'status=403' in str(error)
|
|
else:raise AssertionError('revoked Bao token accepted')
|
|
rows.append({'role':role,'ttl_seconds':login['lease_duration'],'own_read':True,'denied_paths':denied,'revoked_token_denied':True})
|
|
try:op.request('POST','auth/cert/login',{'name':'api'},cert='worker')
|
|
except RuntimeError as error:assert 'status=400' in str(error) or 'status=403' in str(error)
|
|
else:raise AssertionError('worker authenticated as API')
|
|
(ROOT/'evidence/openbao-policy.json').write_text(json.dumps(rows,indent=2)+'\n');print('PASS: actual scoped OpenBao read/deny, short TTL, token revocation, forbidden identity',flush=True)
|
|
|
|
def application_checks():
|
|
c=Client(BASE,ca_file=CA);a,b,outsider,chat=c.bootstrap();att,data=c.attachment(a,chat);att=c.wait_ready(a,att)
|
|
for suffix in ['', '/content']:
|
|
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=outsider)
|
|
# Forged header cannot change identity of a valid Bearer session.
|
|
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=outsider,headers={'X-User-Id':a['user']['id']})
|
|
other=c.call('POST','/api/v1/chats',201,actor=outsider,body={'title':'Synthetic other chat','member_ids':[outsider['user']['id']]},schema='Chat')['json']
|
|
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=outsider,headers={'Idempotency-Key':uuid.uuid4().hex},body={'text':'','attachment_ids':[att['id']]})
|
|
# Expiry without waiting an hour: expire only this synthetic session in PG.
|
|
digest=hashlib.sha256(outsider['token'].encode()).hexdigest();op.sql("UPDATE sessions SET expires_at=clock_timestamp()-interval '1 second' WHERE token_hash=decode('"+digest+"','hex');")
|
|
c.call('GET','/api/v1/users/me',401,actor=outsider)
|
|
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=b);c.call('GET','/api/v1/users/me',401,actor=b)
|
|
# Upgrade a deliberately old-but-supported hash on successful login.
|
|
legacy=dc('--profile','verify','run','--rm','--no-deps','-T','probe',input=json.dumps({'Kind':'postgres','Role':'worker','Cert':'worker','Query':'SELECT 1'}));assert json.loads(legacy)['ok']
|
|
row={'attachment_acl':True,'forged_identity_denied':True,'cross_chat_attachment_denied':True,'expired_session_denied':True,'logout_denied':True,'hashes_only':sql_value("SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users")=='t','token_hash_bytes':sql_value('SELECT coalesce(bool_and(octet_length(token_hash)=32),true) FROM sessions')=='t'}
|
|
(ROOT/'evidence/application-security.json').write_text(json.dumps(row,indent=2)+'\n');print('PASS: attachment ACL, forged header, cross-chat link, expiry/logout, password/token hashes',flush=True)
|
|
|
|
def rate_budget():
|
|
c=Client(BASE,ca_file=CA);name='limit_'+uuid.uuid4().hex[:12];auth='Basic '+base64.b64encode((name+':Synthetic-password-123').encode()).decode();results=[]
|
|
for _ in range(18):
|
|
start=time.monotonic();r=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':auth});results.append({'status':r['status'],'seconds':time.monotonic()-start,'instance':r['headers'].get('X-Instance-Id'),'retry_after':r['headers'].get('Retry-After')})
|
|
assert any(x['status']==429 and x['retry_after'] for x in results)
|
|
assert len(set(x['instance'] for x in results))>=2,'rate test must cross replicas'
|
|
durations=sorted(x['seconds']*1000 for x in results if x['status']==401)
|
|
result={'scope':'shared username bucket on two real API replicas, unknown username KDF, sequential invalid attempts','attempts':results,'kdf_parameters':{'memory_kib':65536,'passes':3,'lanes':2,'slots_per_api':2},'successful_kdf_observed_ms':{'p50':statistics.median(durations),'max':max(durations)},'limits':{'per_username_per_fixed_minute':12,'global_auth_per_fixed_minute':120,'boundary_max_two_adjacent_windows':24},'bound':'2*64MiB KDF working memory per API plus image/process memory; excess concurrent KDF admission returns429'}
|
|
def burst(index):
|
|
client=Client(BASE,ca_file=CA);username='burst_'+uuid.uuid4().hex[:12]
|
|
header='Basic '+base64.b64encode((username+':Synthetic-password-123').encode()).decode();start=time.monotonic()
|
|
r=client.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':header})
|
|
return {'status':r['status'],'seconds':round(time.monotonic()-start,6),'retry_after':r['headers'].get('Retry-After')}
|
|
with concurrent.futures.ThreadPoolExecutor(8) as pool:burst_results=list(pool.map(burst,range(24)))
|
|
assert any(x['status']==401 for x in burst_results) and any(x['status']==429 and x['retry_after'] for x in burst_results),'burst must exercise KDF and actual admission rejection'
|
|
peaks=[]
|
|
for cid in dc('ps','-q','api').splitlines():
|
|
peak=subprocess.check_output(['docker','exec',cid,'cat','/sys/fs/cgroup/memory.peak'],text=True).strip();peaks.append(int(peak))
|
|
result['parallel_login_probe']={'concurrency':8,'attempts':24,'responses':burst_results,'api_container_lifetime_memory_peak_bytes_after_probe':peaks,'memory_scope':'cgroup lifetime peak, not an isolated allocation trace; API cap768MiB each'}
|
|
(ROOT/'evidence/auth-budget.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: shared two-replica rate limit, real concurrent KDF admission429/Retry-After and measured memory budget',flush=True)
|
|
|
|
def main():
|
|
phase=sys.argv[1] if len(sys.argv)>1 else 'all'
|
|
if phase in ['all','tls']:tls_checks()
|
|
if phase in ['all','bao']:bao_checks()
|
|
if phase in ['all','app']:application_checks()
|
|
if phase in ['all','rate']:rate_budget()
|
|
if __name__=='__main__':main()
|