forked from mtusi2026/mtusi2026lab4
Уровень 3: - код lab3 перенесён; MinIO (сборка релиза 2025-10-15, по digest) в общем Compose, идемпотентный bootstrap: приватные bucket, отдельный пользователь API с ограниченной политикой - метаданные вложений в PostgreSQL (миграции 0003, 0004), байты в S3; ключ назначает сервер - upload PNG/JPEG: лимиты до чтения/декодирования, MIME по содержимому, проверка целостности, безопасный filename; 201 только после PUT и COMMIT; download потоком через API - attachment_ids в сообщениях (только файлы своего чата, FK в БД) - 503 API больше не повторяется в HAProxy (отказ общей зависимости), S3 не входит в readiness Уровень 4: - 45 тестов вложений: размер, повреждение, подмена MIME, чужой id, файл другого чата, отказы S3/БД - компенсация при сбое COMMIT; слоты загрузки (8 на реплику) против неограниченной памяти - эксперименты: пик RAM при 10-40 одновременных загрузках, оборванная загрузка и сироты; исправлены удержание соединения БД во время загрузки и таймаут отправки в S3 Уровень 5, трек 2: - reconciler: слияние листинга S3 и курсора БД, 7 категорий расхождений, dry-run, grace period, перепроверка перед действием, тормоз --max-deletes, advisory lock; сервис reconciler в Compose - 8 тестов сверки; эксперимент с 70 внедрёнными ошибками на 10 000 объектах (точное обнаружение, безопасное исправление, идемпотентность) и замер стоимости обхода на 1k/10k/50k
356 lines
18 KiB
Python
356 lines
18 KiB
Python
"""Вложения: загрузка, скачивание, негативные сценарии, отказ S3/БД и очистка объектов-сирот.
|
|
|
|
Нужны запущенные postgres и minio (docker compose up). Объекты пишутся в отдельный bucket
|
|
messenger-attachments-test, метаданные — в базу messenger_test.
|
|
"""
|
|
import asyncio
|
|
import hashlib
|
|
import io
|
|
import struct
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
import zlib
|
|
|
|
import pytest
|
|
from minio.error import S3Error
|
|
from PIL import Image
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.exc import IntegrityError, OperationalError
|
|
|
|
from api.v1 import attachments_rout
|
|
from conftest import assert_error, with_key
|
|
from core import s3
|
|
from core.config import settings
|
|
from core.db import SessionLocal
|
|
from maintenance.reconcile import reconcile
|
|
from models import Attachment, MessageAttachment
|
|
|
|
|
|
def make_image(fmt="PNG", size=(64, 48), color=(10, 200, 30)) -> bytes:
|
|
buffer = io.BytesIO()
|
|
Image.new("RGB", size, color).save(buffer, fmt)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def png_header_only(width: int, height: int) -> bytes:
|
|
"""Корректный по структуре PNG, который заявляет огромные размеры, но почти ничего не содержит."""
|
|
def chunk(kind: bytes, data: bytes) -> bytes:
|
|
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
|
|
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"\x00" * 16)) + chunk(b"IEND", b"")
|
|
|
|
|
|
PNG = make_image("PNG")
|
|
JPEG = make_image("JPEG", size=(320, 200))
|
|
|
|
|
|
def upload(client, user, chat_id, data, content_type="image/png", filename="photo.png"):
|
|
return client.post(f"/api/v1/chats/{chat_id}/attachments", params={"filename": filename}, content=data,
|
|
headers={**user["auth"], "Content-Type": content_type})
|
|
|
|
|
|
def attachments_in_db() -> int:
|
|
with SessionLocal() as db:
|
|
return db.scalar(select(func.count()).select_from(Attachment))
|
|
|
|
|
|
def objects_in_bucket() -> list[str]:
|
|
return [stored.key for stored in s3.list_objects("")]
|
|
|
|
|
|
def send_message(client, user, chat_id, body, key=None):
|
|
return client.post(f"/api/v1/chats/{chat_id}/messages", headers=with_key(user["auth"], key), json=body)
|
|
|
|
|
|
# --- Успешный путь ---
|
|
|
|
def test_upload_png_and_download_by_other_member(client, alice, bob, chat):
|
|
response = upload(client, alice, chat["id"], PNG)
|
|
assert response.status_code == 201
|
|
attachment = response.json()
|
|
assert attachment["status"] == "ready" and attachment["variants"] == [] and attachment["error_code"] is None
|
|
assert attachment["chat_id"] == chat["id"] and attachment["owner_id"] == alice["id"]
|
|
assert attachment["sha256"] == hashlib.sha256(PNG).hexdigest() and attachment["size_bytes"] == len(PNG)
|
|
assert attachment["content_type"] == "image/png" and attachment["filename"] == "photo.png"
|
|
# Внутренний ключ S3 наружу не отдаётся; ключ назначен сервером, имя файла в него не входит.
|
|
assert "object_key" not in attachment
|
|
assert objects_in_bucket() == [f"originals/{attachment['id']}"]
|
|
|
|
assert client.get(f"/api/v1/attachments/{attachment['id']}", headers=bob["auth"]).json() == attachment
|
|
content = client.get(f"/api/v1/attachments/{attachment['id']}/content", headers=bob["auth"])
|
|
assert content.status_code == 200
|
|
assert content.content == PNG
|
|
assert content.headers["content-type"] == "image/png"
|
|
|
|
|
|
def test_upload_jpeg_with_unicode_filename(client, alice, chat):
|
|
response = upload(client, alice, chat["id"], JPEG, "image/jpeg", "фото отпуск.jpg")
|
|
assert response.status_code == 201
|
|
assert response.json()["filename"] == "фото отпуск.jpg"
|
|
content = client.get(f"/api/v1/attachments/{response.json()['id']}/content", headers=alice["auth"])
|
|
assert content.content == JPEG and content.headers["content-type"] == "image/jpeg"
|
|
|
|
|
|
def test_message_with_attachments_keeps_order_and_is_readable(client, alice, bob, chat):
|
|
first = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
second = upload(client, alice, chat["id"], JPEG, "image/jpeg").json()["id"]
|
|
response = send_message(client, alice, chat["id"], {"text": "", "attachment_ids": [second, first]})
|
|
assert response.status_code == 201
|
|
assert response.json()["attachment_ids"] == [second, first]
|
|
history = client.get(f"/api/v1/chats/{chat['id']}/messages", headers=bob["auth"]).json()
|
|
assert history["items"][0]["attachment_ids"] == [second, first]
|
|
|
|
|
|
def test_missing_attachment_ids_equals_empty_list_for_idempotency(client, alice, chat):
|
|
key = uuid.uuid4().hex
|
|
first = send_message(client, alice, chat["id"], {"text": "привет"}, key)
|
|
replay = send_message(client, alice, chat["id"], {"attachment_ids": [], "text": "привет"}, key)
|
|
assert first.status_code == replay.status_code == 201
|
|
assert replay.json() == first.json() and first.json()["attachment_ids"] == []
|
|
|
|
|
|
# --- Размер, повреждение, подмена MIME, пиксели ---
|
|
|
|
def test_too_large_file_is_rejected_before_reading(client, alice, chat):
|
|
too_large = PNG + b"\x00" * settings.attachments.max_bytes
|
|
assert_error(upload(client, alice, chat["id"], too_large), 413, "payload_too_large")
|
|
assert attachments_in_db() == 0 and objects_in_bucket() == []
|
|
|
|
|
|
def test_too_large_stream_without_content_length(client, alice, chat):
|
|
# Без Content-Length сервер считает фактические байты и обрывает чтение на лимите.
|
|
def chunks():
|
|
yield PNG
|
|
for _ in range(11):
|
|
yield b"\x00" * (1024 * 1024)
|
|
response = client.post(f"/api/v1/chats/{chat['id']}/attachments", params={"filename": "big.png"},
|
|
content=chunks(), headers={**alice["auth"], "Content-Type": "image/png"})
|
|
assert_error(response, 413, "payload_too_large")
|
|
assert attachments_in_db() == 0
|
|
|
|
|
|
def test_exactly_max_bytes_is_accepted(client, alice, chat):
|
|
# Граница включительно: ровно 10 MiB (PNG + данные после IEND, которые декодеры игнорируют).
|
|
data = PNG + b"\x00" * (settings.attachments.max_bytes - len(PNG))
|
|
response = upload(client, alice, chat["id"], data)
|
|
assert response.status_code == 201 and response.json()["size_bytes"] == settings.attachments.max_bytes
|
|
|
|
|
|
def test_pixel_limit_checked_from_header(client, alice, chat):
|
|
# 10000 x 5000 = 50 млн пикселей при размере файла ~100 байт: отказ до распаковки.
|
|
assert_error(upload(client, alice, chat["id"], png_header_only(10000, 5000)), 413, "payload_too_large")
|
|
|
|
|
|
def broken_crc(data: bytes) -> bytes:
|
|
position = data.index(b"IDAT") + 6
|
|
return data[:position] + bytes([data[position] ^ 0xFF]) + data[position + 1:]
|
|
|
|
|
|
@pytest.mark.parametrize("data,content_type", [
|
|
(PNG[: len(PNG) // 2], "image/png"), # обрезанный PNG
|
|
(broken_crc(PNG), "image/png"), # испорченный байт в данных
|
|
(JPEG[: len(JPEG) // 3], "image/jpeg"), # обрезанный JPEG
|
|
(b"\x89PNG\r\n\x1a\n" + b"\x00" * 64, "image/png"), # только сигнатура
|
|
(b"not an image at all", "image/png"),
|
|
], ids=["truncated-png", "png-bad-crc", "truncated-jpeg", "png-signature-only", "text"])
|
|
def test_corrupted_image_is_415(client, alice, chat, data, content_type):
|
|
assert_error(upload(client, alice, chat["id"], data, content_type), 415, "unsupported_media_type")
|
|
assert attachments_in_db() == 0 and objects_in_bucket() == []
|
|
|
|
|
|
@pytest.mark.parametrize("data,content_type", [
|
|
(PNG, "image/jpeg"),
|
|
(JPEG, "image/png"),
|
|
(PNG, "text/plain"),
|
|
(PNG, "image/gif"),
|
|
(b"GIF89a" + b"\x00" * 32, "image/png"),
|
|
], ids=["png-as-jpeg", "jpeg-as-png", "png-as-text", "png-as-gif", "gif-as-png"])
|
|
def test_mime_spoofing_is_415(client, alice, chat, data, content_type):
|
|
assert_error(upload(client, alice, chat["id"], data, content_type), 415, "unsupported_media_type")
|
|
|
|
|
|
def test_empty_body_is_400(client, alice, chat):
|
|
assert_error(upload(client, alice, chat["id"], b""), 400, "invalid_request")
|
|
|
|
|
|
@pytest.mark.parametrize("filename", ["a/b.png", "..\\evil.png", "a\x00b.png", "line\nbreak.png", "tab\t.png",
|
|
" ", "..", "x" * 256])
|
|
def test_dangerous_filename_is_400(client, alice, chat, filename):
|
|
assert_error(upload(client, alice, chat["id"], PNG, filename=filename), 400, "invalid_request")
|
|
assert objects_in_bucket() == []
|
|
|
|
|
|
def test_missing_filename_is_400(client, alice, chat):
|
|
response = client.post(f"/api/v1/chats/{chat['id']}/attachments", content=PNG,
|
|
headers={**alice["auth"], "Content-Type": "image/png"})
|
|
assert_error(response, 400, "invalid_request")
|
|
|
|
|
|
# --- Доступ: чужой чат, чужое attachment_id, файл другого чата ---
|
|
|
|
def test_outsider_cannot_upload_or_read(client, alice, eve, chat):
|
|
assert_error(upload(client, eve, chat["id"], PNG), 404, "not_found")
|
|
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
assert_error(client.get(f"/api/v1/attachments/{attachment_id}", headers=eve["auth"]), 404, "not_found")
|
|
assert_error(client.get(f"/api/v1/attachments/{attachment_id}/content", headers=eve["auth"]), 404, "not_found")
|
|
|
|
|
|
def test_unknown_and_unauthenticated(client, alice, chat):
|
|
unknown = uuid.uuid4()
|
|
assert_error(client.get(f"/api/v1/attachments/{unknown}", headers=alice["auth"]), 404, "not_found")
|
|
assert_error(client.get(f"/api/v1/attachments/{unknown}/content", headers=alice["auth"]), 404, "not_found")
|
|
response = client.post(f"/api/v1/chats/{chat['id']}/attachments", params={"filename": "a.png"}, content=PNG,
|
|
headers={"Content-Type": "image/png"})
|
|
assert_error(response, 401, "unauthorized")
|
|
assert_error(client.get(f"/api/v1/attachments/{unknown}", headers={}), 401, "unauthorized")
|
|
|
|
|
|
def test_missing_variant_is_404_and_bad_variant_is_400(client, alice, chat):
|
|
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
path = f"/api/v1/attachments/{attachment_id}/content"
|
|
assert_error(client.get(path, params={"variant": "thumbnail"}, headers=alice["auth"]), 404, "not_found")
|
|
assert_error(client.get(path, params={"variant": "huge"}, headers=alice["auth"]), 400, "invalid_request")
|
|
|
|
|
|
def test_foreign_attachment_id_in_message_is_404(client, alice, bob, eve, chat):
|
|
# Файл из чата alice+eve нельзя прикрепить к сообщению в чате alice+bob, хотя alice состоит в обоих.
|
|
other_chat = client.post("/api/v1/chats", headers=alice["auth"],
|
|
json={"title": "другой", "member_ids": [alice["id"], eve["id"]]}).json()
|
|
foreign = upload(client, alice, other_chat["id"], PNG).json()["id"]
|
|
key = uuid.uuid4().hex
|
|
assert_error(send_message(client, alice, chat["id"], {"text": "", "attachment_ids": [foreign]}, key),
|
|
404, "not_found")
|
|
assert_error(send_message(client, bob, chat["id"], {"text": "x", "attachment_ids": [str(uuid.uuid4())]}),
|
|
404, "not_found")
|
|
assert client.get(f"/api/v1/chats/{chat['id']}/messages", headers=alice["auth"]).json()["items"] == []
|
|
# Отказ не «занял» ключ: исправленный запрос с тем же ключом проходит.
|
|
own = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
assert send_message(client, alice, chat["id"], {"text": "", "attachment_ids": [own]}, key).status_code == 201
|
|
|
|
|
|
def test_database_rejects_link_to_attachment_of_other_chat(client, alice, eve, chat):
|
|
other_chat = client.post("/api/v1/chats", headers=alice["auth"],
|
|
json={"title": "другой", "member_ids": [alice["id"], eve["id"]]}).json()
|
|
foreign = upload(client, alice, other_chat["id"], PNG).json()["id"]
|
|
message_id = send_message(client, alice, chat["id"], {"text": "hi"}).json()["id"]
|
|
with SessionLocal() as db, pytest.raises(IntegrityError):
|
|
db.add(MessageAttachment(message_id=message_id, attachment_id=foreign, chat_id=chat["id"], position=0))
|
|
db.commit()
|
|
|
|
|
|
@pytest.mark.parametrize("body", [
|
|
{"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]},
|
|
{"text": " "},
|
|
{"text": "", "attachment_ids": []},
|
|
{"text": "x", "attachment_ids": ["not-a-uuid"]},
|
|
], ids=["11-ids", "blank-text", "empty-without-attachments", "bad-uuid"])
|
|
def test_invalid_message_attachments_are_400(client, alice, chat, body):
|
|
assert_error(send_message(client, alice, chat["id"], body), 400, "invalid_request")
|
|
|
|
|
|
def test_duplicate_attachment_ids_are_400(client, alice, chat):
|
|
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
body = {"text": "", "attachment_ids": [attachment_id, attachment_id]}
|
|
assert_error(send_message(client, alice, chat["id"], body), 400, "invalid_request")
|
|
|
|
|
|
# --- Отказы S3 и БД, компенсация и очистка сирот ---
|
|
|
|
def test_storage_down_on_upload_is_503_without_metadata(client, alice, chat, monkeypatch):
|
|
def fail(*args, **kwargs):
|
|
raise s3.StorageUnavailable()
|
|
monkeypatch.setattr(s3, "put_object", fail)
|
|
assert_error(upload(client, alice, chat["id"], PNG), 503, "unavailable")
|
|
assert attachments_in_db() == 0
|
|
|
|
|
|
def test_storage_down_on_download_is_503(client, alice, chat, monkeypatch):
|
|
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
|
|
def fail(*args, **kwargs):
|
|
raise s3.StorageUnavailable()
|
|
monkeypatch.setattr(s3, "open_object", fail)
|
|
assert_error(client.get(f"/api/v1/attachments/{attachment_id}/content", headers=alice["auth"]), 503, "unavailable")
|
|
|
|
|
|
def db_commit_fails(*args, **kwargs):
|
|
raise OperationalError("INSERT INTO attachments", {}, Exception("connection lost"))
|
|
|
|
|
|
def test_commit_failure_after_put_deletes_object(client, alice, chat, monkeypatch):
|
|
# PUT в S3 прошёл, COMMIT — нет: API сразу удаляет объект (компенсация).
|
|
monkeypatch.setattr(attachments_rout, "create_attachment", db_commit_fails)
|
|
assert_error(upload(client, alice, chat["id"], PNG), 503, "unavailable")
|
|
assert attachments_in_db() == 0
|
|
assert objects_in_bucket() == []
|
|
|
|
|
|
def test_orphan_left_by_failed_compensation_is_removed_only_after_grace(client, alice, bob, chat, monkeypatch):
|
|
# Используемое вложение и прикреплённое к сообщению — не должны пострадать.
|
|
kept = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
send_message(client, alice, chat["id"], {"text": "", "attachment_ids": [kept]})
|
|
|
|
# COMMIT не прошёл, и удалить объект тоже не удалось (S3 «моргнул»): остаётся сирота.
|
|
monkeypatch.setattr(attachments_rout, "create_attachment", db_commit_fails)
|
|
|
|
def delete_fails(key):
|
|
raise s3.StorageUnavailable()
|
|
monkeypatch.setattr(s3, "delete_object", delete_fails)
|
|
assert_error(upload(client, bob, chat["id"], JPEG, "image/jpeg"), 503, "unavailable")
|
|
monkeypatch.undo()
|
|
assert attachments_in_db() == 1 and len(objects_in_bucket()) == 2
|
|
|
|
with SessionLocal() as db:
|
|
# Свежая сирота может принадлежать загрузке «между PUT и COMMIT» — не трогаем.
|
|
fresh = reconcile(db, apply=True, grace_seconds=3600)
|
|
assert fresh["issues"]["orphan_object_fresh"] == 1 and fresh["ok"] == 1
|
|
assert fresh["actions"]["objects_deleted"] == 0
|
|
# Dry-run показывает, но не удаляет.
|
|
dry = reconcile(db, apply=False, grace_seconds=0)
|
|
assert dry["issues"]["orphan_object"] == 1 and len(objects_in_bucket()) == 2
|
|
applied = reconcile(db, apply=True, grace_seconds=0)
|
|
assert applied["actions"]["objects_deleted"] == 1
|
|
# Повторный запуск ничего не находит.
|
|
again = reconcile(db, apply=True, grace_seconds=0)
|
|
assert sum(again["issues"].values()) == 0 and again["ok"] == 1
|
|
|
|
assert objects_in_bucket() == [f"originals/{kept}"]
|
|
content = client.get(f"/api/v1/attachments/{kept}/content", headers=bob["auth"])
|
|
assert content.status_code == 200 and content.content == PNG
|
|
|
|
|
|
def test_upload_slots_exhausted_is_503(client, alice, chat, monkeypatch):
|
|
monkeypatch.setattr(attachments_rout, "upload_slots", asyncio.Semaphore(0))
|
|
monkeypatch.setattr(settings.attachments, "slot_wait_seconds", 0.1)
|
|
response = upload(client, alice, chat["id"], PNG)
|
|
assert_error(response, 503, "unavailable")
|
|
assert response.headers["Retry-After"] == "1"
|
|
|
|
|
|
# --- Приватность bucket и права credentials API (проверки вне API) ---
|
|
|
|
def anonymous_get(url):
|
|
try:
|
|
with urllib.request.urlopen(url, timeout=5) as response:
|
|
return response.status
|
|
except urllib.error.HTTPError as exc:
|
|
return exc.code
|
|
|
|
|
|
def test_bucket_is_private_outside_api(client, alice, chat):
|
|
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
|
|
base = f"{settings.s3.endpoint}/{settings.s3.bucket}"
|
|
assert anonymous_get(f"{base}/originals/{attachment_id}") == 403
|
|
assert anonymous_get(f"{base}?list-type=2") == 403
|
|
|
|
|
|
def test_api_credentials_cannot_administer_storage():
|
|
# Пользователь API не root: MinIO показывает ему только bucket из его политики, создавать новые нельзя.
|
|
client = s3.get_client()
|
|
assert {bucket.name for bucket in client.list_buckets()} <= {"messenger-attachments", "messenger-attachments-test",
|
|
"messenger-attachments-bench"}
|
|
with pytest.raises(S3Error) as creating:
|
|
client.make_bucket("not-allowed-" + uuid.uuid4().hex[:8])
|
|
assert creating.value.code == "AccessDenied"
|