Files
mtusi2026lab2/evidence/auth-review-2026-10-13-8d403a11/seeded-diagnostics.py
T
OlegRood 834876c938 ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
2026-10-28 13:30:26 +03:00

81 lines
5.6 KiB
Python

import base64,datetime as dt,hashlib,json,secrets,subprocess,sys,time,uuid
from pathlib import Path
s=json.loads(Path('/tmp/highload-auth-review-state.json').read_text())
root=Path(s['root'])
sys.path.insert(0,str(root/'tests'))
from client import Client,Failure,check
c=Client('http://'+s['api_address'],timeout=5)
base=['docker','compose','-p',s['project'],'-f',str(root/'compose.yaml'),'-f',s['override']]
assert s['project'].startswith('highload-auth-review-')
results=[]
def record(name,fn):
try:
value=fn()
results.append({'name':name,'status':'PASS','detail':value})
except (Failure,ValueError,OSError,subprocess.SubprocessError) as e:
results.append({'name':name,'status':'FAIL','detail':str(e) if isinstance(e,Failure) else type(e).__name__})
print(json.dumps(results[-1]),flush=True)
def sql(statement):
p=subprocess.run(base+['exec','-T','postgres','psql','-U','messenger','-d','messenger','-qAt','-v','ON_ERROR_STOP=1'],input=statement,text=True,capture_output=True,timeout=10)
check(p.returncode==0,'diagnostic fixture SQL failed (details suppressed)')
return p.stdout.strip()
def actor(expired=False):
body={'username':'probe_'+uuid.uuid4().hex[:18],'display_name':'Diagnostic','password':'Synthetic:'+uuid.uuid4().hex}
user=c.call('POST','/api/v1/users',201,body=body,schema='User')['json']
token=secrets.token_urlsafe(32)
token_hash=hashlib.sha256(token.encode()).hexdigest()
times="now()-interval '2 minutes', now()-interval '1 minute'" if expired else "now(), now()+interval '1 hour'"
sql("INSERT INTO sessions(token_hash,user_id,created_at,expires_at) VALUES (decode('"+token_hash+"','hex'),'"+user['id']+"',"+times+");")
return {'id':user['id'],'token':token,'user':user,'registration':body,'hash':token_hash}
a,b,e=actor(),actor(),actor()
record('fixture session authenticates user',lambda:check(c.call('GET','/api/v1/users/me',actor=a,schema='User')['json']==a['user'],'wrong session owner'))
record('X-User-Id cannot override bearer',lambda:check(c.call('GET','/api/v1/users/me',actor=a,headers={'X-User-Id':e['id']},schema='User')['json']==a['user'],'legacy identity override'))
record('unknown token is unauthorized',lambda:c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Bearer '+secrets.token_urlsafe(32)}) and None)
record('missing auth has one JSON error',lambda:c.call('GET','/api/v1/users/me',401) and None)
expired=actor(expired=True)
record('expired stored token is unauthorized',lambda:c.call('GET','/api/v1/users/me',401,actor=expired) and None)
room=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Diagnostic','member_ids':[a['id'],b['id']]},schema='Chat')['json']
path='/api/v1/chats/'+room['id']
record('outsider chat stays hidden',lambda:c.call('GET',path,404,actor=e) and None)
sent=c.call('POST',path+'/messages',201,actor=a,headers={'X-User-Id':b['id']},body={'text':'Diagnostic sender'},schema='Message')['json']
record('sender derives from bearer',lambda:check(sent['sender_id']==a['id'],'incorrect sender'))
second=c.message(b,room,'Diagnostic second')['json']
from urllib.parse import quote
def history():
p1=c.call('GET',path+'/messages?limit=1',actor=a,schema='MessagePage')['json']
check(p1['next_cursor'] is not None,'missing continuation')
p2=c.call('GET',path+'/messages?limit=1&cursor='+quote(p1['next_cursor'],safe=''),actor=a,schema='MessagePage')['json']
check(p1['items']+p2['items']==[sent,second] and p2['next_cursor'] is None,'incorrect ascending pages')
record('history ascending with keyset',history)
record('contract logout path returns 204',lambda:c.call('DELETE','/api/v1/auth/sessions/current',204,actor=e) and None)
original_expiry=sql("SELECT expires_at FROM sessions WHERE token_hash=decode('"+a['hash']+"','hex');")
def restart():
p=subprocess.run(base+['restart','api','postgres'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=90)
check(p.returncode==0,'test-stack restart failed')
for _ in range(90):
try:
if c.call('GET','/api/v1/users/me',actor=a,schema='User')['json']==a['user']: break
except Failure: pass
time.sleep(.3)
else: raise Failure('existing session did not survive full restart')
messages=c.call('GET',path+'/messages',actor=b,schema='MessagePage')['json']['items']
check(messages==[sent,second],'confirmed messages changed after restart')
check(sql("SELECT expires_at FROM sessions WHERE token_hash=decode('"+a['hash']+"','hex');")==original_expiry,'restart extended session TTL')
record('full restart preserves seeded token/messages/deadline',restart)
try:
p=subprocess.run(base+['stop','postgres'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=70)
check(p.returncode==0,'test PostgreSQL stop failed')
record('live stays available during PostgreSQL outage',lambda:c.call('GET','/health/live',schema='Health') and None)
record('ready returns 503 during PostgreSQL outage',lambda:c.call('GET','/health/ready',503) and None)
record('valid bearer returns 503 during PostgreSQL outage',lambda:c.call('GET','/api/v1/users/me',503,actor=a) and None)
finally:
p=subprocess.run(base+['start','postgres'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=30)
check(p.returncode==0,'test PostgreSQL recovery failed')
for _ in range(50):
try:
c.call('GET','/api/v1/users/me',actor=a,schema='User');break
except Failure: time.sleep(.3)
else: raise Failure('session unavailable after PostgreSQL recovery')
record('session recovers after PostgreSQL outage',lambda:check(c.call('GET','/api/v1/users/me',actor=a,schema='User')['json']==a['user'],'session changed'))
Path(s['directory'],'seeded-diagnostics.json').write_text(json.dumps({'scope':'DIAGNOSTIC ONLY: sessions inserted into isolated test DB, login endpoint NOT validated by these probes','results':results},indent=2))