Files
mtusi2026lab7-fork/student-tests/public_security.py

64 lines
4.2 KiB
Python

"""Verified HTTPS ACL, session expiry, legacy rehash, global login budget and KDF cost."""
import base64,hashlib,json,statistics,subprocess,sys,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'));a,b,e,chat=c.bootstrap();results={}
att,original=c.attachment(a,chat);att=c.wait_ready(b,att)
path='/api/v1/attachments/'+att['id']
for endpoint in (path,path+'/content'):c.call('GET',endpoint,404,actor=e)
c.call('GET',path,404,actor=e,headers={'X-User-Id':a['id']})
check(c.call('GET','/api/v1/users/me',actor=a,headers={'X-User-Id':e['id']},schema='User')['json']['id']==a['id'],'identity spoof')
other=c.call('POST','/api/v1/chats',201,actor=e,body={'title':'Own chat','member_ids':[e['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=e,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
results['attachment_acl_and_identity_spoof']=True
# Legacy hash is generated in the runtime, with the password passed via stdin.
code="""
import json,sys,time,statistics
from messenger import security
from messenger.config import Config
from messenger.db import Database
v=json.load(sys.stdin);db=Database(Config.from_env());db.open()
with db.cursor() as cur:
cur.execute('UPDATE users SET password_hash=%s WHERE id=%s',(security.legacy_hash_password(v['password']),v['id']))
samples=[]
for _ in range(12):
start=time.perf_counter();security.hash_password('synthetic-benchmark-password');samples.append((time.perf_counter()-start)*1000)
print(json.dumps({'argon2_memory_kib':19456,'iterations':2,'parallelism':1,'samples':len(samples),'median_ms':statistics.median(samples),'max_ms':max(samples),'max_concurrent_per_api':2}))
db.close()
"""
result=subprocess.run(['docker','compose','exec','-T','api-a','python','-c',code],cwd=ROOT,input=json.dumps({'id':a['id'],'password':a['registration']['password']}),text=True,capture_output=True,check=True)
results['kdf_budget']=json.loads(result.stdout)
credential=base64.b64encode((a['registration']['username']+':'+a['registration']['password']).encode()).decode()
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
code="""
import sys
from messenger.config import Config
from messenger.db import Database
db=Database(Config.from_env());db.open()
with db.cursor() as cur:
cur.execute('SELECT password_hash FROM users WHERE id=%s',(sys.argv[1],));assert cur.fetchone()['password_hash'].startswith('$argon2id$v=19$m=19456,t=2,p=1$')
print('PASS')
"""
subprocess.run(['docker','compose','exec','-T','api-a','python','-c',code,a['id']],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
results['legacy_rehash']=True
# Force expiry of a real session; Redis must not override PostgreSQL expiry.
digest=hashlib.sha256(b['token'].encode()).hexdigest()
sql="UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token_hash='"+digest+"';"
subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger'],cwd=ROOT,input=sql,text=True,check=True,stdout=subprocess.DEVNULL)
c.call('GET','/api/v1/users/me',401,actor=b)
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a);c.call('GET','/api/v1/users/me',401,actor=a)
results['session_expiry_logout']=True
time.sleep(11)
instances=set();limited=0
for _ in range(38):
reply=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':'Basic '+base64.b64encode(b'unknown-user:wrong-password').decode()})
instances.add(reply['headers']['X-Instance-Id'])
if reply['status']==429:
check(reply['headers'].get('Retry-After')=='10','missing Retry-After');limited+=1
check(len(instances)==2 and limited>=8,'rate budget not shared across two replicas')
results['global_login_rate_limit']={'replicas':len(instances),'limited_requests':limited,'requests':38,'limit':'30 per 10 seconds'}
(ROOT/'evidence/public-security.json').write_text(json.dumps(results,indent=2)+'\n')
time.sleep(11) # Leave the shared budget usable for subsequent independent checks.
print('PASS ACL, rehash, expiry/logout, shared login budget and Argon2 benchmark')