feat: Саватеев А трек 4

This commit is contained in:
Enterxx2
2026-11-02 23:13:38 +03:00
parent 445cfe4789
commit 081d0fd2c8
76 changed files with 6387 additions and 77 deletions
+49 -1
View File
@@ -5,7 +5,15 @@ from pathlib import Path
import httpx
import pytest
from helpers import auth, basic, message_headers, unique_password, unique_username
from helpers import (
auth,
basic,
message_headers,
png_bytes,
unique_password,
unique_username,
upload_raw,
)
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
@@ -74,3 +82,43 @@ def send_message(api: httpx.Client) -> Callable[..., dict]:
return response.json()
return send
@pytest.fixture
def upload(api: httpx.Client) -> Callable[..., dict]:
"""Успешная загрузка вложения: 201 и Attachment"""
def create(
user: dict,
chat: dict,
content: bytes | None = None,
content_type: str = "image/png",
filename: str = "image.png",
) -> dict:
response = upload_raw(
api, user, chat["id"], content or png_bytes(), content_type, filename
)
assert response.status_code == 201, response.text
return response.json()
return create
@pytest.fixture
def send_attachments(api: httpx.Client) -> Callable[..., httpx.Response]:
"""POST сообщения с attachment_ids; ответ не проверяется"""
def send(
user: dict,
chat: dict,
attachment_ids: list[str],
text: str = "",
key: str | None = None,
) -> httpx.Response:
return api.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text, "attachment_ids": attachment_ids},
headers=message_headers(user, key),
)
return send
+113
View File
@@ -1,11 +1,16 @@
"""Общие проверки для собственных black-box тестов"""
import base64
import json
import io
import struct
import subprocess
import uuid
import zlib
from pathlib import Path
import httpx
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
@@ -101,3 +106,111 @@ def psql(sql: str) -> str:
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
stdin=sql,
).strip()
# --- Изображения и вложения (lab4) ---
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
MAX_IMAGE_PIXELS = 40_000_000
FIXTURE_PNG = ROOT / "tests/fixtures/sample.png"
def png_bytes(width: int = 32, height: int = 20, noise: bool = False) -> bytes:
"""Настоящий PNG; noise — плохо сжимаемое содержимое"""
image = (
Image.effect_noise((width, height), 64).convert("RGB")
if noise
else Image.new("RGB", (width, height), (200, 30, 90))
)
buffer = io.BytesIO()
image.save(buffer, "PNG")
return buffer.getvalue()
def jpeg_bytes(width: int = 32, height: int = 20, progressive: bool = False) -> bytes:
image = Image.effect_noise((width, height), 64).convert("RGB")
buffer = io.BytesIO()
image.save(buffer, "JPEG", quality=85, progressive=progressive)
return buffer.getvalue()
def bilevel_png(width: int, height: int) -> bytes:
"""Огромное по пикселям, но крошечное по байтам изображение (1 бит, нули)"""
buffer = io.BytesIO()
Image.new("1", (width, height)).save(buffer, "PNG")
return buffer.getvalue()
def png_chunk(chunk_type: bytes, data: bytes) -> bytes:
return (
struct.pack(">I", len(data))
+ chunk_type
+ data
+ struct.pack(">I", zlib.crc32(chunk_type + data))
)
def png_of_size(size: int) -> bytes:
"""
Валидный PNG ровно size байт: перед IEND вставляется chunk tEXt
с корректным CRC нужной длины.
"""
base = png_bytes()
iend = base[-12:]
padding = size - len(base) - 12
keyword = b"Comment\x00"
text = png_chunk(b"tEXt", keyword + b"a" * (padding - len(keyword)))
result = base[:-12] + text + iend
assert len(result) == size
return result
def upload_headers(user: dict, content_type: str = "image/png") -> dict[str, str]:
return {**auth(user), "Content-Type": content_type}
def upload_raw(
api: httpx.Client,
user: dict,
chat_id: str,
content: bytes,
content_type: str | None = "image/png",
filename: str = "image.png",
) -> httpx.Response:
"""POST сырых байт; content_type=None — без заголовка Content-Type"""
headers = auth(user) if content_type is None else upload_headers(user, content_type)
return api.post(
f"/api/v1/chats/{chat_id}/attachments",
params={"filename": filename},
content=content,
headers=headers,
)
def assert_not_server_error(response: httpx.Response) -> None:
"""Ошибка пользователя не превращается в 5xx и имеет формат контракта"""
assert response.status_code < 500, response.text
assert response.headers["X-Instance-Id"]
def last_json_line(output: str) -> dict:
"""Результат скрипта — последняя JSON-строка stdout; выше — журнал loguru"""
return json.loads(
next(line for line in reversed(output.splitlines()) if line.startswith("{"))
)
def container_json(service: str, script: str) -> dict:
"""
Python-скрипт внутри контейнера стенда: его сети, секреты и код из src.
Скрипт печатает результат одной JSON-строкой.
"""
prelude = "import sys\nsys.path.insert(0, 'src')\n"
output = compose("exec", "-T", service, "python", "-", stdin=prelude + script)
return last_json_line(output)
def run_janitor(*args: str) -> dict:
"""Один проход janitor внутри его контейнера; отчёт сверки"""
output = compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args)
return last_json_line(output)
+65
View File
@@ -0,0 +1,65 @@
"""
Upload → остановка именно той API-реплики, что приняла файл → download через
другую реплику возвращает тот же файл. На репликах нет локальной копии
оригинала: байты лежат в общем S3.
Останавливает контейнер (scripts/stop-one.sh) и возвращает его
(scripts/restore.sh), поэтому запускается явно: make test-failures.
"""
import hashlib
import os
import subprocess
import httpx
import pytest
from helpers import ROOT, auth, png_bytes, upload_raw
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_FAILURE_TESTS") != "1",
reason="останавливает API-реплику: запускайте через make test-failures",
)
DOWNLOADS_AFTER_STOP = 10
HOOK_TIMEOUT_SEC = 90
def run_script(name: str, **env: str) -> None:
subprocess.run(
[str(ROOT / "scripts" / name)],
cwd=ROOT,
env={**os.environ, **env},
capture_output=True,
timeout=HOOK_TIMEOUT_SEC,
check=True,
)
def test_download_survives_stop_of_uploading_replica(
api: httpx.Client, make_user, make_chat
) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
content = png_bytes(800, 600, noise=True)
uploaded = upload_raw(api, alice, chat["id"], content)
assert uploaded.status_code == 201, uploaded.text
attachment = uploaded.json()
uploader = uploaded.headers["X-Instance-Id"]
run_script("stop-one.sh", TARGET_INSTANCE_ID=uploader)
try:
served_by = set()
for _ in range(DOWNLOADS_AFTER_STOP):
response = api.get(
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(bob)
)
assert response.status_code == 200, response.text
assert hashlib.sha256(response.content).hexdigest() == attachment["sha256"]
assert response.content == content
served_by.add(response.headers["X-Instance-Id"])
print(f"\nUPLOADED BY {uploader}, DOWNLOADED FROM {sorted(served_by)}")
assert uploader not in served_by
finally:
run_script("restore.sh")
+384
View File
@@ -0,0 +1,384 @@
"""
Вложения: загрузка, побайтное скачивание, доступ, лимиты и проверка содержимого.
Любая ошибка пользователя — 4xx в формате контракта, никогда не 5xx.
"""
import hashlib
import uuid
from urllib.parse import unquote
import httpx
import pytest
from helpers import (
FIXTURE_PNG,
MAX_IMAGE_PIXELS,
MAX_UPLOAD_BYTES,
assert_error,
assert_not_server_error,
auth,
bilevel_png,
jpeg_bytes,
png_bytes,
png_of_size,
upload_raw,
)
ATTACHMENT_FIELDS = {
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"status",
"variants",
"error_code",
"created_at",
"updated_at",
}
def download(api: httpx.Client, user: dict, attachment_id: str) -> httpx.Response:
return api.get(f"/api/v1/attachments/{attachment_id}/content", headers=auth(user))
@pytest.mark.parametrize(
("content", "content_type"),
[
(FIXTURE_PNG.read_bytes(), "image/png"),
(jpeg_bytes(640, 480), "image/jpeg"),
(jpeg_bytes(640, 480, progressive=True), "image/jpeg"),
],
ids=["png-fixture", "jpeg-baseline", "jpeg-progressive"],
)
def test_upload_and_download_byte_exact(
api: httpx.Client, make_user, make_chat, upload, content: bytes, content_type: str
) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
attachment = upload(alice, chat, content, content_type, "photo")
assert set(attachment) == ATTACHMENT_FIELDS
assert attachment["status"] == "ready"
assert attachment["variants"] == [] and attachment["error_code"] is None
assert attachment["chat_id"] == chat["id"] and attachment["owner_id"] == alice["id"]
assert attachment["content_type"] == content_type
assert attachment["size_bytes"] == len(content)
assert attachment["sha256"] == hashlib.sha256(content).hexdigest()
assert attachment["created_at"].endswith("Z")
metadata = api.get(f"/api/v1/attachments/{attachment['id']}", headers=auth(bob))
assert metadata.status_code == 200 and metadata.json() == attachment
response = download(api, bob, attachment["id"])
assert response.status_code == 200
assert response.content == content
assert response.headers["content-type"] == content_type
assert response.headers["content-length"] == str(len(content))
assert response.headers["x-content-type-options"] == "nosniff"
assert response.headers["X-Instance-Id"]
def test_public_api_does_not_expose_storage_details(
api: httpx.Client, make_user, make_chat, upload
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
response = download(api, alice, attachment["id"])
exposed = (str(attachment) + str(dict(response.headers))).lower()
for marker in ("originals/", "s3:9000", "messenger-attachments", "amz"):
assert marker not in exposed
assert response.status_code == 200
assert not response.history, "download must not redirect to storage"
def test_unicode_filename_is_preserved(
api: httpx.Client, make_user, make_chat, upload
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
name = "Фото отпуска 😀 «море» — 1.png"
attachment = upload(alice, chat, filename=name)
assert attachment["filename"] == name
disposition = download(api, alice, attachment["id"]).headers["content-disposition"]
assert disposition.startswith("inline; filename*=UTF-8''")
assert unquote(disposition.split("''", 1)[1]) == name
def test_outsider_and_unknown_get_indistinguishable_404(
api: httpx.Client, make_user, make_chat, upload
) -> None:
alice = make_user("alice")
eve = make_user("eve")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
for suffix in ("", "/content"):
foreign = api.get(f"/api/v1/attachments/{attachment['id']}{suffix}", headers=auth(eve))
missing = api.get(f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers=auth(eve))
assert_error(foreign, 404, "not_found")
assert_error(missing, 404, "not_found")
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
def test_outsider_cannot_upload_into_foreign_chat(
api: httpx.Client, make_user, make_chat
) -> None:
alice = make_user("alice")
eve = make_user("eve")
chat = make_chat(alice, [alice])
assert_error(upload_raw(api, eve, chat["id"], png_bytes()), 404, "not_found")
assert_error(upload_raw(api, eve, str(uuid.uuid4()), png_bytes()), 404, "not_found")
def test_authentication_is_required(api: httpx.Client, make_user, make_chat, upload) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
anonymous = {"token": "x" * 43}
for response in (
api.post(
f"/api/v1/chats/{chat['id']}/attachments",
params={"filename": "a.png"},
content=png_bytes(),
headers={"Content-Type": "image/png"},
),
api.get(f"/api/v1/attachments/{attachment['id']}"),
download(api, anonymous, attachment["id"]),
):
assert_error(response, 401, "unauthorized")
def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upload) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
path = f"/api/v1/attachments/{attachment['id']}/content"
original = api.get(path, params={"variant": "original"}, headers=auth(alice))
assert original.status_code == 200
# Вариант из контракта, но в lab4 его нет у ready-вложения
missing = api.get(path, params={"variant": "thumbnail"}, headers=auth(alice))
assert_error(missing, 404, "not_found")
unknown = api.get(path, params={"variant": "../../etc"}, headers=auth(alice))
assert_error(unknown, 400, "invalid_request")
malformed = api.get("/api/v1/attachments/not-a-uuid", headers=auth(alice))
assert_error(malformed, 400, "invalid_request")
# --- Размер ---
def test_exactly_max_bytes_is_accepted(api: httpx.Client, make_user, make_chat, upload) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
content = png_of_size(MAX_UPLOAD_BYTES)
attachment = upload(alice, chat, content)
assert attachment["size_bytes"] == MAX_UPLOAD_BYTES
assert download(api, alice, attachment["id"]).content == content
def test_too_large_file_is_rejected_by_api(api: httpx.Client, make_user, make_chat) -> None:
"""10 MiB + 1 байт отклоняет реплика (X-Instance-Id), а не только LB"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], png_of_size(MAX_UPLOAD_BYTES + 1))
assert_error(response, 413, "payload_too_large")
assert response.headers["X-Instance-Id"]
def test_huge_body_is_rejected_by_balancer(api: httpx.Client, make_user, make_chat) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], b"\x00" * (12 * 1024 * 1024))
assert_error(response, 413, "payload_too_large")
def test_empty_body_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
assert_error(upload_raw(api, alice, chat["id"], b""), 400, "invalid_request")
@pytest.mark.parametrize(
("width", "height", "status"),
[
(8000, 5000, 201),
(8000, 5001, 413),
(20000, 20000, 413),
],
)
def test_pixel_limit_applies_before_decoding(
api: httpx.Client, make_user, make_chat, width: int, height: int, status: int
) -> None:
"""Файл крошечный по байтам: лимит считается по заголовку, а не по размеру"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
content = bilevel_png(width, height)
assert len(content) < 1024 * 1024
response = upload_raw(api, alice, chat["id"], content)
if status == 201:
assert width * height == MAX_IMAGE_PIXELS
assert response.status_code == 201, response.text
else:
assert_error(response, 413, "payload_too_large")
# --- Содержимое и MIME ---
def corrupted_payloads() -> list[tuple[str, bytes, str]]:
png = png_bytes(300, 200, noise=True)
jpeg = jpeg_bytes(300, 200)
flipped = bytearray(png)
flipped[len(png) // 2] ^= 0xFF
return [
("png-truncated", png[: len(png) // 2], "image/png"),
("png-bit-flip-crc", bytes(flipped), "image/png"),
("png-signature-garbage", png[:8] + b"\x00garbage" * 64, "image/png"),
("png-without-iend", png[:-12], "image/png"),
("jpeg-truncated", jpeg[: len(jpeg) // 2], "image/jpeg"),
("jpeg-signature-garbage", b"\xff\xd8\xff" + b"garbage" * 64, "image/jpeg"),
]
@pytest.mark.parametrize(
("name", "content", "content_type"),
corrupted_payloads(),
ids=[item[0] for item in corrupted_payloads()],
)
def test_corrupted_image_is_rejected(
api: httpx.Client, make_user, make_chat, name: str, content: bytes, content_type: str
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], content, content_type)
assert_not_server_error(response)
assert_error(response, 415, "unsupported_media_type")
@pytest.mark.parametrize(
("content", "content_type"),
[
(png_bytes(), "image/jpeg"),
(jpeg_bytes(), "image/png"),
(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;", "image/png"),
(b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png"),
(b"%PDF-1.7\n", "image/jpeg"),
(png_bytes(), "application/octet-stream"),
(png_bytes(), "image/gif"),
(png_bytes(), "text/html"),
(png_bytes(), None),
],
ids=[
"png-as-jpeg",
"jpeg-as-png",
"gif-as-png",
"svg-as-png",
"pdf-as-jpeg",
"octet-stream",
"image-gif",
"text-html",
"no-content-type",
],
)
def test_mime_spoofing_is_rejected(
api: httpx.Client, make_user, make_chat, content: bytes, content_type: str | None
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], content, content_type)
assert_not_server_error(response)
assert_error(response, 415, "unsupported_media_type")
def test_content_type_parameters_are_ignored(
api: httpx.Client, make_user, make_chat
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], png_bytes(), "Image/PNG; foo=bar")
assert response.status_code == 201, response.text
assert response.json()["content_type"] == "image/png"
# --- Имя файла ---
@pytest.mark.parametrize(
"filename",
[
"../../etc/passwd",
"dir/photo.png",
"C:\\photo.png",
"a\x00b.png",
"line\nbreak.png",
"tab\t.png",
"bell\x07.png",
"photo\u202egnp.exe",
"",
" ",
".",
"..",
"x" * 256,
],
ids=[
"traversal",
"slash",
"backslash",
"nul",
"newline",
"tab",
"control",
"bidi-override",
"empty",
"blank",
"dot",
"dotdot",
"too-long",
],
)
def test_dangerous_filename_is_rejected(
api: httpx.Client, make_user, make_chat, filename: str
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], png_bytes(), filename=filename)
assert_not_server_error(response)
assert_error(response, 400, "invalid_request")
def test_missing_filename_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = api.post(
f"/api/v1/chats/{chat['id']}/attachments",
content=png_bytes(),
headers={**auth(alice), "Content-Type": "image/png"},
)
assert_error(response, 400, "invalid_request")
def test_longest_filename_is_accepted(make_user, make_chat, upload) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
name = "я" * 251 + ".png"
assert upload(alice, chat, filename=name)["filename"] == name
def test_same_filename_gets_separate_attachments(
api: httpx.Client, make_user, make_chat, upload
) -> None:
"""filename — только отображение: одинаковые имена не перезаписывают файл"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
first_content, second_content = png_bytes(10, 10), png_bytes(20, 20)
first = upload(alice, chat, first_content, filename="same.png")
second = upload(alice, chat, second_content, filename="same.png")
assert first["id"] != second["id"]
assert download(api, alice, first["id"]).content == first_content
assert download(api, alice, second["id"]).content == second_content
+166
View File
@@ -0,0 +1,166 @@
"""
Сообщения с attachment_ids: вложение только своего чата, порядок, пустой
текст, идемпотентность; при любом отказе сообщение не появляется.
"""
import uuid
import httpx
import pytest
from helpers import (
assert_error,
assert_not_server_error,
auth,
message_headers,
png_bytes,
read_all_messages,
)
def history(api: httpx.Client, user: dict, chat: dict) -> list[dict]:
items, _ = read_all_messages(api, user, chat["id"], 100)
return items
def test_message_with_attachment_is_readable_by_members(
api: httpx.Client, make_user, make_chat, upload, send_attachments
) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
attachment = upload(alice, chat)
response = send_attachments(alice, chat, [attachment["id"]])
assert response.status_code == 201, response.text
message = response.json()
assert message["text"] == "" and message["attachment_ids"] == [attachment["id"]]
assert history(api, bob, chat) == [message]
content = api.get(
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(bob)
)
assert content.status_code == 200
def test_any_member_may_reference_chat_attachment_and_order_is_kept(
make_user, make_chat, upload, send_attachments
) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
ids = [upload(alice, chat, png_bytes(i + 1, i + 1))["id"] for i in range(10)]
reordered = list(reversed(ids))
response = send_attachments(bob, chat, reordered, text="от Боба")
assert response.status_code == 201, response.text
assert response.json()["attachment_ids"] == reordered
def test_text_message_has_empty_attachment_ids(make_user, make_chat, send_message) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
assert send_message(alice, chat, "только текст")["attachment_ids"] == []
def test_attachment_of_other_chat_is_rejected(
api: httpx.Client, make_user, make_chat, upload, send_attachments
) -> None:
"""Алиса — участник обоих чатов, но файл привязан к другому чату"""
alice = make_user("alice")
chat = make_chat(alice, [alice], title="Чат A")
other = make_chat(alice, [alice], title="Чат B")
foreign = upload(alice, other)
own = upload(alice, chat)
for ids in ([foreign["id"]], [own["id"], foreign["id"]]):
response = send_attachments(alice, chat, ids, text="чужой файл")
assert_not_server_error(response)
assert_error(response, 404, "not_found")
assert history(api, alice, chat) == []
def test_foreign_attachment_id_is_rejected(
api: httpx.Client, make_user, make_chat, upload, send_attachments
) -> None:
"""Вложение из чата, где пользователь не участник, и несуществующее — 404"""
alice = make_user("alice")
eve = make_user("eve")
chat = make_chat(alice, [alice])
eve_chat = make_chat(eve, [eve])
eve_attachment = upload(eve, eve_chat)
foreign = send_attachments(alice, chat, [eve_attachment["id"]])
missing = send_attachments(alice, chat, [str(uuid.uuid4())])
assert_error(foreign, 404, "not_found")
assert_error(missing, 404, "not_found")
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
assert history(api, alice, chat) == []
@pytest.mark.parametrize(
"body",
[
{"text": ""},
{"text": " "},
{"text": "", "attachment_ids": []},
{"text": "x", "attachment_ids": ["not-a-uuid"]},
{"text": "x", "attachment_ids": "a"},
{"text": "x", "attachment_ids": None},
{"text": "x", "attachment_ids": [str(uuid.uuid4())] * 2},
{"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]},
],
ids=[
"empty-text",
"blank-text",
"empty-both",
"bad-uuid",
"not-array",
"null",
"duplicates",
"too-many",
],
)
def test_invalid_attachment_ids_are_rejected(
api: httpx.Client, make_user, make_chat, body: dict
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = api.post(
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=message_headers(alice)
)
assert_error(response, 400, "invalid_request")
def test_idempotent_replay_with_attachments(
api: httpx.Client, make_user, make_chat, upload, send_attachments
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
first, second = upload(alice, chat), upload(alice, chat)
key = uuid.uuid4().hex
created = send_attachments(alice, chat, [first["id"]], key=key)
replay = send_attachments(alice, chat, [first["id"]], key=key)
assert created.status_code == replay.status_code == 201
assert created.json() == replay.json()
changed = send_attachments(alice, chat, [first["id"], second["id"]], key=key)
assert_error(changed, 409, "conflict")
assert history(api, alice, chat) == [created.json()]
def test_missing_attachment_ids_equals_empty_list_for_idempotency(
api: httpx.Client, make_user, make_chat
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
key = uuid.uuid4().hex
path = f"/api/v1/chats/{chat['id']}/messages"
first = api.post(path, json={"text": "a"}, headers=message_headers(alice, key))
second = api.post(
path,
json={"attachment_ids": [], "text": "a"},
headers=message_headers(alice, key),
)
assert first.status_code == second.status_code == 201
assert first.json() == second.json()
+188
View File
@@ -0,0 +1,188 @@
"""
Согласованность S3 и PostgreSQL на живом стенде.
Сбои внедряются напрямую в хранилища: строка pending с объектом — процесс
упал между PUT в S3 и подтверждением в БД; объект без строки — сирота.
Затем janitor (тот же код и ключи, что в сервисе janitor) выполняет проход
с коротким grace period. Обрыв загрузки идёт напрямую в API-реплику, минуя
буферизацию nginx.
Запуск явно: make test-storage (RUN_STORAGE_TESTS=1).
"""
import json
import os
import time
import uuid
import httpx
import pytest
from helpers import auth, container_json, png_bytes, psql, run_janitor
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_STORAGE_TESTS") != "1",
reason="меняет данные стенда напрямую: запускайте через make test-storage",
)
# Запас на время docker exec janitor (импорт кода под лимитом CPU 0.25)
GRACE_SECONDS = 20
STALE_ROW_AGE_SECONDS = 300
PUT_OBJECTS = """
import asyncio, json
from infrastructure.dependencies import storage_manager
async def main():
s3 = await storage_manager.create_client()
for key in {keys!r}:
await s3.put_object(Bucket=storage_manager.bucket, Key=key, Body=b"x")
await storage_manager.close()
print(json.dumps({{"put": len({keys!r})}}))
asyncio.run(main())
"""
EXISTING_OBJECTS = """
import asyncio, json
from infrastructure.dependencies import storage_manager
async def main():
s3 = await storage_manager.create_client()
found = {{}}
for key in {keys!r}:
try:
await s3.head_object(Bucket=storage_manager.bucket, Key=key)
found[key] = True
except Exception:
found[key] = False
await storage_manager.close()
print(json.dumps(found))
asyncio.run(main())
"""
def put_objects(*keys: str) -> None:
container_json("janitor", PUT_OBJECTS.format(keys=list(keys)))
def existing_objects(*keys: str) -> dict[str, bool]:
return container_json("janitor", EXISTING_OBJECTS.format(keys=list(keys)))
def insert_pending(chat: dict, owner: dict, key: str, age_seconds: int) -> None:
"""Строка, какую оставляет падение API между PUT и подтверждением"""
psql(
f"""
INSERT INTO attachments
(chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, status, created_at, updated_at)
VALUES
('{chat["id"]}', '{owner["id"]}', 'crash.png', 'image/png', 1,
sha256('x'), '{key}', 'pending',
clock_timestamp() - make_interval(secs => {age_seconds}),
clock_timestamp());
"""
)
def row_status(key: str) -> str:
return psql(f"SELECT coalesce(max(status), 'absent') FROM attachments WHERE object_key = '{key}';")
def test_janitor_cleans_only_stale_unaccounted_data(
api: httpx.Client, make_user, make_chat, upload, send_attachments
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
ready = upload(alice, chat, png_bytes(12, 12))
linked = upload(alice, chat, png_bytes(13, 13))
assert send_attachments(alice, chat, [linked["id"]]).status_code == 201
run_id = uuid.uuid4().hex
crashed = f"originals/test-crashed-{run_id}"
crashed_no_object = f"originals/test-crashed-before-put-{run_id}"
orphan_old = f"originals/test-orphan-old-{run_id}"
fresh_pending = f"originals/test-fresh-pending-{run_id}"
orphan_fresh = f"originals/test-orphan-fresh-{run_id}"
# «Старые» сбои: строка старше grace по часам БД, объект — по времени ожидания.
# Возраст меньше grace фонового сервиса janitor (900 с): строки забирает
# только проход теста, без гонки с сервисом
insert_pending(chat, alice, crashed, age_seconds=STALE_ROW_AGE_SECONDS)
insert_pending(chat, alice, crashed_no_object, age_seconds=STALE_ROW_AGE_SECONDS)
put_objects(crashed, orphan_old)
time.sleep(GRACE_SECONDS + 2)
dry = run_janitor("--dry-run", "--grace-seconds", str(GRACE_SECONDS))
assert dry["unfinished_claimed"] >= 2 and dry["orphan_objects_found"] >= 1
assert existing_objects(crashed, orphan_old) == {crashed: True, orphan_old: True}
# «Свежие»: загрузка, которая могла бы ещё идти
insert_pending(chat, alice, fresh_pending, age_seconds=0)
put_objects(fresh_pending, orphan_fresh)
report = run_janitor("--grace-seconds", str(GRACE_SECONDS))
print("\nJANITOR REPORT:", json.dumps(report))
assert existing_objects(crashed, orphan_old, fresh_pending, orphan_fresh) == {
crashed: False,
orphan_old: False,
fresh_pending: True,
orphan_fresh: True,
}
assert row_status(crashed) == row_status(crashed_no_object) == "absent"
assert row_status(fresh_pending) == "pending"
# Готовые вложения (в том числе привязанные к сообщению) не тронуты
for attachment in (ready, linked):
response = api.get(
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)
)
assert response.status_code == 200
# Свежие данные становятся «старыми» и тоже убираются
time.sleep(GRACE_SECONDS + 1)
run_janitor("--grace-seconds", str(GRACE_SECONDS))
assert existing_objects(fresh_pending, orphan_fresh) == {
fresh_pending: False,
orphan_fresh: False,
}
assert row_status(fresh_pending) == "absent"
again = run_janitor("--dry-run", "--grace-seconds", str(GRACE_SECONDS))
assert again["orphan_objects_found"] == 0
INTERRUPTED_UPLOAD = """
import json, socket
body = {body!r}
request = (
"POST /api/v1/chats/{chat_id}/attachments?filename=cut.png HTTP/1.1\\r\\n"
"Host: api\\r\\n"
"Authorization: Bearer {token}\\r\\n"
"Content-Type: image/png\\r\\n"
"Content-Length: " + str(len(body)) + "\\r\\n\\r\\n"
).encode()
sent = 0
with socket.create_connection(("api", 8080), timeout=5) as connection:
connection.sendall(request)
connection.sendall(body[: len(body) // 3])
sent = len(body) // 3
print(json.dumps({{"sent": sent, "declared": len(body)}}))
"""
def test_interrupted_upload_leaves_nothing(make_user, make_chat) -> None:
"""Клиент оборвал соединение посреди тела, прямо к реплике API"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
body = list(png_bytes(400, 400, noise=True))
result = container_json(
"janitor",
INTERRUPTED_UPLOAD.format(
body=bytes(body), chat_id=chat["id"], token=alice["token"]
),
)
assert 0 < result["sent"] < result["declared"]
time.sleep(1)
rows = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{chat['id']}';")
assert rows == "0"
+99
View File
@@ -0,0 +1,99 @@
"""
Недоступность S3: контейнер s3 останавливается через docker compose
(volume сохраняется), затем запускается снова.
Ожидаемое поведение: загрузка и скачивание — быстрый 503 в формате контракта,
readiness — 503 (вложения входят в обязательный путь lab4), но метаданные
и сообщения продолжают работать: nginx не исключает реплики по readiness.
После восстановления незавершённых строк не остаётся: компенсация или
janitor их дочищают.
Запуск явно: make test-s3-failure (RUN_FAILURE_TESTS=1).
"""
import os
import time
import httpx
import pytest
from helpers import (
assert_error,
auth,
compose,
png_bytes,
psql,
run_janitor,
upload_raw,
)
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_FAILURE_TESTS") != "1",
reason="останавливает контейнер s3: запускайте через make test-s3-failure",
)
# connect timeout 2 с × 2 попытки + проверка изображения
BOUNDED_RESPONSE_SEC = 6
READY_TIMEOUT_SEC = 60
def unfinished_rows(chat_id: str) -> int:
return int(
psql(
f"SELECT count(*) FROM attachments "
f"WHERE chat_id = '{chat_id}' AND status <> 'ready';"
)
)
def wait_upload_works(api: httpx.Client, user: dict, chat_id: str) -> httpx.Response:
deadline = time.monotonic() + READY_TIMEOUT_SEC
while True:
response = upload_raw(api, user, chat_id, png_bytes())
if response.status_code == 201 or time.monotonic() > deadline:
return response
time.sleep(1)
def test_s3_outage_is_isolated_and_leaves_no_garbage(
api: httpx.Client, make_user, make_chat, upload, send_attachments
) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
before = upload(alice, chat)
compose("stop", "s3")
try:
started = time.monotonic()
failed_upload = upload_raw(api, alice, chat["id"], png_bytes(64, 64))
elapsed = time.monotonic() - started
assert_error(failed_upload, 503, "unavailable")
assert elapsed < BOUNDED_RESPONSE_SEC, elapsed
assert "s3" not in failed_upload.json()["error"]["message"].lower()
download = api.get(
f"/api/v1/attachments/{before['id']}/content", headers=auth(bob)
)
assert_error(download, 503, "unavailable")
# Путь без байтов S3 работает: метаданные и сообщения
metadata = api.get(f"/api/v1/attachments/{before['id']}", headers=auth(bob))
assert metadata.status_code == 200 and metadata.json() == before
message = send_attachments(alice, chat, [before["id"]], text="S3 лежит")
assert message.status_code == 201, message.text
assert api.get("/health/live").status_code == 200
started = time.monotonic()
assert_error(api.get("/health/ready"), 503, "unavailable")
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
finally:
compose("up", "-d", "--wait", "s3")
after = wait_upload_works(api, alice, chat["id"])
assert after.status_code == 201, after.text
content = api.get(f"/api/v1/attachments/{before['id']}/content", headers=auth(bob))
assert content.status_code == 200
# Компенсация не смогла удалить объект при лежащем S3: строка deleting
# дочищается janitor независимо от grace period
run_janitor()
assert unfinished_rows(chat["id"]) == 0
+157
View File
@@ -0,0 +1,157 @@
"""
Защита хранилища вне API: приватный bucket, ограниченные ключи API,
закрытые административные интерфейсы, идемпотентный bootstrap.
Проверки заходят внутрь контейнеров стенда (docker compose exec/run),
поэтому запускаются явно: make test-storage (RUN_STORAGE_TESTS=1).
"""
import json
import os
import subprocess
import httpx
import pytest
from helpers import ROOT, auth, compose, container_json
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_STORAGE_TESTS") != "1",
reason="заходит в контейнеры стенда: запускайте через make test-storage",
)
# Порты SeaweedFS кроме S3: master, volume, filer (HTTP с веб-интерфейсами
# и gRPC). Они слушают только loopback контейнера s3.
ADMIN_PORTS = (9333, 19333, 8080, 18080, 8888, 18888, 8181, 9101)
def test_anonymous_s3_access_is_denied(api: httpx.Client, make_user, make_chat, upload) -> None:
"""Прямой неподписанный GET объекта (ключ известен) и списка bucket — 403"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
object_key = compose(
"exec",
"-T",
"postgres",
"sh",
"-c",
'psql -X -q -tA -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c '
f"\"SELECT object_key FROM attachments WHERE id = '{attachment['id']}'\"",
).strip()
assert object_key.startswith("originals/")
result = container_json(
"api",
f"""
import json, urllib.error, urllib.request
from config import S3_BUCKET, S3_ENDPOINT
codes = {{}}
for name, path in {{
"object": "/" + S3_BUCKET + "/{object_key}",
"bucket_list": "/" + S3_BUCKET,
"service": "/",
}}.items():
try:
with urllib.request.urlopen(S3_ENDPOINT + path, timeout=3) as response:
codes[name] = response.status
except urllib.error.HTTPError as error:
codes[name] = error.code
print(json.dumps(codes))
""",
)
assert result == {"object": 403, "bucket_list": 403, "service": 403}
# Через API участник по-прежнему скачивает файл
content = api.get(f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice))
assert content.status_code == 200
def test_api_credentials_are_limited_to_own_bucket_objects() -> None:
"""Ключи API: объекты своего bucket — да; bucket, политика, ACL — нет"""
result = container_json(
"api",
"""
import asyncio, json
from infrastructure.dependencies import storage_manager
from infrastructure.utils import storage_error_code
async def attempt(name, call, results):
try:
await call
results[name] = "allowed"
except Exception as error:
results[name] = storage_error_code(error)
async def main():
s3 = await storage_manager.create_client()
bucket = storage_manager.bucket
key = "originals/security-probe"
policy = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Principal": "*", "Action": "s3:GetObject",
"Resource": "arn:aws:s3:::" + bucket + "/*"}]})
results = {}
await attempt("put_object", s3.put_object(Bucket=bucket, Key=key, Body=b"x"), results)
await attempt("get_object", s3.get_object(Bucket=bucket, Key=key), results)
await attempt("delete_object", s3.delete_object(Bucket=bucket, Key=key), results)
await attempt("create_bucket", s3.create_bucket(Bucket="intruder-bucket"), results)
await attempt("delete_bucket", s3.delete_bucket(Bucket=bucket), results)
await attempt("put_bucket_policy", s3.put_bucket_policy(Bucket=bucket, Policy=policy), results)
await attempt("put_bucket_acl", s3.put_bucket_acl(Bucket=bucket, ACL="public-read"), results)
await storage_manager.close()
print(json.dumps(results))
asyncio.run(main())
""",
)
assert result["put_object"] == result["get_object"] == "allowed"
assert result["delete_object"] == "allowed"
for forbidden in ("create_bucket", "delete_bucket", "put_bucket_policy", "put_bucket_acl"):
assert result[forbidden] == "AccessDenied", result
def test_api_container_has_no_admin_credentials() -> None:
files = compose("exec", "-T", "api", "ls", "/run/secrets").split()
assert sorted(files) == ["s3_access_key_id", "s3_secret_access_key"]
def test_admin_interfaces_are_not_reachable() -> None:
"""Из сети storage открыт только S3 API; наружу стенда S3 не опубликован"""
result = container_json(
"api",
f"""
import json, socket
state = {{}}
for port in (9000,) + {ADMIN_PORTS!r}:
try:
socket.create_connection(("s3", port), timeout=2).close()
state[port] = "open"
except OSError as error:
state[port] = type(error).__name__
print(json.dumps(state))
""",
)
assert result.pop("9000") == "open"
assert all(value != "open" for value in result.values()), result
for line in compose("ps", "--format", "json", "s3").splitlines():
publishers = json.loads(line)["Publishers"] or []
assert all(item["PublishedPort"] == 0 for item in publishers), publishers
def test_balancer_network_cannot_reach_storage() -> None:
"""nginx (сеть edge) не видит S3: клиентский трафик идёт только через API"""
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "exec", "-T", "nginx",
"wget", "-q", "-T", "2", "-O", "/dev/null", "http://s3:9000/"],
cwd=ROOT,
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode != 0
def test_bucket_bootstrap_is_idempotent() -> None:
for _ in range(2):
output = compose("run", "--rm", "--no-deps", "s3-bootstrap")
assert "уже существует" in output
assert "приватен" in output
+12
View File
@@ -0,0 +1,12 @@
"""
Unit-тесты слоя сервисов без стенда: зависимости заменены фейками интерфейсов.
Конфигурация берётся из .env.example; сеть, PostgreSQL и S3 не нужны.
"""
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
os.environ["ENV_FILE"] = str(ROOT / ".env.example")
sys.path.insert(0, str(ROOT / "src"))
+219
View File
@@ -0,0 +1,219 @@
"""
In-memory реализации интерфейсов с внедрением отказов.
fail — имена методов, которые бросают UnavailableError (как репозитории
при недоступной БД/S3); hang — методы, которые зависают.
"""
import asyncio
import io
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from typing import BinaryIO
from uuid import UUID, uuid4
from domain import (
AttachmentSchema,
AttachmentStatus,
ChatSchema,
NewAttachmentSchema,
PageKey,
StoredAttachmentSchema,
UnfinishedUploadSchema,
)
from domain.errors import UnavailableError
from interfaces import AttachmentRepository, ChatRepository, ObjectStorage, StoredObject
HANG_SEC = 3600
class FaultInjection:
def __init__(self) -> None:
self.fail: set[str] = set()
self.hang: set[str] = set()
self.calls: list[str] = []
async def _enter(self, name: str) -> None:
self.calls.append(name)
if name in self.hang:
await asyncio.sleep(HANG_SEC)
if name in self.fail:
raise UnavailableError()
class FakeChatRepository(ChatRepository):
"""Пользователь — участник любого чата, кроме перечисленных в foreign"""
def __init__(self) -> None:
self.foreign: set[UUID] = set()
async def create(self, title: str, created_by: UUID, member_ids: list[UUID]) -> ChatSchema:
raise NotImplementedError
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
if chat_id in self.foreign:
return None
return ChatSchema(
id=chat_id, title="chat", member_ids=[member_id], created_at=datetime.now(UTC)
)
async def list_for_member(
self, member_id: UUID, after: PageKey | None, limit: int
) -> list[ChatSchema]:
raise NotImplementedError
class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
def __init__(self) -> None:
super().__init__()
self.rows: dict[UUID, dict] = {}
self.ready_returns_none = False
def add_row(self, object_key: str, status: AttachmentStatus, age_seconds: float) -> UUID:
attachment_id = uuid4()
self.rows[attachment_id] = {
"status": status,
"object_key": object_key,
"created_at": datetime.now(UTC) - timedelta(seconds=age_seconds),
"new": None,
}
return attachment_id
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
await self._enter("create_pending")
attachment_id = self.add_row(attachment.object_key, AttachmentStatus.PENDING, 0)
self.rows[attachment_id]["new"] = attachment
return attachment_id
async def mark_ready(self, attachment_id: UUID, grace_seconds: int) -> AttachmentSchema | None:
await self._enter("mark_ready")
row = self.rows.get(attachment_id)
if self.ready_returns_none or row is None or row["status"] != AttachmentStatus.PENDING:
return None
if row["created_at"] <= datetime.now(UTC) - timedelta(seconds=grace_seconds):
return None
row["status"] = AttachmentStatus.READY
new: NewAttachmentSchema = row["new"]
return AttachmentSchema(
id=attachment_id,
chat_id=new.chat_id,
owner_id=new.owner_id,
filename=new.filename,
content_type=new.content_type,
size_bytes=new.size_bytes,
sha256=new.sha256.hex(),
created_at=row["created_at"],
updated_at=datetime.now(UTC),
)
async def claim_pending(self, attachment_id: UUID) -> UnfinishedUploadSchema | None:
await self._enter("claim_pending")
row = self.rows.get(attachment_id)
if row is None or row["status"] != AttachmentStatus.PENDING:
return None
row["status"] = AttachmentStatus.DELETING
return UnfinishedUploadSchema(id=attachment_id, object_key=row["object_key"])
def _unfinished(self, grace_seconds: int) -> list[UUID]:
threshold = datetime.now(UTC) - timedelta(seconds=grace_seconds)
return [
attachment_id
for attachment_id, row in self.rows.items()
if row["status"] == AttachmentStatus.DELETING
or (row["status"] == AttachmentStatus.PENDING and row["created_at"] < threshold)
]
async def claim_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
await self._enter("claim_unfinished")
# Повторный вызов в том же проходе не должен возвращать те же строки
claimed = [
attachment_id
for attachment_id in self._unfinished(grace_seconds)
if not self.rows[attachment_id].get("claimed_now")
][:limit]
for attachment_id in claimed:
self.rows[attachment_id]["status"] = AttachmentStatus.DELETING
self.rows[attachment_id]["claimed_now"] = True
return [
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"]) for i in claimed
]
async def list_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
await self._enter("list_unfinished")
return [
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
for i in self._unfinished(grace_seconds)[:limit]
]
async def delete_claimed(self, attachment_ids: list[UUID]) -> int:
await self._enter("delete_claimed")
deleted = [
i
for i in attachment_ids
if i in self.rows and self.rows[i]["status"] == AttachmentStatus.DELETING
]
for attachment_id in deleted:
del self.rows[attachment_id]
return len(deleted)
async def get_for_member(
self, attachment_id: UUID, member_id: UUID
) -> StoredAttachmentSchema | None:
raise NotImplementedError
async def find_known_keys(self, object_keys: list[str]) -> set[str]:
await self._enter("find_known_keys")
known = {row["object_key"] for row in self.rows.values()}
return {key for key in object_keys if key in known}
def statuses(self) -> list[str]:
return sorted(row["status"] for row in self.rows.values())
class FakeStoredObject(StoredObject):
def __init__(self, data: bytes) -> None:
self._data = data
self.content_length = len(data)
async def iter_chunks(self) -> AsyncIterator[bytes]:
yield self._data
async def close(self) -> None:
pass
class FakeObjectStorage(FaultInjection, ObjectStorage):
def __init__(self) -> None:
super().__init__()
self.objects: dict[str, tuple[bytes, datetime]] = {}
def add_object(self, key: str, age_seconds: float) -> None:
self.objects[key] = (b"x", datetime.now(UTC) - timedelta(seconds=age_seconds))
async def put(
self, key: str, body: BinaryIO, size: int, content_type: str, sha256: bytes
) -> None:
# Как S3: объект появляется до того, как вызывающий получит ответ
self.objects[key] = (body.read(), datetime.now(UTC))
await self._enter("put")
async def open(self, key: str) -> StoredObject | None:
await self._enter("open")
stored = self.objects.get(key)
return FakeStoredObject(stored[0]) if stored else None
async def delete(self, key: str) -> None:
await self._enter("delete")
self.objects.pop(key, None)
async def list_objects(self, prefix: str) -> AsyncIterator[tuple[str, datetime]]:
await self._enter("list_objects")
for key, (_, modified_at) in list(self.objects.items()):
if key.startswith(prefix):
yield key, modified_at
async def chunks_of(data: bytes, size: int = 64 * 1024) -> AsyncIterator[bytes]:
stream = io.BytesIO(data)
while chunk := stream.read(size):
yield chunk
@@ -0,0 +1,261 @@
"""
Согласованность S3 и БД при загрузке: любой отказ после записи строки
не оставляет неучтённых объектов — компенсация сразу или janitor позже.
"""
import asyncio
import hashlib
import io
from collections.abc import AsyncIterator
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from fakes import (
FakeAttachmentRepository,
FakeChatRepository,
FakeObjectStorage,
chunks_of,
)
from PIL import Image
from domain import (
AttachmentStatus,
AttachmentVariant,
StoredAttachmentSchema,
UserSchema,
)
from domain.errors import (
InvalidRequestError,
NotFoundError,
PayloadTooLargeError,
UnavailableError,
UnsupportedMediaTypeError,
)
from infrastructure.media import ImageInspector
from infrastructure.services import AttachmentService, StorageReconciler
MAX_BYTES = 1024 * 1024
GRACE_SECONDS = 900
USER = UserSchema(
id=uuid4(), username="alice", display_name="Алиса", created_at=datetime.now(UTC)
)
def png(width: int = 8, height: int = 8) -> bytes:
buffer = io.BytesIO()
Image.new("RGB", (width, height), (1, 2, 3)).save(buffer, "PNG")
return buffer.getvalue()
class Stand:
"""Сервис с фейками; inspector настоящий"""
def __init__(self, store_timeout: float = 5) -> None:
self.chats = FakeChatRepository()
self.attachments = FakeAttachmentRepository()
self.storage = FakeObjectStorage()
self.inspector = ImageInspector(workers=1, max_pixels=1_000_000)
self.service = AttachmentService(
self.chats,
self.attachments,
self.storage,
self.inspector,
max_upload_bytes=MAX_BYTES,
spool_memory_bytes=1024,
store_timeout_seconds=store_timeout,
pending_grace_seconds=GRACE_SECONDS,
)
async def upload(self, data: bytes | None = None, content_type: str = "image/png"):
data = data if data is not None else png()
return await self.service.upload(
USER, uuid4(), "a.png", content_type, len(data), chunks_of(data, 100)
)
async def reconcile(self, grace_seconds: int = GRACE_SECONDS):
reconciler = StorageReconciler(self.attachments, self.storage, grace_seconds)
return await reconciler.run_once()
def run(coro):
return asyncio.run(coro)
def test_success_stores_object_and_ready_row() -> None:
stand = Stand()
data = png()
attachment = run(stand.upload(data))
assert attachment.sha256 == hashlib.sha256(data).hexdigest()
assert stand.attachments.statuses() == [AttachmentStatus.READY]
[(stored, _)] = stand.storage.objects.values()
assert stored == data
[key] = stand.storage.objects
assert key.startswith("originals/") and "a.png" not in key
# Строка записана до PUT, подтверждена после
assert stand.attachments.calls[:2] == ["create_pending", "mark_ready"]
def test_s3_failure_after_write_is_compensated() -> None:
"""PUT дошёл до S3, но ответ — ошибка: объект удаляется, строка тоже"""
stand = Stand()
stand.storage.fail.add("put")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {}
assert stand.attachments.rows == {}
def test_db_failure_between_s3_and_commit_is_compensated() -> None:
"""Объект записан в S3, подтверждение в БД не прошло"""
stand = Stand()
stand.attachments.fail.add("mark_ready")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {}
assert stand.attachments.rows == {}
def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
"""
БД пропала после PUT: ни подтвердить, ни компенсировать. Объект учтён
строкой pending; janitor после grace period удаляет и объект, и строку.
"""
stand = Stand()
stand.attachments.fail.update({"mark_ready", "claim_pending"})
with pytest.raises(UnavailableError):
run(stand.upload())
assert len(stand.storage.objects) == 1
assert stand.attachments.statuses() == [AttachmentStatus.PENDING]
stand.attachments.fail.clear()
fresh = run(stand.reconcile(GRACE_SECONDS))
assert fresh.unfinished_claimed == 0, "свежая загрузка не трогается"
assert len(stand.storage.objects) == 1
report = run(stand.reconcile(grace_seconds=0))
assert report.unfinished_objects_deleted == report.unfinished_rows_deleted == 1
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_s3_down_during_compensation_leaves_deleting_row_for_janitor() -> None:
stand = Stand()
stand.attachments.fail.add("mark_ready")
stand.storage.fail.add("delete")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.attachments.statuses() == [AttachmentStatus.DELETING]
assert len(stand.storage.objects) == 1
stand.storage.fail.clear()
# deleting очищается независимо от возраста
report = run(stand.reconcile(GRACE_SECONDS))
assert report.unfinished_rows_deleted == 1
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_store_timeout_is_compensated() -> None:
stand = Stand(store_timeout=0.2)
stand.storage.hang.add("put")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_cancelled_upload_is_compensated() -> None:
"""Остановка реплики посреди PUT: задача отменяется, компенсация выполняется"""
stand = Stand()
stand.storage.hang.add("put")
async def scenario() -> None:
task = asyncio.create_task(stand.upload())
while "put" not in stand.storage.calls:
await asyncio.sleep(0.01)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
run(scenario())
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_upload_claimed_by_janitor_is_not_confirmed() -> None:
stand = Stand()
stand.attachments.ready_returns_none = True
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_validation_errors_store_nothing() -> None:
stand = Stand()
cases = [
(png(), "image/jpeg", UnsupportedMediaTypeError),
(b"not an image", "image/png", UnsupportedMediaTypeError),
(png()[:40], "image/png", UnsupportedMediaTypeError),
(png(2000, 1000), "image/png", PayloadTooLargeError),
(b"", "image/png", InvalidRequestError),
]
for data, content_type, error in cases:
with pytest.raises(error):
run(stand.upload(data, content_type))
assert stand.storage.objects == {} and stand.attachments.rows == {}
assert "create_pending" not in stand.attachments.calls
def test_declared_length_over_limit_is_rejected_without_reading() -> None:
stand = Stand()
consumed = []
async def body() -> AsyncIterator[bytes]:
consumed.append(True)
yield b"x"
with pytest.raises(PayloadTooLargeError):
run(
stand.service.upload(
USER, uuid4(), "a.png", "image/png", MAX_BYTES + 1, body()
)
)
assert consumed == []
def test_streamed_body_over_limit_stops_reading() -> None:
"""Без Content-Length чтение обрывается на первом байте сверх лимита"""
stand = Stand()
chunks_read = 0
async def endless() -> AsyncIterator[bytes]:
nonlocal chunks_read
while True:
chunks_read += 1
yield b"\x00" * 64 * 1024
with pytest.raises(PayloadTooLargeError):
run(stand.service.upload(USER, uuid4(), "a.png", "image/png", None, endless()))
assert chunks_read == MAX_BYTES // (64 * 1024) + 1
def test_foreign_chat_is_404_before_reading_body() -> None:
stand = Stand()
chat_id = uuid4()
stand.chats.foreign.add(chat_id)
with pytest.raises(NotFoundError):
run(stand.service.upload(USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")))
def test_missing_variant_is_404() -> None:
stand = Stand()
attachment = run(stand.upload())
async def get_for_member(attachment_id, member_id):
[key] = stand.storage.objects
return StoredAttachmentSchema(attachment=attachment, object_key=key)
stand.attachments.get_for_member = get_for_member
_, content = run(
stand.service.open_content(USER, attachment.id, AttachmentVariant.ORIGINAL)
)
assert content.content_length == attachment.size_bytes
with pytest.raises(NotFoundError):
run(stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL))
@@ -0,0 +1,96 @@
"""
Janitor: незавершённые загрузки и сироты удаляются только после grace period;
готовые и свежие вложения не трогаются; dry-run ничего не меняет.
"""
import asyncio
import pytest
from fakes import FakeAttachmentRepository, FakeObjectStorage
from domain import AttachmentStatus
from domain.errors import UnavailableError
from infrastructure.services import StorageReconciler
GRACE = 600
OLD = 3600
FRESH = 1
def build() -> tuple[FakeAttachmentRepository, FakeObjectStorage]:
rows, storage = FakeAttachmentRepository(), FakeObjectStorage()
cases = {
"originals/ready-old": (AttachmentStatus.READY, OLD),
"originals/ready-fresh": (AttachmentStatus.READY, FRESH),
"originals/pending-old": (AttachmentStatus.PENDING, OLD),
"originals/pending-fresh": (AttachmentStatus.PENDING, FRESH),
"originals/deleting-fresh": (AttachmentStatus.DELETING, FRESH),
}
for key, (status, age) in cases.items():
rows.add_row(key, status, age)
storage.add_object(key, age)
# pending без объекта: процесс упал до PUT
rows.add_row("originals/pending-no-object", AttachmentStatus.PENDING, OLD)
storage.add_object("originals/orphan-old", OLD)
storage.add_object("originals/orphan-fresh", FRESH)
storage.add_object("other/not-ours", OLD)
return rows, storage
def run(rows, storage, dry_run: bool = False):
return asyncio.run(StorageReconciler(rows, storage, GRACE).run_once(dry_run))
def test_reconcile_removes_only_stale_unaccounted_data() -> None:
rows, storage = build()
report = run(rows, storage)
assert sorted(storage.objects) == [
"originals/orphan-fresh",
"originals/pending-fresh",
"originals/ready-fresh",
"originals/ready-old",
"other/not-ours",
]
assert sorted(row["object_key"] for row in rows.rows.values()) == [
"originals/pending-fresh",
"originals/ready-fresh",
"originals/ready-old",
]
assert report.unfinished_claimed == 3
assert report.unfinished_rows_deleted == 3
assert report.orphan_objects_found == report.orphan_objects_deleted == 1
def test_dry_run_changes_nothing() -> None:
rows, storage = build()
before_rows = {k: dict(v) for k, v in rows.rows.items()}
before_objects = dict(storage.objects)
report = run(rows, storage, dry_run=True)
assert rows.rows == before_rows and storage.objects == before_objects
assert report.unfinished_claimed == 3 and report.orphan_objects_found == 1
assert report.orphan_objects_deleted == 0
def test_second_run_is_noop() -> None:
rows, storage = build()
run(rows, storage)
report = run(rows, storage)
assert report.unfinished_claimed == 0 and report.orphan_objects_found == 0
def test_interrupted_cleanup_is_resumed() -> None:
"""S3 упал после claim: строки остаются deleting и дочищаются в следующий раз"""
rows, storage = build()
storage.fail.add("delete")
with pytest.raises(UnavailableError):
run(rows, storage)
assert AttachmentStatus.PENDING not in [
row["status"] for row in rows.rows.values() if "old" in row["object_key"]
]
storage.fail.clear()
for row in rows.rows.values():
row.pop("claimed_now", None)
run(rows, storage)
assert not any("old" in key and "ready" not in key for key in storage.objects)
assert all(row["status"] != AttachmentStatus.DELETING for row in rows.rows.values())