#!/usr/bin/env python3 """Attachment contract checks against the running lab5 stack.""" import hashlib import http.client from io import BytesIO from pathlib import Path import struct import sys import uuid import zlib from urllib.parse import quote, urlsplit from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client, arguments, check, run def main(): args = arguments(__doc__) c = Client(args.base_url, args.ca_file, timeout=30) alice, bob, eve, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes() def upload(data, mime='image/png', filename='photo.png', status=202, actor=alice): return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data, headers={'Content-Type': mime}, schema='Attachment' if status == 202 else None) for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]: buf = BytesIO() Image.new('RGB', (32, 20), 'blue').save(buf, fmt) data = buf.getvalue() att = upload(data, mime)['json'] check(att['variants'] == [] and att['status'] == 'queued', 'wrong attachment state') att = c.wait_ready(bob, att) check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum') content_path = '/api/v1/attachments/' + att['id'] check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att, 'metadata changed') check(c.call('GET', content_path + '/content', actor=bob)['bytes'] == data, 'bytes changed') c.call('GET', content_path, 404, actor=eve) c.call('GET', content_path + '/content', 404, actor=eve) c.call('GET', content_path + '/content', 401) c.call('GET', content_path + '/content?variant=thumbnail', actor=bob) message = c.message(bob, chat, '', attachments=[att['id']])['json'] history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=alice, schema='MessagePage')['json']['items'] check(message in history, 'attachment message missing in history') print('PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL') for name in ('../x.png', 'x/y.png', 'x\\y.png', 'x\x00.png', 'x\n.png', 'x\x7f.png', ' ', 'x' * 256): upload(png, filename=name, status=400) upload(png, mime='image/jpeg', status=415) upload(b'not an image', status=415) upload(png[:30], status=415) upload(png, mime='application/octet-stream', status=415) upload(png, status=404, actor=eve) upload(b'x' * (10485760 + 1), status=413) # Valid PNG header with an oversized canvas: reject before attempting pixel decoding. def chunk(kind, data): return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8001, 5000, 8, 2, 0, 0, 0)) huge += chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'') upload(huge, status=413) # No Content-Length: limits must also work for chunked requests. url = urlsplit(c.base) connection = http.client.HTTPConnection(url.hostname, url.port, timeout=30) connection.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161), headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}, encode_chunked=True) response = connection.getresponse() check(response.status == 413, 'chunked upload bypassed byte limit') response.read() connection.close() print('PASS: filename, MIME, malformed image, byte/pixel and chunked limits') att = upload(png)['json'] other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json'] for target, ids, code in ((chat, [str(uuid.uuid4())], 404), (other_chat, [att['id']], 404), (chat, [att['id'], att['id']], 400)): c.call('POST', '/api/v1/chats/' + target['id'] + '/messages', code, actor=alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex}) key = uuid.uuid4().hex first = c.message(alice, chat, 'same', key=key)['json'] check(c.message(alice, chat, 'same', key=key, attachments=[])['json'] == first, 'omitted and empty attachment_ids differ') key = uuid.uuid4().hex first = c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] check(c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] == first, 'replay differs') c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice, body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key}) print('PASS: attachment scope, duplicates and idempotency normalization') # Exact limits are accepted; original bytes (including PNG trailing data) survive. exact = png + b'\0' * (10485760 - len(png)) att = upload(exact)['json'] c.wait_ready(bob, att) check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact, '10 MiB original changed') buf = BytesIO() Image.new('RGB', (8000, 5000)).save(buf, 'PNG') att = upload(buf.getvalue())['json'] check(att['size_bytes'] == len(buf.getvalue()), '40M pixel upload failed') print('PASS: inclusive 10 MiB and 40 million pixel boundaries') if __name__ == '__main__': run(main)