Files
mtusi2026lab5/student-tests/test_attachments.py
T
2026-10-26 19:40:34 +03:00

291 lines
20 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""lab4–lab5: вложения через API (входит в make student-test; нужен только запущенный стенд).
С lab5 загрузка отвечает 202 queued, а ready выясняется опросом GET (worker обрабатывает асинхронно).
Уровень 3: PNG и JPEG принимаются, после обработки оригинал скачивается побайтно, у каждого
вложения ровно один набор вариантов; посторонний получает 404.
Варианты по контракту: thumbnail — JPEG, вписан в 256×256 без увеличения (fixture 320×200 ->
256×160); crop — JPEG 128×128 (маленькие увеличиваются); optimized — WebP, вписан в 1280×1280
без увеличения. Размеры проверяются по самим байтам (заголовки JPEG и WebP), а не только по JSON.
Без метаданных: в вариантах нет EXIF (APP1), ICC (APP2), блоков EXIF/XMP/ICCP у WebP.
Уровень 4 (lab4, сохранено): слишком большой файл, «бомба» по пикселям, повреждённые файлы,
подмена MIME, опасные filename, чужое attachment_id и вложение другого чата — точные коды, без 500.
Замечание к MR (lab5): JPEG с ошибками в заголовках (SOS ссылается на компонент, которого нет в SOF,
неопределённые таблицы, неверные параметры сканов, RST не по порядку и др.) — 415 сразу, а не 202 -> failed.
lab5: failed-вложение нельзя прикрепить (409), его байты — 409; ровно 10 MiB и ровно 40 млн
пикселей принимаются, на байт/пиксель больше — 413.
"""
import hashlib
import unittest
import uuid
from urllib.parse import quote
from filegen import (PROGRESSIVE_JPEG, RESTART_JPEG, SAMPLE_JPEG, SAMPLE_PNG, bad_filter_png, bomb_png,
broken_structure_jpegs, corrupt_crc, garbage_scan_jpeg, gray_png, jpeg_markers, png, png_exact_size,
raw_upload, truncated, wait_status, webp_chunks, webp_size)
from helpers import Client, idempotency
from image_probe import jpeg_size
MAX = 10 * 1024 * 1024
FIXTURE_VARIANTS = {"thumbnail": ("image/jpeg", 256, 160), "crop": ("image/jpeg", 128, 128),
"optimized": ("image/webp", 320, 200)}
class AttachmentTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = Client(timeout=30)
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
# Второй чат Алисы (с Евой) и чат Евы с Бобом: для проверок «чужое» и «из другого чата».
cls.other_chat = cls.chat_of(cls.alice, cls.eve)
cls.eve_chat = cls.chat_of(cls.eve, cls.bob)
@classmethod
def chat_of(cls, creator, other):
return cls.api.call("POST", "/api/v1/chats", 201, actor=creator, schema="Chat",
body={"title": "lab5", "member_ids": [creator["id"], other["id"]]})["json"]
def upload(self, data, ctype="image/png", name="photo.png", expected=202, actor=None, chat=None):
chat = chat or self.chat
query = "" if name is None else "?filename=" + quote(name, safe="")
return self.api.call("POST", f"/api/v1/chats/{chat['id']}/attachments{query}", expected,
actor=actor or self.alice, raw=data, headers={"Content-Type": ctype},
schema="Attachment" if expected == 202 else None)
def ready(self, attachment_id, actor=None):
return wait_status(self.api, actor or self.bob, attachment_id, ("ready",))
def post_message(self, body, expected=201, key=None):
return self.api.call("POST", f"/api/v1/chats/{self.chat['id']}/messages", expected, actor=self.alice,
body=body, headers=idempotency(key), schema="Message" if expected == 201 else None)
def content(self, attachment_id, variant=None, expected=200, actor=None):
suffix = "" if variant is None else "?variant=" + variant
return self.api.call("GET", f"/api/v1/attachments/{attachment_id}/content{suffix}", expected,
actor=actor or self.bob)
# ---------- уровень 3 ----------
def test_png_and_jpeg_roundtrip_for_member(self):
for data, ctype, name in ((SAMPLE_PNG, "image/png", "sample.png"), (SAMPLE_JPEG, "image/jpeg", "кот 🐱.jpg")):
att = self.upload(data, ctype, name)["json"]
# 202 — снимок «принято в обработку»: статус queued, вариантов ещё нет.
self.assertEqual((att["status"], att["variants"], att["error_code"]), ("queued", [], None))
self.assertEqual((att["content_type"], att["filename"], att["size_bytes"]), (ctype, name, len(data)))
self.assertEqual(att["sha256"], hashlib.sha256(data).hexdigest())
meta = self.ready(att["id"])
self.assertEqual((meta["status"], meta["error_code"]), ("ready", None))
self.assertEqual([v["name"] for v in meta["variants"]], ["thumbnail", "crop", "optimized"])
# size_bytes/sha256/content_type по-прежнему описывают ОРИГИНАЛ.
self.assertEqual((meta["size_bytes"], meta["sha256"], meta["content_type"]),
(att["size_bytes"], att["sha256"], att["content_type"]))
got = self.content(att["id"])
self.assertEqual(got["bytes"], data)
self.assertEqual(got["headers"].get_content_type(), ctype)
self.assertEqual(got["headers"].get("X-Content-Type-Options"), "nosniff")
for suffix in ("", "/content", "/content?variant=thumbnail"): # посторонний не узнаёт, что вложение есть
self.api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, actor=self.eve)
self.api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 401)
def test_variants_follow_the_contract(self):
att = self.upload(SAMPLE_PNG, name="variants.png")["json"]
meta = self.ready(att["id"])
for variant in meta["variants"]:
name = variant["name"]
ctype, width, height = FIXTURE_VARIANTS[name]
self.assertEqual((variant["content_type"], variant["width"], variant["height"]), (ctype, width, height))
got = self.content(att["id"], name)
body = got["bytes"]
self.assertEqual(got["headers"].get_content_type(), ctype)
self.assertEqual((len(body), hashlib.sha256(body).hexdigest()), (variant["size_bytes"], variant["sha256"]))
if ctype == "image/jpeg":
self.assertEqual(jpeg_size(body), (width, height)) # реальный размер из заголовка JPEG
markers = jpeg_markers(body)
self.assertNotIn(0xE1, markers, f"{name}: EXIF/XMP (APP1) must be stripped")
self.assertNotIn(0xE2, markers, f"{name}: ICC (APP2) must be stripped")
else:
self.assertEqual(webp_size(body), (width, height))
self.assertFalse({b"EXIF", b"XMP ", b"ICCP"} & set(webp_chunks(body)), "WebP metadata must be stripped")
# Маленький JPEG 48×32: thumbnail и optimized не увеличиваются, crop — увеличивается до 128×128.
small = self.ready(self.upload(SAMPLE_JPEG, "image/jpeg", "small.jpg")["json"]["id"])
sizes = {v["name"]: (v["width"], v["height"]) for v in small["variants"]}
self.assertEqual(sizes, {"thumbnail": (48, 32), "crop": (128, 128), "optimized": (48, 32)})
print(f"\n fixture 320×200 -> thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized 320×200 WebP; "
f"48×32 -> {sizes}")
def test_outsider_and_anonymous_cannot_upload(self):
self.upload(SAMPLE_PNG, actor=self.eve, expected=404) # Ева не участник чата
self.api.call("POST", f"/api/v1/chats/{self.chat['id']}/attachments?filename=a.png", 401,
raw=SAMPLE_PNG, headers={"Content-Type": "image/png"})
self.upload(SAMPLE_PNG, chat={"id": str(uuid.uuid4())}, expected=404)
self.upload(SAMPLE_PNG, chat={"id": "not-a-uuid"}, expected=400)
# ---------- уровень 4: размер ----------
def test_too_large_is_413_before_reading(self):
# Заявлено 10 MiB + 1 байт: ответ 413 приходит сразу, сервер тело не читает.
reply = raw_upload(f"/api/v1/chats/{self.chat['id']}/attachments?filename=big.png",
self.alice["token"], b"", content_length=MAX + 1)
self.assertIsNotNone(reply, "no HTTP response")
status, _, body = reply
self.assertEqual((status, body["error"]["code"]), (413, "payload_too_large"))
def test_too_large_stream_is_413(self):
# Тот же размер по частям (chunked, без Content-Length): сервер считает байты при чтении.
data = SAMPLE_PNG + b"\x00" * (MAX + 1 - len(SAMPLE_PNG))
reply = raw_upload(f"/api/v1/chats/{self.chat['id']}/attachments?filename=big.png",
self.alice["token"], data, content_length=-1)
self.assertIsNotNone(reply, "no HTTP response")
status, _, body = reply
self.assertEqual((status, body["error"]["code"]), (413, "payload_too_large"))
def test_exact_limits(self):
# Ровно 10 485 760 байт и ровно 40 000 000 пикселей — принимаются; на 1 больше — 413.
exact = png_exact_size(MAX)
self.assertEqual(len(exact), MAX)
self.ready(self.upload(exact, name="exact-10mib.png")["json"]["id"])
self.upload(png_exact_size(MAX + 1), name="over.png", expected=413)
self.ready(self.upload(gray_png(6400, 6250), name="exact-40mp.png")["json"]["id"])
self.upload(gray_png(40_000_001, 1), name="over-40mp.png", expected=413)
print("\n 10 485 760 байт и 6400×6250 = 40 000 000 px: 202 -> ready; на 1 байт/пиксель больше: 413")
def test_pixel_bomb_is_413(self):
bomb = bomb_png()
self.assertLess(len(bomb), MAX) # по байтам файл маленький
reply = self.upload(bomb, expected=413)["json"]
self.assertIn("пиксел", reply["error"]["message"]) # отклонён именно по пикселям
def test_large_real_image_within_limits_is_accepted(self):
data = png(1600, 1200, noise=True) # ~5,8 МБ, 1,9 млн пикселей
att = self.upload(data, name="noise.png")["json"]
meta = self.ready(att["id"])
got = self.content(att["id"])
self.assertEqual(hashlib.sha256(got["bytes"]).hexdigest(), hashlib.sha256(data).hexdigest())
sizes = {v["name"]: (v["width"], v["height"]) for v in meta["variants"]}
self.assertEqual(sizes, {"thumbnail": (256, 192), "crop": (128, 128), "optimized": (1280, 960)})
# ---------- уровень 4: содержимое ----------
def test_corrupted_images_are_415(self):
for data, ctype in ((truncated(SAMPLE_PNG), "image/png"), (corrupt_crc(SAMPLE_PNG), "image/png"),
(truncated(SAMPLE_JPEG), "image/jpeg"), (b"\x89PNG\r\n\x1a\n" + b"x" * 100, "image/png"),
(bytes(range(256)) * 10, "image/png"), (bad_filter_png(), "image/png"),
(SAMPLE_PNG + b"<html>tail</html>", "image/png")):
with self.subTest(size=len(data), ctype=ctype):
self.assertEqual(self.upload(data, ctype, expected=415)["json"]["error"]["code"],
"unsupported_media_type")
self.upload(b"", expected=400) # пустое тело
def test_structurally_broken_jpeg_is_415(self):
# Замечание к MR: первый SOS ссылался на компонент 250, которого нет в SOF, а API отвечал
# 202 (потом failed/invalid_image). Теперь всё, что строгий декодер worker отвергает по
# маркерам и заголовкам, отклоняется сразу: 415, в БД и S3 ничего не появляется.
for name, data in broken_structure_jpegs():
with self.subTest(name):
reply = self.upload(data, "image/jpeg", "broken.jpg", expected=415)
self.assertEqual(reply["json"]["error"]["code"], "unsupported_media_type")
def test_valid_jpeg_variants_are_accepted(self):
# Обратная сторона: строгая проверка не отклоняет правильные progressive JPEG и JPEG
# с маркерами RST — они проходят и доходят до ready с тремя вариантами.
for name, data in (("progressive", PROGRESSIVE_JPEG), ("restart-markers", RESTART_JPEG)):
with self.subTest(name):
att = self.upload(data, "image/jpeg", f"{name}.jpg")["json"]
ready = self.ready(att["id"])
self.assertEqual(sorted(v["name"] for v in ready["variants"]), ["crop", "optimized", "thumbnail"])
self.assertEqual(self.content(att["id"])["bytes"], data)
def test_mime_spoofing_is_415(self):
cases = ((SAMPLE_PNG, "image/jpeg"), # PNG под видом JPEG
(SAMPLE_JPEG, "image/png"), # JPEG под видом PNG
(b"GIF89a" + b"\x00" * 50, "image/png"), # GIF под видом PNG
(b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png"),
(SAMPLE_PNG, "image/gif"), (SAMPLE_PNG, "text/plain"),
(SAMPLE_PNG, "application/x-www-form-urlencoded")) # по сути «Content-Type не указан»
for data, ctype in cases:
with self.subTest(ctype=ctype, head=data[:4]):
self.upload(data, ctype, expected=415)
def test_dangerous_filenames_are_400(self):
for name in (None, "", " ", "a/b.png", "..\\b.png", "a\x00b.png", "a\nb.png", "a\tb.png", "..",
"photo‮gnp.exe", "c1\u0085.png", "line
break.png", "x" * 256):
with self.subTest(name=repr(name)):
self.upload(SAMPLE_PNG, name=name, expected=400)
name = "отпуск 2026 (1).png" # Unicode и пробелы — можно
self.assertEqual(self.upload(SAMPLE_PNG, name=name)["json"]["filename"], name)
def test_broken_scan_becomes_failed_and_cannot_be_attached(self):
# Структура JPEG цела (API принимает: 202), но сжатые данные — мусор: worker при строгом
# декодировании даёт постоянную ошибку -> failed с invalid_image, без повторов.
att = self.upload(garbage_scan_jpeg(), "image/jpeg", "broken.jpg")["json"]
failed = wait_status(self.api, self.bob, att["id"], ("failed",))
self.assertEqual((failed["error_code"], failed["variants"]), ("invalid_image", []))
self.content(att["id"], expected=409)
self.content(att["id"], "thumbnail", expected=409)
self.post_message({"text": "", "attachment_ids": [att["id"]]}, 409)
good = self.upload(SAMPLE_PNG, name="good.png")["json"]["id"]
self.post_message({"text": "x", "attachment_ids": [good, att["id"]]}, 409) # одно failed — отказ целиком
self.post_message({"text": "x", "attachment_ids": [att["id"], str(uuid.uuid4())]}, 404) # неизвестное — 404
# ---------- уровень 4: привязка к сообщению ----------
def test_message_with_attachments(self):
a1 = self.upload(SAMPLE_PNG)["json"]["id"]
a2 = self.upload(SAMPLE_JPEG, "image/jpeg", "b.jpg")["json"]["id"]
# Ещё не обработанное (queued/processing) вложение прикреплять можно (lab5).
message = self.post_message({"text": "", "attachment_ids": [a2, a1]})["json"]
self.assertEqual(message["attachment_ids"], [a2, a1]) # порядок сохраняется
page = self.api.call("GET", f"/api/v1/chats/{self.chat['id']}/messages?limit=100", actor=self.bob,
schema="MessagePage")["json"]
self.assertIn(message, page["items"]) # история отдаёт те же attachment_ids
again = self.post_message({"text": "то же вложение ещё раз", "attachment_ids": [a1]})["json"]
self.assertEqual(again["attachment_ids"], [a1]) # одно вложение — в нескольких сообщениях
plain = self.post_message({"text": "без вложений"})["json"]
self.assertEqual(plain["attachment_ids"], [])
def test_attachment_rules_without_500(self):
att = self.upload(SAMPLE_PNG)["json"]["id"]
foreign = self.upload(SAMPLE_PNG, actor=self.eve, chat=self.eve_chat)["json"]["id"] # чужое
other = self.upload(SAMPLE_PNG, chat=self.other_chat)["json"]["id"] # Алисы, но другой чат
self.post_message({"text": "", "attachment_ids": [foreign]}, 404)
self.post_message({"text": "", "attachment_ids": [other]}, 404)
self.post_message({"text": "x", "attachment_ids": [att, str(uuid.uuid4())]}, 404) # одно неизвестное
self.post_message({"text": ""}, 400) # пусто и без вложений
self.post_message({"text": " ", "attachment_ids": []}, 400)
self.post_message({"text": "x", "attachment_ids": [att, att]}, 400) # дубликаты
self.post_message({"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, 400)
self.post_message({"text": "x", "attachment_ids": ["not-a-uuid"]}, 400)
self.post_message({"text": "x", "attachment_ids": att}, 400) # не массив
self.post_message({"attachment_ids": [att]}, 400) # нет text
self.post_message({"text": None, "attachment_ids": [att]}, 400)
self.post_message({"text": "x", "attachment_ids": None}, 400)
# Провал не «занимает» сообщение: в истории нет ни одного из отклонённых.
page = self.api.call("GET", f"/api/v1/chats/{self.chat['id']}/messages?limit=100", actor=self.alice,
schema="MessagePage")["json"]["items"]
self.assertFalse([m for m in page if foreign in m["attachment_ids"] or other in m["attachment_ids"]])
def test_idempotency_with_attachments(self):
att = self.upload(SAMPLE_PNG)["json"]["id"]
key = uuid.uuid4().hex
first = self.post_message({"text": "фото"}, key=key)["json"]
replay = self.post_message({"attachment_ids": [], "text": "фото"}, key=key)["json"] # [] == отсутствует
self.assertEqual(first, replay)
self.post_message({"text": "фото", "attachment_ids": [att]}, 409, key=key) # другое тело
key2 = uuid.uuid4().hex
with_att = self.post_message({"text": "", "attachment_ids": [att]}, key=key2)["json"]
self.assertEqual(self.post_message({"text": "", "attachment_ids": [att]}, key=key2)["json"], with_att)
def test_variants_and_bad_ids(self):
att = self.upload(SAMPLE_PNG)["json"]["id"]
self.ready(att)
path = f"/api/v1/attachments/{att}/content"
self.assertEqual(self.api.call("GET", path + "?variant=original", actor=self.bob)["bytes"], SAMPLE_PNG)
self.api.call("GET", path + "?variant=thumbnail", actor=self.bob)
self.api.call("GET", path + "?variant=huge", 400, actor=self.bob)
self.api.call("GET", "/api/v1/attachments/not-a-uuid", 400, actor=self.bob)
self.api.call("GET", f"/api/v1/attachments/{uuid.uuid4()}/content", 404, actor=self.bob)
self.api.call("GET", f"/api/v1/attachments/{uuid.uuid4()}", 404, actor=self.bob)
if __name__ == "__main__":
unittest.main(verbosity=2)