Files
mtusi2026lab7/scripts/verify.py
T
Angelika ee9d70af85
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Lab7 solution / integration (pull_request) Blocked by required conditions
ЛР 7 — БВТ2303 — Брезгунова — на 5
2026-12-04 17:07:57 +03:00

129 lines
7.0 KiB
Python

"""Explicit security/fault campaign scoped to mtusi-lab7. No secrets in evidence."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
BASE='https://localhost:8443'
CA=str(ROOT/'pki/ca.crt')
DC=['docker','compose','--env-file','.env']
def command(args,name=None):
p=subprocess.run(args,cwd=ROOT,capture_output=True,text=True,encoding='utf-8',errors='replace',timeout=300)
if name:(ROOT/'evidence'/name).write_text(p.stdout+p.stderr,encoding='utf-8')
check(p.returncode==0,'command failed: '+' '.join(args)+'\n'+p.stdout+p.stderr)
return p.stdout
def compose(*args):return command(DC+list(args))
def operator(script,*args):return compose('run','--rm','--no-deps','operator','python',script,*args)
def save(name,data):(ROOT/'evidence'/name).write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf-8')
def wait(fn,timeout=100):
until=time.monotonic()+timeout
while time.monotonic()<until:
try:
if result:=fn():return result
except Exception:pass
time.sleep(1)
raise AssertionError('deadline waiting for recovery')
def snapshot():
ids=compose('ps','-a','-q').split()
values=json.loads(command(['docker','inspect',*ids]))
return {x['Config']['Labels']['com.docker.compose.service']:{'id':x['Id'],'image':x['Image'],
'started_at':x['State']['StartedAt'],'user':x['Config']['User'],'privileged':x['HostConfig']['Privileged'],
'network_mode':x['HostConfig']['NetworkMode'],'read_only':x['HostConfig']['ReadonlyRootfs'],
'cap_drop':x['HostConfig']['CapDrop'],'security_opt':x['HostConfig']['SecurityOpt'],
'memory_limit':x['HostConfig']['Memory'],'cpu_limit':x['HostConfig']['NanoCpus'],
'ports':x['HostConfig']['PortBindings'],'mount_destinations':[m['Destination'] for m in x['Mounts']]} for x in values}
def main():
c=Client(BASE,CA,timeout=10)
wait(lambda:c.call('GET','/health/ready',schema='Health'))
command([sys.executable,'-X','utf8','scripts/check_contract.py'],'check.txt')
command([sys.executable,'-X','utf8','tests/smoke.py','--base-url',BASE,'--ca-file',CA],'smoke.txt')
command([sys.executable,'-X','utf8','tests/security.py','--base-url',BASE,'--ca-file',CA],'external-tls.txt')
print('PASS: public HTTPS smoke and external trust',flush=True)
text=operator('student-tests/security.py');(ROOT/'evidence/security-audit.txt').write_text(text,encoding='utf-8')
print(text,flush=True)
a,b,e,chat=c.bootstrap()
try:
# Seal leaves bounded cache grace. Afterwards API must fail closed.
started=time.monotonic()
operator('student-tests/lifecycle.py','seal')
time.sleep(17)
# LB correctly removes unready APIs and can generate its own 503 without
# API headers. Probe the actual API over the required LB mTLS identity.
operator('student-tests/lifecycle.py','probe-sealed')
operator('scripts/bootstrap.py','unseal')
restored=time.monotonic()
wait(lambda:c.call('GET','/api/v1/users/me',actor=a,schema='User'))
save('bao-sealed.json',{'result':'PASS','sealed_failure_status':503,
'cache_grace_bound_seconds':15,'observed_after_seconds':round(time.monotonic()-started,3),
'recovery_seconds':round(time.monotonic()-restored,3),'fallback':'none'})
print('PASS: sealed Bao -> bounded grace -> 503 -> operator unseal -> recovery',flush=True)
# Simulated compromise: worker identity is revoked, accepted work stays durable.
compose('stop','-t','1','worker')
pending=[c.attachment(a,chat) for _ in range(3)]
before=snapshot()
operator('student-tests/lifecycle.py','revoke')
compose('start','worker')
time.sleep(3)
metadata=[c.call('GET','/api/v1/attachments/'+att['id'],actor=a,schema='Attachment')['json'] for att,raw in pending]
check(all(x['status']=='queued' for x in metadata),'revoked worker processed job')
compose('stop','-t','1','worker')
operator('student-tests/lifecycle.py','rotate')
compose('run','--rm','s3-bootstrap')
operator('student-tests/lifecycle.py','old-denied')
restored=time.monotonic()
compose('start','worker')
for att,raw in pending:
ready=c.wait_ready(a,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=a)['bytes']==raw,'accepted bytes lost')
check(len(ready['variants'])==3,'incomplete result')
after=snapshot()
check(before['worker']['image']==after['worker']['image'],'rotation rebuilt image')
save('worker-compromise.json',{'result':'PASS','accepted_jobs':3,'queued_while_revoked':True,
'ready_after_rotation':3,'originals_verified':3,'variants_each':3,
'recovery_seconds':round(time.monotonic()-restored,3),'image_unchanged':True,
'hypothesis':'Scoped worker loses authority to unrelated secrets, user/session/message DB and producer/admin broker operations; revocation blocks new worker connections while durable jobs survive.',
'before_worker':before['worker'],'after_worker':after['worker'],
'limitation':'Authorized worker can still alter allowed image results and job state. Revocation is bounded by cache/active connection lifetime; host/operator compromise is outside this model.'})
print('PASS: compromised worker revoked; leaf and three credentials rotated; 3 jobs preserved',flush=True)
finally:
operator('scripts/bootstrap.py','unseal')
compose('start','api1','api2','worker')
suffix='.cmd' if os.name=='nt' else '.sh'
save('before-restart.json',snapshot())
command([sys.executable,'-X','utf8','tests/resilience.py','--mode','persistence','--action-script',str(ROOT/'scripts'/('restart'+suffix)),'--base-url',BASE,'--ca-file',CA],'persistence.txt')
save('after-restart.json',snapshot())
print('PASS: public HTTPS persistence',flush=True)
try:
command([sys.executable,'-X','utf8','tests/resilience.py','--mode','failover','--action-script',str(ROOT/'scripts'/('stop-one'+suffix)),'--base-url',BASE,'--ca-file',CA],'failover.txt')
finally:
compose('start','api1','api2')
compose('up','-d','--no-deps','--force-recreate','api1-tls','api2-tls')
wait(lambda:c.call('GET','/health/ready',schema='Health'))
command([sys.executable,'-X','utf8','tests/smoke.py','--base-url',BASE,'--ca-file',CA],'final-smoke.txt')
save('final-containers.json',snapshot())
save('verification.json',{'result':'PASS','HTTPS_smoke':True,'public_TLS_negative':True,'internal_mTLS':True,
'scoped_roles':True,'ACL_sessions_rehash_rate_limit':True,'Bao_sealed_fail_closed':True,
'secret_and_leaf_rotation':True,'worker_compromise_track':True,'persistence':True,'failover':True})
print('PASS: lab7 security campaign complete',flush=True)
if __name__=='__main__':main()