Files
mtusi2026lab4/student-tests/test_attachments.py

136 lines
7.2 KiB
Python

"""Lab4 binary API checks without additional dependencies on the test host."""
import hashlib
import http.client
import os
from pathlib import Path
import struct
import sys
import unittest
from urllib.parse import quote, urlsplit
from uuid import uuid4
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client
def png(width, height, pixels=None):
def chunk(name, data):
return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data))
header = struct.pack('!IIBBBBB', width, height, 8, 2, 0, 0, 0)
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header)
+ chunk(b'IDAT', zlib.compress(pixels or b'\0\xff\0\0')) + chunk(b'IEND', b''))
class Attachments(unittest.TestCase):
def setUp(self):
self.c = Client(os.environ.get('BASE_URL', 'http://127.0.0.1:8080'))
self.a, self.b, self.e, self.chat = self.c.bootstrap()
self.path = '/api/v1/chats/' + self.chat['id']
self.data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
def upload(self, data=None, mime='image/png', name='фото.png', expected=201, actor=None):
return self.c.call('POST', self.path + '/attachments?filename=' + quote(name, safe=''),
expected, actor=actor or self.a, raw=self.data if data is None else data,
headers={'Content-Type': mime}, schema='Attachment' if expected == 201 else None)
def test_original_and_message_shared_with_member(self):
att = self.upload()['json']
self.assertEqual(att['sha256'], hashlib.sha256(self.data).hexdigest())
self.assertEqual(att['size_bytes'], len(self.data))
self.assertEqual(att['variants'], [])
base = '/api/v1/attachments/' + att['id']
self.assertEqual(self.c.call('GET', base, actor=self.b, schema='Attachment')['json'], att)
result = self.c.call('GET', base + '/content?variant=original', actor=self.b)
self.assertEqual(result['bytes'], self.data)
self.assertEqual(result['headers'].get_content_type(), 'image/png')
self.c.call('GET', base + '/content?variant=thumbnail', 404, actor=self.b)
msg = self.c.message(self.b, self.chat, '', attachments=[att['id']])['json']
self.assertEqual(self.c.call('GET', self.path + '/messages', actor=self.a,
schema='MessagePage')['json']['items'], [msg])
def test_jpeg_original_and_truncation(self):
data = (Path(__file__).parent / 'fixtures/sample.jpg').read_bytes()
att = self.upload(data=data, mime='image/jpeg', name='photo.jpg')['json']
result = self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=self.b)
self.assertEqual(result['bytes'], data)
self.assertEqual(result['headers'].get_content_type(), 'image/jpeg')
self.upload(data=data[:-30], mime='image/jpeg', expected=415)
def test_acl_before_image_validation(self):
self.upload(data=b'broken', expected=404, actor=self.e)
att = self.upload()['json']
for suffix in ('', '/content'):
self.c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=self.e)
self.c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 401)
def test_filename(self):
for name in ('../photo.png', 'a\\b.png', 'a\x00.png', 'a\n.png', 'a\x7f.png', '', 'x' * 256):
self.upload(name=name, expected=400)
def test_image_validation(self):
self.upload(mime='image/jpeg', expected=415)
self.upload(mime='application/octet-stream', expected=415)
for data in (b'', b'not an image', self.data[:30], self.data[:-20]):
self.upload(data=data, expected=415)
# Header announces 40,010,000 px, with valid CRC; reject before decoding.
self.upload(data=png(10000, 4001), expected=413)
def test_maximum_byte_size_accepted(self):
padding = b'x' * (10485760 - len(self.data) - 12)
chunk = struct.pack('!I', len(padding)) + b'vpAD' + padding + struct.pack('!I', zlib.crc32(b'vpAD' + padding))
data = self.data[:33] + chunk + self.data[33:]
self.assertEqual(len(data), 10485760)
att = self.upload(data=data)['json']
self.assertEqual(att['size_bytes'], 10485760)
result = self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=self.b)
self.assertEqual(result['bytes'], data)
def test_exactly_40_million_pixels_accepted(self):
def chunk(name, data):
return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data))
# Valid 1-bit grayscale PNG, 8000*5000 pixels. Small compressed fixture.
data = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', 8000, 5000, 1, 0, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(b'\0' * (1001 * 5000))) + chunk(b'IEND', b''))
att = self.upload(data=data)['json']
self.assertEqual(att['sha256'], hashlib.sha256(data).hexdigest())
def test_byte_limit_before_reading_body(self):
url = urlsplit(self.c.base)
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=5)
try:
conn.putrequest('POST', self.path + '/attachments?filename=too-big.png')
conn.putheader('Authorization', 'Bearer ' + self.a['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(10485761))
conn.endheaders() # No body: server must reject using the header alone.
response = conn.getresponse()
self.assertEqual(response.status, 413)
self.assertTrue(response.getheader('X-Request-Id'))
response.read()
finally:
conn.close()
def test_attachment_scope_and_idempotency(self):
att = self.upload()['json']
other = self.c.call('POST', '/api/v1/chats', 201, actor=self.a,
body={'title': 'other', 'member_ids': [self.a['id']]}, schema='Chat')['json']
for ids in ([att['id']], [str(uuid4())]):
self.c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=self.a,
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid4().hex})
for ids in ([att['id'], att['id']], 'wrong', [None], [att['id']] * 11):
self.c.call('POST', self.path + '/messages', 400, actor=self.a,
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid4().hex})
key = uuid4().hex
msg = self.c.message(self.a, self.chat, '', key=key, attachments=[att['id']])['json']
self.assertEqual(self.c.message(self.a, self.chat, '', key=key, attachments=[att['id']])['json'], msg)
self.c.call('POST', self.path + '/messages', 409, actor=self.a,
body={'text': 'changed', 'attachment_ids': []}, headers={'Idempotency-Key': key})
key = uuid4().hex
msg = self.c.message(self.a, self.chat, 'text', key=key)['json']
self.assertEqual(self.c.message(self.a, self.chat, 'text', key=key, attachments=[])['json'], msg)
if __name__ == '__main__':
unittest.main()