328 lines
17 KiB
Python
328 lines
17 KiB
Python
"""Негативные и граничные сценарии вложений lab4 (только stdlib).
|
||
|
||
Проверяет, что пользовательская ошибка никогда не становится 500:
|
||
- размер: ровно 10 MiB -> 201; 10 MiB + 1 по Content-Length и chunked -> 413;
|
||
- пиксели: ровно 40 млн -> 201; 50 млн (маленький файл, «бомба») -> 413;
|
||
- повреждённые PNG/JPEG (обрезка, CRC, мусор в IDAT), чужие форматы -> 415;
|
||
- подмена MIME: PNG как image/jpeg, JPEG как image/png, text/plain, multipart -> 415;
|
||
- опасные filename (/, \\, NUL, управляющие, bidi, пустой, 256 символов) -> 400;
|
||
- чужой пользователь: upload в чужой чат, metadata, content -> 404;
|
||
- message: вложение другого чата / неизвестное -> 404, дубли / 11 ID -> 400,
|
||
text="" с вложением -> 201, повтор Idempotency-Key -> то же сообщение;
|
||
- оборванная загрузка не ломает реплику; variant без варианта -> 404.
|
||
|
||
Запуск: docker compose --profile tools run --rm tester python3 student-tests/attachment_edge_cases.py
|
||
или с хоста: python student-tests/attachment_edge_cases.py --base-url http://localhost:8080
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import hashlib
|
||
import http.client
|
||
import json
|
||
import os
|
||
import socket
|
||
import struct
|
||
import sys
|
||
import urllib.parse
|
||
import uuid
|
||
import zlib
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
SAMPLE_PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||
SAMPLE_JPG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
||
MIB10 = 10 * 1024 * 1024
|
||
|
||
|
||
# --- синтетические изображения ---------------------------------------------
|
||
|
||
def png_chunk(kind: bytes, data: bytes) -> bytes:
|
||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||
|
||
|
||
def png(width: int, height: int, bit_depth: int = 8, color_type: int = 0, idat: bytes | None = None,
|
||
extra: bytes = b'') -> bytes:
|
||
if idat is None:
|
||
row_bytes = (width * bit_depth * {0: 1, 2: 3}[color_type] + 7) // 8
|
||
raw = (b'\x00' + b'\x00' * row_bytes) * height
|
||
idat = zlib.compress(raw, 9)
|
||
ihdr = struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0)
|
||
return (b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + extra
|
||
+ png_chunk(b'IDAT', idat) + png_chunk(b'IEND', b''))
|
||
|
||
|
||
def png_exactly(size: int) -> bytes:
|
||
"""Валидный PNG ровно size байт: добивается приватным ancillary-чанком."""
|
||
base = png(8, 8)
|
||
pad = size - len(base) - 12
|
||
return png(8, 8, extra=png_chunk(b'zpAD', b'\x00' * pad))
|
||
|
||
|
||
def pixels_png(width: int, height: int) -> bytes:
|
||
"""1-битный grayscale: 40 млн пикселей занимают ~5 MB raw, ~10 KB zlib."""
|
||
row = b'\x00' + b'\x00' * ((width + 7) // 8)
|
||
compressor = zlib.compressobj(9)
|
||
idat = b''.join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||
return png(width, height, bit_depth=1, idat=idat)
|
||
|
||
|
||
def corrupt_crc(data: bytes) -> bytes:
|
||
i = data.index(b'IDAT') + 6
|
||
return data[:i] + bytes([data[i] ^ 0xFF]) + data[i + 1:]
|
||
|
||
|
||
def corrupt_idat(data: bytes) -> bytes:
|
||
"""Мусор в zlib-потоке с ПРАВИЛЬНЫМ CRC: ловится только распаковкой."""
|
||
return png(320, 200, color_type=2, idat=b'\x78\x9c' + os.urandom(2000))
|
||
|
||
|
||
# --- HTTP ------------------------------------------------------------------
|
||
|
||
class Api:
|
||
def __init__(self, base_url: str):
|
||
parts = urllib.parse.urlsplit(base_url)
|
||
self.host = parts.hostname
|
||
self.port = parts.port or 80
|
||
|
||
def conn(self) -> http.client.HTTPConnection:
|
||
return http.client.HTTPConnection(self.host, self.port, timeout=60)
|
||
|
||
def call(self, method, path, body=None, headers=None, raw=None, chunks=None):
|
||
h = dict(headers or {})
|
||
if body is not None:
|
||
raw = json.dumps(body).encode()
|
||
h['Content-Type'] = 'application/json'
|
||
c = self.conn()
|
||
try:
|
||
if chunks is not None:
|
||
c.request(method, '/api/v1' + path, body=chunks, headers=h, encode_chunked=True)
|
||
else:
|
||
c.request(method, '/api/v1' + path, body=raw, headers=h)
|
||
r = c.getresponse()
|
||
data = r.read()
|
||
except (BrokenPipeError, ConnectionResetError):
|
||
# Сервер ответил 413 и закрыл соединение, не дочитав тело.
|
||
r = c.getresponse()
|
||
data = r.read()
|
||
finally:
|
||
c.close()
|
||
ctype = r.getheader('Content-Type', '')
|
||
parsed = json.loads(data) if data and ctype.startswith('application/json') else None
|
||
return r.status, parsed, data, r
|
||
|
||
|
||
def main() -> int:
|
||
p = argparse.ArgumentParser()
|
||
p.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
|
||
args = p.parse_args()
|
||
api = Api(args.base_url)
|
||
failed = 0
|
||
|
||
def code(resp):
|
||
return resp.get('error', {}).get('code') if isinstance(resp, dict) else None
|
||
|
||
def check(label, status, resp, want_status, want_code=None, extra_ok=True):
|
||
nonlocal failed
|
||
ok = status == want_status and (want_code is None or code(resp) == want_code) and extra_ok
|
||
failed += not ok
|
||
print(f"{'OK ' if ok else 'FAIL'} {label}: {status} {code(resp) or ''} "
|
||
f"(ожидается {want_status} {want_code or ''})", flush=True)
|
||
|
||
def new_user():
|
||
name = 'att' + uuid.uuid4().hex[:12]
|
||
password = 'attachment-edge-password'
|
||
s, user, _, _ = api.call('POST', '/users', {'username': name, 'display_name': 'Вложения', 'password': password})
|
||
assert s == 201, f'register: {s}'
|
||
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||
s, session, _, _ = api.call('POST', '/auth/sessions', headers={'Authorization': basic})
|
||
assert s == 201, f'login: {s}'
|
||
return user, {'Authorization': 'Bearer ' + session['token']}
|
||
|
||
def new_chat(auth, members, title='attachments'):
|
||
s, chat, _, _ = api.call('POST', '/chats', {'title': title, 'member_ids': members}, headers=auth)
|
||
assert s == 201, f'chat: {s}'
|
||
return chat
|
||
|
||
def upload(auth, chat_id, data, content_type='image/png', filename='photo.png', **kw):
|
||
query = '' if filename is None else '?filename=' + urllib.parse.quote(filename, safe='')
|
||
h = dict(auth)
|
||
if content_type is not None:
|
||
h['Content-Type'] = content_type
|
||
return api.call('POST', f'/chats/{chat_id}/attachments{query}', headers=h, raw=data, **kw)
|
||
|
||
def message(auth, chat_id, text, ids=None, key=None):
|
||
body = {'text': text}
|
||
if ids is not None:
|
||
body['attachment_ids'] = ids
|
||
h = dict(auth, **{'Idempotency-Key': key or uuid.uuid4().hex})
|
||
return api.call('POST', f'/chats/{chat_id}/messages', body, headers=h)
|
||
|
||
alice, a_auth = new_user()
|
||
bob, b_auth = new_user()
|
||
eve, e_auth = new_user()
|
||
chat = new_chat(a_auth, [alice['id'], bob['id']])
|
||
other_chat = new_chat(a_auth, [alice['id']], 'other')
|
||
eve_chat = new_chat(e_auth, [eve['id']], 'eve')
|
||
|
||
# --- успешные границы ---------------------------------------------------
|
||
s, att, _, r = upload(a_auth, chat['id'], SAMPLE_JPG, 'image/jpeg', 'фото 😀 v1.0.jpg')
|
||
check('JPEG fixture -> 201 ready', s, att, 201, extra_ok=s == 201 and att['status'] == 'ready'
|
||
and att['sha256'] == hashlib.sha256(SAMPLE_JPG).hexdigest() and att['size_bytes'] == len(SAMPLE_JPG)
|
||
and att['filename'] == 'фото 😀 v1.0.jpg' and att['variants'] == [] and att['error_code'] is None
|
||
and 'object_key' not in att)
|
||
jpg_id = att['id']
|
||
s, _, data, r = api.call('GET', f'/attachments/{jpg_id}/content', headers=b_auth)
|
||
check('участник скачивает JPEG побайтно, без redirect', s, None, 200,
|
||
extra_ok=data == SAMPLE_JPG and r.getheader('Content-Type') == 'image/jpeg')
|
||
|
||
exact = png_exactly(MIB10)
|
||
s, att, _, _ = upload(a_auth, chat['id'], exact)
|
||
check('PNG ровно 10 MiB -> 201', s, att, 201, extra_ok=s == 201 and att['size_bytes'] == MIB10)
|
||
if s == 201:
|
||
s, _, data, _ = api.call('GET', f"/attachments/{att['id']}/content", headers=a_auth)
|
||
check('10 MiB скачан побайтно', s, None, 200, extra_ok=hashlib.sha256(data).digest() == hashlib.sha256(exact).digest())
|
||
|
||
s, att, _, _ = upload(a_auth, chat['id'], pixels_png(8000, 5000))
|
||
check('PNG ровно 40 млн пикселей -> 201', s, att, 201)
|
||
|
||
# --- размер -------------------------------------------------------------
|
||
s, r, _, _ = upload(a_auth, chat['id'], png_exactly(MIB10 + 1))
|
||
check('10 MiB + 1 байт (Content-Length) -> 413', s, r, 413, 'payload_too_large')
|
||
|
||
def big_chunks():
|
||
block = png_exactly(MIB10)[:1024 * 1024]
|
||
for _ in range(11):
|
||
yield block
|
||
|
||
s, r, _, _ = upload(a_auth, chat['id'], None, chunks=big_chunks())
|
||
check('11 MiB chunked без Content-Length -> 413', s, r, 413, 'payload_too_large')
|
||
|
||
s, r, _, _ = upload(a_auth, chat['id'], pixels_png(10000, 5000))
|
||
check('PNG-«бомба» 50 млн пикселей (~10 KB файл) -> 413', s, r, 413, 'payload_too_large')
|
||
s, r, _, _ = upload(a_auth, chat['id'], png(0x7FFFFFFF, 0x7FFFFFFF, idat=b'x'))
|
||
check('PNG 2^31-1 x 2^31-1 в IHDR -> 413', s, r, 413, 'payload_too_large')
|
||
|
||
s, r, _, _ = upload(a_auth, chat['id'], b'')
|
||
check('пустое тело -> 400', s, r, 400, 'invalid_request')
|
||
|
||
# --- повреждённые и чужие форматы --------------------------------------
|
||
for label, data, ctype in [
|
||
('PNG обрезан пополам', SAMPLE_PNG[:len(SAMPLE_PNG) // 2], 'image/png'),
|
||
('PNG с неверным CRC', corrupt_crc(SAMPLE_PNG), 'image/png'),
|
||
('PNG с мусором в zlib при верном CRC', corrupt_idat(SAMPLE_PNG), 'image/png'),
|
||
('PNG без IEND', SAMPLE_PNG[:-12], 'image/png'),
|
||
('JPEG обрезан', SAMPLE_JPG[:len(SAMPLE_JPG) // 2], 'image/jpeg'),
|
||
('JPEG только сигнатура', b'\xff\xd8\xff\xe0' + b'\x00' * 100, 'image/jpeg'),
|
||
('GIF как image/png', b'GIF89a' + b'\x00' * 100, 'image/png'),
|
||
('случайные байты как image/png', os.urandom(4096), 'image/png'),
|
||
('HTML как image/jpeg', b'<html><script>alert(1)</script></html>', 'image/jpeg'),
|
||
]:
|
||
s, r, _, _ = upload(a_auth, chat['id'], data, ctype)
|
||
check(label + ' -> 415', s, r, 415, 'unsupported_media_type')
|
||
|
||
# --- подмена MIME -------------------------------------------------------
|
||
for label, data, ctype in [
|
||
('PNG под Content-Type image/jpeg', SAMPLE_PNG, 'image/jpeg'),
|
||
('JPEG под Content-Type image/png', SAMPLE_JPG, 'image/png'),
|
||
('PNG под text/plain', SAMPLE_PNG, 'text/plain'),
|
||
('PNG под image/gif', SAMPLE_PNG, 'image/gif'),
|
||
('multipart/form-data', b'--x\r\n\r\n' + SAMPLE_PNG + b'\r\n--x--', 'multipart/form-data; boundary=x'),
|
||
('без Content-Type', SAMPLE_PNG, None),
|
||
]:
|
||
s, r, _, _ = upload(a_auth, chat['id'], data, ctype)
|
||
check(label + ' -> 415', s, r, 415, 'unsupported_media_type')
|
||
|
||
# --- filename -----------------------------------------------------------
|
||
for label, name in [
|
||
('../../etc/passwd', '../../etc/passwd'),
|
||
('C:\\boot.png', 'C:\\boot.png'),
|
||
('NUL в имени', 'a\x00.png'),
|
||
('перевод строки', 'a\nb.png'),
|
||
('ESC-последовательность', '\x1b[31mred.png'),
|
||
('bidi override (gnp.exe)', 'photo\u202egnp.exe'),
|
||
('только пробелы', ' '),
|
||
('..', '..'),
|
||
('256 символов', 'a' * 252 + '.png'),
|
||
('пустой filename', ''),
|
||
('нет filename', None),
|
||
]:
|
||
s, r, _, _ = upload(a_auth, chat['id'], SAMPLE_PNG, filename=name)
|
||
check(f'filename {label} -> 400', s, r, 400, 'invalid_request')
|
||
s, r, _, _ = upload(a_auth, chat['id'], SAMPLE_PNG, filename='a' * 251 + '.png')
|
||
check('filename ровно 255 символов -> 201', s, r, 201)
|
||
|
||
# --- доступ -------------------------------------------------------------
|
||
s, r, _, _ = upload({}, chat['id'], SAMPLE_PNG)
|
||
check('upload без токена -> 401', s, r, 401, 'unauthorized')
|
||
s, r, _, _ = upload(e_auth, chat['id'], SAMPLE_PNG)
|
||
check('посторонний upload в чужой чат -> 404', s, r, 404, 'not_found')
|
||
s, r, _, _ = upload(a_auth, str(uuid.uuid4()), SAMPLE_PNG)
|
||
check('upload в несуществующий чат -> 404', s, r, 404, 'not_found')
|
||
for suffix in ('', '/content'):
|
||
s, r, _, _ = api.call('GET', f'/attachments/{jpg_id}{suffix}', headers=e_auth)
|
||
check(f'посторонний GET /attachments/id{suffix} -> 404', s, r, 404, 'not_found')
|
||
s, r, _, _ = api.call('GET', f'/attachments/{uuid.uuid4()}{suffix}', headers=a_auth)
|
||
check(f'неизвестный attachment{suffix} -> 404', s, r, 404, 'not_found')
|
||
s, r, _, _ = api.call('GET', '/attachments/not-a-uuid', headers=a_auth)
|
||
check('attachment_id не UUID -> 400', s, r, 400, 'invalid_request')
|
||
s, r, _, _ = api.call('GET', f'/attachments/{jpg_id}/content?variant=thumbnail', headers=a_auth)
|
||
check('ready без варианта thumbnail -> 404', s, r, 404, 'not_found')
|
||
s, r, _, _ = api.call('GET', f'/attachments/{jpg_id}/content?variant=../../x', headers=a_auth)
|
||
check('variant неизвестного имени -> 400', s, r, 400, 'invalid_request')
|
||
|
||
# --- привязка к сообщению -----------------------------------------------
|
||
s, other_att, _, _ = upload(a_auth, other_chat['id'], SAMPLE_PNG)
|
||
s, eve_att, _, _ = upload(e_auth, eve_chat['id'], SAMPLE_PNG)
|
||
s, r, _, _ = message(a_auth, chat['id'], 'x', [other_att['id']])
|
||
check('вложение другого чата (своего) -> 404', s, r, 404, 'not_found')
|
||
s, r, _, _ = message(a_auth, chat['id'], 'x', [eve_att['id']])
|
||
check('вложение чужого чата -> 404', s, r, 404, 'not_found')
|
||
s, r, _, _ = message(a_auth, chat['id'], 'x', [jpg_id, str(uuid.uuid4())])
|
||
check('одно из ID неизвестно -> 404, ничего не создано', s, r, 404, 'not_found')
|
||
s, r, _, _ = message(a_auth, chat['id'], 'x', [jpg_id, jpg_id])
|
||
check('дубли attachment_ids -> 400', s, r, 400, 'invalid_request')
|
||
s, r, _, _ = message(a_auth, chat['id'], 'x', [str(uuid.uuid4()) for _ in range(11)])
|
||
check('11 attachment_ids -> 400', s, r, 400, 'invalid_request')
|
||
s, r, _, _ = message(a_auth, chat['id'], 'x', ['not-a-uuid'])
|
||
check('attachment_id не UUID -> 400', s, r, 400, 'invalid_request')
|
||
s, r, _, _ = message(a_auth, chat['id'], ' ', [])
|
||
check('пробельный text без вложений -> 400', s, r, 400, 'invalid_request')
|
||
|
||
key = uuid.uuid4().hex
|
||
s, m1, _, _ = message(b_auth, chat['id'], '', [jpg_id], key)
|
||
check('Bob: text="" + вложение Alice из общего чата -> 201', s, m1, 201,
|
||
extra_ok=s == 201 and m1['attachment_ids'] == [jpg_id] and m1['text'] == '')
|
||
s, m2, _, _ = message(b_auth, chat['id'], '', [jpg_id], key)
|
||
check('повтор Idempotency-Key -> то же сообщение', s, m2, 201, extra_ok=s == 201 and m2['id'] == m1['id'])
|
||
s, r, _, _ = message(b_auth, chat['id'], 'другой текст', [], key)
|
||
check('тот же ключ, другое тело -> 409', s, r, 409, 'conflict')
|
||
s, page, _, _ = api.call('GET', f"/chats/{chat['id']}/messages?limit=100", headers=a_auth)
|
||
linked = [m for m in page['items'] if m['attachment_ids']]
|
||
check('история: ровно одно сообщение с вложением', s, page, 200,
|
||
extra_ok=len(linked) == 1 and linked[0]['attachment_ids'] == [jpg_id])
|
||
|
||
# --- оборванная загрузка ------------------------------------------------
|
||
sock = socket.create_connection((api.host, api.port), timeout=10)
|
||
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=cut.png HTTP/1.1\r\n"
|
||
f"Host: {api.host}\r\nAuthorization: {a_auth['Authorization']}\r\n"
|
||
f"Content-Type: image/png\r\nContent-Length: {len(SAMPLE_PNG)}\r\n\r\n")
|
||
sock.sendall(head.encode() + SAMPLE_PNG[:len(SAMPLE_PNG) // 3])
|
||
sock.close()
|
||
s, r, _, _ = upload(a_auth, chat['id'], SAMPLE_PNG)
|
||
check('после оборванной загрузки API работает', s, r, 201)
|
||
|
||
# --- формат ошибок ------------------------------------------------------
|
||
s, r, _, resp = upload(a_auth, chat['id'], b'not an image')
|
||
check('ошибка в общем формате с request_id', s, r, 415, extra_ok=bool(r)
|
||
and r['error']['request_id'] == resp.getheader('X-Request-Id') and bool(resp.getheader('X-Instance-Id')))
|
||
|
||
print('PASS: граничные случаи вложений соответствуют контракту' if not failed
|
||
else f'FAIL: {failed} проверок не прошло')
|
||
return 1 if failed else 0
|
||
|
||
|
||
if __name__ == '__main__':
|
||
sys.exit(main())
|