Files
mtusi2026lab4/student-tests/attachments.py
T
2026-10-16 22:47:54 +03:00

88 lines
5.2 KiB
Python

"""Контракт файлов: реальные изображения, лимиты, ACL и ключи сообщений."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import http.client
import io
from pathlib import Path
import struct
import sys
from urllib.parse import quote, urlsplit
import uuid
import zlib
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('Attachment negative and concurrent checks')
c = Client(args.base_url, args.ca_file)
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()
headers = {'Content-Type': 'image/png'}
att = c.call('POST', path+'sample.png', 201, actor=alice, raw=png, headers=headers, schema='Attachment')['json']
check('object_key' not in att and 'url' not in att, 'private storage details leaked')
for filename in ['../a.png', 'a\\b.png', 'x\x00.png', 'x\n.png', '..', ' ']:
c.call('POST', path+quote(filename, safe=''), 400, actor=alice, raw=png, headers=headers)
for data, mime in [(b'not an image', 'image/png'), (png[:30], 'image/png'),
(png[:-12], 'image/png'), (png, 'image/jpeg'), (png, 'application/octet-stream')]:
c.call('POST', path+'invalid.png', 415, actor=alice, raw=data, headers={'Content-Type': mime})
jpeg = io.BytesIO()
Image.new('RGB', (64, 64), 'red').save(jpeg, format='JPEG')
data = jpeg.getvalue()
j = c.call('POST', path+'real.jpg', 201, actor=alice, raw=data,
headers={'Content-Type': 'image/jpeg'}, schema='Attachment')['json']
downloaded = c.call('GET', '/api/v1/attachments/'+j['id']+'/content', actor=bob)
check(downloaded['bytes'] == data, 'JPEG bytes changed')
c.call('POST', path+'broken.jpg', 415, actor=alice, raw=data[:-20], headers={'Content-Type': 'image/jpeg'})
# Валидный IHDR заявляет >40M пикселей. Отклонение происходит до декодирования.
ihdr = struct.pack('>IIBBBBB', 9000, 5000, 8, 2, 0, 0, 0)
header = b'\x89PNG\r\n\x1a\n' + struct.pack('>I', len(ihdr)) + b'IHDR' + ihdr
header += struct.pack('>I', zlib.crc32(b'IHDR'+ihdr))
header += png[33:]
c.call('POST', path+'huge-pixels.png', 413, actor=alice, raw=header, headers=headers)
# Отправляем только headers заведомо большого файла: доказываем ранний byte limit.
base = urlsplit(c.base)
connection = http.client.HTTPConnection(base.hostname, base.port or 80, timeout=10)
connection.putrequest('POST', path+'too-big.png')
connection.putheader('Authorization', 'Bearer '+alice['token'])
connection.putheader('Content-Type', 'image/png')
connection.putheader('Content-Length', str(10485761))
connection.endheaders()
response = connection.getresponse()
check(response.status == 413, 'oversized body was not rejected before reading')
response.read(); connection.close()
c.call('POST', path+'outsider.png', 404, actor=eve, raw=png, headers=headers)
for suffix in ['', '/content']:
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/'+att['id']+'/content?variant=thumbnail', 404, actor=bob)
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
message_path = '/api/v1/chats/'+other_chat['id']+'/messages'
c.call('POST', message_path, 404, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
message_path = '/api/v1/chats/'+chat['id']+'/messages'
for ids, code in [([str(uuid.uuid4())], 404), ([att['id'], att['id']], 400), ([att['id']]*11, 400)]:
c.call('POST', message_path, code, actor=alice, body={'text': '', 'attachment_ids': ids},
headers={'Idempotency-Key': uuid.uuid4().hex})
key = uuid.uuid4().hex
def send(_):
return Client(args.base_url).message(bob, chat, '', key=key, attachments=[att['id']])
with ThreadPoolExecutor(max_workers=8) as pool:
replies = list(pool.map(send, range(16)))
check(all(r['json'] == replies[0]['json'] for r in replies), 'attachment replay created different messages')
check(len({r['headers']['X-Instance-Id'] for r in replies}) >= 2, 'attachment race did not cross replicas')
# Отсутствие attachment_ids и [] одинаковы и для хеша повтора.
text_key = uuid.uuid4().hex
text_message = c.message(alice, chat, 'Только текст', key=text_key)['json']
check(c.message(alice, chat, 'Только текст', key=text_key, attachments=[])['json'] == text_message,
'default [] changes key semantics')
check(att['sha256'] == hashlib.sha256(png).hexdigest(), 'wrong original checksum')
print('PASS: PNG/JPEG, bytes/pixels limits, filename/MIME, ACL, attachment message replay')
if __name__ == '__main__':
run(main)