Files
mtusi2026lab5/student-tests/attachments.py

134 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Негативные проверки вложений для оценки 4: лимиты, MIME, ACL, чужой чат."""
import json
import os
import struct
import sys
import time
import uuid
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
EVIDENCE = ROOT / "evidence"
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def png(width: int, height: int, extra: bytes = b"") -> bytes:
def chunk(tag: bytes, data: bytes) -> bytes:
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + extra + chunk(b"IEND", b"")
def upload(client, actor, chat, filename, body, content_type, expected):
return client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename),
expected,
actor=actor,
raw=body,
headers={"Content-Type": content_type},
schema="Attachment" if expected in (201, 202) else None,
)
def main():
client = Client(BASE, timeout=30)
alice, bob, eve, chat = client.bootstrap()
other = client.call(
"POST",
"/api/v1/chats",
201,
actor=eve,
body={"title": "Чужой", "member_ids": [eve["id"]]},
schema="Chat",
)["json"]
att, content = client.attachment(alice, chat)
att = client.wait_ready(alice, att)
check(content == SAMPLE, "fixture changed")
too_big = upload(client, alice, chat, "big.png", SAMPLE + b"x" * (10 * 1024 * 1024), "image/png", 413)
check(too_big["json"]["error"]["code"] == "payload_too_large", "oversize code")
spoof = upload(client, alice, chat, "spoof.png", SAMPLE, "image/jpeg", 415)
check(spoof["json"]["error"]["code"] == "unsupported_media_type", "spoofed MIME code")
broken = upload(client, alice, chat, "broken.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415)
check(broken["json"]["error"]["code"] == "unsupported_media_type", "corrupt image code")
huge = upload(client, alice, chat, "huge.png", png(10001, 4000), "image/png", 413)
check(huge["json"]["error"]["code"] == "payload_too_large", "pixel limit code")
slash = upload(client, alice, chat, "a/b.png", SAMPLE, "image/png", 400)
check(slash["json"]["error"]["code"] == "invalid_request", "slash filename code")
missing = client.call(
"GET",
"/api/v1/attachments/%s" % uuid.uuid4(),
404,
actor=alice,
)
check(missing["json"]["error"]["code"] == "not_found", "unknown attachment")
stolen = client.call("GET", "/api/v1/attachments/%s" % att["id"], 404, actor=eve)
check(stolen["json"]["error"]["code"] == "not_found", "outsider metadata")
stolen_bytes = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], 404, actor=eve)
check(stolen_bytes["json"]["error"]["code"] == "not_found", "outsider bytes")
foreign_file = upload(client, eve, other, "other.png", SAMPLE, "image/png", 202)["json"]
linked = client.call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
404,
actor=alice,
body={"text": "", "attachment_ids": [foreign_file["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(linked["json"]["error"]["code"] == "not_found", "cross-chat attachment")
unknown_link = client.call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
404,
actor=alice,
body={"text": "x", "attachment_ids": [str(uuid.uuid4())]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
check(unknown_link["json"]["error"]["code"] == "not_found", "unknown attachment_id")
ok = client.message(alice, chat, "", attachments=[att["id"]])["json"]
check(ok["attachment_ids"] == [att["id"]], "empty text with attachment")
download = client.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
check(download["bytes"] == SAMPLE, "member download mismatch")
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "attachments.json").write_text(
json.dumps(
{
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"oversize": too_big["status"],
"spoofed_mime": spoof["status"],
"corrupt": broken["status"],
"pixels": huge["status"],
"foreign_chat": linked["status"],
"outsider": stolen["status"],
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print("PASS: attachment validation and ACL")
if __name__ == "__main__":
run(main)