"""Negative attachment scenarios against a running stand (lab4). Run: python student-tests/test_api_negative.py --base-url http://localhost:8081 Creates only synthetic users, chats and files. """ import os import sys import uuid from io import BytesIO from pathlib import Path from urllib.parse import quote from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, check # noqa: E402 MAX_UPLOAD_BYTES = 10_485_760 MAX_PIXELS = 40_000_000 def upload(client, actor, chat, content, content_type, filename="photo.png", expected=201): path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename, safe="") return client.call( "POST", path, expected, actor=actor, raw=content, headers={"Content-Type": content_type}, schema="Attachment" if expected == 201 else None, ) def base_url(): for index, argument in enumerate(sys.argv): if argument == "--base-url" and index + 1 < len(sys.argv): return sys.argv[index + 1] if argument.startswith("--base-url="): return argument.split("=", 1)[1] return os.environ.get("BASE_URL", "http://127.0.0.1:8081") def main(): base = base_url() client = Client(base) alice, bob, eve, chat = client.bootstrap() other = client.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "Второй чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat", )["json"] sample = (ROOT / "tests/fixtures/sample.png").read_bytes() failures = [] def scenario(name, function): try: function() print("PASS:", name) except AssertionError as error: failures.append(name + ": " + str(error)) print("FAIL:", name, "-", error) def too_large(): payload = b"\x89PNG\r\n\x1a\n" + b"\x00" * (MAX_UPLOAD_BYTES + 1 - 8) response = upload(client, alice, chat, payload, "image/png", expected=413) check(response["json"]["error"]["code"] == "payload_too_large", "wrong error code") def corrupt(): upload(client, alice, chat, b"\x89PNG\r\n\x1a\n" + b"broken" * 500, "image/png", expected=415) def mime_mismatch(): upload(client, alice, chat, sample, "image/jpeg", expected=415) def unsupported_type(): upload(client, alice, chat, sample, "image/gif", expected=415) def dangerous_names(): for bad in ("a/b.png", "a\b.png", "a\x00b.png", "a\nb.png"): response = upload(client, alice, chat, sample, "image/png", filename=bad, expected=400) check(response["json"]["error"]["code"] == "invalid_request", "wrong error code") def pixel_limit(): buffer = BytesIO() side_width, side_height = 7000, 6000 # 42 Mpx > configured 40 Mpx limit Image.new("L", (side_width, side_height), 128).save(buffer, "PNG", optimize=True) payload = buffer.getvalue() check(len(payload) <= MAX_UPLOAD_BYTES, "fixture exceeds byte limit, adjust the test") check(side_width * side_height > MAX_PIXELS, "fixture must exceed the pixel limit") upload(client, alice, chat, payload, "image/png", filename="huge.png", expected=413) def cross_chat_attachment(): attachment = upload(client, alice, chat, sample, "image/png")["json"] response = client.call( "POST", "/api/v1/chats/" + other["id"] + "/messages", 404, actor=alice, body={"text": "", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) check(response["json"]["error"]["code"] == "not_found", "wrong error code") page = client.call( "GET", "/api/v1/chats/" + other["id"] + "/messages?limit=100", actor=alice, schema="MessagePage" )["json"] check( all(attachment["id"] not in item["attachment_ids"] for item in page["items"]), "rejected attachment leaked into a message", ) def unknown_attachment(): client.call( "POST", "/api/v1/chats/" + chat["id"] + "/messages", 404, actor=alice, body={"text": "нет такого файла", "attachment_ids": [str(uuid.uuid4())]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) def outsider_access(): attachment = upload(client, alice, chat, sample, "image/png")["json"] for suffix in ("", "/content"): client.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=eve) def member_access_and_checksum(): import hashlib attachment = upload(client, alice, chat, sample, "image/png")["json"] check(attachment["sha256"] == hashlib.sha256(sample).hexdigest(), "checksum mismatch") content = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob) check(content["bytes"] == sample, "download differs from upload") check(content["headers"].get_content_type() == "image/png", "content type mismatch") def real_jpeg_roundtrip(): import hashlib buffer = BytesIO() Image.new("RGB", (640, 480), "navy").save(buffer, "JPEG", quality=90) payload = buffer.getvalue() attachment = upload(client, alice, chat, payload, "image/jpeg", filename="photo.jpg")["json"] check(attachment["status"] == "ready", "JPEG was not accepted") check(attachment["content_type"] == "image/jpeg", "JPEG content type mismatch") check(attachment["size_bytes"] == len(payload), "JPEG size mismatch") check(attachment["sha256"] == hashlib.sha256(payload).hexdigest(), "JPEG checksum mismatch") content = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob) check(content["bytes"] == payload, "JPEG download differs from upload") check(content["headers"].get_content_type() == "image/jpeg", "JPEG download type mismatch") def attachment_ids_survive_history(): attachment = upload(client, alice, chat, sample, "image/png")["json"] created = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/messages", 201, actor=alice, body={"text": "", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, schema="Message", )["json"] page = client.call( "GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=bob, schema="MessagePage" )["json"] found = [item for item in page["items"] if item["id"] == created["id"]] check(len(found) == 1, "message with attachment is missing from history") check(found[0]["attachment_ids"] == [attachment["id"]], "history lost attachment_ids") check(found[0] == created, "history item differs from the POST response") scenario("oversized upload returns 413 before decoding", too_large) scenario("corrupt image returns 415", corrupt) scenario("MIME mismatch returns 415", mime_mismatch) scenario("unsupported declared type returns 415", unsupported_type) scenario("path-like and control-character filenames return 400", dangerous_names) scenario("pixel limit returns 413", pixel_limit) scenario("attachment from another chat cannot be attached", cross_chat_attachment) scenario("unknown attachment id returns 404", unknown_attachment) scenario("outsider cannot read metadata or bytes", outsider_access) scenario("chat member downloads identical bytes", member_access_and_checksum) scenario("real JPEG upload roundtrip", real_jpeg_roundtrip) scenario("attachment_ids survive message history", attachment_ids_survive_history) if failures: print("\nFAILED:", len(failures)) for failure in failures: print(" -", failure) raise SystemExit(1) print("\nPASS: all attachment scenarios (limits, MIME, access, roundtrip, history)") if __name__ == "__main__": main()