Files
mtusi2026lab4/student-tests/test_attachments.py
T

67 lines
3.1 KiB
Python

import base64
import io
import json
import urllib.request
import urllib.error
import uuid
import pytest
BASE = "http://127.0.0.1:8080"
PASSWORD = "Example-only-not-a-real-secret-123"
def call(method, path, body=None, token=None, raw_data=None, content_type=None):
h = {"Accept": "application/json"}
if token: h["Authorization"] = f"Bearer {token}"
data = None
if raw_data is not None:
data = raw_data
if content_type: h["Content-Type"] = content_type
elif body is not None:
data = json.dumps(body).encode("utf-8")
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
with urllib.request.urlopen(req, timeout=10) as r:
payload = r.read()
return r.status, (json.loads(payload) if payload and r.headers.get_content_type()=="application/json" else payload)
except urllib.error.HTTPError as e:
payload = e.read()
try: return e.code, json.loads(payload)
except: return e.code, payload
def setup():
name = f"test_{uuid.uuid4().hex[:6]}"
s, u = call("POST", "/api/v1/users", {"username": name, "display_name": name, "password": PASSWORD})
cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
req = urllib.request.Request(BASE + "/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}, method="POST")
with urllib.request.urlopen(req) as r:
tok = json.loads(r.read())["token"]
s, chat = call("POST", "/api/v1/chats", {"title": "test", "member_ids": [u["id"]]}, token=tok)
return u, tok, chat["id"]
def test_large_file():
u, tok, cid = setup()
big_data = b"\x89PNG\r\n\x1a\n" + b"0" * (11 * 1024 * 1024) # 11 MB
s, _ = call("POST", f"/api/v1/chats/{cid}/attachments?filename=big.png", token=tok, raw_data=big_data, content_type="image/png")
assert s == 413
def test_corrupted_image():
u, tok, cid = setup()
s, _ = call("POST", f"/api/v1/chats/{cid}/attachments?filename=bad.png", token=tok, raw_data=b"not an image", content_type="image/png")
assert s == 415
def test_mime_spoofing():
u, tok, cid = setup()
# отправляем текст, но притворяемся картинкой
s, _ = call("POST", f"/api/v1/chats/{cid}/attachments?filename=fake.png", token=tok, raw_data=b"<html>hack</html>", content_type="image/png")
assert s == 415
def test_foreign_attachment():
# создаем двух пользователей
u1, tok1, cid1 = setup()
u2, tok2, cid2 = setup()
# u1 загружает файл
s, att = call("POST", f"/api/v1/chats/{cid1}/attachments?filename=test.png", token=tok1, raw_data=b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82", content_type="image/png")
# u2 пытается прикрепить этот файл в свой чат
s, _ = call("POST", f"/api/v1/chats/{cid2}/messages", {"text": "hi", "attachment_ids": [att["id"]]}, token=tok2)
assert s == 404