Files
mtusi2026lab4/student-tests/attachments.py
T

63 lines
3.0 KiB
Python

"""Verify limits, actual image type and chat-scoped attachments."""
from pathlib import Path
import struct
import sys
from urllib.parse import quote
import uuid
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Student checks: attachment byte/pixel limits and access')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
path = '/api/v1/chats/' + chat['id']
upload = path + '/attachments?filename='
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
jpeg = (ROOT / 'student-tests/sample.jpg').read_bytes()
png_type = {'Content-Type': 'image/png'}
jpeg_type = {'Content-Type': 'image/jpeg'}
header = b'IHDR' + struct.pack('>II', 8000, 8000) + png[24:29]
oversized_pixels = png[:12] + header + struct.pack('>I', zlib.crc32(header)) + png[33:]
cases = [
(413, png_type, b'x' * (10 * 1024 * 1024 + 1)),
(413, png_type, oversized_pixels),
(415, png_type, png[:len(png) // 2]),
(415, jpeg_type, png),
(415, png_type, b'text disguised as an image'),
]
for expected, headers, content in cases:
client.call('POST', upload + 'sample.png', expected, actor=alice, headers=headers, raw=content)
for filename in ('../sample.png', 'x\\sample.png', 'x\x00.png'):
client.call('POST', upload + quote(filename, safe=''), 400,
actor=alice, headers=png_type, raw=png)
client.call('POST', upload + 'sample.png', 404, actor=eve, headers=png_type, raw=png)
attachment = client.call('POST', upload + quote('Снимок.jpg'), 201,
actor=alice, headers=jpeg_type, raw=jpeg, schema='Attachment')['json']
check(attachment['filename'] == 'Снимок.jpg', 'display filename changed')
route = '/api/v1/attachments/' + attachment['id']
response = client.call('GET', route + '/content', actor=bob)
check(response['bytes'] == jpeg, 'JPEG bytes changed')
check(response['headers'].get_content_type() == 'image/jpeg', 'JPEG MIME changed')
client.call('GET', route + '/content', 404, actor=eve)
other_chat = client.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
body={'title': 'Другой чат', 'member_ids': [alice['id']]})['json']
client.call('POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404,
actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex},
body={'text': '', 'attachment_ids': [attachment['id']]})
key = uuid.uuid4().hex
message = client.message(alice, chat, 'Текст', key=key)['json']
replay = client.message(alice, chat, 'Текст', key=key, attachments=[])['json']
check(message == replay, 'omitted attachment_ids and [] were treated differently')
print('PASS: JPEG, unsafe filenames, byte/pixel limits, malformed image, MIME mismatch and chat ACL')
if __name__ == '__main__':
run(main)