#!/usr/bin/env python3 """Real PostgreSQL/S3/RabbitMQ invariant and security checks, synthetic data only.""" import json from pathlib import Path import time from pipeline_integration import Client, check, compose, remote, wait, ROOT def main(): results = [] c = Client('http://localhost:8080', timeout=30) alice, bob, eve, chat = c.bootstrap() att, _ = c.attachment(alice, chat) wait(c, bob, att) from io import BytesIO from PIL import Image for name, fmt, bound in (('thumbnail', 'JPEG', 256), ('crop', 'JPEG', 128), ('optimized', 'WEBP', 1280)): content = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + name, actor=bob)['bytes'] with Image.open(BytesIO(content)) as image: check(image.format == fmt and max(image.size) <= bound and not image.getexif(), 'variant format/size/EXIF') if name == 'crop': check(image.size == (128, 128), 'crop dimensions') results.append('actual thumbnail/crop/WebP formats, dimensions and removed EXIF') # Verify actual private object key, not a nonexistent legacy key. private = remote('''import urllib.request, urllib.error key = await db.pool.fetchval('SELECT original_key FROM attachments WHERE id=$1', UUID(V['id'])) try: urllib.request.urlopen('http://s3:8333/' + s3.settings.bucket + '/' + key, timeout=5) except urllib.error.HTTPError as error: assert error.code == 403, error.code else: raise AssertionError('anonymous object leaked') print('true')''', id=att['id']) check(private, 'private S3 check failed') for variant in ('thumbnail', 'crop', 'optimized'): c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + variant, 404, actor=eve) results.append('anonymous S3 403 on existing object; variant ACL 404') lock = remote('''import time entered = asyncio.Event() async def writer(): async with db.attachment_transaction(): entered.set() await asyncio.sleep(1) task = asyncio.create_task(writer()) await entered.wait() started = time.monotonic() async with db.attachment_transaction(maintenance=True): waited = time.monotonic() - started await task assert waited >= .9, waited print(json.dumps({'maintenance_wait_seconds': waited}))''') results.append(lock) # Poison staging only for a newly created synthetic attachment and update its # digest so invalid-image classification (not transport checksum) is exercised. compose('stop', '-t', '2', 'worker') guarded, _ = c.attachment(alice, chat) fence = remote('''key = UUID(V['id']) job_id = await db.pool.fetchval('SELECT job_id FROM attachment_jobs WHERE attachment_id=$1', key) before = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id) await db.pool.execute("UPDATE attachment_jobs SET updated_at=now()-interval '61 seconds' WHERE attachment_id=$1", key) await db.schedule_due_jobs() after = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id) assert after == before + 1, 'unclaimed published job stranded' assert await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', key) == 1 await db.schedule_due_jobs() assert await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id) == after, 'watchdog floods outbox' first = await db.claim_attachment_job(key, 30) assert first is not None assert await db.retry_attachment_job(key, 5, 30, first['claim_time']) assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed retry delay' await db.pool.execute("UPDATE attachment_jobs SET next_attempt_at=now() WHERE attachment_id=$1", key) await db.schedule_due_jobs() second = await db.claim_attachment_job(key, 30) assert second is not None and second['attempt'] == 2 assert not await db.complete_attachment_job(key, 'invalid-stale-key', [], first['claim_time']) assert not await db.retry_attachment_job(key, 5, 0, first['claim_time']) await db.pool.execute("UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE attachment_id=$1", key) assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed lease attempt accounting' await db.schedule_due_jobs() third = await db.claim_attachment_job(key, 30) assert third['attempt'] == 3 assert await db.retry_attachment_job(key, 5, 0, third['claim_time']) print('true')''', id=guarded['id']) check(fence, 'SQL fencing/backoff invariant') results.append('real SQL: queued watchdog republishes without attempt increment/flood; duplicate respects backoff; expired lease counted; stale completion/retry fenced') att, _ = c.attachment(alice, chat) remote('''from io import BytesIO from hashlib import sha256 data = b'invalid image payload' await s3.put('staging/' + V['id'] + '/original', BytesIO(data), len(data), 'image/png') await db.pool.execute('UPDATE attachments SET size_bytes=$2, sha256=$3 WHERE id=$1', UUID(V['id']), len(data), sha256(data).hexdigest()) print('true')''', id=att['id']) compose('start', 'worker') wait(c, alice, guarded) failed = wait(c, alice, att, 'failed') check(failed['error_code'] == 'invalid_image', 'permanent classification failed') attempt = remote("print(await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', UUID(V['id'])))", id=att['id']) check(attempt == 1, 'permanent error retried') results.append('permanent invalid_image reaches failed on attempt 1') # DLQ uses confirmed persistent publication; count change avoids consuming # messages belonging to a different test. dlq = remote('''from src.broker import _connection, _publish, DLQ connection = _connection(); channel = connection.channel() before = channel.queue_declare(queue=DLQ, durable=True).method.message_count connection.close() _publish({'malformed': True}) print(json.dumps({'before': before}))''') deadline = time.monotonic() + 20 while time.monotonic() < deadline: count = remote('''from src.broker import _connection, DLQ connection = _connection() print(connection.channel().queue_declare(queue=DLQ, durable=True).method.message_count) connection.close()''') if count > dlq['before']: break time.sleep(.5) check(count == dlq['before'] + 1, 'invalid job not delivered to DLQ') results.append('malformed broker message delivered to DLQ') # Actual Linux child timeout: no renderer can finish within this deadline. timeout = remote('''from src.worker import render_isolated try: render_isolated(b'x', .000001) except TimeoutError: print('true') else: raise AssertionError('timeout not enforced')''') check(timeout, 'timeout missing') results.append('Linux render subprocess killed/reaped on deadline') (ROOT / 'evidence/pipeline-invariants.json').write_text(json.dumps(results, indent=2) + '\n') print(json.dumps(results, indent=2), flush=True) if __name__ == '__main__': try: main() finally: compose('up', '-d', '--no-deps', '--wait', 'worker')