Files
mtusi2026lab4/student-tests/lab4.py
2026-11-13 20:27:25 +03:00

60 lines
3.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""Lab4 grade-4 checks for upload validation and attachment authorization."""
import hashlib
import os
import sys
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
args = parser.parse_args()
client = Client(args.base_url)
alice, bob, eve, chat = client.bootstrap()
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
# Correct content succeeds and is byte-for-byte downloadable by another member.
uploaded = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 201,
actor=alice, raw=fixture, headers={"Content-Type": "image/png"}, schema="Attachment")
attachment = uploaded["json"]
downloaded = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
check(downloaded["bytes"] == fixture, "downloaded object differs from upload")
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == attachment["sha256"], "checksum mismatch")
# Too large, corrupt image, and mismatched MIME are controlled client errors.
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=large.png", 413,
actor=alice, raw=b"\x89PNG\r\n\x1a\n" + b"x" * (10 * 1024 * 1024),
headers={"Content-Type": "image/png"})
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=bad.png", 415,
actor=alice, raw=b"not-an-image", headers={"Content-Type": "image/png"})
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=spoof.png", 415,
actor=alice, raw=fixture, headers={"Content-Type": "image/jpeg"})
# Outsider cannot read metadata or bytes; a random ID is also hidden as 404.
client.call("GET", f"/api/v1/attachments/{attachment['id']}", 404, actor=eve)
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 404, actor=eve)
client.call("GET", f"/api/v1/attachments/{uuid.uuid4()}", 404, actor=alice)
# An attachment from another chat cannot be referenced by a message.
other_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Другой чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
client.call("POST", f"/api/v1/chats/{other_chat['id']}/messages", 404, actor=alice,
body={"text": "wrong chat", "attachment_ids": [attachment["id"]]},
headers={"Idempotency-Key": "wrong-chat-" + uuid.uuid4().hex})
print("PASS: attachment limits, MIME validation, authorization and chat binding")
if __name__ == "__main__":
try:
main()
except (Failure, AssertionError, OSError) as error:
print("FAIL:", error)
raise SystemExit(1)