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
+94 -3
View File
@@ -2,6 +2,7 @@
import base64
import dataclasses
import hashlib
import secrets
import uuid
from collections.abc import Callable, Sequence
@@ -231,15 +232,105 @@ class Api:
text: str,
*,
key: str | None = None,
attachment_ids: Sequence[str] | None = None,
) -> dict[str, Any]:
"""Успешная отправка: 201 и `Message`; без `key` — новый ключ."""
"""Успешная отправка: 201 и `Message`; без `key` — новый ключ.
`attachment_ids=None` — поля в теле нет.
"""
body: dict[str, Any] = {"text": text}
if attachment_ids is not None:
body["attachment_ids"] = list(attachment_ids)
resp = self.post_message(
actor,
chat_id,
key=new_key() if key is None else key,
json={"text": text},
json=body,
)
message = assert_ok(resp, 201, "Message")
if attachment_ids is not None:
assert message["attachment_ids"] == [
item.lower() for item in attachment_ids
], "attachment_ids differ from sent"
return message
def post_attachment(
self,
actor: Actor | None,
chat_id: str,
data: Any,
*,
content_type: str | None = "image/png",
filename: str | None = "image.png",
headers: dict[str, str] | None = None,
) -> httpx.Response:
"""Загрузка как есть: сырые байты (или итератор — частями, без
`Content-Length`); `None` — без заголовка или параметра."""
merged = dict(headers or {})
if content_type is not None:
merged["Content-Type"] = content_type
params = {} if filename is None else {"filename": filename}
return self.request(
"POST",
f"{API}/chats/{chat_id}/attachments",
actor=actor,
headers=merged,
params=params,
content=data,
)
def upload(
self,
actor: Actor,
chat_id: str,
data: bytes,
*,
content_type: str = "image/png",
filename: str = "image.png",
) -> dict[str, Any]:
"""Успешная загрузка: 201 и `Attachment` с размером и SHA-256."""
resp = self.post_attachment(
actor,
chat_id,
data,
content_type=content_type,
filename=filename,
)
attachment = assert_ok(resp, 201, "Attachment")
assert attachment["size_bytes"] == len(data), "size_bytes differs"
assert attachment["sha256"] == hashlib.sha256(data).hexdigest(), (
"sha256 differs"
)
assert attachment["chat_id"] == chat_id.lower(), "chat_id differs"
assert attachment["owner_id"] == actor.id, "owner_id differs"
assert attachment["filename"] == filename, "filename changed"
return attachment
def attachment_meta(
self,
actor: Actor | None,
attachment_id: str,
) -> httpx.Response:
return self.request(
"GET",
f"{API}/attachments/{attachment_id}",
actor=actor,
)
def attachment_content(
self,
actor: Actor | None,
attachment_id: str,
*,
variant: str | None = None,
) -> httpx.Response:
params = {} if variant is None else {"variant": variant}
return self.request(
"GET",
f"{API}/attachments/{attachment_id}/content",
actor=actor,
params=params,
)
return assert_ok(resp, 201, "Message")
def messages_page(
self,
+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", "")
+57 -2
View File
@@ -28,15 +28,25 @@
db-sessions pg_stat_database.sessions базы стенда:
сколько сессий PostgreSQL приняла за всё
время (учитывает и сессию самого вызова)
count-attachments вложения в базе стенда по статусам:
`pending=N ready=M`
count-objects число вложений с объектами в bucket стенда:
каталоги `<id>` под `<база>/attachments/`
(filer через `weed shell` на loopback
контейнера s3)
Пароли не печатает: valkey-cli берёт пароль из VALKEYCLI_AUTH
контейнера, psql работает от POSTGRES_USER контейнера. Только stdlib.
Bucket и имя базы для count-objects — FAULT_S3_BUCKET и FAULT_DATABASE,
их задаёт run_failures.py. Пароли и ключи не печатает: valkey-cli берёт
пароль из VALKEYCLI_AUTH контейнера, psql работает от POSTGRES_USER
контейнера, weed shell — с ключом подписи из окружения контейнера s3.
Только stdlib.
"""
from __future__ import annotations
import json
import os
import re
import subprocess
import sys
import time
@@ -168,6 +178,20 @@ for d in /proc/[0-9]*; do
esac
done
"""
COUNT_ATTACHMENTS_SQL = """\
SELECT 'pending=' || count(*) FILTER (WHERE status = 'pending')
|| ' ready=' || count(*) FILTER (WHERE status = 'ready')
FROM attachments;
"""
# как S3_BUCKET_NAME_PATTERN в src/utils/constants.py; имя базы — как в
# run_isolated.py: путь filer собирается только из проверенных имён
BUCKET_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
DB_NAME_RE = re.compile(r"^[a-z0-9_]+$")
# каталог вложения в filer — его id; копия ATTACHMENT_KEY_PREFIX
ATTACHMENT_DIR_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
)
ATTACHMENT_KEY_PREFIX = "attachments"
PROBE_SQL_SH = (
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq -c "SELECT 1"'
)
@@ -383,6 +407,33 @@ def clear_connections(project: str) -> str:
raise HookError(f"connections are not freed in {FILL_TIMEOUT_S}s")
def count_objects(project: str) -> str:
"""Каталоги вложений в bucket стенда: у каждого объекта `original`
свой каталог `<id>`. Нет префикса — 0 (fs.ls ничего не печатает)."""
bucket = os.environ.get("FAULT_S3_BUCKET", "")
database = os.environ.get("FAULT_DATABASE", "")
if not BUCKET_NAME_RE.fullmatch(bucket):
raise HookError(f"FAULT_S3_BUCKET is not a bucket name: {bucket!r}")
if not DB_NAME_RE.fullmatch(database):
raise HookError(f"FAULT_DATABASE is not a database name: {database!r}")
listing = compose(
project,
"exec",
"-T",
"s3",
"sh",
"-c",
"exec weed shell -master=127.0.0.1:9333 2>&1",
stdin=f"fs.ls /buckets/{bucket}/{database}/{ATTACHMENT_KEY_PREFIX}\n",
)
return str(
sum(
bool(ATTACHMENT_DIR_RE.fullmatch(line.strip()))
for line in listing.splitlines()
),
)
def run(project: str, action: str, args: list[str]) -> str:
"""Выполнить действие; синтаксис без match: hook запускают и 3.9."""
if action in ("stop", "pause") and len(args) == 1:
@@ -415,6 +466,10 @@ def run(project: str, action: str, args: list[str]) -> str:
return clear_connections(project)
if action == "db-sessions" and not args:
return psql(project, DB_SESSIONS_SQL)
if action == "count-attachments" and not args:
return psql(project, COUNT_ATTACHMENTS_SQL)
if action == "count-objects" and not args:
return count_objects(project)
raise HookError(f"unknown action or arguments: {action} {args}")
+227
View File
@@ -0,0 +1,227 @@
"""Изображения для тестов вложений: настоящие, повреждённые, огромные.
PNG собираются на stdlib — любые IHDR и IDAT, Adam7, точный размер файла
чанком-заполнителем `tEXt`, «бомба», порча CRC. JPEG — через Pillow
(dev-группа): прогрессивный, серый, CMYK, с EXIF, с подменой размеров в
SOF. Большие файлы и «бомбы» живут только в памяти теста и в git не
попадают (`tests/fixtures/README.md`).
"""
import functools
import io
import struct
import zlib
from pathlib import Path
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
SAMPLE_PNG_PATH = (
Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png"
)
# лимиты контракта лабы 4
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
_ADAM7 = (
(0, 0, 8, 8),
(4, 0, 8, 8),
(0, 4, 4, 8),
(2, 0, 4, 4),
(0, 2, 2, 4),
(1, 0, 2, 2),
(0, 1, 1, 2),
)
@functools.cache
def sample_png() -> bytes:
"""Публичный fixture `tests/fixtures/sample.png` (320 × 200)."""
return SAMPLE_PNG_PATH.read_bytes()
def chunk(kind: bytes, body: bytes) -> bytes:
"""Чанк PNG с верной CRC."""
crc = zlib.crc32(kind + body)
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", crc)
def _rows(
width: int,
height: int,
*,
bits_per_pixel: int,
interlace: bool,
) -> bytes:
"""Распакованные данные: строки с фильтром 0 и узором в пикселях."""
passes = _ADAM7 if interlace else ((0, 0, 1, 1),)
out = bytearray()
for x0, y0, dx, dy in passes:
pass_width = (width - x0 + dx - 1) // dx if width > x0 else 0
pass_height = (height - y0 + dy - 1) // dy if height > y0 else 0
if not pass_width or not pass_height:
continue
row_bytes = (pass_width * bits_per_pixel + 7) // 8
row = bytes((i * 7) % 256 for i in range(row_bytes))
out += (b"\x00" + row) * pass_height
return bytes(out)
def png(
width: int = 64,
height: int = 48,
*,
color: int = 2,
depth: int = 8,
interlace: bool = False,
idat: bytes | None = None,
) -> bytes:
"""Настоящий PNG: IHDR, PLTE для палитры, IDAT, IEND.
`idat` — готовый сжатый поток вместо строк по размерам (огромные
размеры в маленьком файле, «бомба»).
"""
ihdr = struct.pack(
">IIBBBBB",
width,
height,
depth,
color,
0,
0,
1 if interlace else 0,
)
if idat is None:
idat = zlib.compress(
_rows(
width,
height,
bits_per_pixel=depth * _CHANNELS[color],
interlace=interlace,
),
9,
)
palette = chunk(b"PLTE", bytes(range(48))) if color == 3 else b""
return (
PNG_SIGNATURE
+ chunk(b"IHDR", ihdr)
+ palette
+ chunk(b"IDAT", idat)
+ chunk(b"IEND", b"")
)
def png_of_size(size: int) -> bytes:
"""Настоящий PNG 64 × 48 ровно `size` байт: добор чанком `tEXt`."""
base = png()
filler = size - len(base) - 12
assert filler >= 2, f"size {size} is too small"
text = chunk(b"tEXt", b"k\x00" + b"x" * (filler - 2))
# tEXt — после IHDR (8 + 25 байт), до IDAT
data = base[:33] + text + base[33:]
assert len(data) == size
return data
def png_huge(width: int, height: int) -> bytes:
"""Несколько килобайт с огромными размерами в IHDR."""
return png(
width,
height,
color=0,
depth=1,
idat=zlib.compress(bytes(4096)),
)
def png_bomb(unpacked_mib: int = 200) -> bytes:
"""PNG 100 × 100, IDAT которого распаковывается в `unpacked_mib` MiB."""
compressor = zlib.compressobj(9)
block = bytes(1024 * 1024)
stream = b"".join(compressor.compress(block) for _ in range(unpacked_mib))
return png(100, 100, idat=stream + compressor.flush())
def flip_byte(data: bytes, offset: int) -> bytes:
damaged = bytearray(data)
damaged[offset] ^= 0x55
return bytes(damaged)
def png_idat_byte_changed(data: bytes | None = None) -> bytes:
"""Изменённый байт внутри первого IDAT (CRC чанка не сходится)."""
data = data or sample_png()
return flip_byte(data, data.index(b"IDAT") + 40)
def truncated(data: bytes, keep: float = 0.5) -> bytes:
return data[: int(len(data) * keep)]
def with_tail(data: bytes, tail: bytes = b"TAIL" * 64) -> bytes:
"""Байты после IEND или EOI."""
return data + tail
def _pillow_image(mode: str, size: tuple[int, int]) -> object:
from PIL import Image # noqa: PLC0415 — Pillow только для JPEG
width, height = size
image = Image.new("RGB", size)
image.putdata(
[
((x * 7) % 256, (y * 13) % 256, (x * y) % 256)
for y in range(height)
for x in range(width)
],
)
return image.convert(mode)
def jpeg(
mode: str = "RGB",
size: tuple[int, int] = (64, 48),
**save: object,
) -> bytes:
"""Настоящий JPEG через Pillow; `save` — параметры `Image.save`."""
from PIL import Image # noqa: PLC0415
buffer = io.BytesIO()
image = _pillow_image(mode, size)
if "exif" in save and save["exif"] is True:
exif = Image.Exif()
exif[0x010F] = "student-tests"
exif[0x0112] = 1
save["exif"] = exif
image.save(buffer, "JPEG", **save)
return buffer.getvalue()
def jpeg_huge(width: int, height: int) -> bytes:
"""Маленький JPEG с подменёнными размерами в SOF0."""
data = bytearray(jpeg())
sof = data.index(b"\xff\xc0")
data[sof + 5 : sof + 9] = struct.pack(">HH", height, width)
return bytes(data)
def png_variants() -> dict[str, bytes]:
"""Разновидности PNG спека: палитра, альфа, серый с альфой, 16 и 1
бит, Adam7."""
return {
"palette": png(color=3, depth=8),
"rgba": png(color=6),
"gray-alpha": png(color=4),
"rgb-16-bit": png(color=2, depth=16),
"gray-1-bit": png(color=0, depth=1),
"adam7": png(37, 29, interlace=True),
}
def jpeg_variants() -> dict[str, bytes]:
"""Разновидности JPEG спека: прогрессивный, серый, CMYK, с EXIF."""
return {
"progressive": jpeg(progressive=True),
"gray": jpeg("L"),
"cmyk": jpeg("CMYK"),
"exif": jpeg(exif=True),
}
+21 -6
View File
@@ -118,6 +118,17 @@ def app_port() -> str:
return "8080"
def storage_names(project: str) -> dict[str, str]:
"""Bucket и имя базы стенда — из окружения сервиса `api` в его
конфигурации compose: по ним hook считает объекты вложений."""
config = dc(project, "config", "--format", "json", quiet=True)
environment = json.loads(config.stdout)["services"]["api"]["environment"]
return {
"FAULT_S3_BUCKET": environment["S3__BUCKET"],
"FAULT_DATABASE": environment["DATABASE__NAME"],
}
def free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
@@ -276,12 +287,16 @@ def main() -> int:
base_url = start_api(project, default_name, free_port(), {})
tight_url = start_api(project, tight_name, free_port(), TIGHT_ENV)
say(f"ready: api={base_url} tight={tight_url}")
env = os.environ | {
"BASE_URL": base_url,
"FAULT_TIGHT_BASE_URL": tight_url,
"FAULT_HOOK": str(FAULT_HOOK),
"FAULT_PROJECT": project,
}
env = (
os.environ
| {
"BASE_URL": base_url,
"FAULT_TIGHT_BASE_URL": tight_url,
"FAULT_HOOK": str(FAULT_HOOK),
"FAULT_PROJECT": project,
}
| storage_names(project)
)
say("pytest -m fault")
results["fault"] = run(
"uv",
+21
View File
@@ -23,6 +23,7 @@ CAPABILITIES = (
"chat-cache",
"health",
"idempotency",
"attachments",
)
SCENARIO_RE = re.compile(r"^#### Scenario: (.+?)\s*$", re.MULTILINE)
@@ -105,6 +106,26 @@ EXCLUDED: dict[Scenario, Exclusion] = {
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh — "
"evidence/replicas/test-persistence.md",
),
("attachments", "Принявшая реплика остановлена"): Exclusion(
reason="нужно остановить реплику API, тесты стенд не трогают",
check="driver.py --port <LB> attachment-failover [--mode stop|kill] "
"скилла run-mtusi-messenger: загрузка через LB, scripts/stop-one.sh "
"реплики ответа, скачивание через другую с тем же SHA-256, 404 "
"постороннему — evidence/attachments/failover.md",
),
("attachments", "Байты не в БД и не на диске API"): Exclusion(
reason="нужен взгляд в схему PostgreSQL, bucket S3 и файловые "
"системы контейнеров, а тесты ходят по HTTP",
check="driver.py --port <LB> attachment-storage: колонки таблиц "
"вложений, вид object_key, объект в bucket, анонимный GET — 403, "
"docker diff реплик — evidence/attachments/storage.md",
),
("attachments", "Рестарт стенда"): Exclusion(
reason="нужен рестарт стенда, тесты сервер не трогают",
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh: с "
"LAB=4 проверка скачивает тот же оригинал прежним токеном — "
"evidence/replicas/test-persistence.md",
),
("users", "Хэш в БД"): Exclusion(
reason="нужен доступ к таблице users, а тесты ходят по HTTP",
check="driver.py --port <LB> auth-storage: префикс $argon2id$ и "
+69
View File
@@ -10,6 +10,7 @@ from typing import Any
import httpx
import pytest
import images
from api_client import (
API,
Actor,
@@ -19,6 +20,7 @@ from api_client import (
unique_username,
)
from contract import (
assert_content,
assert_created_at,
assert_error,
assert_errors,
@@ -389,3 +391,70 @@ def test_upper_case_uuid_in_path(
"MessagePage",
)
assert upper_page == lower_page == {"items": [sent], "next_cursor": None}
@pytest.mark.spec("api-conventions", "Лимит и тип вложения")
def test_attachment_limit_and_type_codes(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
over = images.png_of_size(images.MAX_BYTES + 1)
assert_error(api.post_attachment(alice, chat["id"], over), 413)
text = "не картинка".encode()
assert_error(api.post_attachment(alice, chat["id"], text), 415)
def attachment_requests(
api: Api,
actor: Actor,
attachment_id: str,
) -> dict[str, httpx.Response]:
quoted = urllib.parse.quote(attachment_id, safe="")
return {
"meta": api.attachment_meta(actor, quoted),
"content": api.attachment_content(actor, quoted),
}
@pytest.mark.spec("api-conventions", "Идентификаторы вложений в другой записи")
def test_attachment_ids_in_other_forms(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
responses = {
f"{name} / {form}": resp
for form, value in other_uuid_forms(attachment["id"]).items()
for name, resp in attachment_requests(api, alice, value).items()
}
responses |= {
f"attachment_ids / {form}": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [value]},
)
for form, value in other_uuid_forms(attachment["id"]).items()
}
assert_errors(responses, 400)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec(
"api-conventions",
"Идентификаторы вложений в верхнем регистре",
)
def test_attachment_ids_in_upper_case(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
upper = attachment["id"].upper()
meta = assert_ok(api.attachment_meta(alice, upper), 200, "Attachment")
assert meta == attachment
assert_content(api.attachment_content(alice, upper), data, "image/png")
message = api.send_message(alice, chat["id"], "x", attachment_ids=[upper])
assert message["attachment_ids"] == [attachment["id"]]
+657
View File
@@ -0,0 +1,657 @@
"""Спек `attachments`: загрузка, лимиты, тип и целостность, имя файла,
доступ, метаданные, скачивание, повтор, реплики.
Проверки отказов S3 — `test_failures.py`; сценарии, которым нужен стенд
(остановка реплики, рестарт, взгляд в БД и bucket), — исключения сверки
покрытия (`spec_coverage.py`).
"""
import hashlib
import urllib.parse
import uuid
from collections.abc import Iterator
from typing import Any
import pytest
import images
from api_client import Actor, Api
from contract import (
BEARER_CHALLENGE,
assert_content,
assert_error,
assert_errors,
assert_instance_id,
assert_no_storage_traces,
assert_ok,
assert_replicas,
assert_unauthorized,
)
# больше лимита в 3 раза: 30 MiB
BIG_BYTES = 30 * 1024 * 1024
# сколько скачиваний ждать ответа другой реплики (round-robin LB)
REPLICA_ATTEMPTS = 20
def chunks(data: bytes, size: int = 1024 * 1024) -> Iterator[bytes]:
"""Тело частями: httpx шлёт его без `Content-Length`."""
for offset in range(0, len(data), size):
yield data[offset : offset + size]
def big_body() -> bytes:
"""30 MiB, которые начинаются как PNG."""
return images.PNG_SIGNATURE + bytes(BIG_BYTES - len(images.PNG_SIGNATURE))
@pytest.mark.spec("attachments", "Загрузка PNG")
def test_upload_png(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data, filename="sample.png")
assert attachment["status"] == "ready"
assert attachment["variants"] == []
assert attachment["error_code"] is None
assert attachment["content_type"] == "image/png"
assert attachment["size_bytes"] == 111817
assert attachment["sha256"] == (
"99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75"
)
@pytest.mark.spec("attachments", "Загрузка JPEG")
def test_upload_jpeg(api: Api, bob: Actor, chat: dict[str, Any]) -> None:
data = images.jpeg(size=(320, 200))
attachment = api.upload(
bob,
chat["id"],
data,
content_type="image/jpeg",
filename="photo.jpg",
)
assert attachment["content_type"] == "image/jpeg"
@pytest.mark.spec("attachments", "Разновидности PNG и JPEG")
def test_image_kinds(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
kinds = [
("image/png", name, data)
for name, data in images.png_variants().items()
] + [
("image/jpeg", name, data)
for name, data in images.jpeg_variants().items()
]
for content_type, name, data in kinds:
attachment = api.upload(
alice,
chat["id"],
data,
content_type=content_type,
filename=f"{name}.img",
)
assert attachment["content_type"] == content_type, name
@pytest.mark.spec("attachments", "Граница размера")
def test_size_boundary(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
exact = images.png_of_size(images.MAX_BYTES)
api.upload(alice, chat["id"], exact)
over = images.png_of_size(images.MAX_BYTES + 1)
assert_error(api.post_attachment(alice, chat["id"], over), 413)
@pytest.mark.spec("attachments", "Заявленный размер больше лимита")
def test_declared_size_over_limit(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_attachment(alice, chat["id"], big_body())
assert resp.request.headers["Content-Length"] == str(BIG_BYTES)
assert_error(resp, 413)
@pytest.mark.spec("attachments", "Большое тело без Content-Length")
def test_chunked_body_over_limit(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_attachment(alice, chat["id"], chunks(big_body()))
assert "Content-Length" not in resp.request.headers
assert_error(resp, 413)
@pytest.mark.spec("attachments", "Огромные размеры в маленьком файле")
def test_huge_dimensions(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert_errors(
{
"png 8000x5001": api.post_attachment(
alice,
chat["id"],
images.png_huge(8000, 5001),
),
"png 1x40000001": api.post_attachment(
alice,
chat["id"],
images.png_huge(1, 40_000_001),
),
"jpeg 10000x4001": api.post_attachment(
alice,
chat["id"],
images.jpeg_huge(10000, 4001),
content_type="image/jpeg",
),
"jpeg 65535x65535": api.post_attachment(
alice,
chat["id"],
images.jpeg_huge(65535, 65535),
content_type="image/jpeg",
),
},
413,
)
@pytest.mark.spec("attachments", "Ровно 40 млн пикселей")
def test_exactly_max_pixels(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.png(8000, 5000, color=0, depth=1)
api.upload(alice, chat["id"], data)
@pytest.mark.spec("attachments", "Данные длиннее размеров")
def test_decompression_bomb(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
assert_error(
api.post_attachment(alice, chat["id"], images.png_bomb()),
415,
)
@pytest.mark.spec("attachments", "Не изображение")
def test_not_an_image(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert_errors(
{
name: api.post_attachment(alice, chat["id"], data)
for name, data in (
("text", "просто текст".encode()),
("gif", b"GIF89a" + bytes(64)),
("empty", b""),
)
},
415,
)
@pytest.mark.spec("attachments", "Подмена MIME")
def test_mime_spoofing(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert_errors(
{
"jpeg as png": api.post_attachment(
alice,
chat["id"],
images.jpeg(),
content_type="image/png",
),
"png as jpeg": api.post_attachment(
alice,
chat["id"],
images.sample_png(),
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("attachments", "Неподходящий Content-Type")
def test_unsuitable_content_type(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
assert_errors(
{
str(content_type): api.post_attachment(
alice,
chat["id"],
data,
content_type=content_type,
)
for content_type in (
"application/octet-stream",
"text/plain",
None,
)
},
415,
)
resp = api.post_attachment(
alice,
chat["id"],
data,
content_type="IMAGE/PNG; charset=binary",
)
assert assert_ok(resp, 201, "Attachment")["content_type"] == "image/png"
@pytest.mark.spec("attachments", "Обрезанный файл")
def test_truncated_files(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
png, jpeg = images.sample_png(), images.jpeg(size=(320, 200))
assert_errors(
{
"png half": api.post_attachment(
alice,
chat["id"],
images.truncated(png),
),
"png -1 byte": api.post_attachment(alice, chat["id"], png[:-1]),
"jpeg half": api.post_attachment(
alice,
chat["id"],
images.truncated(jpeg),
content_type="image/jpeg",
),
"jpeg -2 bytes": api.post_attachment(
alice,
chat["id"],
jpeg[:-2],
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("attachments", "Испорченные данные PNG")
def test_damaged_png_data(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
garbage = images.PNG_SIGNATURE + uuid.uuid4().bytes * 256
assert_errors(
{
"idat byte": api.post_attachment(
alice,
chat["id"],
images.png_idat_byte_changed(),
),
"garbage": api.post_attachment(alice, chat["id"], garbage),
},
415,
)
@pytest.mark.spec("attachments", "Хвост после конца изображения")
def test_tail_after_end(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
for content_type, data in (
("image/png", images.with_tail(images.sample_png())),
("image/jpeg", images.with_tail(images.jpeg())),
):
attachment = api.upload(
alice,
chat["id"],
data,
content_type=content_type,
)
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
content_type,
)
@pytest.mark.spec("attachments", "Опасное имя")
def test_dangerous_filename(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
names = {
"dot-dot": "../x.png",
"slash": "a/b.png",
"backslash": "a\\b.png",
"nul": "a\x00b.png",
"newline": "a\nb.png",
"del": "a\x7fb.png",
"c1 nel": "a\x85b.png",
"empty": "",
"spaces": " ",
"256": "я" * 256,
}
assert_errors(
{
name: api.post_attachment(alice, chat["id"], data, filename=value)
for name, value in names.items()
}
| {
"missing": api.post_attachment(
alice,
chat["id"],
data,
filename=None,
),
},
400,
)
def assert_name_kept(
api: Api,
actor: Actor,
chat_id: str,
filename: str,
) -> None:
attachment = api.upload(
actor,
chat_id,
images.sample_png(),
filename=filename,
)
meta = assert_ok(
api.attachment_meta(actor, attachment["id"]),
200,
"Attachment",
)
assert meta["filename"] == attachment["filename"] == filename
@pytest.mark.spec("attachments", "Имя в Unicode")
def test_unicode_filename(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
family = "👨‍👩‍👧"
core = f"фото {family} отпуска"
name = " " + core + "ё" * (253 - len(core)) + " "
assert len(name) == 255
assert_name_kept(api, alice, chat["id"], name)
@pytest.mark.spec("attachments", "Символы форматирования в имени")
def test_format_characters_in_filename(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
for name in (
"‮gnp.exe",
"⁦שלום⁩.png",
"строка
вторая.png",
"пере­нос.png",
):
assert_name_kept(api, alice, chat["id"], name)
@pytest.mark.spec("attachments", "Посторонний с большим файлом")
def test_outsider_with_big_file(
api: Api,
eve: Actor,
chat: dict[str, Any],
) -> None:
assert_error(api.post_attachment(eve, chat["id"], big_body()), 404)
@pytest.mark.spec("attachments", "Без сессии с опасным именем")
def test_no_session_with_dangerous_name(
api: Api,
chat: dict[str, Any],
) -> None:
for filename in ("a/b.png", "ok.png"):
resp = api.post_attachment(
None,
chat["id"],
images.sample_png(),
filename=filename,
)
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("attachments", "Неверный тип и большой размер")
def test_wrong_type_and_big_size(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_attachment(
alice,
chat["id"],
big_body(),
content_type="text/plain",
)
assert_error(resp, 415)
@pytest.mark.spec("attachments", "Другой участник")
def test_other_member_reads(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
assert_ok(api.attachment_meta(bob, attachment["id"]), 200, "Attachment")
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
"image/png",
)
@pytest.mark.spec("attachments", "Посторонний и неизвестный id")
def test_outsider_and_unknown_id(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
unknown = str(uuid.uuid4())
responses = {
"eve meta": api.attachment_meta(eve, attachment["id"]),
"eve content": api.attachment_content(eve, attachment["id"]),
"unknown meta": api.attachment_meta(alice, unknown),
"unknown content": api.attachment_content(alice, unknown),
}
assert_errors(responses, 404)
messages = {resp.json()["error"]["message"] for resp in responses.values()}
assert len(messages) == 1, messages
@pytest.mark.spec("attachments", "Неверный id вложения")
def test_bad_attachment_id(api: Api, alice: Actor) -> None:
assert_errors(
{
f"{kind} {value}": call(alice, value)
for value in ("123", "abc")
for kind, call in (
("meta", api.attachment_meta),
("content", api.attachment_content),
)
},
400,
)
@pytest.mark.spec("attachments", "Чтение без сессии")
def test_read_without_session(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
for resp in (
api.attachment_meta(None, attachment["id"]),
api.attachment_content(None, attachment["id"]),
):
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("attachments", "Метаданные равны ответу загрузки")
def test_meta_equals_upload(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
meta = assert_ok(
api.attachment_meta(bob, attachment["id"]),
200,
"Attachment",
)
assert meta == attachment
@pytest.mark.spec("attachments", "Побайтный оригинал")
def test_original_bytes(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
for content_type, data in (
("image/png", images.sample_png()),
("image/jpeg", images.jpeg(size=(320, 200))),
):
attachment = api.upload(
alice,
chat["id"],
data,
content_type=content_type,
)
resp = api.attachment_content(bob, attachment["id"])
assert not resp.is_redirect
assert_content(resp, data, content_type)
assert hashlib.sha256(resp.content).hexdigest() == attachment["sha256"]
@pytest.mark.spec("attachments", "Вариант original")
def test_variant_original(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
assert_content(
api.attachment_content(alice, attachment["id"], variant="original"),
data,
"image/png",
)
assert_errors(
{
variant or "empty": api.attachment_content(
alice,
attachment["id"],
variant=variant,
)
for variant in ("thumbnail", "")
},
400,
)
@pytest.mark.spec("attachments", "Без следов хранилища в ответе")
def test_no_storage_traces(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
upload = api.post_attachment(alice, chat["id"], data)
# assert_ok сверяет тело со схемой контракта: лишних полей нет
attachment = assert_ok(upload, 201, "Attachment")
meta = api.attachment_meta(alice, attachment["id"])
assert_ok(meta, 200, "Attachment")
content = api.attachment_content(alice, attachment["id"])
assert_content(content, data, "image/png")
for resp in (upload, meta, content):
assert_no_storage_traces(resp)
@pytest.mark.spec("attachments", "Повторная загрузка")
def test_repeated_upload(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
first = api.upload(alice, chat["id"], data)
second = api.upload(alice, chat["id"], data)
assert first["id"] != second["id"]
assert first["sha256"] == second["sha256"]
for attachment in (first, second):
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
"image/png",
)
@pytest.mark.spec("attachments", "Скачивание через другую реплику")
def test_download_through_other_replica(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
replicas: int,
) -> None:
data = images.sample_png()
upload = api.post_attachment(alice, chat["id"], data)
attachment = assert_ok(upload, 201, "Attachment")
uploaded_via = assert_instance_id(upload)
seen = {uploaded_via}
for _ in range(REPLICA_ATTEMPTS):
resp = api.attachment_content(bob, attachment["id"])
assert_content(resp, data, "image/png")
seen.add(assert_instance_id(resp))
if assert_instance_id(resp) != uploaded_via:
break
assert_replicas(seen, replicas)
print(f"uploaded via {uploaded_via}, downloaded via {sorted(seen)}")
def test_upload_path_with_quoted_chat_id(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `api-conventions`, «UUID на входе»: `chat_id` загрузки в
другой записи — 400, как у остальных ручек чата."""
data = images.sample_png()
value = chat["id"]
assert_errors(
{
form: api.post_attachment(
alice,
urllib.parse.quote(raw, safe=""),
data,
)
for form, raw in (
("no hyphens", value.replace("-", "")),
("urn", f"urn:uuid:{value}"),
("braces", f"{{{value}}}"),
("number", "123"),
)
},
400,
)
+35 -1
View File
@@ -4,9 +4,12 @@
`spec_coverage.py`.
"""
from typing import Any
import pytest
from api_client import API, Actor, Api
import images
from api_client import API, Actor, Api, new_key
from contract import assert_ok
@@ -35,3 +38,34 @@ def test_member_order_kept(api: Api, alice: Actor, bob: Actor) -> None:
for chat in page["items"]
}
assert listed[created["id"]] == expected
@pytest.mark.spec("data-storage", "Порядок вложений")
def test_attachment_order_kept(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
a, b, c = (
api.upload(alice, chat["id"], images.sample_png())["id"]
for _ in range(3)
)
key = new_key()
order = [c, a, b]
sent = api.send_message(
alice,
chat["id"],
"порядок",
key=key,
attachment_ids=order,
)
assert sent["attachment_ids"] == order
assert api.all_messages(alice, chat["id"]) == [sent]
replay = api.send_message(
alice,
chat["id"],
"порядок",
key=key,
attachment_ids=order,
)
assert replay["attachment_ids"] == order
+163
View File
@@ -18,9 +18,11 @@ from typing import Any
import httpx
import pytest
import images
from api_client import API, Actor, Api, new_key
from contract import (
BEARER_CHALLENGE,
assert_content,
assert_error,
assert_ok,
assert_unauthorized,
@@ -45,6 +47,8 @@ READINESS_TIMEOUT_S = 2
# health без S3: проверка к S3 не обращается, ответ быстрее секунды (спек
# health, «Хранилище объектов недоступно»); срок вызова S3 — 5 с
OBJECT_STORAGE_HEALTH_S = 1
# [s3] timeout_seconds по умолчанию: срок одного вызова S3
S3_TIMEOUT_S = 5
# сколько секунд hook держит слоты max_connections; clear-connections
# освобождает их раньше
FILL_HOLD_S = 30
@@ -526,3 +530,162 @@ def test_key_free_after_ttl(tight_api: Api) -> None:
assert second["id"] != first["id"]
history = tight_api.all_messages(alice, chat["id"])
assert [item["id"] for item in history] == [first["id"], second["id"]]
# ---------------------------------------------------------------------------
# Вложения: S3 остановлен или заморожен, счётчики строк и объектов — hook
# ---------------------------------------------------------------------------
def attachment_counts(stand: Stand) -> dict[str, int]:
"""Вложения стенда по статусам: `pending=N ready=M` от hook."""
return {
name: int(value)
for name, value in (
item.split("=") for item in stand("count-attachments").split()
)
}
def object_count(stand: Stand) -> int:
return int(stand("count-objects"))
def upload_raw(
api: Api,
actor: Actor,
chat: dict[str, Any],
data: Any,
**kwargs: Any,
) -> httpx.Response:
return api.post_attachment(actor, chat["id"], data, **kwargs)
@pytest.mark.spec("attachments", "Запись в S3 не удалась")
def test_upload_with_object_storage_stopped(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
before = attachment_counts(stand)
with outage(stand, "stop", "s3"):
resp, elapsed = timed(lambda: upload_raw(api, alice, chat, data))
assert_error(resp, 503)
assert elapsed < S3_TIMEOUT_S + SLACK_S, f"503 after {elapsed:.2f}s"
after = attachment_counts(stand)
# строка-намерение осталась, готовых не прибавилось; её уберёт
# уборщик change upload-consistency
assert after == {
"pending": before["pending"] + 1,
"ready": before["ready"],
}
api.send_message(alice, chat["id"], "текст без S3")
api.upload(alice, chat["id"], data)
@pytest.mark.spec("attachments", "Отклонённая загрузка ничего не оставляет")
def test_rejected_uploads_leave_nothing(
api: Api,
stand: Stand,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
big = images.PNG_SIGNATURE + bytes(images.MAX_BYTES * 2)
def chunked() -> Iterator[bytes]:
for offset in range(0, len(big), 1024 * 1024):
yield big[offset : offset + 1024 * 1024]
# хотя бы одно готовое вложение: счётчики hook не нулевые случайно
api.upload(alice, chat["id"], images.sample_png())
before = (attachment_counts(stand), object_count(stand))
assert before[0]["ready"] >= 1, before
assert before[1] >= 1, before
rejected = (
(404, upload_raw(api, eve, chat, images.sample_png())),
(413, upload_raw(api, alice, chat, big)),
(413, upload_raw(api, alice, chat, chunked())),
(413, upload_raw(api, alice, chat, images.png_huge(8000, 5001))),
(
415,
upload_raw(
api,
alice,
chat,
images.sample_png(),
content_type="text/plain",
),
),
(415, upload_raw(api, alice, chat, images.png_idat_byte_changed())),
)
for status, resp in rejected:
assert_error(resp, status)
assert (attachment_counts(stand), object_count(stand)) == before
@pytest.mark.spec("attachments", "S3 остановлен")
def test_object_storage_stopped(
api: Api,
stand: Stand,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
with outage(stand, "stop", "s3"):
resp, elapsed = timed(
lambda: api.attachment_content(bob, attachment["id"]),
)
assert_error(resp, 503)
assert elapsed < S3_TIMEOUT_S + SLACK_S, f"503 after {elapsed:.2f}s"
meta = assert_ok(
api.attachment_meta(bob, attachment["id"]),
200,
"Attachment",
)
assert meta == attachment
api.send_message(
bob,
chat["id"],
"",
attachment_ids=[attachment["id"]],
)
assert_ok(api.request("GET", "/health/ready"), 200, "Health")
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
"image/png",
)
@pytest.mark.spec("attachments", "S3 завис")
def test_object_storage_paused(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
# срок клиента больше срока вызова S3: ждём ответ API, а не свой обрыв
slow = Api(str(api.client.base_url), timeout=3 * S3_TIMEOUT_S)
with slow, outage(stand, "pause", "s3"):
for call in (
lambda: upload_raw(slow, alice, chat, data),
lambda: slow.attachment_content(alice, attachment["id"]),
):
resp, elapsed = timed(call)
assert_error(resp, 503)
# срок вызова S3 и немного на шаги с БД, а не зависание
assert elapsed < S3_TIMEOUT_S + 2 * SLACK_S, (
f"503 after {elapsed:.2f}s"
)
assert_content(
api.attachment_content(alice, attachment["id"]),
data,
"image/png",
)
+90
View File
@@ -11,6 +11,7 @@ from typing import Any
import pytest
import images
from api_client import (
API,
IDEMPOTENCY_KEY,
@@ -148,6 +149,95 @@ def test_other_body_conflict(
assert api.send_message(alice, chat["id"], "первое", key=key) == first
def two_attachments(api: Api, actor: Actor, chat_id: str) -> list[str]:
return [
api.upload(actor, chat_id, images.sample_png())["id"] for _ in range(2)
]
@pytest.mark.spec("idempotency", "Вложения по умолчанию")
def test_replay_with_default_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "без файлов", key=key)
again = api.send_message(
alice,
chat["id"],
"без файлов",
key=key,
attachment_ids=[],
)
assert again == first
assert texts(api, alice, chat["id"]) == ["без файлов"]
@pytest.mark.spec("idempotency", "Повтор сообщения с вложениями")
def test_replay_with_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first_id, second_id = two_attachments(api, alice, chat["id"])
key = new_key()
ids = [first_id, second_id]
first = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=ids,
)
again = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=ids,
)
upper = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=[item.upper() for item in ids],
)
assert first == again == upper
assert first["attachment_ids"] == ids
history = api.all_messages(alice, chat["id"])
assert [item["id"] for item in history] == [first["id"]]
@pytest.mark.spec("idempotency", "Другие вложения")
def test_other_attachments_conflict(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first_id, second_id = two_attachments(api, alice, chat["id"])
key = new_key()
first = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=[first_id, second_id],
)
for body in (
{"text": "файлы", "attachment_ids": [second_id, first_id]},
{"text": "файлы"},
):
assert_error(
api.post_message(alice, chat["id"], key=key, json=body),
409,
)
history = api.all_messages(alice, chat["id"])
assert history == [first]
assert history[0]["attachment_ids"] == [first_id, second_id]
@pytest.mark.spec("idempotency", "Другой пользователь")
def test_same_key_other_user(
api: Api,
+215 -2
View File
@@ -1,12 +1,14 @@
"""Спек `messages`: отправка, валидация текста, история."""
"""Спек `messages`: отправка, валидация текста, история, вложения."""
import uuid
from typing import Any
import httpx
import pytest
import images
from api_client import Actor, Api, order_key
from contract import assert_error, assert_ok
from contract import assert_error, assert_errors, assert_ok
def send_raw(
@@ -30,6 +32,217 @@ def test_member_sends(
assert message["sender_id"] == alice.id
assert message["chat_id"] == chat["id"]
assert message["text"] == "Привет, мир 👋"
assert message["attachment_ids"] == []
def upload(api: Api, actor: Actor, chat_id: str) -> str:
"""Готовое вложение чата; id."""
return api.upload(actor, chat_id, images.sample_png())["id"]
@pytest.mark.spec("messages", "Сообщение с вложениями")
def test_message_with_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first, second = (
upload(api, alice, chat["id"]),
upload(api, alice, chat["id"]),
)
message = api.send_message(
alice,
chat["id"],
"два файла",
attachment_ids=[second, first],
)
assert message["attachment_ids"] == [second, first]
@pytest.mark.spec("messages", "Пустой текст с вложением")
def test_empty_text_with_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
message = api.send_message(
alice,
chat["id"],
"",
attachment_ids=[attachment_id],
)
assert message["text"] == ""
assert message["attachment_ids"] == [attachment_id]
@pytest.mark.spec("messages", "Пробелы с вложением")
def test_blank_text_with_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Согласовано с преподавателем 2026-10-20: пустой текст — и `""`, и
из одних пробелов; с вложением допустим и не нормализуется."""
attachment_id = upload(api, alice, chat["id"])
message = api.send_message(
alice,
chat["id"],
" ",
attachment_ids=[attachment_id],
)
assert message["text"] == " "
assert message["attachment_ids"] == [attachment_id]
assert_error(send_raw(api, alice, chat["id"], {"text": " "}), 400)
assert [item["id"] for item in api.all_messages(alice, chat["id"])] == [
message["id"],
]
@pytest.mark.spec("messages", "Вложения в истории")
def test_attachments_in_history(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
first, second = (
upload(api, alice, chat["id"]),
upload(api, alice, chat["id"]),
)
with_files = api.send_message(
alice,
chat["id"],
"с файлами",
attachment_ids=[second, first],
)
plain = api.send_message(bob, chat["id"], "без файлов")
history = api.all_messages(bob, chat["id"])
assert history == sorted([with_files, plain], key=order_key)
by_id = {item["id"]: item["attachment_ids"] for item in history}
assert by_id == {with_files["id"]: [second, first], plain["id"]: []}
@pytest.mark.spec("messages", "Вложение другого участника")
def test_attachment_of_other_member(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
api.send_message(bob, chat["id"], "ответ", attachment_ids=[attachment_id])
@pytest.mark.spec("messages", "Вложение другого чата")
def test_attachment_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
other = api.create_chat(alice, bob, title="Y")
attachment_id = upload(api, alice, other["id"])
resp = send_raw(
api,
alice,
chat["id"],
{"text": "чужой чат", "attachment_ids": [attachment_id]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Чужое вложение")
def test_foreign_attachment(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
eve_chat = api.create_chat(eve, title="Ева")
attachment_id = upload(api, eve, eve_chat["id"])
resp = send_raw(
api,
alice,
chat["id"],
{"text": "", "attachment_ids": [attachment_id]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Неизвестное вложение")
def test_unknown_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = send_raw(
api,
alice,
chat["id"],
{"text": "x", "attachment_ids": [str(uuid.uuid4())]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Неверный список вложений")
def test_bad_attachment_list(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
bodies = {
"repeat": [attachment_id, attachment_id],
"repeat upper": [attachment_id, attachment_id.upper()],
"eleven": [str(uuid.uuid4()) for _ in range(11)],
"string": attachment_id,
"number item": [123],
"123 item": ["123"],
}
assert_errors(
{
name: send_raw(
api,
alice,
chat["id"],
{"text": "x", "attachment_ids": value},
)
for name, value in bodies.items()
},
400,
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Одно вложение в двух сообщениях")
def test_one_attachment_in_two_messages(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
first = api.send_message(
alice,
chat["id"],
"раз",
attachment_ids=[attachment_id],
)
second = api.send_message(
alice,
chat["id"],
"два",
attachment_ids=[attachment_id],
)
assert first["id"] != second["id"]
history = api.all_messages(alice, chat["id"])
assert [item["attachment_ids"] for item in history] == [
[attachment_id],
[attachment_id],
]
@pytest.mark.spec("messages", "Граница длины")
+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"]) == []