#!/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()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()