forked from mtusi2026/mtusi2026lab7
128 lines
7.5 KiB
Python
128 lines
7.5 KiB
Python
"""Operator-driven lifecycle tests. Synthetic data; volumes are never deleted."""
|
|
import hashlib
|
|
import json
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
sys.path[:0]=[str(ROOT),str(ROOT/'tests')]
|
|
from scripts import lab7 as op
|
|
from client import Client
|
|
|
|
|
|
def main():
|
|
evidence=ROOT/'evidence';evidence.mkdir(exist_ok=True)
|
|
checks=[]
|
|
def ok(name,condition=True,**details):
|
|
assert condition,name
|
|
checks.append({'test':name,'passed':True,**details});print('PASS: '+name,flush=True)
|
|
(evidence/'lifecycle.json').write_text(json.dumps(checks,indent=2),encoding='utf-8')
|
|
def audit(code):
|
|
return op.compose('run','--rm','--no-deps','-T','audit','-',data=code).stdout
|
|
def ready():
|
|
try:return c.call('GET','/health/ready',schema='Health')['status']==200
|
|
except Exception:return False
|
|
def saved():
|
|
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
|
history=c.call('GET',f"/api/v1/chats/{chat['id']}/messages?limit=100",actor=bob,schema='MessagePage')['json']['items']
|
|
assert original in history
|
|
content=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content",actor=bob)['bytes']
|
|
assert content==blob
|
|
thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes']
|
|
assert thumbnail==original_thumbnail
|
|
c=Client('https://127.0.0.1:8443',str(ROOT/'secrets/ca.crt'),timeout=5)
|
|
alice,bob,eve,chat=c.bootstrap()
|
|
canary='private-message-'+hashlib.sha256(alice['token'].encode()).hexdigest()
|
|
original=c.message(alice,chat,canary)['json']
|
|
attachment,blob=c.attachment(alice,chat);c.wait_ready(alice,attachment)
|
|
original_thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes']
|
|
foreign=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other chat','member_ids':[eve['id']]},schema='Chat')['json']
|
|
c.call('POST',f"/api/v1/chats/{foreign['id']}/messages",404,actor=eve,
|
|
body={'text':'','attachment_ids':[attachment['id']]},headers={'Idempotency-Key':'cross-chat-probe'})
|
|
ok('Cannot attach another chat file')
|
|
c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
|
|
ok('Request size is bounded')
|
|
ids={name:op.compose('exec','-T',name,'hostname').stdout.strip() for name in ['api1','api2']}
|
|
for target in ['api1','api2']:
|
|
op.compose('stop',target)
|
|
start=time.monotonic()
|
|
try:
|
|
successes=0;failures=0
|
|
while successes<5:
|
|
try:
|
|
response=c.call('GET','/api/v1/users/me',actor=alice)
|
|
assert response['headers']['X-Instance-Id']!=ids[target]
|
|
successes+=1
|
|
except Exception:
|
|
failures+=1;successes=0
|
|
assert time.monotonic()-start<10,'failover did not recover within 10s'
|
|
saved()
|
|
ok('Replica failover '+target,recovery_seconds=round(time.monotonic()-start,2),failed_attempts=failures)
|
|
finally:
|
|
op.compose('start',target);op.compose('restart',target+'-tls')
|
|
time.sleep(12)
|
|
# Restart the complete stack, including sealed persistent OpenBao.
|
|
op.restart_stack()
|
|
op.wait_service(ready,90);saved()
|
|
ok('Full restart preserves sessions, messages, original and processed attachment')
|
|
old=json.loads((op.PRIVATE/'credentials.json').read_text())['api']['db']
|
|
image_before=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip()
|
|
op.rotate_secret();time.sleep(12);op.wait_service(ready,30)
|
|
code="""import psycopg
|
|
try:
|
|
psycopg.connect(host='postgres',dbname='messenger',user='api',password=OLD,sslmode='verify-full',sslrootcert='/audit-secrets/ca.crt',connect_timeout=3)
|
|
except psycopg.OperationalError as e:
|
|
assert 'password authentication failed' in str(e)
|
|
print('old DB password rejected')
|
|
else:raise AssertionError('old DB password accepted')
|
|
""".replace('password=OLD','password='+repr(old))
|
|
audit(code);saved();ok('Working DB secret rotated; old password rejected on new connection')
|
|
op.rotate_leaf();op.wait_service(ready,30);saved()
|
|
output=op.compose('run','--rm','--no-deps','audit','/audit/internal.py').stdout
|
|
(evidence/'internal.txt').write_text(output,encoding='utf-8')
|
|
ok('Leaf rotated and old LB identity revoked on both replicas')
|
|
image_after=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip()
|
|
ok('Rotations do not rebuild image',image_before==image_after,image=image_after)
|
|
# Obtain a real scoped token, let it expire, then demonstrate sealed fail-closed.
|
|
auth=op.bao('POST','auth/cert/login',{'name':'api'},role='api')['auth']
|
|
started=time.monotonic()
|
|
time.sleep(auth['lease_duration']+2)
|
|
try:op.bao('GET','secret/data/api',token=auth['client_token'],role='api')
|
|
except RuntimeError as exc:ok('Expired OpenBao token denied','HTTP 403' in str(exc))
|
|
else:raise AssertionError('expired token accepted')
|
|
admin=json.loads((op.PRIVATE/'bao-init.json').read_text())['root_token']
|
|
op.bao('PUT','sys/seal',token=admin)
|
|
started=time.monotonic()
|
|
try:
|
|
time.sleep(70)
|
|
ok('Sealed OpenBao stops API within bounded secret cache',not ready(),elapsed_seconds=round(time.monotonic()-started,2))
|
|
for name in ['worker','dispatcher','cleanup']:
|
|
code="import pathlib; x=[p.read_bytes() for p in pathlib.Path('/proc').glob('[0-9]*/cmdline')]; assert not any(b'python\\x00-m\\x00src.' in v and b'src.secure_run' not in v for v in x)"
|
|
op.compose('exec','-T',name,'python','-c',code)
|
|
ok('Sealed OpenBao stops background consumers too')
|
|
finally:
|
|
op.unseal()
|
|
op.wait_service(ready,45);saved();ok('Unseal recovers without baked-in fallback secret')
|
|
# Public API errors and telemetry must not contain actual secrets or canaries.
|
|
credentials=json.loads((op.PRIVATE/'credentials.json').read_text())
|
|
values=[v for role in credentials.values() for v in role.values()]
|
|
values += [alice['token'],alice['registration']['password'],canary]
|
|
logs=op.compose('logs','--no-color','--since','30m','api1','api2','worker','dispatcher','cleanup','otel-collector','loki','tempo').stdout
|
|
ok('Container logs do not expose credentials or private message',not any(v in logs for v in values))
|
|
telemetry_code="import sys; sys.path.insert(0,'/audit'); from telemetry import check; check("+repr(values)+")"
|
|
print(audit(telemetry_code),flush=True);ok('Live metrics/logs/traces have no credential leaks; datasource writes denied')
|
|
deployed=json.loads(op.compose('config','--format','json').stdout)['services']
|
|
for name,spec in deployed.items():
|
|
assert spec['read_only'] and 'ALL' in spec['cap_drop'] and 'no-new-privileges:true' in spec['security_opt']
|
|
assert spec.get('mem_limit') and spec.get('cpus')
|
|
ok('All services have read_only, no-new-privileges, cap_drop and limits')
|
|
hardware=json.loads(op.docker('info','--format','{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"os":{{json .OperatingSystem}},"architecture":{{json .Architecture}}}').stdout)
|
|
hardware['app_image']=image_after
|
|
hardware['services']={name:{key:spec.get(key) for key in ['image','cpus','mem_limit','user','read_only','cap_drop','cap_add','security_opt']} for name,spec in deployed.items()}
|
|
(evidence/'environment.json').write_text(json.dumps(hardware,indent=2),encoding='utf-8')
|
|
ok('Complete lifecycle suite')
|
|
|
|
|
|
if __name__=='__main__':main()
|