import hashlib import http.client import io import json import struct from urllib.parse import urlencode, urlsplit from uuid import uuid4 import zlib from PIL import Image from helpers import ApiTestCase, ROOT class AttachmentTests(ApiTestCase): def upload(self, data=None, filename="photo.png", content_type="image/png", expected=201, actor=None): if data is None: data = (ROOT / "tests/fixtures/sample.png").read_bytes() return self.client.call("POST", self.path + "/attachments?" + urlencode({"filename": filename}), expected, actor=actor or self.alice, raw=data, headers={"Content-Type": content_type}, schema="Attachment" if expected == 201 else None) def test_png_and_jpeg_originals(self): jpeg = io.BytesIO() Image.new("RGB", (100, 60), "orange").save(jpeg, format="JPEG") for data, mime, filename in (((ROOT / "tests/fixtures/sample.png").read_bytes(), "image/png", "Фото 👋.png"), (jpeg.getvalue(), "image/jpeg", "photo.jpeg")): with self.subTest(mime=mime): attachment = self.upload(data, filename, mime)["json"] self.assertEqual(attachment["filename"], filename) self.assertEqual(attachment["status"], "ready") self.assertEqual(attachment["variants"], []) self.assertIsNone(attachment["error_code"]) self.assertEqual(attachment["sha256"], hashlib.sha256(data).hexdigest()) self.assertEqual(attachment["size_bytes"], len(data)) self.assertEqual(self.client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=self.bob, schema="Attachment")["json"], attachment) result = self.client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=self.bob) self.assertEqual(result["bytes"], data) self.assertEqual(result["headers"].get_content_type(), mime) self.assertEqual(result["headers"]["X-Content-Type-Options"], "nosniff") def test_corruption_and_mime_spoof(self): png = (ROOT / "tests/fixtures/sample.png").read_bytes() for data, mime in ((png, "image/jpeg"), (png[:50], "image/png"), (b"not an image", "image/png"), (b"", "image/png"), (b"GIF89a", "image/png"), (png, "application/octet-stream")): with self.subTest(size=len(data), mime=mime): result = self.upload(data, content_type=mime, expected=415) self.assertEqual(result["json"]["error"]["code"], "unsupported_media_type") def test_filename_rejected_before_storage(self): for filename in ("", " ", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\r\n.png", "a\x7f.png", "a" * 256): with self.subTest(filename=repr(filename)): result = self.upload(filename=filename, expected=400) self.assertEqual(result["json"]["error"]["code"], "invalid_request") self.client.call("POST", self.path + "/attachments", 400, actor=self.alice, raw=b"x", headers={"Content-Type": "image/png"}) def test_content_length_limit_before_body(self): self.client.call("POST", self.path + "/attachments?filename=a.png", 413, actor=self.alice, raw=b"x", headers={"Content-Type": "image/png", "Content-Length": str(10485761)}) def test_chunked_limit_without_content_length(self): target = urlsplit(self.client.base) connection = http.client.HTTPConnection(target.hostname, target.port, timeout=15) try: connection.request("POST", self.path + "/attachments?filename=large.png", body=iter([b"x" * 65536] * 160 + [b"x"]), headers={"Authorization": "Bearer " + self.alice["token"], "Content-Type": "image/png"}, encode_chunked=True) response = connection.getresponse() self.assertEqual(response.status, 413) self.assertEqual(json.loads(response.read())["error"]["code"], "payload_too_large") finally: connection.close() def test_pixel_limit_before_decode(self): def chunk(kind, data): return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) # Размеры в корректном IHDR превышают лимит; pixel data вообще не выделяется. data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 10000, 4001, 8, 2, 0, 0, 0)) data += chunk(b"IDAT", b"") + chunk(b"IEND", b"") self.upload(data, expected=413) def test_access_and_authentication(self): attachment = self.upload()["json"] for suffix in ("", "/content"): path = "/api/v1/attachments/" + attachment["id"] + suffix self.assert_error("GET", path, 401, "unauthorized") self.assert_error("GET", path, 404, "not_found", actor=self.eve) self.assert_error("GET", "/api/v1/attachments/" + str(uuid4()) + suffix, 404, "not_found", actor=self.eve) self.upload(expected=404, actor=self.eve) self.client.call("POST", self.path + "/attachments?filename=../bad", 401, raw=b"x", headers={"Content-Type": "image/png"}) self.assert_error("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", 404, "not_found", actor=self.alice) def test_attachment_only_message_and_other_member(self): attachment = self.upload()["json"] message = self.client.message(self.bob, self.chat, "", attachments=[attachment["id"]])["json"] self.assertEqual(message["attachment_ids"], [attachment["id"]]) self.assertEqual(message["sender_id"], self.bob["id"]) self.assertEqual(self.read_all(self.path + "/messages", self.alice, "MessagePage"), [message]) def test_foreign_and_unknown_attachment_ids(self): attachment = self.upload()["json"] other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat", body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"] for chat_id, ids in ((self.chat["id"], [str(uuid4())]), (other["id"], [attachment["id"]])): self.assert_error("POST", "/api/v1/chats/" + chat_id + "/messages", 404, "not_found", actor=self.alice, body={"text": "", "attachment_ids": ids}) def test_invalid_attachment_lists(self): attachment = self.upload()["json"] for ids in ([attachment["id"], attachment["id"].upper()], [str(uuid4()) for _ in range(11)], ["not-a-uuid"], [True], None, "uuid"): self.assert_error("POST", self.path + "/messages", 400, "invalid_request", actor=self.alice, body={"text": "Текст", "attachment_ids": ids}) def test_idempotency_includes_ordered_attachment_ids(self): first, second = self.upload()["json"], self.upload()["json"] key = uuid4().hex ids = [first["id"], second["id"]] saved = self.client.message(self.alice, self.chat, "", key=key, attachments=ids)["json"] self.assertEqual(self.client.message(self.alice, self.chat, "", key=key, attachments=ids)["json"], saved) for changed in ([second["id"], first["id"]], [first["id"]]): self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice, body={"text": "", "attachment_ids": changed}, headers={"Idempotency-Key": key}) key = uuid4().hex saved = self.client.message(self.alice, self.chat, "Без файла", key=key)["json"] self.assertEqual(self.client.message(self.alice, self.chat, "Без файла", key=key, attachments=[])["json"], saved)