"""lab4: вложения через API (входит в make student-test; нужен только запущенный стенд). Уровень 3: PNG и JPEG загружаются и скачиваются побайтно, посторонний получает 404. Уровень 4: слишком большой файл, «бомба» по пикселям, повреждённые файлы, подмена MIME, опасные filename, чужое attachment_id и вложение другого чата. Каждый случай проверяется по точному коду ответа: пользовательская ошибка никогда не превращается в 500. """ import hashlib import unittest import uuid from urllib.parse import quote from filegen import (SAMPLE_JPEG, SAMPLE_PNG, bomb_png, corrupt_crc, png, raw_upload, truncated) from helpers import Client, idempotency MAX = 10 * 1024 * 1024 class AttachmentTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = Client() 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": "lab4", "member_ids": [creator["id"], other["id"]]})["json"] def upload(self, data, ctype="image/png", name="photo.png", expected=201, 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 == 201 else None) 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) # ---------- уровень 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"] self.assertEqual((att["status"], att["variants"], att["error_code"]), ("ready", [], 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.api.call("GET", f"/api/v1/attachments/{att['id']}", actor=self.bob, schema="Attachment") self.assertEqual(meta["json"], att) got = self.api.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=self.bob) 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"): # посторонний не узнаёт, что вложение существует 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_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_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"] got = self.api.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=self.bob) self.assertEqual(hashlib.sha256(got["bytes"]).hexdigest(), hashlib.sha256(data).hexdigest()) # ---------- уровень 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")): 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_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"", "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", "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) # ---------- уровень 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"] 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) # не массив # Провал не «занимает» сообщение: в истории нет ни одного из отклонённых. 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"] 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", 404, actor=self.bob) # варианты появятся в lab5 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) if __name__ == "__main__": unittest.main(verbosity=2)