Files
mtusi2026lab4/student-tests/test_attachments_negative.py
T
2026-10-30 22:16:54 +03:00

75 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Негативные сценарии вложений. Запускается против запущенного стенда."""
import sys
import uuid
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run # noqa: E402
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
def main():
args = arguments("Lab4 attachment negative tests")
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
other_chat = c.call(
"POST", "/api/v1/chats", 201, actor=bob,
body={"title": "Другой чат", "member_ids": [bob["id"]]}, schema="Chat")["json"]
base = "/api/v1/chats/%s/attachments" % chat["id"]
png_fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
# 1. Слишком большой файл: 10 MiB + 1 байт, Content-Length сразу отвергается.
big = PNG_MAGIC + b"\x00" * (10485760)
r = c.call("POST", base + "?filename=big.png", 413, actor=alice, raw=big,
headers={"Content-Type": "image/png"})
check(r["status"] == 413, "oversize not rejected")
# 2. Подмена MIME: объявляем image/png, а байты не PNG.
r = c.call("POST", base + "?filename=x.png", 415, actor=alice,
raw=b"not an image at all",
headers={"Content-Type": "image/png"})
check(r["status"] == 415, "mime mismatch not rejected")
# 3. Повреждённый PNG: валидный заголовок, битая структура.
broken = png_fixture[:20] + b"\x00" * 32 + png_fixture[52:]
c.call("POST", base + "?filename=broken.png", 415, actor=alice, raw=broken,
headers={"Content-Type": "image/png"})
# 4. Опасное имя файла. URL-кодируем: NUL, /, \ в URL напрямую запрещены
# клиентом (http.client), но после декодирования сервер обязан отклонить.
for bad in ("../etc/passwd", "a\\b.png", "a\x00b.png", "a/b.png"):
c.call("POST", base + "?filename=" + quote(bad, safe=""), 400, actor=alice,
raw=png_fixture, headers={"Content-Type": "image/png"})
# 5. Чужой чат: eve не участник — 404 до чтения тела.
c.call("POST", base + "?filename=sample.png", 404, actor=eve,
raw=png_fixture, headers={"Content-Type": "image/png"})
# 6. Сослаться на чужое вложение в сообщении.
foreign = c.call("POST", "/api/v1/chats/%s/attachments?filename=s.png" % other_chat["id"],
201, actor=bob, raw=png_fixture,
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
actor=alice,
body={"text": "hi", "attachment_ids": [foreign["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex})
# 7. Чтение чужого attachment_id — 404 на metadata и bytes.
c.call("GET", "/api/v1/attachments/" + foreign["id"], 404, actor=eve)
c.call("GET", "/api/v1/attachments/" + foreign["id"] + "/content", 404, actor=eve)
# 8. Несуществующий id — 404, не 500.
ghost = str(uuid.uuid4())
c.call("GET", "/api/v1/attachments/" + ghost, 404, actor=alice)
c.call("GET", "/api/v1/attachments/" + ghost + "/content", 404, actor=alice)
print("PASS: 8 negative attachment scenarios")
if __name__ == "__main__":
run(main)