Files
mtusi2026lab2/evidence/auth-retest-2026-10-13-658e0bd7/focused-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

64 lines
5.4 KiB
Python

import datetime as dt,hashlib,json,pathlib,subprocess,sys,time
s=json.loads(pathlib.Path('/tmp/highload-current-auth-retest.json').read_text());tmp=pathlib.Path(s['tmp']);root=pathlib.Path(s['root'])
sys.path.insert(0,str(root/'tests'));from client import Client,Failure,check
assert s['project'].startswith('highload-auth-retest-')
base=['docker','compose','-p',s['project'],'--project-directory',str(root),'-f',str(root/'compose.yaml'),'-f',str(tmp/'compose.test.yaml')]
c=Client(s['base_url'],timeout=5);results=[]
def record(name,fn):
try:fn();results.append({'check':name,'status':'PASS'})
except (Failure,ValueError,OSError,subprocess.SubprocessError) as e:results.append({'check':name,'status':'FAIL','detail':str(e) if isinstance(e,Failure) else type(e).__name__})
print(name+': '+results[-1]['status'],flush=True)
def hook(action):
p=subprocess.run([str(tmp/('test-'+action))],capture_output=True,text=True,timeout=90)
check(p.returncode==0,'controlled '+action+' hook failed')
def sql(statement):
p=subprocess.run(base+['exec','-T','postgres','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger'],input=statement+'\n',capture_output=True,text=True,timeout=10)
check(p.returncode==0,'SQL fixture inspection failed (details suppressed)');return p.stdout.strip()
a,b,e=c.user('probe_a'),c.user('probe_b'),c.user('probe_e')
room=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Focused retest','member_ids':[a['id'],b['id']]},schema='Chat')['json']
original=c.message(a,room,'Confirmed before full restart')['json']
hash_value=hashlib.sha256(a['token'].encode()).hexdigest()
lookup="SELECT expires_at FROM sessions WHERE token_hash=decode('"+hash_value+"','hex');"
before=sql(lookup)
record('working login and Bearer identity',lambda:check(c.call('GET','/api/v1/users/me',actor=a,schema='User')['json']==a['user'],'wrong session identity'))
record('required logout route returns 204',lambda:c.call('DELETE','/api/v1/auth/sessions/current',204,actor=e))
# This diagnostic confirms revocation implementation separately from the wrong route.
record('implemented alternate logout route revokes its token',lambda:c.call('DELETE','/api/v1/auth/current',204,actor=e))
record('revoked session is rejected',lambda:c.call('GET','/api/v1/users/me',401,actor=e))
def full_restart():
hook('restart')
check(c.call('GET','/api/v1/users/me',actor=a,schema='User')['json']==a['user'],'existing session/user lost across restart')
check(c.call('GET','/api/v1/chats/'+room['id']+'/messages',actor=b,schema='MessagePage')['json']['items']==[original],'confirmed message changed')
check(sql(lookup)==before,'full restart or read extended stored expiry')
record('actual issued token messages and expiry survive full API/Postgres restart',full_restart)
try:
hook('failure')
record('live stays 200 during PostgreSQL outage',lambda:c.call('GET','/health/live',schema='Health'))
record('anonymous request stays 401 during outage',lambda:c.call('GET','/api/v1/users/me',401))
record('ready 503 follows Error schema',lambda:c.call('GET','/health/ready',503))
# Save only the health status and response field names, no credentials.
import urllib.request,urllib.error
try:
urllib.request.urlopen(s['base_url']+'/health/ready',timeout=5)
except urllib.error.HTTPError as response:
payload=json.load(response)
(tmp/'readiness-outage-shape.json').write_text(json.dumps({'status':response.code,'body':payload,'x_request_id_present':bool(response.headers.get('X-Request-Id'))},indent=2))
record('valid Bearer request returns 503 unavailable during outage',lambda:check(c.call('GET','/api/v1/users/me',503,actor=a)['json']['error']['code']=='unavailable','wrong outage error'))
record('registration returns 503 during outage',lambda:c.call('POST','/api/v1/users',503,body={'username':'outage_'+hash_value[:16],'display_name':'Outage','password':'Synthetic-Outage-Fixture-123'}))
import base64
headers={'Authorization':'Basic '+base64.b64encode((a['registration']['username']+':'+a['registration']['password']).encode()).decode()}
record('login returns 503 during outage',lambda:c.call('POST','/api/v1/auth/sessions',503,headers=headers))
record('logout does not succeed during outage',lambda:c.call('DELETE','/api/v1/auth/sessions/current',503,actor=a))
finally:hook('recovery')
record('original session recovers after PostgreSQL returns',lambda:check(c.call('GET','/api/v1/users/me',actor=a,schema='User')['json']==a['user'],'session changed after recovery'))
record('revoked token remains revoked after database recovery',lambda:c.call('GET','/api/v1/users/me',401,actor=e))
proofs=[json.loads(line) for line in (tmp/'hook-proof.jsonl').read_text().splitlines()]
def restart_proof():
restarts=[p for p in proofs if p['action']=='restart'];check(bool(restarts),'restart hook never executed')
for p in restarts:
for svc in ('api','postgres'):check(p['before'][svc]['started_at']!=p['after'][svc]['started_at'] and p['after'][svc]['running'],'service was not restarted')
check(p['before']['postgres']['volumes']==p['after']['postgres']['volumes'],'restart changed PostgreSQL volume')
record('restart evidence shows both processes restarted with same volume',restart_proof)
(tmp/'focused-diagnostics.json').write_text(json.dumps({'scope':'actual sessions issued by HTTP API; alternate logout route is diagnostic only and does not satisfy contract','results':results},indent=2))
raise SystemExit(0 if all(x['status']=='PASS' for x in results) else 1)