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
+45 -3
View File
@@ -23,8 +23,10 @@ UUID_RE = re.compile(
)
# RFC 3339 в UTC: шесть знаков долей секунды и суффикс Z
CREATED_AT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$")
ID_KEYS = frozenset({"id", "chat_id", "sender_id"})
TIME_KEYS = frozenset({"created_at", "expires_at"})
ID_KEYS = frozenset({"id", "chat_id", "sender_id", "owner_id"})
# списки UUID в ответах: участники чата и с лабы 4 вложения сообщения
ID_LIST_KEYS = frozenset({"member_ids", "attachment_ids"})
TIME_KEYS = frozenset({"created_at", "expires_at", "updated_at"})
# WWW-Authenticate у 401 (contracts/README.md): вход и остальные запросы
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
@@ -40,6 +42,8 @@ ERROR_CODES = {
404: "not_found",
405: "invalid_request",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
500: "internal_error",
503: "unavailable",
}
@@ -86,7 +90,7 @@ def check_formats(value: Any, path: str = "") -> None:
where = f"{path}/{key}"
if key in ID_KEYS:
assert_uuid(item, where)
elif key == "member_ids":
elif key in ID_LIST_KEYS:
for number, member in enumerate(item):
assert_uuid(member, f"{where}/{number}")
elif key in TIME_KEYS:
@@ -173,6 +177,44 @@ def assert_unauthorized(
return error
def assert_no_storage_traces(resp: httpx.Response) -> None:
"""Ни перенаправления, ни заголовков S3 в ответе API."""
assert "location" not in resp.headers, describe(resp, "has Location")
amz = [name for name in resp.headers if name.lower().startswith("x-amz-")]
assert not amz, describe(resp, f"S3 headers {amz}")
def assert_content(
resp: httpx.Response,
data: bytes,
content_type: str,
) -> None:
"""Байты оригинала: 200, тип без параметров, длина, `nosniff`, те же
байты, без перенаправления и следов S3."""
assert resp.status_code == 200, describe(resp, "expected 200")
assert resp.headers.get("X-Request-Id", "").strip(), describe(
resp,
"no X-Request-Id",
)
assert_instance_id(resp)
assert resp.headers.get("Content-Type") == content_type, describe(
resp,
f"Content-Type is not {content_type}",
)
assert resp.headers.get("Content-Length") == str(len(data)), describe(
resp,
f"Content-Length is not {len(data)}",
)
assert resp.headers.get("X-Content-Type-Options") == "nosniff", describe(
resp,
"no X-Content-Type-Options: nosniff",
)
assert_no_storage_traces(resp)
assert resp.content == data, (
f"downloaded {len(resp.content)} bytes differ from {len(data)} sent"
)
def assert_instance_id(resp: httpx.Response) -> str:
"""Непустой `X-Instance-Id` допустимого формата; возвращает значение."""
instance_id = resp.headers.get("X-Instance-Id", "")