164 lines
7.7 KiB
Python
164 lines
7.7 KiB
Python
"""Собственные проверки лабораторной 4: вложения, лимиты и отказы.
|
|
|
|
Проверки идут через публичный контракт и LB, не подменяют приложение и не
|
|
управляют Docker. Инфраструктурные сценарии (S3 outage, reconciler, память)
|
|
лежат в отдельных скриптах и evidence.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import struct
|
|
import unittest
|
|
import uuid
|
|
import zlib
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
import harness
|
|
from client import Client
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
|
JPEG = (Path(__file__).resolve().parent / "fixtures" / "sample.jpg").read_bytes()
|
|
MAX_BYTES = 10_485_760
|
|
|
|
|
|
def upload(api: Client, actor: dict, chat: dict, content: bytes, *, filename: str = "photo.png", content_type: str = "image/png", expected: int = 201):
|
|
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
|
|
return api.call(
|
|
"POST",
|
|
path,
|
|
expected,
|
|
actor=actor,
|
|
raw=content,
|
|
headers={"Content-Type": content_type},
|
|
schema="Attachment" if expected == 201 else None,
|
|
)
|
|
|
|
|
|
def png_with_dimensions(width: int, height: int) -> bytes:
|
|
"""Меняет IHDR у реального PNG и пересчитывает CRC: файл остаётся PNG."""
|
|
data = bytearray(PNG)
|
|
struct.pack_into(">I", data, 16, width)
|
|
struct.pack_into(">I", data, 20, height)
|
|
struct.pack_into(">I", data, 29, zlib.crc32(bytes(data[12:29])) & 0xFFFFFFFF)
|
|
return bytes(data)
|
|
|
|
|
|
class Lab4AttachmentTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls) -> None:
|
|
harness.wait_ready()
|
|
cls.api = harness.client()
|
|
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
|
cls.other_chat = cls.api.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
201,
|
|
actor=cls.alice,
|
|
body={"title": "Другой чат lab4", "member_ids": [cls.alice["id"], cls.bob["id"]]},
|
|
schema="Chat",
|
|
)["json"]
|
|
|
|
def test_01_png_jpeg_and_metadata(self) -> None:
|
|
for content, content_type, filename in ((PNG, "image/png", "sample.png"), (JPEG, "image/jpeg", "sample.jpg")):
|
|
attachment = upload(self.api, self.alice, self.chat, content, filename=filename, content_type=content_type)["json"]
|
|
self.assertEqual(attachment["status"], "ready")
|
|
self.assertEqual(attachment["variants"], [])
|
|
self.assertIsNone(attachment["error_code"])
|
|
self.assertEqual(attachment["chat_id"], self.chat["id"])
|
|
self.assertEqual(attachment["owner_id"], self.alice["id"])
|
|
self.assertEqual(attachment["content_type"], content_type)
|
|
self.assertEqual(attachment["size_bytes"], len(content))
|
|
self.assertEqual(attachment["sha256"], hashlib.sha256(content).hexdigest())
|
|
metadata = self.api.call("GET", "/api/v1/attachments/" + attachment["id"], actor=self.bob, schema="Attachment")["json"]
|
|
self.assertEqual(metadata, attachment)
|
|
downloaded = self.api.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=self.bob)
|
|
self.assertEqual(downloaded["bytes"], content)
|
|
self.assertEqual(downloaded["headers"].get_content_type(), content_type)
|
|
self.assertEqual(downloaded["headers"].get("Content-Length"), str(len(content)))
|
|
|
|
def test_02_stranger_and_nonmember(self) -> None:
|
|
attachment = upload(self.api, self.alice, self.chat, PNG)["json"]
|
|
for suffix in ("", "/content"):
|
|
self.api.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=self.eve)
|
|
# Посторонний не может загрузить файл в чужой чат.
|
|
upload(self.api, self.eve, self.chat, PNG, expected=404)
|
|
|
|
def test_03_attachment_from_another_chat_is_404(self) -> None:
|
|
foreign = upload(self.api, self.alice, self.other_chat, PNG)["json"]
|
|
self.api.call(
|
|
"POST",
|
|
"/api/v1/chats/" + self.chat["id"] + "/messages",
|
|
404,
|
|
actor=self.alice,
|
|
body={"text": "", "attachment_ids": [foreign["id"]]},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
# В своём чате это же вложение допустимо.
|
|
own = self.api.message(self.alice, self.other_chat, "", attachments=[foreign["id"]])["json"]
|
|
self.assertEqual(own["attachment_ids"], [foreign["id"]])
|
|
|
|
def test_04_message_attachment_validation_and_idempotency(self) -> None:
|
|
attachment = upload(self.api, self.alice, self.chat, PNG)["json"]
|
|
path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
|
self.api.call("POST", path, 400, actor=self.alice, body={"text": ""}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
|
self.api.call(
|
|
"POST",
|
|
path,
|
|
400,
|
|
actor=self.alice,
|
|
body={"text": "too many", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
self.api.call(
|
|
"POST",
|
|
path,
|
|
400,
|
|
actor=self.alice,
|
|
body={"text": "duplicate", "attachment_ids": [attachment["id"], attachment["id"]]},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
self.api.call(
|
|
"POST",
|
|
path,
|
|
404,
|
|
actor=self.alice,
|
|
body={"text": "unknown", "attachment_ids": [str(uuid.uuid4())]},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
key = uuid.uuid4().hex
|
|
first = self.api.message(self.alice, self.chat, "", key=key, attachments=[attachment["id"]])["json"]
|
|
self.assertEqual(first["text"], "")
|
|
self.assertEqual(first["attachment_ids"], [attachment["id"]])
|
|
replay = self.api.message(self.alice, self.chat, "", key=key, attachments=[attachment["id"]])["json"]
|
|
self.assertEqual(replay, first)
|
|
self.api.call(
|
|
"POST",
|
|
path,
|
|
409,
|
|
actor=self.alice,
|
|
body={"text": "different", "attachment_ids": []},
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
|
|
def test_05_rejects_bad_images_and_filenames(self) -> None:
|
|
# Слишком большое тело отсекается по Content-Length до чтения.
|
|
upload(self.api, self.alice, self.chat, b"\x00" * (MAX_BYTES + 1), expected=413)
|
|
# Повреждённый PNG, подмена MIME содержимым и не-изображение.
|
|
upload(self.api, self.alice, self.chat, PNG[:100], expected=415)
|
|
upload(self.api, self.alice, self.chat, PNG, content_type="image/jpeg", expected=415)
|
|
upload(self.api, self.alice, self.chat, b"not an image", expected=415)
|
|
upload(self.api, self.alice, self.chat, b"", expected=415)
|
|
# Размеры читаются из заголовка и проверяются до распаковки.
|
|
upload(self.api, self.alice, self.chat, png_with_dimensions(8000, 6000), expected=413)
|
|
# 100 Мп выше порога Pillow DecompressionBombWarning; это всё ещё 413, не 500.
|
|
upload(self.api, self.alice, self.chat, png_with_dimensions(10000, 10000), expected=413)
|
|
for bad in ("../secret.png", "a/b.png", "a\\b.png", "a\x00b.png", "a\nb.png", "x" * 256):
|
|
upload(self.api, self.alice, self.chat, PNG, filename=bad, expected=400)
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|