ЛР4 на 5: вложения в MinIO, отказоустойчивость, трек 2 (сверка S3 и PostgreSQL)

Уровень 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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
unknown
2026-11-12 17:28:39 +03:00
co-authored by Claude Opus 5.5
parent ec540a1a72
commit 0ccaf8e542
94 changed files with 7471 additions and 31 deletions
+115
View File
@@ -0,0 +1,115 @@
import base64
import os
import uuid
from pathlib import Path
# Отдельная тестовая база; задаётся до импорта приложения (настройки читаются при импорте).
TEST_DB_NAME = "messenger_test"
os.environ["APP_CONFIG__DB__NAME"] = TEST_DB_NAME
# Отдельный приватный bucket (создаёт minio-init): тестовые объекты не смешиваются с рабочими.
os.environ["APP_CONFIG__S3__BUCKET"] = "messenger-attachments-test"
import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, text
from core import s3
from core.db import build_url, engine
from main import app
APP_DIR = Path(__file__).resolve().parents[1] / "app"
PASSWORD = "Test-password-123"
@pytest.fixture(scope="session", autouse=True)
def test_database():
# CREATE DATABASE нельзя выполнить в транзакции, поэтому AUTOCOMMIT.
admin = create_engine(build_url().set(database="postgres"), isolation_level="AUTOCOMMIT")
with admin.connect() as connection:
exists = connection.scalar(text("SELECT 1 FROM pg_database WHERE datname = :name"), {"name": TEST_DB_NAME})
if not exists:
connection.execute(text(f'CREATE DATABASE "{TEST_DB_NAME}"'))
admin.dispose()
command.upgrade(Config(str(APP_DIR / "alembic.ini")), "head")
yield
engine.dispose()
@pytest.fixture(autouse=True)
def clean_database():
with engine.begin() as connection:
connection.execute(text("TRUNCATE users, sessions, chats, chat_members, messages, idempotency_keys, "
"attachments, message_attachments"))
# Вместе с метаданными — и объекты тестового bucket.
for stored in s3.list_objects(""):
s3.delete_object(stored.key)
@pytest.fixture
def client():
return TestClient(app)
def basic(username, password):
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
return {"Authorization": "Basic " + credential}
def login(client, username, password=PASSWORD):
response = client.post("/api/v1/auth/sessions", headers=basic(username, password))
assert response.status_code == 201
return response.json()
def bearer(token):
return {"Authorization": "Bearer " + token}
def with_key(headers, key=None):
"""Добавить обязательный с lab3 Idempotency-Key (по умолчанию — новый уникальный)."""
return {**headers, "Idempotency-Key": key or uuid.uuid4().hex}
def create_user(client, username):
"""Регистрация + вход; заголовок авторизации — в поле "auth"."""
response = client.post("/api/v1/users", json={"username": username, "display_name": "Имя " + username,
"password": PASSWORD})
assert response.status_code == 201
user = response.json()
user["token"] = login(client, username)["token"]
user["auth"] = bearer(user["token"])
return user
@pytest.fixture
def alice(client):
return create_user(client, "alice")
@pytest.fixture
def bob(client):
return create_user(client, "bob")
@pytest.fixture
def eve(client):
return create_user(client, "eve")
@pytest.fixture
def chat(client, alice, bob):
"""Чат alice и bob; eve в него не входит."""
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Тестовый чат", "member_ids": [alice["id"], bob["id"]]})
assert response.status_code == 201
return response.json()
def assert_error(response, status_code, code):
assert response.status_code == status_code
body = response.json()
assert body["error"]["code"] == code
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
+355
View File
@@ -0,0 +1,355 @@
"""Вложения: загрузка, скачивание, негативные сценарии, отказ 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"
+107
View File
@@ -0,0 +1,107 @@
import time
import jwt
from sqlalchemy import text
from conftest import PASSWORD, assert_error, basic, bearer, login
from core.config import settings
from core.db import engine
def assert_challenge(response, scheme):
assert response.headers["WWW-Authenticate"].startswith(scheme + ' realm="messenger"')
def test_login_returns_session(client, alice):
session = login(client, "alice")
assert session["token_type"] == "Bearer"
assert len(session["token"]) >= 32
assert session["expires_at"].endswith("Z")
assert session["user"]["id"] == alice["id"]
assert "password" not in session["user"] and "password_hash" not in session["user"]
assert login(client, "alice")["token"] != session["token"]
def test_jwt_payload_contains_sub_exp_jti(client, alice):
payload = jwt.decode(alice["token"], options={"verify_signature": False})
assert payload["sub"] == alice["id"]
assert payload["exp"] - payload["iat"] == settings.jwt.session_ttl_seconds
assert len(payload["jti"]) >= 43
def test_wrong_password_and_unknown_user_give_same_401(client, alice):
wrong = client.post("/api/v1/auth/sessions", headers=basic("alice", "Wrong-password-1"))
unknown = client.post("/api/v1/auth/sessions", headers=basic("nobody", PASSWORD))
for response in (wrong, unknown):
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Basic")
assert 'charset="UTF-8"' in response.headers["WWW-Authenticate"]
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
def test_malformed_basic_returns_401(client):
for header in ("", "Basic", "Basic !!!not-base64!!!", "Bearer abc", "Basic " + "YWxpY2U="): # последний — без ':'
response = client.post("/api/v1/auth/sessions", headers={"Authorization": header})
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Basic")
def test_login_with_body_returns_400_and_creates_no_session(client, alice):
with engine.connect() as connection:
before = connection.scalar(text("SELECT count(*) FROM sessions"))
for kwargs in ({"json": {"unexpected": True}}, {"json": {}}, {"content": b"x"}):
response = client.post("/api/v1/auth/sessions", headers=basic("alice", PASSWORD), **kwargs)
assert_error(response, 400, "invalid_request")
with engine.connect() as connection:
assert connection.scalar(text("SELECT count(*) FROM sessions")) == before
# Без тела вход по-прежнему работает.
assert login(client, "alice")["user"]["id"] == alice["id"]
def test_password_with_colon_and_unicode(client):
password = "пароль:с:двоеточиями 👋"
client.post("/api/v1/users", json={"username": "colon", "display_name": "C", "password": password})
assert login(client, "colon", password)["user"]["username"] == "colon"
def test_protected_endpoint_requires_bearer(client, alice):
cases = [{}, basic("alice", PASSWORD), bearer("not-a-jwt"), {"Authorization": "Bearer"}]
for headers in cases:
response = client.get("/api/v1/users/me", headers=headers)
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Bearer")
def test_x_user_id_does_not_override_token(client, alice, eve):
response = client.get("/api/v1/users/me", headers={**alice["auth"], "X-User-Id": eve["id"]})
assert response.json()["id"] == alice["id"]
def test_forged_token_is_rejected(client, alice):
payload = jwt.decode(alice["token"], options={"verify_signature": False})
forged = jwt.encode(payload, "attacker-key-attacker-key-attacker-key!!", algorithm="HS256")
assert_error(client.get("/api/v1/users/me", headers=bearer(forged)), 401, "unauthorized")
unsigned = jwt.encode(payload, None, algorithm="none")
assert_error(client.get("/api/v1/users/me", headers=bearer(unsigned)), 401, "unauthorized")
def test_logout_revokes_only_current_token(client, alice):
second = login(client, "alice")["token"]
response = client.delete("/api/v1/auth/sessions/current", headers=alice["auth"])
assert response.status_code == 204
assert response.content == b""
assert_error(client.get("/api/v1/users/me", headers=alice["auth"]), 401, "unauthorized")
assert_error(client.delete("/api/v1/auth/sessions/current", headers=alice["auth"]), 401, "unauthorized")
# Другая сессия того же пользователя продолжает работать.
assert client.get("/api/v1/users/me", headers=bearer(second)).status_code == 200
def test_session_expires(client, alice, monkeypatch):
# TTL с запасом на вход (Argon2 под нагрузкой бывает ~1 с): с TTL 1 с тест изредка падал до первой проверки.
monkeypatch.setattr(settings.jwt, "session_ttl_seconds", 3)
token = login(client, "alice")["token"]
assert client.get("/api/v1/users/me", headers=bearer(token)).status_code == 200
time.sleep(4.1)
response = client.get("/api/v1/users/me", headers=bearer(token))
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Bearer")
+54
View File
@@ -0,0 +1,54 @@
import uuid
from sqlalchemy import text
from conftest import assert_error, with_key
from core.db import engine
def count_rows(table):
with engine.connect() as connection:
return connection.scalar(text(f"SELECT count(*) FROM {table}"))
def test_unknown_member_returns_400_and_nothing_is_saved(client, alice):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "С призраком", "member_ids": [alice["id"], str(uuid.uuid4())]})
assert_error(response, 400, "invalid_request")
assert count_rows("chats") == 0
assert count_rows("chat_members") == 0
def test_created_chat_is_stored_with_members(client, chat, alice, bob):
assert sorted(chat["member_ids"]) == sorted([alice["id"], bob["id"]])
assert count_rows("chats") == 1
assert count_rows("chat_members") == 2
again = client.get("/api/v1/chats/" + chat["id"], headers=bob["auth"]).json()
assert again == chat
def test_foreign_chat_returns_404(client, chat, eve):
headers = eve["auth"]
path = "/api/v1/chats/" + chat["id"]
assert_error(client.get(path, headers=headers), 404, "not_found")
assert_error(client.get(path + "/messages", headers=headers), 404, "not_found")
assert_error(client.post(path + "/messages", headers=with_key(headers), json={"text": "чужое"}), 404, "not_found")
assert client.get("/api/v1/chats", headers=headers).json()["items"] == []
def test_member_sees_chat(client, chat, bob):
response = client.get("/api/v1/chats", headers=bob["auth"])
assert [c["id"] for c in response.json()["items"]] == [chat["id"]]
def test_creator_must_be_member(client, alice, bob):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Без меня", "member_ids": [bob["id"]]})
assert_error(response, 400, "invalid_request")
def test_duplicate_members_return_400(client, alice):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]})
assert_error(response, 400, "invalid_request")
+162
View File
@@ -0,0 +1,162 @@
import datetime as dt
from concurrent.futures import ThreadPoolExecutor
from fastapi.testclient import TestClient
from sqlalchemy import text
from conftest import assert_error, with_key
from core.config import settings
from core.db import engine
from main import app
from utils import lifecycle
def messages_path(chat):
return "/api/v1/chats/" + chat["id"] + "/messages"
def count_messages():
with engine.connect() as connection:
return connection.scalar(text("SELECT count(*) FROM messages"))
def test_missing_or_invalid_key_returns_400(client, chat, alice):
path = messages_path(chat)
assert_error(client.post(path, headers=alice["auth"], json={"text": "без ключа"}), 400, "invalid_request")
# Только ASCII: HTTP-заголовок с кириллицей тестовый клиент отправить не может.
for key in ("", "a b", "x" * 129, "bad/key", "bad,key"):
response = client.post(path, headers={**alice["auth"], "Idempotency-Key": key}, json={"text": "плохой ключ"})
assert_error(response, 400, "invalid_request")
assert count_messages() == 0
def test_valid_key_alphabet_and_max_length(client, chat, alice):
path = messages_path(chat)
for key in ("A-z_0.9:x", "k" * 128):
assert client.post(path, headers=with_key(alice["auth"], key), json={"text": key[:5]}).status_code == 201
def test_replay_returns_same_message_without_duplicate(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "replay-1")
first = client.post(path, headers=headers, json={"text": "один раз"})
second = client.post(path, headers=headers, json={"text": "один раз"})
assert first.status_code == second.status_code == 201
assert first.json() == second.json()
assert count_messages() == 1
def test_json_key_order_and_whitespace_do_not_matter(client, chat, alice):
path = messages_path(chat)
headers = {**with_key(alice["auth"], "order-1"), "Content-Type": "application/json"}
first = client.post(path, headers=headers, content='{"text": "тот же текст"}')
second = client.post(path, headers=headers, content='{ "text" :"тот же текст" }')
assert first.status_code == second.status_code == 201
assert first.json() == second.json()
assert count_messages() == 1
def test_same_key_with_other_body_returns_409(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "conflict-1")
assert client.post(path, headers=headers, json={"text": "первое"}).status_code == 201
assert_error(client.post(path, headers=headers, json={"text": "другое"}), 409, "conflict")
assert count_messages() == 1
def test_key_scope_is_user_and_chat(client, chat, alice, bob):
path = messages_path(chat)
a = client.post(path, headers=with_key(alice["auth"], "shared"), json={"text": "alice"})
b = client.post(path, headers=with_key(bob["auth"], "shared"), json={"text": "bob"})
assert a.status_code == b.status_code == 201
assert a.json()["id"] != b.json()["id"]
other = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Другой", "member_ids": [alice["id"]]}).json()
c = client.post(messages_path(other), headers=with_key(alice["auth"], "shared"), json={"text": "alice"})
assert c.status_code == 201
assert c.json()["id"] != a.json()["id"]
assert count_messages() == 3
def test_replay_still_checks_session_and_membership(client, chat, alice, eve):
path = messages_path(chat)
assert client.post(path, headers=with_key(alice["auth"], "k1"), json={"text": "секрет"}).status_code == 201
# Посторонний с тем же ключом не получает чужое сообщение.
assert_error(client.post(path, headers=with_key(eve["auth"], "k1"), json={"text": "секрет"}), 404, "not_found")
# Без токена повтор тоже отклоняется.
assert_error(client.post(path, headers={"Idempotency-Key": "k1"}, json={"text": "секрет"}), 401, "unauthorized")
def test_failed_request_does_not_consume_key(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "retry-after-error")
assert_error(client.post(path, headers=headers, json={"text": ""}), 400, "invalid_request")
# Тот же ключ после ошибки валидации можно использовать для корректного запроса.
assert client.post(path, headers=headers, json={"text": "теперь верно"}).status_code == 201
def test_expired_key_is_reusable(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "ttl-1")
first = client.post(path, headers=headers, json={"text": "старое"}).json()
old = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=settings.idempotency.ttl_seconds + 60)
with engine.begin() as connection:
connection.execute(text("UPDATE idempotency_keys SET created_at = :old"), {"old": old})
# Спустя TTL тот же ключ может описывать уже другое сообщение.
second = client.post(path, headers=headers, json={"text": "новое"})
assert second.status_code == 201
assert second.json()["id"] != first["id"]
assert client.post(path, headers=headers, json={"text": "новое"}).json() == second.json()
def test_concurrent_requests_with_one_key_create_one_message(chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "parallel-1")
def send(_):
# Отдельный клиент на поток (без `with`: lifespan закрыл бы общий пул соединений).
return TestClient(app).post(path, headers=headers, json={"text": "гонка"})
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(16)))
assert {r.status_code for r in responses} == {201}
assert len({r.json()["id"] for r in responses}) == 1
assert count_messages() == 1
def test_concurrent_different_bodies_one_key_only_one_wins(chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "parallel-2")
def send(i):
return TestClient(app).post(path, headers=headers, json={"text": f"вариант {i % 2}"})
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(send, range(8)))
statuses = sorted(r.status_code for r in responses)
assert set(statuses) <= {201, 409} and 201 in statuses
assert count_messages() == 1
def test_instance_id_header_is_present_and_stable(client, alice):
first = client.get("/health/live")
second = client.get("/api/v1/users/me", headers=alice["auth"])
error = client.get("/api/v1/users/me")
assert first.headers["X-Instance-Id"] == settings.run.instance_id
assert second.headers["X-Instance-Id"] == error.headers["X-Instance-Id"] == first.headers["X-Instance-Id"]
assert error.status_code == 401
def test_ready_returns_503_while_draining(client):
assert client.get("/health/ready").status_code == 200
lifecycle._draining.set()
try:
ready = client.get("/health/ready")
assert_error(ready, 503, "unavailable")
assert client.get("/health/live").status_code == 200 # процесс жив и обслуживает запросы
finally:
lifecycle._draining.clear()
assert client.get("/health/ready").status_code == 200
+66
View File
@@ -0,0 +1,66 @@
from conftest import assert_error, with_key
def test_empty_message_returns_400(client, chat, alice):
path = "/api/v1/chats/" + chat["id"] + "/messages"
headers = with_key(alice["auth"])
assert_error(client.post(path, headers=headers, json={"text": ""}), 400, "invalid_request")
assert_error(client.post(path, headers=headers, json={"text": " \n\t"}), 400, "invalid_request")
def test_sender_is_taken_from_token(client, chat, alice, bob):
path = "/api/v1/chats/" + chat["id"] + "/messages"
response = client.post(path, headers=with_key(bob["auth"]), json={"text": "Привет 👋"})
assert response.status_code == 201
assert response.json()["sender_id"] == bob["id"]
assert response.json()["text"] == "Привет 👋"
spoof = client.post(path, headers=with_key(bob["auth"]), json={"text": "x", "sender_id": alice["id"]})
assert_error(spoof, 400, "invalid_request")
def test_pagination_over_several_pages(client, chat, alice):
path = "/api/v1/chats/" + chat["id"] + "/messages"
headers = alice["auth"]
sent = [client.post(path, headers=with_key(headers), json={"text": f"сообщение {i}"}).json() for i in range(7)]
received = []
pages = 0
cursor = None
while True:
params = {"limit": 3}
if cursor:
params["cursor"] = cursor
page = client.get(path, headers=headers, params=params).json()
received += page["items"]
pages += 1
cursor = page["next_cursor"]
if cursor is None:
break
assert pages == 3 # 3 + 3 + 1
assert received == sent # тот же порядок, ничего не потеряно
assert len({m["id"] for m in received}) == 7 # без повторов
def test_cursor_from_another_chat_returns_400(client, chat, alice):
headers = alice["auth"]
path = "/api/v1/chats/" + chat["id"] + "/messages"
for i in range(2):
client.post(path, headers=with_key(headers), json={"text": f"m{i}"})
cursor = client.get(path, headers=headers, params={"limit": 1}).json()["next_cursor"]
other = client.post("/api/v1/chats", headers=headers, json={"title": "Другой", "member_ids": [alice["id"]]}).json()
response = client.get("/api/v1/chats/" + other["id"] + "/messages", headers=headers, params={"cursor": cursor})
assert_error(response, 400, "invalid_request")
response = client.get(path, headers=headers, params={"cursor": "мусор"})
assert_error(response, 400, "invalid_request")
def test_invalid_limit_returns_400(client, chat, alice):
path = "/api/v1/chats/" + chat["id"] + "/messages"
for limit in (0, 101, "abc"):
response = client.get(path, headers=alice["auth"], params={"limit": limit})
assert_error(response, 400, "invalid_request")
+148
View File
@@ -0,0 +1,148 @@
"""Сверка хранилищ (трек 2): обнаружение расхождений с обеих сторон и безопасное исправление."""
import uuid
import pytest
from sqlalchemy import text, update
from conftest import with_key
from core import s3
from core.db import SessionLocal, engine
from maintenance import reconcile as rec
from models import Attachment
from test_attachments_api import JPEG, PNG, objects_in_bucket, upload
HOUR_AGO = text("clock_timestamp() - interval '2 hours'")
def attach(client, user, chat_id, attachment_ids):
response = client.post(f"/api/v1/chats/{chat_id}/messages", headers=with_key(user["auth"]),
json={"text": "", "attachment_ids": attachment_ids})
assert response.status_code == 201
def backdate(*attachment_ids):
with SessionLocal() as db:
db.execute(update(Attachment).where(Attachment.id.in_(attachment_ids)).values(created_at=HOUR_AGO))
db.commit()
@pytest.fixture
def broken_state(client, alice, chat):
"""По одному вложению каждого вида. Объекты S3 изменить «задним числом» нельзя, поэтому все сироты свежие."""
ids = {name: upload(client, alice, chat["id"], PNG).json()["id"]
for name in ("ok_referenced", "ok_free", "missing_free", "missing_referenced", "missing_fresh",
"size_mismatch", "checksum_mismatch")}
attach(client, alice, chat["id"], [ids["ok_referenced"], ids["missing_referenced"]])
for name in ("missing_free", "missing_referenced", "missing_fresh"):
s3.delete_object(f"originals/{ids[name]}")
with SessionLocal() as db:
db.execute(update(Attachment).where(Attachment.id == ids["size_mismatch"])
.values(size_bytes=Attachment.size_bytes + 1))
db.commit()
# Тот же размер, другие байты: заметит только проверка SHA-256.
s3.put_object(f"originals/{ids['checksum_mismatch']}", bytes(len(PNG)), "image/png", "0" * 64)
ids["orphan_fresh"] = str(uuid.uuid4())
s3.put_object(f"originals/{ids['orphan_fresh']}", JPEG, "image/jpeg", "0" * 64)
backdate(*(ids[name] for name in ids if name not in ("missing_fresh", "orphan_fresh")))
return ids
def test_detects_both_sides_and_fixes_only_safe_cases(client, alice, chat, broken_state):
ids = broken_state
with SessionLocal() as db:
dry = rec.reconcile(db, apply=False, grace_seconds=3600, verify_checksums=True)
assert dry["issues"] == {"orphan_object": 0, "orphan_object_fresh": 1, "missing_object": 1,
"missing_object_referenced": 1, "missing_object_fresh": 1,
"size_mismatch": 1, "checksum_mismatch": 1}
assert dry["ok"] == 2 and dry["samples"]["missing_object"] == [ids["missing_free"]]
assert dry["actions"] == {"objects_deleted": 0, "rows_deleted": 0, "skipped_on_recheck": 0}
applied = rec.reconcile(db, apply=True, grace_seconds=3600, verify_checksums=True)
# Исправляется только безопасное: строка без объекта, ни к чему не прикреплённая и не свежая.
assert applied["actions"] == {"objects_deleted": 0, "rows_deleted": 1, "skipped_on_recheck": 0}
again = rec.reconcile(db, apply=True, grace_seconds=3600, verify_checksums=True)
assert again["issues"]["missing_object"] == 0
assert again["actions"] == {"objects_deleted": 0, "rows_deleted": 0, "skipped_on_recheck": 0}
# Без чтения объектов подмену содержимого того же размера не видно.
shallow = rec.reconcile(db, apply=False, grace_seconds=3600)
assert shallow["issues"]["checksum_mismatch"] == 0 and shallow["ok"] == 3
get = lambda name: client.get(f"/api/v1/attachments/{ids[name]}", headers=alice["auth"]).status_code
assert get("missing_free") == 404
# Прикреплённое к сообщению, свежее и повреждённые — на месте (их чинят из бэкапа, а не удалением).
for name in ("ok_referenced", "ok_free", "missing_referenced", "missing_fresh", "size_mismatch",
"checksum_mismatch"):
assert get(name) == 200
for name in ("ok_referenced", "ok_free"):
content = client.get(f"/api/v1/attachments/{ids[name]}/content", headers=alice["auth"])
assert content.status_code == 200 and content.content == PNG
assert f"originals/{ids['orphan_fresh']}" in objects_in_bucket()
def test_message_cannot_use_attachment_removed_by_reconcile(client, alice, chat, broken_state):
with SessionLocal() as db:
rec.reconcile(db, apply=True, grace_seconds=3600)
response = client.post(f"/api/v1/chats/{chat['id']}/messages", headers=with_key(alice["auth"]),
json={"text": "", "attachment_ids": [broken_state["missing_free"]]})
assert response.status_code == 404
def test_old_orphans_deleted_and_used_objects_kept(client, alice, chat):
used = upload(client, alice, chat["id"], PNG).json()["id"]
attach(client, alice, chat["id"], [used])
orphans = [f"originals/{uuid.uuid4()}" for _ in range(3)]
for key in orphans:
s3.put_object(key, PNG, "image/png", "0" * 64)
with SessionLocal() as db:
# grace 0: все сироты «старые».
report = rec.reconcile(db, apply=True, grace_seconds=0)
assert report["issues"]["orphan_object"] == 3 and report["actions"]["objects_deleted"] == 3
assert objects_in_bucket() == [f"originals/{used}"]
def test_apply_refuses_mass_delete(client, alice, chat):
for _ in range(3):
s3.put_object(f"originals/{uuid.uuid4()}", PNG, "image/png", "0" * 64)
with SessionLocal() as db:
report = rec.reconcile(db, apply=True, grace_seconds=0, max_deletes=2)
assert "aborted" in report and report["actions"]["objects_deleted"] == 0
assert len(objects_in_bucket()) == 3
def test_recheck_keeps_object_whose_metadata_appeared_after_listing(client, alice, chat):
# Объект попал в листинг без строки, а до удаления загрузка успела закоммитить метаданные.
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
key = f"originals/{attachment_id}"
stored = next(o for o in s3.list_objects("originals/") if o.key == key)
with SessionLocal() as db:
assert rec.delete_orphan_object(db, stored) is False
assert key in objects_in_bucket()
def test_recheck_keeps_row_that_got_referenced(client, alice, chat):
attachment_id = upload(client, alice, chat["id"], PNG).json()["id"]
s3.delete_object(f"originals/{attachment_id}")
with SessionLocal() as db:
row = next(r for r in rec.stream_rows(db, "originals/") if str(r.id) == attachment_id)
db.commit()
# После сканирования строку прикрепили к сообщению — удалять её уже нельзя.
attach(client, alice, chat["id"], [attachment_id])
with SessionLocal() as db:
assert rec.delete_missing_row(db, row) is False
assert client.get(f"/api/v1/attachments/{attachment_id}", headers=alice["auth"]).status_code == 200
def test_second_run_is_refused_while_first_holds_lock():
with engine.connect() as other:
other.execute(text("SELECT pg_advisory_lock(:id)"), {"id": rec.ADVISORY_LOCK_ID})
try:
with pytest.raises(rec.ReconcileAborted):
rec.run_locked(apply=True)
finally:
other.execute(text("SELECT pg_advisory_unlock(:id)"), {"id": rec.ADVISORY_LOCK_ID})
def test_unordered_stream_aborts():
with pytest.raises(rec.ReconcileAborted):
list(rec.ordered(iter(["b", "a"]), lambda k: k.encode(), "S3"))
+69
View File
@@ -0,0 +1,69 @@
import uuid
from sqlalchemy import text
from conftest import PASSWORD, assert_error
from core.db import engine
def test_invalid_json_returns_400(client):
response = client.post("/api/v1/users", content=b'{"username": "bob",',
headers={"Content-Type": "application/json"})
assert_error(response, 400, "invalid_request")
def test_extra_field_and_wrong_type_return_400(client):
response = client.post("/api/v1/users", json={"username": "bob", "display_name": "Bob", "password": PASSWORD,
"admin": True})
assert_error(response, 400, "invalid_request")
response = client.post("/api/v1/users", json={"username": "bob", "display_name": 123, "password": PASSWORD})
assert_error(response, 400, "invalid_request")
def test_duplicate_username_returns_409(client, alice):
response = client.post("/api/v1/users", json={"username": "alice", "display_name": "Другая Алиса",
"password": PASSWORD})
assert_error(response, 409, "conflict")
def test_unicode_display_name_is_kept(client):
response = client.post("/api/v1/users", json={"username": "uni", "display_name": "Алиса 👋",
"password": PASSWORD})
assert response.status_code == 201
assert response.json()["display_name"] == "Алиса 👋"
def test_password_is_required_and_length_checked(client):
for password in (None, "short", "x" * 129):
body = {"username": "pwd", "display_name": "P"}
if password is not None:
body["password"] = password
assert_error(client.post("/api/v1/users", json=body), 400, "invalid_request")
# 12 символов (не байт) — допустимо.
response = client.post("/api/v1/users", json={"username": "pwd", "display_name": "P", "password": "пароль123456"})
assert response.status_code == 201
def test_password_is_hashed_and_never_returned(client, alice):
assert "password" not in alice and "password_hash" not in alice
with engine.connect() as connection:
stored = connection.scalar(text("SELECT password_hash FROM users WHERE username = 'alice'"))
assert stored.startswith("$argon2id$")
assert PASSWORD not in stored
def test_me_returns_current_user(client, alice):
response = client.get("/api/v1/users/me", headers=alice["auth"])
assert response.status_code == 200
assert response.json() == {key: alice[key] for key in ("id", "username", "display_name", "created_at")}
def test_x_user_id_no_longer_authenticates(client, alice):
assert_error(client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}), 401, "unauthorized")
assert_error(client.get("/api/v1/users/me", headers={"X-User-Id": str(uuid.uuid4())}), 401, "unauthorized")
def test_every_response_has_request_id(client):
assert client.get("/health/live").headers["X-Request-Id"]
assert client.get("/health/ready").headers["X-Request-Id"]
assert_error(client.get("/no/such/path"), 404, "not_found")