"""Required original-file, replica-switch, bucket and S3-outage demonstrations.""" import hashlib from io import BytesIO import json import os from pathlib import Path import subprocess import sys import time import urllib.error import urllib.request ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT / 'tests'), str(ROOT / 'scripts')] from client import Client, check from labctl import containers, restore, save def compose(*args, payload=None): process = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8') if process.returncode: raise RuntimeError('Compose action failed: ' + args[0]) return process.stdout.strip() def wait_ready(c): deadline = time.monotonic() + 60 while time.monotonic() < deadline: try: c.call('GET', '/health/ready', schema='Health') return except AssertionError: time.sleep(.5) raise RuntimeError('Readiness did not recover') def inside_probe(): """Called in one API container with existing synthetic actors over stdin.""" sys.path.insert(0, str(ROOT / 'src')) from messenger.core import Config, Store from PIL import Image data = json.load(sys.stdin) c = Client('http://localhost:8080') alice, bob, eve, chat, att = (data[x] for x in ('alice', 'bob', 'eve', 'chat', 'att')) if data['mode'] == 'private': store = Store(Config.from_env()) try: row = store.attachments.get(alice['id'], att['id']) url = os.environ['S3_ENDPOINT'] + '/' + os.environ['S3_BUCKET'] + '/' + row['object_key'] try: urllib.request.urlopen(url, timeout=3) raise AssertionError('Anonymous object read succeeded') except urllib.error.HTTPError as error: check(error.code == 403, 'Expected anonymous S3 403') images = [] for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]: buf = BytesIO() Image.new('RGB', (32, 24), 'blue').save(buf, format=fmt) raw = buf.getvalue() uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=real.' + fmt.lower(), 201, actor=alice, raw=raw, headers={'Content-Type': mime}, schema='Attachment')['json'] downloaded = c.call('GET', '/api/v1/attachments/' + uploaded['id'] + '/content', actor=bob) check(downloaded['bytes'] == raw, 'Original changed') images.append(dict(format=fmt, bytes=len(raw), sha256=uploaded['sha256'])) print(json.dumps(dict(anonymous_get=403, real_images=images))) finally: store.close() else: c.call('GET', '/health/live', schema='Health') c.call('GET', '/health/ready', 503) raw = (ROOT / 'tests/fixtures/sample.png').read_bytes() c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png', 503, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}) c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 503, actor=bob) c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment') print(json.dumps(dict(live=200, ready=503, upload=503, content=503, metadata=200))) def main(): c = Client(os.getenv('BASE_URL', 'http://127.0.0.1:8084')) alice, bob, eve, chat = c.bootstrap() raw = (ROOT / 'tests/fixtures/sample.png').read_bytes() response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 201, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment') att, uploader = response['json'], response['headers']['X-Instance-Id'] message = c.message(alice, chat, '', attachments=[att['id']])['json'] before = containers('api') target = next(x for x in before if uploader.startswith(x['hostname'] + '-')) try: subprocess.run(['docker', 'stop', '--time', '8', target['id']], check=True, stdout=subprocess.PIPE) after = containers('api', True) check(next(x for x in after if x['id'] == target['id'])['status'] == 'exited', 'Uploader not stopped') wait_ready(c) downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob) reader = downloaded['headers']['X-Instance-Id'] check(reader != uploader and downloaded['bytes'] == raw, 'Replica-switch original mismatch') page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json'] check(message in page['items'], 'Attached message missing from history') for suffix in ('', '/content'): c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve) result = dict(uploader=uploader, downloader=reader, before=before, after=after, bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest(), same_original=True, attached_message_read=True, stranger_metadata=404, stranger_content=404) save('upload-failover.json', result) print('PASS: uploading API stopped; another API returned identical original and attached message.') finally: restore() data = dict(alice=alice, bob=bob, eve=eve, chat=chat, att=att, mode='private') result = compose('exec', '-T', 'api', 'python', 'student-tests/grade3.py', '--inside', payload=json.dumps(data)) save('private-and-formats.json', json.loads(result)) print('PASS: real PNG/JPEG originals and anonymous S3 403.') before = containers('s3') started = time.monotonic() try: compose('stop', '--timeout', '8', 's3') check(not containers('s3'), 'MinIO still running') data['mode'] = 'outage' result = compose('exec', '-T', 'api', 'python', 'student-tests/grade3.py', '--inside', payload=json.dumps(data)) observation = json.loads(result) finally: compose('start', 's3') wait_ready(c) downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob) check(downloaded['bytes'] == raw, 'Original changed after S3 outage') save('s3-outage.json', dict(before=before, after=containers('s3'), observation=observation, recovered_within_seconds=round(time.monotonic() - started, 3), original_preserved=True)) print('PASS: unavailable S3 yields 503; restart restores the same original and existing session.') if __name__ == '__main__': inside_probe() if '--inside' in sys.argv else main()