"""Real lab4-only fault injection. Restores services/triggers in finally. Operator invokes explicitly; never removes volumes or user objects. """ import base64 import json import os from pathlib import Path import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, check ROOT = Path(__file__).resolve().parents[1] COMPOSE = ['docker', 'compose', '--env-file', str(ROOT / '.env')] def compose(*args, data=None): result = subprocess.run(COMPOSE + list(args), input=data, text=True, capture_output=True, cwd=ROOT) if result.returncode: raise RuntimeError('compose action failed: ' + ' '.join(args[:2])) return result.stdout.strip() def sql(statement): return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-At', data=statement) def remote(code, data=None): return compose('exec', '-T', 'api', 'python', '-c', code, data=data) def ready(c): deadline = time.monotonic() + 60 while time.monotonic() < deadline: try: c.call('GET', '/health/ready') return except AssertionError: time.sleep(.5) raise RuntimeError('readiness timeout') S3_SUMMARY = '''from src.storage import s3, BUCKET import json objects = [o['Key'] for p in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET, Prefix='originals/') for o in p.get('Contents', [])] print(json.dumps(objects))''' def main(): c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=40) alice, bob, eve, chat = c.bootstrap() attachment, image = c.attachment(alice, chat) passed = [] # Only our unique filename will trigger a database failure AFTER a real S3 PUT. filename = 'fault-' + chat['id'] + '.png' trigger = f'''CREATE OR REPLACE FUNCTION student_fail_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename = '{filename}' THEN RAISE EXCEPTION 'synthetic attachment failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER student_fail_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_fail_attachment();''' try: before = set(json.loads(remote(S3_SUMMARY))) referenced = set(json.loads(remote('''from src.database import open_database, get_connection open_database() import json with get_connection() as conn: print(json.dumps([r['object_key'] for r in conn.execute('SELECT object_key FROM attachments').fetchall()]))'''))) sql(trigger) c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, 503, actor=alice, raw=image, headers={'Content-Type': 'image/png'}) sql('DROP TRIGGER IF EXISTS student_fail_attachment ON attachments; DROP FUNCTION IF EXISTS student_fail_attachment();') after = set(json.loads(remote(S3_SUMMARY))) orphan = after - before check(len(orphan) == 1, 'did not observe a real orphan after DB rollback') passed.append('S3_PUT_then_DB_failure_returns_503_with_real_orphan') # Fresh objects survive a real cleanup. Clock advance is confined to this test # process: production grace period and object timestamps are not changed. result = json.loads(remote('''from src.database import open_database open_database() from src.cleanup import cleanup import json print(json.dumps(cleanup()))''')) check(result['deleted'] == 0 and result['fresh'] > 0, 'fresh object deleted') passed.append('fresh_orphan_survives_one_hour_grace') result = json.loads(remote('''from src.database import open_database open_database() import src.cleanup as cleaner from datetime import datetime, timezone, timedelta class Future(datetime): @classmethod def now(cls, tz=None): return datetime.now(timezone.utc) + timedelta(hours=2) cleaner.datetime = Future import json print(json.dumps(cleaner.cleanup()))''')) check(result['deleted'] >= 1 and result['referenced'] > 0, 'cleanup failed to preserve references / delete orphan') final = set(json.loads(remote(S3_SUMMARY))) check(not orphan & final and referenced <= final, 'cleanup lost used data') passed.append('expired_orphan_deleted_referenced_objects_preserved_test_clock') repeat = json.loads(remote('''from src.database import open_database open_database() from src.cleanup import cleanup import json print(json.dumps(cleanup()))''')) check(repeat['deleted'] == 0, 'cleanup not repeatable') passed.append('cleanup_repeatable') # API credentials: anonymous GET/list denied, bucket policy/admin denied. privacy = json.loads(remote('''from src.storage import s3, BUCKET from botocore import UNSIGNED from botocore.config import Config from botocore.exceptions import ClientError import boto3, json, urllib.request, urllib.error key=s3.list_objects_v2(Bucket=BUCKET,Prefix='originals/',MaxKeys=1)['Contents'][0]['Key'] result=[] for suffix in ('/'+BUCKET+'/'+key, '/'+BUCKET+'?list-type=2'): try: urllib.request.urlopen('http://s3:9000'+suffix,timeout=3) result.append(200) except urllib.error.HTTPError as e: result.append(e.code) try: s3.get_bucket_policy(Bucket=BUCKET) result.append(200) except ClientError as e: result.append(e.response['ResponseMetadata']['HTTPStatusCode']) print(json.dumps(result))''')) check(privacy == [403, 403, 403], 'bucket or API credentials overexposed') passed.append('anonymous_GET_and_LIST_denied_API_cannot_read_policy') # Probe API itself, not a load-balancer-generated failure. request = json.dumps({'token': alice['token'], 'chat': chat['id'], 'image': base64.b64encode(image).decode()}) probe = '''import sys,json,base64,urllib.request,urllib.error x=json.load(sys.stdin) r=urllib.request.Request('http://127.0.0.1:8080/api/v1/chats/'+x['chat']+'/attachments?filename=outage.png',data=base64.b64decode(x['image']),headers={'Authorization':'Bearer '+x['token'],'Content-Type':'image/png'},method='POST') try: response=urllib.request.urlopen(r,timeout=20) except urllib.error.HTTPError as e: response=e print(json.dumps({'status':response.code,'body':json.loads(response.read()),'request_id':bool(response.headers.get('X-Request-Id')),'instance_id':bool(response.headers.get('X-Instance-Id'))}))''' for service in ('s3', 'postgres'): compose('stop', service) try: failure = json.loads(remote(probe, data=request)) check(failure['status'] == 503 and failure['request_id'] and failure['instance_id'], service + ' outage mishandled') check(failure['body']['error']['code'] == 'unavailable', 'wrong error format') finally: compose('start', service) ready(c) passed.append(service + '_outage_API_503') # An actual disconnect cannot create an object because PUT follows full validation. before = set(json.loads(remote(S3_SUMMARY))) import socket from urllib.parse import urlsplit url = urlsplit(c.base) con = socket.create_connection((url.hostname, url.port)) con.sendall((f'POST /api/v1/chats/{chat["id"]}/attachments?filename=aborted.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {alice["token"]}\r\nContent-Type: image/png\r\nContent-Length: {len(image)}\r\n\r\n').encode() + image[:100]) con.close() time.sleep(2) check(before == set(json.loads(remote(S3_SUMMARY))), 'aborted upload left an S3 object') passed.append('interrupted_upload_no_S3_object') # Kill the process while the metadata INSERT sleeps after PUT. sql(f'''CREATE OR REPLACE FUNCTION student_fail_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename = '{filename}' THEN PERFORM pg_sleep(20); END IF; RETURN NEW; END $$; CREATE TRIGGER student_fail_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_fail_attachment();''') before = set(json.loads(remote(S3_SUMMARY))) with ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(c.call, 'POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+filename, 201, actor=alice, raw=image, headers={'Content-Type':'image/png'}) deadline = time.monotonic() + 15 while time.monotonic() < deadline: observed = set(json.loads(remote(S3_SUMMARY))) - before if observed: break time.sleep(.2) check(len(observed) == 1, 'PUT not observed before crash') compose('kill', '-s', 'SIGKILL', 'api') try: future.result() raise RuntimeError('crashed request unexpectedly completed') except AssertionError: pass compose('up', '-d', '--no-deps', 'api') sql('DROP TRIGGER IF EXISTS student_fail_attachment ON attachments; DROP FUNCTION IF EXISTS student_fail_attachment();') ready(c) check(int(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")) == 0, 'crash committed metadata') check(observed <= set(json.loads(remote(S3_SUMMARY))), 'crash orphan not observed') passed.append('API_SIGKILL_after_PUT_before_COMMIT_orphan_recoverable') crash_cleanup = json.loads(remote('''from src.database import open_database open_database() import src.cleanup as cleaner from datetime import datetime, timezone, timedelta class Future(datetime): @classmethod def now(cls, tz=None): return datetime.now(timezone.utc) + timedelta(hours=2) cleaner.datetime = Future import json print(json.dumps(cleaner.cleanup()))''')) check(crash_cleanup['deleted'] >= 1, 'crash orphan cleanup did not run') check(not observed & set(json.loads(remote(S3_SUMMARY))), 'crash orphan not removed') passed.append('API_crash_orphan_actually_cleaned_after_test_clock_grace') got = c.call('GET', '/api/v1/attachments/'+attachment['id']+'/content', actor=bob)['bytes'] check(got == image, 'confirmed attachment lost during failures') passed.append('confirmed_original_survives_faults') print(json.dumps({'passed': passed, 'count': len(passed), 'privacy_status_codes': privacy, 'cleanup_expired_result': result, 'grace_test': 'test process clock +2h; production grace remains 1h'}, indent=2)) finally: compose('start', 'postgres', 's3') compose('up', '-d', '--no-deps', 'api') sql('DROP TRIGGER IF EXISTS student_fail_attachment ON attachments; DROP FUNCTION IF EXISTS student_fail_attachment();') if __name__ == '__main__': main()