#!/usr/bin/env python3 """Defense scenarios for background attachment processing; run inside the tools container.""" import base64 import hashlib import json import os import subprocess import sys import time import urllib.error import urllib.request import uuid BASE = os.environ.get('BASE_URL', 'http://localhost:8080') SAMPLE = open(os.path.join(os.path.dirname(__file__), '..', 'tests', 'fixtures', 'sample.png'), 'rb').read() STARTED = time.monotonic() def log(*parts): print('[%6.1fs]' % (time.monotonic() - STARTED), *parts, flush=True) def call(method, path, body=None, headers=None, raw=None): data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) all_headers = dict(headers or {}) if body is not None: all_headers['Content-Type'] = 'application/json' request = urllib.request.Request(BASE + path, data=data, method=method, headers=all_headers) try: with urllib.request.urlopen(request, timeout=15) as response: return response.status, response.read(), response.headers except urllib.error.HTTPError as error: return error.code, error.read(), error.headers except OSError as error: return 0, str(error).encode(), {} def json_of(raw): try: return json.loads(raw or b'null') except ValueError: return None def compose(*args): log('$ docker compose', ' '.join(args)) subprocess.run(['docker', 'compose', *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def psql(sql): out = subprocess.run( ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tA', '-F', ' | ', '-c', sql], check=True, capture_output=True, text=True, ) return out.stdout.strip() def queue_depth(): time.sleep(6) out = subprocess.run( ['docker', 'compose', 'exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'type', 'durable', 'messages_ready', 'messages_unacknowledged'], capture_output=True, text=True, ) return out.stdout.strip() or out.stderr.strip() def wait_ready(timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: if call('GET', '/health/ready')[0] == 200: return time.sleep(1) sys.exit('API did not become ready') def session(): username = 'job_' + uuid.uuid4().hex[:8] password = 'Job-scenario-' + uuid.uuid4().hex code, raw, _ = call('POST', '/api/v1/users', {'username': username, 'display_name': 'Job scenario', 'password': password}) if code != 201: sys.exit('register failed: %s' % code) user = json_of(raw) credential = base64.b64encode((username + ':' + password).encode()).decode() code, raw, _ = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential}) if code != 201: sys.exit('login failed: %s' % code) auth = {'Authorization': 'Bearer ' + json_of(raw)['token']} code, raw, _ = call('POST', '/api/v1/chats', {'title': 'Job scenario', 'member_ids': [user['id']]}, auth) if code != 201: sys.exit('chat failed: %s' % code) chat = json_of(raw)['id'] log('user', user['id'], 'chat', chat) return auth, chat def upload(auth, chat, body=SAMPLE): code, raw, headers = call( 'POST', '/api/v1/chats/%s/attachments?filename=sample.png' % chat, headers={**auth, 'Content-Type': 'image/png'}, raw=body, ) attachment = json_of(raw) log('POST attachment ->', code, 'status=%s' % attachment.get('status'), 'id=%s' % attachment.get('id'), 'instance=%s' % headers.get('X-Instance-Id')) if code != 202: sys.exit('upload failed') return attachment['id'] def message(auth, chat, text, attachments=()): code, raw, _ = call( 'POST', '/api/v1/chats/%s/messages' % chat, {'text': text, 'attachment_ids': list(attachments)}, {**auth, 'Idempotency-Key': uuid.uuid4().hex}, ) log('POST message', 'with %d attachment(s)' % len(attachments), '->', code, 'id=%s' % (json_of(raw) or {}).get('id')) return code def metadata(auth, attachment): code, raw, _ = call('GET', '/api/v1/attachments/' + attachment, headers=auth) return code, json_of(raw) def content_status(auth, attachment, variant='original'): return call('GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment, variant), headers=auth)[0] def wait_status(auth, attachment, wanted, timeout=150): deadline = time.monotonic() + timeout last = None while time.monotonic() < deadline: code, meta = metadata(auth, attachment) if code == 200 and meta['status'] != last: last = meta['status'] log('GET attachment -> status=%s error_code=%s' % (last, meta['error_code'])) if code == 200 and meta['status'] in wanted: return meta time.sleep(1) sys.exit('attachment did not reach %s' % '/'.join(wanted)) def check_ready(auth, attachment, meta): code, raw, _ = call('GET', '/api/v1/attachments/%s/content' % attachment, headers=auth) log('original ->', code, 'sha256 matches upload:', code == 200 and hashlib.sha256(raw).hexdigest() == hashlib.sha256(SAMPLE).hexdigest()) for variant in meta['variants']: code, raw, headers = call('GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment, variant['name']), headers=auth) log('%-9s -> %s %s %dx%d sha256 matches metadata: %s' % ( variant['name'], code, headers.get('Content-Type'), variant['width'], variant['height'], hashlib.sha256(raw).hexdigest() == variant['sha256'])) def job_state(attachment): log('job:', psql("SELECT id, status, attempt, max_attempts, error_code FROM attachment_jobs WHERE attachment_id = '%s'" % attachment)) log('variants rows:', psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % attachment)) log('events:', psql("SELECT string_agg(e.event, ' -> ' ORDER BY e.id) FROM job_events e JOIN attachment_jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment)) def scenario_restart(): """Level 3: worker down -> upload 202 -> restart API and broker -> worker up -> ready.""" wait_ready() auth, chat = session() compose('stop', 'worker') attachment = upload(auth, chat) log('content while queued ->', content_status(auth, attachment)) message(auth, chat, '', [attachment]) message(auth, chat, 'other messages keep working') log('queues:', queue_depth()) compose('restart', 'api', 'rabbitmq') wait_ready() log('queues after broker restart:', queue_depth()) log('status after restarts:', metadata(auth, attachment)[1]['status']) compose('start', 'worker') meta = wait_status(auth, attachment, ['ready', 'failed']) check_ready(auth, attachment, meta) job_state(attachment) SCENARIOS = {'restart': scenario_restart} if __name__ == '__main__': if len(sys.argv) != 2 or sys.argv[1] not in SCENARIOS: sys.exit('usage: job-scenario.py %s' % '|'.join(SCENARIOS)) SCENARIOS[sys.argv[1]]()