feat: add image attachments to messages

- upload, metadata and download endpoints for PNG/JPEG attachments:
  limits before reading and decompression, type by content,
  structural integrity check without decoding pixels, safe filename
- write order: pending row with object key -> PUT to S3 -> ready;
  per-step DB sessions so no pool connection is held during transfers
- attachment_ids in messages (validation, idempotency hash, history);
  whitespace-only text allowed with an attachment (teacher, 2026-10-20)
- migration: attachments and message_attachments tables, text length
  CHECK relaxed with NOT VALID
- student tests, fault checks and driver commands for attachments;
  rollout profile starts from e1161f7 and checks the commit first
- sync attachments deltas into main specs; rules, AGENTS.md, PLAN.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 01:08:56 +03:00
co-authored by Claude Opus 5.5
parent 73779f7acd
commit 116d8d3bf0
72 changed files with 5546 additions and 247 deletions
+147
View File
@@ -1,15 +1,18 @@
"""Обязательные сценарии уровня «4» (README.md, рубрика)."""
import uuid
from collections.abc import Iterator
from typing import Any
import pytest
import images
from api_client import API, Actor, Api, key_headers, order_key, registration
from contract import (
BASIC_CHALLENGE,
BEARER_CHALLENGE,
assert_error,
assert_errors,
assert_unauthorized,
)
@@ -134,3 +137,147 @@ def test_history_walk_across_pages(
items = [item for page in pages for item in page["items"]]
assert len({item["id"] for item in items}) == len(sent)
assert items == sorted(sent, key=order_key)
# --- лаба 4: негативные тесты вложений (спек student-tests) -------------
def _chunks(data: bytes, size: int = 1024 * 1024) -> Iterator[bytes]:
for offset in range(0, len(data), size):
yield data[offset : offset + size]
@pytest.mark.spec("attachments", "Заявленный размер больше лимита")
@pytest.mark.spec("attachments", "Большое тело без Content-Length")
def test_rubric_too_big_file(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Слишком большой файл в рубрике»: больше
10 MiB с `Content-Length` и частями — 413 в формате контракта."""
data = images.png_of_size(images.MAX_BYTES + 1024 * 1024)
assert_errors(
{
"content-length": api.post_attachment(alice, chat["id"], data),
"chunked": api.post_attachment(alice, chat["id"], _chunks(data)),
},
413,
)
@pytest.mark.spec("attachments", "Обрезанный файл")
@pytest.mark.spec("attachments", "Испорченные данные PNG")
def test_rubric_damaged_image(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Повреждённое изображение в рубрике»:
обрезанные PNG и JPEG и PNG с изменённым байтом данных — 415."""
assert_errors(
{
"png cut": api.post_attachment(
alice,
chat["id"],
images.truncated(images.sample_png()),
),
"jpeg cut": api.post_attachment(
alice,
chat["id"],
images.truncated(images.jpeg()),
content_type="image/jpeg",
),
"png byte": api.post_attachment(
alice,
chat["id"],
images.png_idat_byte_changed(),
),
},
415,
)
@pytest.mark.spec("attachments", "Подмена MIME")
@pytest.mark.spec("attachments", "Не изображение")
def test_rubric_mime_spoofing(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Подмена MIME в рубрике»: JPEG как PNG и
текст как JPEG — 415."""
assert_errors(
{
"jpeg as png": api.post_attachment(
alice,
chat["id"],
images.jpeg(),
content_type="image/png",
),
"text as jpeg": api.post_attachment(
alice,
chat["id"],
b"plain text, not an image",
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("messages", "Чужое вложение")
@pytest.mark.spec("messages", "Неизвестное вложение")
@pytest.mark.spec("attachments", "Посторонний и неизвестный id")
def test_rubric_foreign_attachment_id(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Чужое attachment_id в рубрике»: сообщение с
вложением чужого чата и с неизвестным id, чтение постороннего — 404."""
eve_chat = api.create_chat(eve, title="Ева")
eve_attachment = api.upload(eve, eve_chat["id"], images.sample_png())
alice_attachment = api.upload(alice, chat["id"], images.sample_png())
assert_errors(
{
"foreign in message": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [eve_attachment["id"]]},
),
"unknown in message": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [str(uuid.uuid4())]},
),
"outsider meta": api.attachment_meta(eve, alice_attachment["id"]),
"outsider content": api.attachment_content(
eve,
alice_attachment["id"],
),
},
404,
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Вложение другого чата")
def test_rubric_attachment_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Вложение другого чата в рубрике»: участник
двух чатов шлёт в один вложение другого — 404, в истории пусто."""
other = api.create_chat(alice, bob, title="Второй чат")
attachment = api.upload(alice, other["id"], images.sample_png())
resp = api.post_message(
alice,
chat["id"],
json={"text": "", "attachment_ids": [attachment["id"]]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []