Files
mtusi2026lab4/tests/attachment_checks.py
T
2026-11-22 17:26:57 +03:00

66 lines
2.1 KiB
Python

#!/usr/bin/env python3
import io
import uuid
from PIL import Image
from client import Client, arguments, check, run
def png_bytes(size=(32, 32), color=(40, 120, 200, 255)):
out = io.BytesIO()
Image.new("RGBA", size, color).save(out, format="PNG")
return out.getvalue()
def main():
args = arguments("Level-4 attachment negative checks")
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
oversize = b"x" * (10 * 1024 * 1024 + 1)
c.call(
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=oversize.png",
413, actor=alice, raw=oversize,
headers={"Content-Type": "image/png"},
)
c.call(
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=broken.png",
415, actor=alice, raw=b"not an image",
headers={"Content-Type": "image/png"},
)
jpeg = io.BytesIO()
Image.new("RGB", (32, 32), (200, 100, 30)).save(jpeg, format="JPEG")
c.call(
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=spoof.png",
415, actor=alice, raw=jpeg.getvalue(),
headers={"Content-Type": "image/png"},
)
c.call(
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=bad/name.png",
400, actor=alice, raw=png_bytes(),
headers={"Content-Type": "image/png"},
)
attachment, content = c.attachment(alice, chat)
c.call("GET", f"/api/v1/attachments/{attachment['id']}", 404, actor=eve)
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 404, actor=eve)
other_chat = c.call(
"POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Второй чат", "member_ids": [alice["id"], eve["id"]]},
schema="Chat",
)["json"]
c.call(
"POST", f"/api/v1/chats/{other_chat['id']}/messages",
404, actor=alice,
body={"text": "", "attachment_ids": [attachment["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
print("PASS: oversized, corrupt, MIME-spoof, dangerous filename, foreign attachment and cross-chat checks")
if __name__ == "__main__":
run(main)