forked from mtusi2026/mtusi2026lab2
ЛР 2 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extra assertions on the student's local Compose stack; restores stopped services/TTL."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
COMPOSE = ['docker', 'compose', '--env-file', '.env']
|
||||
BASE = os.environ.get('BASE_URL', 'http://127.0.0.1:8080')
|
||||
|
||||
def command(args, **kwargs):
|
||||
result = subprocess.run(args, cwd=ROOT, capture_output=True, **kwargs)
|
||||
if result.returncode:
|
||||
raise AssertionError('Infrastructure command failed: '+args[0]+' '+args[1])
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
def compose(*args, env=None):
|
||||
return command(COMPOSE+list(args), env=env)
|
||||
|
||||
def sql(query):
|
||||
return command(COMPOSE+['exec', '-T', 'postgres', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-U', 'messenger', '-d', 'messenger', '-At', '-c', query])
|
||||
|
||||
def ready(c):
|
||||
deadline = time.monotonic()+90
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except AssertionError:
|
||||
time.sleep(0.5)
|
||||
raise AssertionError('API readiness timeout')
|
||||
|
||||
def metrics(c):
|
||||
result = c.call('GET', '/metrics')['bytes'].decode()
|
||||
return {line.split()[0]: float(line.split()[1]) for line in result.splitlines() if line and not line.startswith('#') and '{' not in line}
|
||||
|
||||
def main():
|
||||
c = Client(BASE, timeout=5)
|
||||
ready(c)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
results = {}
|
||||
# Database uniqueness, not an application-side check, resolves this race.
|
||||
registration = dict(alice['registration'], username='race_'+uuid.uuid4().hex[:16])
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
statuses = list(pool.map(lambda _: Client(BASE).call('POST', '/api/v1/users', [201,409], body=registration)['status'], range(4)))
|
||||
check(sorted(statuses)==[201,409,409,409], 'duplicate registration race')
|
||||
results['registration_race'] = statuses
|
||||
# Unknown second member fails AFTER inserting a chat and its first member.
|
||||
before = sql('SELECT count(*) FROM chats')
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title':'rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
|
||||
check(sql('SELECT count(*) FROM chats')==before, 'partial chat survived rollback')
|
||||
check(sql('SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id=m.chat_id WHERE c.id IS NULL')=='0', 'orphan membership')
|
||||
results['rollback'] = 'PASS: chat and membership inserts rolled back'
|
||||
# Hash and tokens never stored as plaintext.
|
||||
check(sql("SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users")=='t', 'not all passwords use Argon2id')
|
||||
check(sql('SELECT bool_and(octet_length(token_hash)=32) FROM sessions')=='t', 'invalid token hashes')
|
||||
results['credential_storage'] = 'Argon2id; 32-byte session digests'
|
||||
# Resource-bound cursor, sender spoof, Unicode password beyond bcrypt byte limit.
|
||||
other = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Other','member_ids':[alice['id']]},schema='Chat')['json']
|
||||
c.message(alice,chat,'one');c.message(alice,chat,'two')
|
||||
page = c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=1',actor=alice,schema='MessagePage')['json']
|
||||
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+page['next_cursor'],400,actor=alice)
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=alice,body={'text':'spoof','sender_id':eve['id']})
|
||||
unicode_body = {'username':'uni_'+uuid.uuid4().hex[:16], 'display_name':'Юникод', 'password':'🔑'*127+':'}
|
||||
c.call('POST','/api/v1/users',201,body=unicode_body,schema='User')
|
||||
credential = base64.b64encode((unicode_body['username']+':'+unicode_body['password']).encode()).decode()
|
||||
session = c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json']
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor={'token':session['token']})
|
||||
results['contract_edges'] = 'PASS: cursor scope, no sender spoof, 128 Unicode password characters including colon'
|
||||
# Profile cache proves actual Redis use without caching session authorization.
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
before_hits = metrics(c)['messenger_profile_cache_hits_total']
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
check(metrics(c)['messenger_profile_cache_hits_total']>before_hits, 'Redis profile cache unused')
|
||||
compose('stop','redis')
|
||||
try:
|
||||
start = time.monotonic()
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
c.call('GET','/health/ready',schema='Health')
|
||||
c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']})
|
||||
check(metrics(c)['messenger_profile_cache_failures_total']>0, 'missing cache fallback metric')
|
||||
results['redis_down'] = {'fallback':'PASS','seconds':round(time.monotonic()-start,3)}
|
||||
finally:
|
||||
compose('start','redis')
|
||||
ready(c)
|
||||
# A lost cache is harmless: existing sessions and confirmed messages are in PostgreSQL.
|
||||
compose('exec','-T','redis','redis-cli','FLUSHDB')
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
c.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=bob,schema='MessagePage')
|
||||
results['cache_loss'] = 'PASS: cache rebuild; original session/data valid'
|
||||
compose('stop','postgres')
|
||||
try:
|
||||
start = time.monotonic()
|
||||
c.call('GET','/api/v1/users/me',503,actor=alice)
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']})
|
||||
elapsed = time.monotonic()-start
|
||||
check(elapsed<7, 'database outage unbounded')
|
||||
results['postgres_down'] = {'protected_request':503,'readiness':503,'liveness':200,'seconds':round(elapsed,3)}
|
||||
finally:
|
||||
compose('start','postgres')
|
||||
ready(c)
|
||||
# Re-running migrations on startup changes neither schema version nor data.
|
||||
counts = sql("SELECT (SELECT count(*) FROM schema_migrations)||':'||(SELECT count(*) FROM users)||':'||(SELECT count(*) FROM messages)")
|
||||
compose('restart','api');ready(c)
|
||||
check(sql("SELECT (SELECT count(*) FROM schema_migrations)||':'||(SELECT count(*) FROM users)||':'||(SELECT count(*) FROM messages)")==counts, 'migration replay modified data')
|
||||
results['migration_replay'] = 'PASS: same migration/user/message counts'
|
||||
# Dedicated short TTL run. Restore normal configuration even on assertion failure.
|
||||
short_env = dict(os.environ, SESSION_TTL_SECONDS='2')
|
||||
try:
|
||||
compose('up','-d','--no-deps','api',env=short_env);ready(c)
|
||||
short = c.user('short')
|
||||
c.call('GET','/api/v1/users/me',actor=short,schema='User')
|
||||
time.sleep(2.2)
|
||||
c.call('GET','/api/v1/users/me',401,actor=short)
|
||||
results['expiry'] = 'PASS: SESSION_TTL_SECONDS=2 rejects existing token after expiry'
|
||||
finally:
|
||||
compose('up','-d','--no-deps','api');ready(c)
|
||||
c.call('GET','/api/v1/users/me',401,actor=short)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
results['logout'] = 'PASS: revoked token rejected'
|
||||
(ROOT/'evidence'/'integration.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print('PASS: races, rollback, KDF, cache hit/loss/outage, DB outage, migration replay, expiry, logout')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user