Secure messenger with TLS identities, scoped OpenBao secrets and worker compromise experiments

This commit is contained in:
2026-12-02 17:29:35 +03:00
parent 20afc2c790
commit 047cef4c7f
128 changed files with 10569 additions and 49 deletions
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Committed lab7, truly new clone/CA/credentials/volumes, explicit operator restart."""
import json,os,socket,subprocess,tempfile,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def free():
with socket.socket() as s:s.bind(('127.0.0.1',0));return str(s.getsockname()[1])
project='verify-lab7-'+uuid.uuid4().hex[:10]
with tempfile.TemporaryDirectory(prefix=project+'-') as directory:
clone=Path(directory)/'repo';subprocess.run(['git','clone','--no-hardlinks',str(ROOT),str(clone)],check=True)
env=dict(os.environ,COMPOSE_PROJECT_NAME=project,APP_PORT=free(),GRAFANA_PORT=free(),BAO_PORT=free(),SESSION_TTL_SECONDS='3600')
base='https://localhost:'+env['APP_PORT'];ca=str(clone/'certs/ca.crt')
def run(*args):subprocess.run(args,cwd=clone,env=env,check=True)
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=clone,env=env,text=True).strip()
def snapshot():
result={}
for id in dc('ps','-q').splitlines():
v=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0];result[v['Name']]={'service':v['Config']['Labels']['com.docker.compose.service'],'started_at':v['State']['StartedAt'],'user':v['Config']['User'],'image_id':v['Image'],'pid1':v['Path']}
return result
try:
run('make','up');run('make','check');run('make','test','BASE_URL='+base,'CA_FILE='+ca);run('make','test-security','BASE_URL='+base,'CA_FILE='+ca)
before=snapshot();run('make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base,'CA_FILE='+ca);after=snapshot()
for name,item in before.items():assert after[name]['started_at']!=item['started_at'],name+' not restarted'
for item in after.values():
if item['service'] in ['api','worker','dispatcher','housekeeping']:assert item['user']=='10001:10001' and item['pid1']=='/usr/local/bin/messenger'
request=json.dumps({'Kind':'http','Cert':'operator','URL':'https://grafana:3000/api/dashboards/uid/messenger-lab7','Auth':'grafana','ReturnBody':True})
probe=subprocess.run(['docker','compose','--profile','verify','run','--rm','--no-deps','-T','probe'],cwd=clone,env=env,input=request,capture_output=True,text=True,check=True)
dashboard=json.loads(probe.stdout);assert dashboard['ok'];dashboard=json.loads(dashboard['body'])['dashboard'];assert len(dashboard['panels'])==24
(ROOT/'evidence/persistence-processes.json').write_text(json.dumps({'scope':'disposable real clean clone; fresh CA, secrets and every volume','before':before,'after':after,'fresh_grafana_panels':len(dashboard['panels'])},indent=2)+'\n')
print('PASS: real clean clone, independent CA/secrets/volumes, verified HTTPS, full store/API restart, same session/file, non-root PID1, fresh Grafana provisioning')
finally:
# This unique synthetic project only. Working lab7 and unrelated volumes survive.
run('docker','compose','down','-v','--remove-orphans')
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Grade5 track1: copied worker credentials, bounded probes, quarantine/revoke/recover."""
import concurrent.futures,importlib.util,json,os,shutil,subprocess,sys,threading,time,urllib.parse,uuid
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)
s=importlib.util.spec_from_file_location('rot',ROOT/'scripts/rotate.py');rot=importlib.util.module_from_spec(s);s.loader.exec_module(rot)
op=rot.op;BASE=sec.BASE
def main():
c=Client(BASE,ca_file=sec.CA);a,b,outsider,chat=c.bootstrap();result={'model':'exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker','images_before':sec.dc('images','-q','worker').splitlines()}
raw=sec.dc('exec','-T','worker','cat','/run/runtime/active.json');active=json.loads(raw)
db=urllib.parse.urlparse(active['database_url']);broker=urllib.parse.urlparse(active['broker_url'])
stolen={'worker':{'db_password':db.password,'broker_password':broker.password,'s3_access_key_id':active['s3_access_key_id'],'s3_secret_access_key':active['s3_secret_access_key']}}
(op.OP/'stolen-worker.json').write_text(json.dumps(stolen));os.chmod(op.OP/'stolen-worker.json',0o600)
d=ROOT/'certs/private/stolen-worker'
if d.exists():shutil.rmtree(d)
shutil.copytree(ROOT/'certs/private/worker',d)
defaults={'Role':'worker','Cert':'stolen-worker','CredentialsFile':'/operator/stolen-worker.json'}
probe=lambda **kw:sec.probe(**dict(defaults,**kw))
# A pre-separation model with API SQL credentials/root S3 credentials allows broader access.
broad=json.loads((op.OP/'credentials.json').read_text());broad['baseline']={'s3_access_key_id':broad['s3_root_user'],'s3_secret_access_key':broad['s3_root_password']};(op.OP/'baseline-worker.json').write_text(json.dumps({'baseline':broad['baseline']}));os.chmod(op.OP/'baseline-worker.json',0o600)
result['before_least_privilege']={'password_table':sec.probe(Kind='postgres',Role='api',Cert='stolen-worker',Query='SELECT password_hash FROM users LIMIT 1'),'bucket_administration':sec.probe(Kind='s3',Role='baseline',Cert='stolen-worker',CredentialsFile='/operator/baseline-worker.json',Method='LIST_BUCKETS')}
assert all(x['ok'] for x in result['before_least_privilege'].values())
sec.dc('stop','worker') # quarantine before new secrets become visible to replacement
att,data=c.attachment(a,chat);accepted=[(att,data)]
stage=sec.sql_value("SELECT staging_key FROM attachments WHERE id='"+att['id']+"'")
marker='originals/security-probe-'+uuid.uuid4().hex+'/marker'
good={'db_pipeline':probe(Kind='postgres',Query='SELECT job_id FROM pipeline_jobs LIMIT 1'),'db_execution_update':probe(Kind='postgres',Query="UPDATE attachments SET status=status WHERE id='"+att['id']+"'"),'s3_staging':probe(Kind='s3',Key=stage),'s3_final_put':probe(Kind='s3',Method='PUT',Key=marker,Body='synthetic allowed scope'),'queue_ping':probe(Kind='redis',Command=['PING'])}
assert all(x['ok'] for x in good.values()),good
denied={}
for name,query in [('password_table','SELECT password_hash FROM users'),('sessions','SELECT token_hash FROM sessions'),('messages','SELECT text FROM messages'),('change_owner',"UPDATE attachments SET owner_id=owner_id WHERE false"),('change_checksum',"UPDATE attachments SET sha256=sha256 WHERE false"),('drop_table','BEGIN; DROP TABLE users; ROLLBACK;')]:
denied[name]=probe(Kind='postgres',Query=query);assert not denied[name]['ok'] and denied[name].get('error_category')=='permission_denied',(name,denied[name])
for name,args in [('s3_private_prefix',{'Kind':'s3','Method':'PUT','Key':'private/blocked','Body':'synthetic'}),('s3_staging_write',{'Kind':'s3','Method':'PUT','Key':'staging/blocked','Body':'synthetic'}),('s3_final_delete',{'Kind':'s3','Method':'DELETE','Key':marker}),('bucket_administration',{'Kind':'s3','Method':'LIST_BUCKETS'}),('queue_publish',{'Kind':'redis','Command':['XADD','attachment.jobs.v1','*','payload','{}']}),('queue_flush',{'Kind':'redis','Command':['FLUSHALL']}),('queue_other_key',{'Kind':'redis','Command':['XREADGROUP','GROUP','image-workers','probe','STREAMS','other.stream','>']})]:
denied[name]=probe(**args);assert not denied[name]['ok'] and denied[name].get('error_category')=='permission_denied',(name,denied[name])
login=op.request('POST','auth/cert/login',{'name':'worker'},cert='worker')['auth'];oldtoken=login['client_token'];accessor=login['accessor']
try:op.request('GET','kv/data/api',token=oldtoken,cert='worker')
except RuntimeError:denied['bao_api_secret']={'ok':False,'error_category':'policy_denied'}
else:raise AssertionError('worker read API secret')
for _ in range(7):accepted.append(c.attachment(a,chat))
result['accepted_while_quarantined']=len(accepted);result['least_privilege']={'allowed':good,'denied':denied}
stop=threading.Event();traffic=[]
def send():
client=Client(BASE,ca_file=sec.CA)
while not stop.is_set():
try:client.message(a,chat,'Synthetic during worker revocation');traffic.append(True)
except Exception:traffic.append(False)
time.sleep(.05)
pool=concurrent.futures.ThreadPoolExecutor(2);tasks=[pool.submit(send) for _ in range(2)]
start=time.monotonic();root=json.loads((op.OP/'init.json').read_text())['root_token']
try:
rot.revoke('worker');op.request('DELETE','auth/cert/certs/worker',token=root);op.request('POST','auth/token/revoke-accessor',{'accessor':accessor},root)
after={}
after['old_cert_queue']=probe(Kind='redis',Command=['PING']);after['old_cert_s3']=probe(Kind='s3',Key=stage)
assert not after['old_cert_queue']['ok'] and not after['old_cert_s3']['ok']
try:op.request('GET','kv/data/worker',token=oldtoken,cert='stolen-worker')
except RuntimeError:after['old_bao_token_denied']=True
else:raise AssertionError('revoked Bao token accepted')
rot.rotate('worker',certificate=True)
# Use a NEW accepted TLS identity to prove the old SQL password itself is revoked.
after['old_sql_password']=probe(Kind='postgres',Cert='worker',Query='SELECT 1');assert not after['old_sql_password']['ok'] and after['old_sql_password'].get('error_category')=='credential_denied'
sec.dc('up','-d','--no-deps','--force-recreate','worker')
for attachment,original in accepted:
ready=c.wait_ready(a,attachment);download=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=a);check(download['bytes']==original,'accepted original changed')
elapsed=time.monotonic()-start;result['after_revocation']=after
finally:stop.set();pool.shutdown(wait=True)
result.update(recovery_all_ready_seconds=round(elapsed,3),all_accepted_originals_identical=True,background_messages_success=sum(traffic),background_messages_errors=len(traffic)-sum(traffic),images_after=sec.dc('images','-q','worker').splitlines(),new_worker_connects=sec.probe(Kind='redis',Role='worker',Cert='worker',Command=['PING']))
assert result['images_before']==result['images_after'] and result['new_worker_connects']['ok']
(ROOT/'evidence/worker-compromise.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: bounded worker compromise, before/after least privilege, actual identity/SQL revocation, fresh worker restored all accepted bytes; no image rebuild',flush=True)
if __name__=='__main__':main()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Inspect actual runtime controls; verify no native plaintext bypass or leakage."""
import importlib.util,json,os,subprocess,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
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)
def main():
rows=[];sensitive=[]
credentials=json.loads((ROOT/'secrets/operator/credentials.json').read_text());sensitive += [credentials['postgres_admin'],credentials['s3_root_password'],credentials['cursor_key']]
for role in ['api','worker','dispatcher','housekeeping']:sensitive += [credentials[role][k] for k in ['db_password','broker_password','cache_password','s3_secret_access_key']]
material=json.loads((ROOT/'secrets/operator/init.json').read_text());sensitive += [material['root_token'],*material['keys']]
apps={'api','worker','dispatcher','housekeeping','broker','cache','s3','collector','prometheus','loki','tempo','grafana'}
for id in sec.dc('ps','-q').splitlines():
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0];name=item['Config']['Labels']['com.docker.compose.service'];host=item['HostConfig']
assert not host['Privileged'] and host['NetworkMode']!='host'
assert not any('docker.sock' in m['Source'] or m['Destination']=='/operator' for m in item['Mounts'])
assert not any(value in json.dumps(item['Config'].get('Env',[])) for value in sensitive)
if name in apps:
assert item['Config']['User']=='10001:10001' and host['ReadonlyRootfs'] and 'ALL' in host['CapDrop'] and 'no-new-privileges:true' in host['SecurityOpt']
for bindings in (host.get('PortBindings') or {}).values():
for b in bindings or []:assert name in ['lb','openbao','grafana'] and b['HostIp']=='127.0.0.1'
rows.append({'service':name,'user':item['Config']['User'],'read_only':host['ReadonlyRootfs'],'drop_capabilities':host['CapDrop'],'add_capabilities':host['CapAdd'],'security_options':host['SecurityOpt'],'memory_limit_bytes':host['Memory'],'nano_cpus_limit':host['NanoCpus'],'image_id':item['Image'],'started_at':item['State']['StartedAt'],'published_ports':host.get('PortBindings')})
denied=[]
for service,port in [('api',8081),('broker',6380),('cache',6380),('s3',9001),('s3',9002),('collector',4319),('collector',8890),('prometheus',9091),('loki',3101),('tempo',3201),('grafana',3001)]:
r=sec.probe(Kind='http',URL='https://'+service+':'+str(port)+'/health/ready',Cert='operator')
assert not r['ok'] and r.get('error_category')=='connection_or_action_denied',(service,port,r)
denied.append({'service':service,'native_port':port,'external_namespace_connection_denied':True})
# Worker cannot mutate rootfs or read operator/other-role material.
filesystem={}
for name,command in [('rootfs_write',['touch','/unauthorized-file']),('operator_key',['cat','/operator/init.json']),('other_identity',['cat','/run/tls/lb/key.key'])]:
p=subprocess.run(['docker','compose','exec','-T','worker',*command],cwd=ROOT,capture_output=True);assert p.returncode!=0;filesystem[name]='denied'
logs=sec.dc('logs','--no-color','--tail','500','api','worker','dispatcher','collector-store')
assert not any(v in logs for v in sensitive)
status=sec.dc('exec','-T','worker','cat','/proc/1/status');assert 'CapEff:\t0000000000000000' in status and 'NoNewPrivs:\t1' in status
result={'runtime':rows,'no_native_bypass':denied,'worker_filesystem':filesystem,'worker_effective_caps_zero':True,'worker_no_new_privileges':True,'known_private_values_absent_from_config_env_and_sampled_logs':True,'scope':'runtime containers only; verify-profile compiler/operator tools not persistent runtime; last500 app/collector log lines sampled, not proof of all future logs'}
(ROOT/'evidence/hardening.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: actual non-root/capabilities/read-only/ports, closed native hops, scoped worker mounts and sampled private-value scan',flush=True)
if __name__=='__main__':main()
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Prove the SLI also observes a 503 generated by HAProxy, outside API SDKs."""
import json,time,urllib.request,urllib.error
from observability import ROOT,BASE,Client,check,dc,scalar,wait_for
c=Client(BASE);a,b,e,chat=c.bootstrap();before=scalar('sum(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"})') or 0
try:
dc('stop','api');time.sleep(2)
req=urllib.request.Request(BASE+'/api/v1/users/me',headers={'Authorization':'Bearer '+a['token']})
try:response=urllib.request.urlopen(req,timeout=4)
except urllib.error.HTTPError as error:response=error
with response:check(response.code==503,'expected LB 503');status=response.code
after,delay=wait_for(lambda: (lambda n:n if n is not None and n>before else None)(scalar('sum(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"})')),15)
result={'client_status':status,'api_processes_stopped':True,'ingress_5xx_before':before,'ingress_5xx_after':after,'observation_seconds':delay,'lb_generated_error_counted':True}
(ROOT/'evidence/ingress-guard.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: LB-generated 503 included in business ingress SLI')
finally:dc('up','-d','--no-deps','--wait','api')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Stop each real container, then replace them in sequence under writes."""
import json,os,subprocess,sys,threading,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
BASE=os.environ.get('BASE_URL','https://localhost:8443')
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def inspect(id):return json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
def ready():
deadline=time.monotonic()+45
while time.monotonic()<deadline:
try:
dc('up','-d','--no-deps','--wait','api');time.sleep(2);return
except subprocess.CalledProcessError:time.sleep(1)
raise AssertionError('API did not recover')
def run_phase(c,actor,chat,action,seconds=7):
results=[];failed=0;stop=threading.Event();events=[];seen=set()
def write():
nonlocal failed
client=Client(BASE,ca_file=str(ROOT/'certs/ca.crt'),timeout=2);key=uuid.uuid4().hex
while not stop.is_set():
try:
response=client.message(actor,chat,'operation probe '+key,key=key)
results.append((time.monotonic(),response['json']['id']))
seen.add(response['headers']['X-Instance-Id']);key=uuid.uuid4().hex
except Failure:failed+=1
time.sleep(.02)
worker=threading.Thread(target=write);worker.start();time.sleep(1)
started=time.monotonic();action();action_done=time.monotonic();time.sleep(seconds);stop.set();worker.join()
history=[];path='/api/v1/chats/'+chat['id']+'/messages?limit=100'
from urllib.parse import quote
while True:
page=c.call('GET',path,actor=actor,schema='MessagePage')['json'];history+=page['items']
if page['next_cursor'] is None:break
path='/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+quote(page['next_cursor'],safe='')
ids=[m['id'] for m in history];check(len(ids)==len(set(ids)),'duplicate IDs')
check({i for _,i in results}.issubset(set(ids)),'lost confirmed message')
successes_after=[t for t,_ in results if t>=action_done]
check(successes_after,'no successful write after action')
recovery=successes_after[0]-started
return {'successful_writes':len(results),'errors':failed,'successful_rps':len(results)/(time.monotonic()-started+1),'first_recovery_seconds':round(recovery,3),'action_seconds':round(action_done-started,3),'instances':sorted(seen),'confirmed_preserved':True}
def main():
ready();c=Client(BASE,ca_file=str(ROOT/'certs/ca.crt'));a,b,e,chat=c.bootstrap();results={'failures':[]}
ids=dc('ps','-q','api').splitlines();check(len(ids)==2,'requires two API containers')
for id in ids:
alias=subprocess.check_output(['docker','exec',id,'cat','/run/runtime/instance_alias'],text=True).strip()
env=dict(os.environ,TARGET_INSTANCE_ID=alias)
def action():subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,check=True,stdout=subprocess.DEVNULL)
try:
result=run_phase(c,a,chat,action);result['stopped_alias']=alias
check(not inspect(id)['State']['Running'],'target is still running')
check(result['first_recovery_seconds']<10,'recovery >10s')
results['failures'].append(result)
finally:ready()
check(len(dc('ps','-q','api').splitlines())==2,'failover lost replicas')
(ROOT/'evidence/operations.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS: both API replicas stopped sequentially through verified HTTPS; confirmed writes preserved')
if __name__=='__main__':main()
+36
View File
@@ -0,0 +1,36 @@
#!/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()
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Compare publishable files with actual local private material, without printing values."""
import gzip,json,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
values=set()
def collect(v):
if isinstance(v,str) and len(v)>=12:values.add(v.encode())
elif isinstance(v,dict):
for item in v.values():collect(item)
elif isinstance(v,list):
for item in v:collect(item)
for p in (ROOT/'secrets/operator').glob('*.json'):
try:collect(json.loads(p.read_text()))
except ValueError:pass
for p in (ROOT/'secrets/operator').rglob('*.key'):values.add(p.read_bytes().strip())
files=subprocess.check_output(['git','ls-files','--cached','--others','--exclude-standard','-z'],cwd=ROOT).split(b'\0');bad=[]
for raw in files:
if not raw:continue
name=raw.decode();p=ROOT/name
if not p.is_file():continue
assert not name.startswith(('secrets/','certs/private/')) and p.suffix not in ['.key','.pem'], 'private file staged'
data=p.read_bytes()
if name.endswith('.gz'):data=gzip.decompress(data)
if any(v in data for v in values):bad.append(name)
assert not bad, 'private material found in '+str(bad)
print('PASS: publishable files contain no exact known local credentials/shares/private-key contents; no values printed')
+119
View File
@@ -0,0 +1,119 @@
#!/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()
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Small sanitized runtime manifest; no environment, passwords or tokens."""
import json,platform,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).splitlines()
result={'platform':platform.platform(),'containers':[]}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
result['containers'].append({'service':item['Config']['Labels']['com.docker.compose.service'],'name':item['Name'],'alias':item['Config']['Hostname'],'image':item['Config']['Image'],'image_id':item['Image'],'user':item['Config']['User'],'pid1_path':item['Path'],'started_at':item['State']['StartedAt'],'memory_limit_bytes':item['HostConfig']['Memory'],'nano_cpus_limit':item['HostConfig']['NanoCpus'],'published_ports':item['NetworkSettings']['Ports'],'health':item['State'].get('Health',{}).get('Status'),'mount_targets':[m['Destination'] for m in item['Mounts']]})
result['postgres_durability']=subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT name||'='||setting FROM pg_settings WHERE name IN ('fsync','synchronous_commit','full_page_writes','max_connections') ORDER BY name"],cwd=ROOT,text=True).splitlines()
(ROOT/'evidence/runtime.json').write_text(json.dumps(result,indent=2)+'\n')
print('Saved sanitized runtime manifest: resources, images, PID1, ports, durability')
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Verify actual TLS OTLP/queries, trace chain, provisioned Grafana and privacy."""
import importlib.util,json,time,urllib.parse,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
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)
from client import Client
def query(url,**extra):
r=sec.probe(Kind='http',URL=url,Cert='operator',ReturnBody=True,**extra)
if not r['ok']:raise RuntimeError('telemetry query not ready')
return json.loads(r['body'])
def wait(fn,seconds=60):
start=time.monotonic()
while time.monotonic()-start<seconds:
try:
r=fn()
if r:return r
except (RuntimeError,KeyError,ValueError):pass
time.sleep(1)
raise AssertionError('telemetry did not become visible')
def main():
c=Client(sec.BASE,ca_file=sec.CA);a,b,o,chat=c.bootstrap();traceid=uuid.uuid4().hex;parent=uuid.uuid4().hex[:16]
r=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=synthetic.png',202,actor=a,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png','traceparent':'00-'+traceid+'-'+parent+'-01'},schema='Attachment');c.wait_ready(a,r['json'])
def chain():
raw=query('https://tempo:3200/api/traces/'+traceid);spans=[]
for batch in raw.get('batches',raw.get('resourceSpans',[])):
attrs={x['key']:x['value'].get('stringValue') for x in batch.get('resource',{}).get('attributes',[])}
for scope in batch.get('scopeSpans',batch.get('instrumentationLibrarySpans',[])):
for x in scope.get('spans',[]):spans.append({'service':attrs.get('service.name'),'name':x['name'],'id':x.get('spanId'),'parent':x.get('parentSpanId')})
if not {'queue.publish','queue.consume','s3.request','image.transform'}.issubset({x['name'] for x in spans}):return None
for x in spans:
if x['name']=='queue.consume' and x['parent'] not in {s['id'] for s in spans if s['name']=='queue.publish'}:return None
serialized=json.dumps(raw)
for actor in [a,b,o]:assert actor['token'] not in serialized and actor['registration']['password'] not in serialized
return spans
spans=wait(chain)
params={'query':'{service_name=~"messenger-(api|worker|dispatcher)"} | trace_id="'+traceid+'"','start':str(int((time.time()-180)*1e9)),'end':str(int(time.time()*1e9)),'limit':'100'}
logs=wait(lambda:query('https://loki:3100/loki/api/v1/query_range?'+urllib.parse.urlencode(params))['data']['result'])
assert {'messenger-api','messenger-worker'}.issubset({x['stream']['service_name'] for x in logs})
serialized=json.dumps(logs)
for actor in [a,b,o]:assert actor['token'] not in serialized and actor['registration']['password'] not in serialized
metrics=query('https://prometheus:9090/api/v1/query?'+urllib.parse.urlencode({'query':'sum(http_server_requests_total)'}));assert metrics['data']['result']
grafana=wait(lambda:query('https://grafana:3000/api/dashboards/uid/messenger-lab7',Auth='grafana'))
# Verify provisioned datasource TLS settings by doing actual backend health checks as Grafana.
ds={}
for uid,path in [('prometheus','/api/v1/query?query=1'),('loki','/loki/api/v1/query_range?'+urllib.parse.urlencode(params)),('tempo','/api/traces/'+traceid)]:
# Tempo12 plugin has no health method; exercise real Grafana proxy queries.
value=query('https://grafana:3000/api/datasources/proxy/uid/'+uid+path,Auth='grafana')
assert value,(uid,'empty Grafana query')
ds[uid]='actual query via Grafana proxy succeeded'
result={'trace_id':traceid,'spans':spans,'services':sorted({x['service'] for x in spans}),'log_services':sorted({x['stream']['service_name'] for x in logs}),'log_lines':sum(len(x['values']) for x in logs),'known_synthetic_tokens_passwords_absent':True,'dashboard':{'uid':grafana['dashboard']['uid'],'panels':len(grafana['dashboard']['panels'])},'actual_grafana_datasource_health':ds,'network_protocol':'all queries and OTLP use verified TLS/mTLS; native loopback remains inside gateway boundary'}
(ROOT/'evidence/telemetry.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: real TLS trace/log/metrics chain, privacy and all three provisioned Grafana datasource connections',flush=True)
if __name__=='__main__':main()
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
"""One bounded HTTPS workload with real resources and dataset counts."""
import importlib.util,json,subprocess,sys,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
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)
def counts():return json.loads(sec.sql_value("SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'messages',(SELECT count(*) FROM messages),'attachments',(SELECT count(*) FROM attachments))"))
start=time.monotonic();before=counts();rows=[];ids=sec.dc('ps','-q','api','worker','collector-store').splitlines()
p=subprocess.Popen([sys.executable,'tests/load.py','--base-url',sec.BASE,'--ca-file',sec.CA,'--duration','15','--concurrency','4','--output','evidence/load.json'],cwd=ROOT)
while p.poll() is None:
stats=subprocess.check_output(['docker','stats','--no-stream','--format','{{json .}}',*ids],text=True)
rows.append({'elapsed_seconds':round(time.monotonic()-start,3),'containers':[json.loads(x) for x in stats.splitlines()]});time.sleep(.5)
assert p.returncode==0 and (ROOT/'evidence/load.json').exists()
result={'requested_duration_seconds':15,'concurrency':4,'warmup_seconds':0,'before':before,'after':counts(),'resource_observations':rows,'limits':'closed-loop/coordinated omission, success-only latency percentiles, shared VM, growing dataset; no capacity or TLS off/on comparison'}
(ROOT/'evidence/load-resources.json').write_text(json.dumps(result,indent=2)+'\n');print('MEASURED: verified HTTPS workload, errors, percentiles, CPU/RAM and dataset counts',flush=True)