Files
2026-11-14 15:09:57 +03:00

149 lines
6.4 KiB
Python

import base64
import hashlib
import time
import uuid
import httpx
import pytest
BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=15.0)
def create_user_and_auth(client, username):
pw = "super_password_12345"
client.post("/users", json={"username": username, "display_name": "Test", "password": pw})
b64 = base64.b64encode(f"{username}:{pw}".encode()).decode()
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
return res.json()["token"], res.json()["user"]["id"]
TINY_PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082")
def test_upload_and_download_integrity():
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = create_user_and_auth(client, f"u_att_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat = client.post("/chats", json={"title": "Att Chat", "member_ids": [uid]}, headers=h).json()
cid = chat["id"]
upload_res = client.post(
f"/chats/{cid}/attachments?filename=tiny.png",
content=TINY_PNG,
headers={**h, "Content-Type": "image/png"}
)
assert upload_res.status_code == 201
att_data = upload_res.json()
assert att_data["status"] == "ready"
assert att_data["sha256"] == hashlib.sha256(TINY_PNG).hexdigest().lower()
att_id = att_data["id"]
dl_res = client.get(f"/attachments/{att_id}/content", headers=h)
assert dl_res.status_code == 200
assert dl_res.headers.get("Content-Type") == "image/png"
assert dl_res.content == TINY_PNG
def test_oversized_payload_rejected():
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = create_user_and_auth(client, f"u_over_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat = client.post("/chats", json={"title": "Over Chat", "member_ids": [uid]}, headers=h).json()
huge_payload = b"\x89PNG\r\n\x1a\n" + b"0" * (10485760 + 1024)
res = client.post(
f"/chats/{chat['id']}/attachments?filename=big.png",
content=huge_payload,
headers={**h, "Content-Type": "image/png"}
)
assert res.status_code == 413
assert res.json()["error"]["code"] == "payload_too_large"
def test_mime_mismatch_and_corrupt_image_rejected():
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = create_user_and_auth(client, f"u_mime_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat = client.post("/chats", json={"title": "Mime Chat", "member_ids": [uid]}, headers=h).json()
# 1. Подмена MIME (текст под видом PNG) -> 415
res1 = client.post(
f"/chats/{chat['id']}/attachments?filename=fake.png",
content=b"THIS IS NOT A PNG FILE",
headers={**h, "Content-Type": "image/png"}
)
assert res1.status_code == 415
# 2. Повреждённое изображение (валидные магические байты PNG, но битое тело) -> 415, не 500!
res2 = client.post(
f"/chats/{chat['id']}/attachments?filename=corrupt.png",
content=b"\x89PNG\r\n\x1a\ncorrupted_binary_data_inside",
headers={**h, "Content-Type": "image/png"}
)
assert res2.status_code == 415
def test_dangerous_filename_rejected():
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = create_user_and_auth(client, f"u_fname_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat = client.post("/chats", json={"title": "Fname Chat", "member_ids": [uid]}, headers=h).json()
res = client.post(
f"/chats/{chat['id']}/attachments?filename=../../etc/passwd.png",
content=TINY_PNG,
headers={**h, "Content-Type": "image/png"}
)
assert res.status_code == 400
def test_stranger_cannot_access_or_download_attachment():
with get_client() as client:
ts = int(time.time() * 1000)
token1, uid1 = create_user_and_auth(client, f"u_owner_{ts}")
token2, uid2 = create_user_and_auth(client, f"u_stranger_{ts}")
chat = client.post("/chats", json={"title": "Priv Chat", "member_ids": [uid1]}, headers={"Authorization": f"Bearer {token1}"}).json()
att = client.post(
f"/chats/{chat['id']}/attachments?filename=secret.png",
content=TINY_PNG,
headers={"Authorization": f"Bearer {token1}", "Content-Type": "image/png"}
).json()
r_meta = client.get(f"/attachments/{att['id']}", headers={"Authorization": f"Bearer {token2}"})
assert r_meta.status_code == 404
r_bytes = client.get(f"/attachments/{att['id']}/content", headers={"Authorization": f"Bearer {token2}"})
assert r_bytes.status_code == 404
def test_cross_chat_and_unknown_attachment_rejected():
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = create_user_and_auth(client, f"u_cross_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat1 = client.post("/chats", json={"title": "Chat 1", "member_ids": [uid]}, headers=h).json()
chat2 = client.post("/chats", json={"title": "Chat 2", "member_ids": [uid]}, headers=h).json()
# Загружаем файл в Чат 1
att = client.post(
f"/chats/{chat1['id']}/attachments?filename=c1.png",
content=TINY_PNG,
headers={**h, "Content-Type": "image/png"}
).json()
# 1. Пытаемся прикрепить файл Чата 1 к сообщению в Чате 2 -> 404
res1 = client.post(
f"/chats/{chat2['id']}/messages",
json={"text": "cross chat", "attachment_ids": [att["id"]]},
headers={**h, "Idempotency-Key": str(uuid.uuid4())}
)
assert res1.status_code == 404
# 2. Пытаемся прикрепить несуществующий attachment_id -> 404
res2 = client.post(
f"/chats/{chat2['id']}/messages",
json={"text": "unknown att", "attachment_ids": [str(uuid.uuid4())]},
headers={**h, "Idempotency-Key": str(uuid.uuid4())}
)
assert res2.status_code == 404