#!/usr/bin/env python3 """HTTP, SQL atomicity, dependency failures, persistence, and short TTL checks. Only this lab's Compose services and synthetic users are affected. """ import argparse import base64 from concurrent.futures import ThreadPoolExecutor import json import os from pathlib import Path import subprocess import sys import time import uuid from urllib.parse import quote ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'tests')) from client import Client def compose(*args,env=None): r=subprocess.run(['docker','compose','--env-file','.env',*args],cwd=ROOT,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) if r.returncode:raise RuntimeError('Compose command failed: '+args[0]) return r.stdout.strip() def sql(q):return compose('exec','-T','postgres','psql','-X','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1','-c',q) def cache(*args): # Password is read only inside container; never printed or put on host argv. return compose('exec','-T','valkey','sh','-c','export REDISCLI_AUTH="$(sed -n \'s/^requirepass //p\' /run/secrets/valkey_config)"; exec valkey-cli "$@"','sh',*args) def ready(c): until=time.monotonic()+40 while time.monotonic()future['created_at'];passed('monotonic_chat_clock') good=base64.b64encode((a['registration']['username']+':'+a['registration']['password']).encode()).decode() bad=base64.b64encode((a['registration']['username']+':Synthetic-wrong-password').encode()).decode() c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad}) c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good}) c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':a['id']}) assert c.call('GET','/api/v1/users/me',actor=a,headers={'X-User-Id':e['id']},schema='User')['json']['id']==a['id'] c.call('GET',path,404,actor=e);passed('authentication_and_chat_authorization') assert sql("SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users")=='t' assert sql('SELECT bool_and(octet_length(token_hash)=32) FROM sessions')=='t';passed('password_kdf_and_token_digest_storage') c.call('GET','/api/v1/users/me',actor=a,schema='User') ttl=int(cache('TTL','profile:v1:'+a['id']));assert 00 passed('cache_flush_repopulates_with_same_session') compose('stop','valkey') try: c.call('GET','/health/ready',schema='Health');c.call('GET','/api/v1/users/me',actor=a,schema='User') msg=c.message(a,chat,'cache-off-read-after-write')['json'] # Explicit small chat keeps complete post-write comparison unambiguous. msg=c.message(a,other,'must-be-visible')['json'];assert msg in c.call('GET','/api/v1/chats/'+other['id']+'/messages',actor=a,schema='MessagePage')['json']['items'] c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':a['id']}) passed('cache_down_fallback_and_read_after_write') finally:compose('start','valkey') compose('stop','postgres') try: live=c.call('GET','/health/live',schema='Health');ready_result=c.call('GET','/health/ready',503) begin=time.monotonic();c.call('GET','/api/v1/users/me',503,actor=a);elapsed=time.monotonic()-begin assert elapsed<4;passed('database_down_fails_closed',{'live':live['status'],'ready':ready_result['status'],'request_seconds':round(elapsed,3)}) finally:compose('start','postgres');ready(c) # Revoke while profile remains cached, then retry with the exact token. c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a) c.call('GET','/api/v1/users/me',401,actor=a);c.call('DELETE','/api/v1/auth/sessions/current',401,actor=a) passed('logout_with_warm_cache') before_containers=containers();before_counts=sql('SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions),(SELECT count(*) FROM schema_migrations)') subprocess.run(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+args.base_url],cwd=ROOT,check=True) after_containers=containers();assert all(before_containers[x]!=after_containers[x] for x in before_containers) after_counts=sql('SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions),(SELECT count(*) FROM schema_migrations)') assert sql('SELECT count(*) FROM schema_migrations')=='1' c.call('GET','/api/v1/users/me',actor=b,schema='User') # A cursor created before restart retains its HMAC key. c.call('GET',path+'?limit=1&cursor='+quote(cursor,safe=''),actor=b,schema='MessagePage') passed('full_stack_restart_and_cursor',{'before':before_containers,'after':after_containers,'counts_before':before_counts,'counts_after':after_counts}) # Separate short TTL configuration, no global DB edits and no token saved. short_env=dict(os.environ,SESSION_TTL_SECONDS='2');compose('up','-d','--no-deps','--force-recreate','api',env=short_env);ready(c) try: short=c.user('expiry');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);passed('session_expiry_ttl_2_seconds') # Existing long-lived session's expiry is not recomputed at API restart. c.call('GET','/api/v1/users/me',actor=b,schema='User');passed('restart_does_not_shorten_existing_session') finally:compose('up','-d','--no-deps','--force-recreate','api');ready(c) evidence['result']='PASS';(ROOT/'evidence/integration.json').write_text(json.dumps(evidence,ensure_ascii=False,indent=2)+'\n') print('PASS: all student integration checks') if __name__=='__main__':main()