Files
mtusi2026lab4-fork/student-tests/test_attachments.py
2026-11-06 13:57:29 +03:00

241 lines
11 KiB
Python

"""Вложения: настоящий MinIO, проверка файла, ACL и связь с сообщениями."""
import hashlib
from io import BytesIO
import struct
from urllib.parse import quote
import uuid
import zlib
from PIL import Image
import pytest
from conftest import assert_error, run_sql
MAX_BYTES = 10 * 1024 * 1024
def image_bytes(format="PNG"):
stream = BytesIO()
with Image.new("RGB", (32, 24), (35, 120, 205)) as image:
image.save(stream, format=format)
return stream.getvalue()
def upload(client, person, chat, data=None, filename="photo.png", content_type="image/png"):
path = "/api/v1/chats/" + chat["id"] + "/attachments"
return client.post(
path + "?filename=" + quote(filename, safe=""),
content=image_bytes() if data is None else data,
headers={**person.headers, "Content-Type": content_type},
)
def uploaded(client, person, chat):
reply = upload(client, person, chat)
assert reply.status_code == 201, reply.text
return reply.json()
def attachment_path(attachment):
return "/api/v1/attachments/" + attachment["id"]
def message_path(chat):
return "/api/v1/chats/" + chat["id"] + "/messages"
def png_chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
@pytest.mark.parametrize("format,mime,filename", [("PNG", "image/png", "снимок.png"), ("JPEG", "image/jpeg", "photo.jpeg")])
def test_original_metadata_and_bytes_for_another_member(client, alice, bob, chat, format, mime, filename):
data = image_bytes(format)
reply = upload(client, alice, chat, data, filename, mime)
assert reply.status_code == 201, reply.text
attachment = reply.json()
assert attachment["chat_id"] == chat["id"]
assert attachment["owner_id"] == alice.id
assert attachment["filename"] == filename
assert attachment["status"] == "ready"
assert attachment["variants"] == [] and attachment["error_code"] is None
assert attachment["content_type"] == mime
assert attachment["size_bytes"] == len(data)
assert attachment["sha256"] == hashlib.sha256(data).hexdigest()
assert attachment["updated_at"].endswith("Z")
assert attachment["created_at"].endswith("Z")
assert not {"object_key", "bucket", "url", "access_key", "secret_key"} & attachment.keys()
metadata = client.get(attachment_path(attachment), headers=bob.headers)
assert metadata.status_code == 200 and metadata.json() == attachment
for suffix in ("/content", "/content?variant=original"):
response = client.get(attachment_path(attachment) + suffix, headers=bob.headers, follow_redirects=False)
assert response.status_code == 200
assert response.content == data
assert response.headers["content-type"].split(";")[0] == mime
assert response.headers["X-Request-Id"] and response.headers["X-Instance-Id"]
assert "location" not in response.headers
def test_filename_is_not_an_object_identifier(client, alice, bob, chat):
first = upload(client, alice, chat, image_bytes("PNG"), filename="same.png")
second = upload(client, alice, chat, image_bytes("JPEG"), filename="same.png", content_type="image/jpeg")
assert first.status_code == second.status_code == 201
assert first.json()["id"] != second.json()["id"]
for reply, data in ((first, image_bytes("PNG")), (second, image_bytes("JPEG"))):
actual = client.get(attachment_path(reply.json()) + "/content", headers=bob.headers)
assert actual.status_code == 200 and actual.content == data
def test_outsider_cannot_upload_read_or_reference_an_attachment(client, alice, eve, chat):
attachment = uploaded(client, alice, chat)
assert_error(upload(client, eve, chat), 404, "not_found")
for suffix in ("", "/content"):
assert_error(client.get(attachment_path(attachment) + suffix, headers=eve.headers), 404, "not_found")
assert_error(client.get(attachment_path(attachment) + suffix), 401, "unauthorized")
assert_error(
client.post(message_path(chat), json={"text": "", "attachment_ids": [attachment["id"]]}, headers=eve.headers),
404, "not_found",
)
def test_attachment_cannot_move_between_chats_even_for_same_member(client, alice, bob, chat, make_chat):
attachment = uploaded(client, alice, chat)
other = make_chat(alice, bob)
assert_error(
client.post(message_path(other), json={"text": "file", "attachment_ids": [attachment["id"]]}, headers=alice.headers),
404, "not_found",
)
assert client.get(message_path(other), headers=bob.headers).json()["items"] == []
def test_unknown_attachment_is_404_without_creating_message(client, alice, chat):
absent = str(uuid.uuid4())
assert_error(client.get("/api/v1/attachments/" + absent, headers=alice.headers), 404, "not_found")
assert_error(
client.post(message_path(chat), json={"text": "", "attachment_ids": [absent]}, headers=alice.headers),
404, "not_found",
)
assert client.get(message_path(chat), headers=alice.headers).json()["items"] == []
@pytest.mark.parametrize("text", ["", " \t\n"])
def test_any_member_can_send_attachment_without_text(client, alice, bob, chat, text):
attachment = uploaded(client, alice, chat)
response = client.post(message_path(chat), json={"text": text, "attachment_ids": [attachment["id"]]}, headers=bob.headers)
assert response.status_code == 201, response.text
message = response.json()
assert message["text"] == text and message["attachment_ids"] == [attachment["id"]]
assert message["sender_id"] == bob.id
assert client.get(message_path(chat), headers=alice.headers).json()["items"] == [message]
def test_replay_compares_attachments_and_preserves_order(client, alice, chat):
first = uploaded(client, alice, chat)
second = uploaded(client, alice, chat)
ids = [second["id"], first["id"]]
body = {"text": "files", "attachment_ids": ids}
headers = alice.headers
original = client.post(message_path(chat), json=body, headers=headers)
assert original.status_code == 201, original.text
replay = client.post(message_path(chat), json={"attachment_ids": ids, "text": "files"}, headers=headers)
assert replay.status_code == 201 and replay.json() == original.json()
assert replay.json()["attachment_ids"] == ids
assert_error(
client.post(message_path(chat), json={"text": "files", "attachment_ids": [first["id"]]}, headers=headers),
409, "conflict",
)
history = client.get(message_path(chat), headers=alice.headers).json()["items"]
assert history == [original.json()]
@pytest.mark.parametrize("values", [None, "not-a-list", ["bad-uuid"], [42]])
def test_attachment_list_has_strict_types(client, alice, chat, values):
assert_error(
client.post(message_path(chat), json={"text": "message", "attachment_ids": values}, headers=alice.headers),
400, "invalid_request",
)
def test_duplicate_and_excessive_attachment_ids_are_400(client, alice, chat):
attachment = uploaded(client, alice, chat)
for ids in ([attachment["id"], attachment["id"]], [str(uuid.uuid4()) for _ in range(11)]):
assert_error(
client.post(message_path(chat), json={"text": "message", "attachment_ids": ids}, headers=alice.headers),
400, "invalid_request",
)
@pytest.mark.parametrize("filename", ["", "a" * 256, "../photo.png", "folder/photo.png", "folder\\photo.png", "bad\x00.png", "bad\r\n.png", "bad\t.png", "bad\x7f.png", "bad\x85.png"])
def test_dangerous_or_invalid_filename_is_400(client, alice, chat, filename):
assert_error(upload(client, alice, chat, filename=filename), 400, "invalid_request")
def test_missing_filename_is_400(client, alice, chat):
response = client.post(
"/api/v1/chats/" + chat["id"] + "/attachments",
content=image_bytes(), headers={**alice.headers, "Content-Type": "image/png"},
)
assert_error(response, 400, "invalid_request")
@pytest.mark.parametrize("data,mime", [(b"", "image/png"), (b"not an image", "image/png"), (b"GIF89a\x01\x00\x01\x00", "image/png"), (b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/svg+xml")])
def test_invalid_image_is_415_not_500(client, alice, chat, data, mime):
assert_error(upload(client, alice, chat, data, content_type=mime), 415, "unsupported_media_type")
@pytest.mark.parametrize("format,mime", [("PNG", "image/jpeg"), ("JPEG", "image/png"), ("PNG", "application/octet-stream")])
def test_declared_mime_must_match_real_image(client, alice, chat, format, mime):
assert_error(upload(client, alice, chat, image_bytes(format), content_type=mime), 415, "unsupported_media_type")
@pytest.mark.parametrize("format,mime", [("PNG", "image/png"), ("JPEG", "image/jpeg")])
def test_truncated_image_is_rejected(client, alice, chat, format, mime):
data = image_bytes(format)
assert_error(upload(client, alice, chat, data[:len(data) * 2 // 3], content_type=mime), 415, "unsupported_media_type")
def test_png_with_corrupted_pixel_stream_is_rejected(client, alice, chat):
original = image_bytes()
start = original.index(b"IDAT")
length = struct.unpack(">I", original[start - 4:start])[0]
# Valid CRC with an invalid compressed stream: checking the signature/CRC alone is insufficient.
corrupt = original[:start - 4] + png_chunk(b"IDAT", b"x" * length) + original[start + 4 + length + 4:]
assert_error(upload(client, alice, chat, corrupt), 415, "unsupported_media_type")
def test_byte_limit_with_content_length(client, alice, chat):
assert_error(upload(client, alice, chat, image_bytes() + b"x" * MAX_BYTES), 413, "payload_too_large")
def test_byte_limit_without_content_length(client, alice, chat):
def chunks():
for _ in range(161):
yield b"x" * (64 * 1024)
assert_error(upload(client, alice, chat, chunks()), 413, "payload_too_large")
def test_image_exactly_at_byte_limit_is_accepted(client, alice, bob, chat):
original = image_bytes()
padding = b"\0" * (MAX_BYTES - len(original) - 12)
data = original[:-12] + png_chunk(b"npAD", padding) + original[-12:]
assert len(data) == MAX_BYTES
reply = upload(client, alice, chat, data)
assert reply.status_code == 201, reply.text
response = client.get(attachment_path(reply.json()) + "/content", headers=bob.headers)
assert response.status_code == 200
assert hashlib.sha256(response.content).digest() == hashlib.sha256(data).digest()
def test_pixel_limit_is_checked_before_decoding(client, alice, chat):
header = struct.pack(">IIBBBBB", 8000, 5001, 8, 2, 0, 0, 0)
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", zlib.compress(b"")) + png_chunk(b"IEND", b"")
assert_error(upload(client, alice, chat, data), 413, "payload_too_large")
assert not run_sql("SELECT id FROM attachments WHERE chat_id=$1", uuid.UUID(chat["id"]))
def test_missing_variant_is_404(client, alice, chat):
attachment = uploaded(client, alice, chat)
assert_error(client.get(attachment_path(attachment) + "/content?variant=thumbnail", headers=alice.headers), 404, "not_found")