Files
mtusi2026lab6/tests/attachments.py
T

100 lines
5.1 KiB
Python

"""Lab4 black-box checks against the running Compose stack."""
import hashlib
import io
import struct
import zlib
from concurrent.futures import ThreadPoolExecutor
import uuid
from pathlib import Path
from PIL import Image
from client import Client, arguments, check, run
def main():
args = arguments('Attachment originals, ACL, validation and message limits')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
def upload(data=content, name='photo.png', mime='image/png', status=202, actor=alice):
return c.call('POST', path + '/attachments?filename=' + name, status,
actor=actor, raw=data, headers={'Content-Type': mime},
schema='Attachment' if status == 202 else None)['json']
first = upload()
second = upload() # Same display name must not overwrite the first object.
check(first['id'] != second['id'], 'same filename overwrote attachment')
jpg = io.BytesIO()
Image.new('RGB', (31, 17), 'red').save(jpg, format='JPEG')
jpeg = upload(jpg.getvalue(), 'photo.jpg', 'image/jpeg')
for att, original in [(first, content), (second, content), (jpeg, jpg.getvalue())]:
check(att['sha256'] == hashlib.sha256(original).hexdigest(), 'incorrect digest')
att = c.wait_ready(alice, att)
check({v['name'] for v in att['variants']} == {'thumbnail', 'crop', 'optimized'}, 'incorrect ready metadata')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
check(downloaded['bytes'] == original, 'original changed')
ids = [first['id'], second['id'], jpeg['id']]
key = uuid.uuid4().hex
message = c.message(alice, chat, '', key=key, attachments=ids)['json']
check(message['attachment_ids'] == ids, 'attachment order lost')
check(c.message(alice, chat, '', key=key, attachments=ids)['json'] == message,
'idempotency replay changed message')
c.call('POST', path + '/messages', 409, actor=alice,
body={'text': '', 'attachment_ids': ids[:1]}, headers={'Idempotency-Key': key})
page = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']
check(any(m == message for m in page['items']), 'history lost attachments')
# The contract permits referencing the same accessible chat attachment again.
c.message(bob, chat, 'same image', attachments=[first['id']])
for body in ({'text': '', 'attachment_ids': []},
{'text': '', 'attachment_ids': [first['id']] * 2},
{'text': '', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}):
c.call('POST', path + '/messages', 400, actor=alice, body=body,
headers={'Idempotency-Key': uuid.uuid4().hex})
c.call('POST', path + '/messages', 404, actor=alice,
body={'text': '', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': uuid.uuid4().hex})
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
schema='Chat')['json']
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=alice,
body={'text': '', 'attachment_ids': ids},
headers={'Idempotency-Key': uuid.uuid4().hex})
upload(actor=eve, status=404)
upload(name='..%2Fphoto.png', status=400)
upload(name='a%00b.png', status=400)
upload(data=b'not a PNG', status=415)
upload(data=content[:30], status=415)
upload(mime='image/jpeg', status=415)
upload(mime='application/octet-stream', status=415)
# Oversized dimensions with a valid PNG header; no huge bitmap allocation.
header = struct.pack('>IIBBBBB', 10000, 5000, 8, 2, 0, 0, 0)
bomb = (content[:8] + struct.pack('>I', len(header)) + b'IHDR' + header
+ struct.pack('>I', zlib.crc32(b'IHDR' + header)) + content[33:])
upload(data=bomb, status=413)
upload(data=b'x' * (10485760 + 1), status=413)
c.call('POST', path + '/attachments?filename=a.png', 401,
raw=content, headers={'Content-Type': 'image/png'})
# Exactly 10 distinct attachments must remain valid, including after reading history.
ten = ids + [upload()['id'] for _ in range(7)]
check(len(c.message(alice, chat, '', attachments=ten)['json']['attachment_ids']) == 10,
'10 attachments rejected')
replay_key = uuid.uuid4().hex
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(lambda _: Client(args.base_url, args.ca_file).message(
alice, chat, 'Concurrent image', key=replay_key, attachments=ids
), range(8)))
check(all(r['json'] == responses[0]['json'] for r in responses),
'concurrent attachment retries differ')
print('PASS: PNG/JPEG bytes, metadata, ACL, chat boundaries, limits and idempotency')
if __name__ == '__main__':
run(main)