feat: ЛР2 - PostgreSQL, Redis сессии и keyset-пагинация

This commit is contained in:
Ильяс
2026-10-23 12:45:58 +03:00
parent 5893d051c1
commit 9ddb2244bc
25 changed files with 1332 additions and 423 deletions
+5 -4
View File
@@ -1,15 +1,16 @@
import os
from __future__ import annotations
import os
import pytest
from httpx import ASGITransport, AsyncClient
from app.main import app
@pytest.fixture
async def client():
base_url = os.getenv("BASE_URL", "http://testserver")
base_url = os.getenv("BASE_URL", "http://localhost:8080")
if base_url.startswith("http://testserver"):
from app.main import app
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://testserver") as ac:
yield ac
+349 -198
View File
@@ -1,14 +1,46 @@
from __future__ import annotations
import asyncio
import base64
import uuid
import httpx
import pytest
from httpx import AsyncClient
async def register_and_login(client: AsyncClient, prefix: str = "u") -> dict:
username = f"{prefix}_{uuid.uuid4().hex[:12]}"
password = f"P@ssword_{uuid.uuid4().hex[:8]}"
body = {
"username": username,
"display_name": f"User {prefix}",
"password": password,
}
u_res = await client.post("/api/v1/users", json=body)
assert u_res.status_code == 201, u_res.text
user = u_res.json()
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
s_res = await client.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}
)
assert s_res.status_code == 201, s_res.text
session = s_res.json()
return {
"user": user,
"username": username,
"password": password,
"token": session["token"],
"headers": {"Authorization": f"Bearer {session['token']}"},
}
@pytest.mark.asyncio
async def test_invalid_json_and_extra_fields(client: AsyncClient):
"""Проверка невалидного JSON и запрета лишних полей (400 invalid_request)."""
# 1. Невалидный синтаксис JSON
"""Проверка невалидного JSON, лишних полей, перевода строки и валидации курсора."""
# 1. Невалидный синтаксис JSON -> 400
res_malformed = await client.post(
"/api/v1/users",
content="not a valid json {",
@@ -23,35 +55,34 @@ async def test_invalid_json_and_extra_fields(client: AsyncClient):
== err_malformed["error"]["request_id"]
)
# 2. Лишние поля (additionalProperties: false)
# 2. Лишние поля (additionalProperties: false) -> 400
res_extra = await client.post(
"/api/v1/users",
json={
"username": f"u_{uuid.uuid4().hex[:8]}",
"display_name": "test_user",
"password": "ValidPassword123!",
"unexpected_field": "hacker_payload",
},
)
assert res_extra.status_code == 400
err_extra = res_extra.json()
assert err_extra["error"]["code"] == "invalid_request"
assert res_extra.json()["error"]["code"] == "invalid_request"
# 3. Запрет завершающего перевода строки в username ("abc\n")
# 3. Запрет завершающего перевода строки в username ("abc\n") -> 400
res_newline = await client.post(
"/api/v1/users",
json={"username": "abc\n", "display_name": "test_newline"},
json={
"username": "abc\n",
"display_name": "test_newline",
"password": "ValidPassword123!",
},
)
assert res_newline.status_code == 400
assert res_newline.json()["error"]["code"] == "invalid_request"
# 4. Валидация курсора: не-dict JSON (W10= -> []) и пустой cursor=
user_res = (
await client.post(
"/api/v1/users",
json={"username": f"u_{uuid.uuid4().hex[:8]}", "display_name": "test_cursor_val"},
)
).json()
headers = {"X-User-Id": user_res["id"]}
# 4. Валидация курсора: не-dict JSON (W10= -> []) и пустой cursor= -> 400
actor = await register_and_login(client, "cur_val")
headers = actor["headers"]
# cursor=W10= (декодируется в list [], а не dict)
res_w10 = await client.get("/api/v1/chats?cursor=W10=", headers=headers)
@@ -67,254 +98,374 @@ async def test_invalid_json_and_extra_fields(client: AsyncClient):
@pytest.mark.asyncio
async def test_outsider_chat_access_is_404(client: AsyncClient):
"""Проверка того, что доступ к чужому чату возвращает строго 404 (а не 403)."""
# Создаём двух участников чата
test_user1 = (
await client.post(
"/api/v1/users",
json={"username": f"u1_{uuid.uuid4().hex[:8]}", "display_name": "test_user1"},
)
).json()
test_user2 = (
await client.post(
"/api/v1/users",
json={"username": f"u2_{uuid.uuid4().hex[:8]}", "display_name": "test_user2"},
)
).json()
# Создаём стороннего пользователя
test_user3 = (
await client.post(
"/api/v1/users",
json={"username": f"u3_{uuid.uuid4().hex[:8]}", "display_name": "test_user3"},
)
).json()
alice = await register_and_login(client, "alice")
bob = await register_and_login(client, "bob")
eve = await register_and_login(client, "eve")
# Первый пользователь создаёт чат со вторым
chat = (
await client.post(
"/api/v1/chats",
headers={"X-User-Id": test_user1["id"]},
json={"title": "Private Chat", "member_ids": [test_user1["id"], test_user2["id"]]},
)
).json()
chat_id = chat["id"]
# Сторонний пользователь пытается получить чат по ID -> 404
res_chat = await client.get(
f"/api/v1/chats/{chat_id}", headers={"X-User-Id": test_user3["id"]}
chat_res = await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={
"title": "Private Chat",
"member_ids": [alice["user"]["id"], bob["user"]["id"]],
},
)
assert res_chat.status_code == 404
assert res_chat.json()["error"]["code"] == "not_found"
assert chat_res.status_code == 201
chat_id = chat_res.json()["id"]
# Сторонний пользователь пытается отправить сообщение в чужой чат -> 404
res_post = await client.post(
# Ева пытается получить чужой чат -> 404
res_get = await client.get(f"/api/v1/chats/{chat_id}", headers=eve["headers"])
assert res_get.status_code == 404
assert res_get.json()["error"]["code"] == "not_found"
# Ева пытается отправить сообщение в чужой чат -> 404
res_send = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={"X-User-Id": test_user3["id"]},
json={"text": "Привет извне"},
headers=eve["headers"],
json={"text": "Шпионское сообщение"},
)
assert res_post.status_code == 404
assert res_post.json()["error"]["code"] == "not_found"
assert res_send.status_code == 404
assert res_send.json()["error"]["code"] == "not_found"
# Сторонний пользователь пытается прочитать сообщения чужого чата -> 404
res_msgs = await client.get(
f"/api/v1/chats/{chat_id}/messages", headers={"X-User-Id": test_user3["id"]}
# Ева пытается прочитать сообщения чужого чата -> 404
res_list = await client.get(
f"/api/v1/chats/{chat_id}/messages", headers=eve["headers"]
)
assert res_msgs.status_code == 404
assert res_msgs.json()["error"]["code"] == "not_found"
assert res_list.status_code == 404
assert res_list.json()["error"]["code"] == "not_found"
@pytest.mark.asyncio
async def test_empty_and_whitespace_message(client: AsyncClient):
"""Проверка отправки пустого сообщения или сообщения только из пробелов (400)."""
user = (
await client.post(
"/api/v1/users",
json={"username": f"u_{uuid.uuid4().hex[:8]}", "display_name": "test_user"},
)
).json()
"""Проверка запрета отправки пустого текста или текста из одних пробелов (400)."""
alice = await register_and_login(client, "msg_user")
chat = (
await client.post(
"/api/v1/chats",
headers={"X-User-Id": user["id"]},
json={"title": "Chat", "member_ids": [user["id"]]},
headers=alice["headers"],
json={"title": "Chat", "member_ids": [alice["user"]["id"]]},
)
).json()
# Пустая строка
# Пустая строка -> 400
res_empty = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers={"X-User-Id": user["id"]},
headers=alice["headers"],
json={"text": ""},
)
assert res_empty.status_code == 400
assert res_empty.json()["error"]["code"] == "invalid_request"
# Только пробелы и переводы строк
res_spaces = await client.post(
# Одни пробелы и переводы строк -> 400
res_whitespace = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers={"X-User-Id": user["id"]},
json={"text": " \t \n "},
headers=alice["headers"],
json={"text": " \n\t "},
)
assert res_spaces.status_code == 400
assert res_spaces.json()["error"]["code"] == "invalid_request"
assert res_whitespace.status_code == 400
assert res_whitespace.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_duplicate_username_conflict(client: AsyncClient):
"""Проверка регистрации пользователя с уже занятым username (409)."""
uname = f"unique_{uuid.uuid4().hex[:8]}"
res1 = await client.post(
"/api/v1/users", json={"username": uname, "display_name": "test_user1"}
)
"""Проверка запрета дублирования username (409 conflict)."""
uname = f"uniq_{uuid.uuid4().hex[:10]}"
body = {
"username": uname,
"display_name": "Первый",
"password": "ValidPassword123!",
}
res1 = await client.post("/api/v1/users", json=body)
assert res1.status_code == 201
res2 = await client.post(
"/api/v1/users", json={"username": uname, "display_name": "test_user2"}
"/api/v1/users",
json={
"username": uname,
"display_name": "Второй с тем же ником",
"password": "AnotherPassword123!",
},
)
assert res2.status_code == 409
err = res2.json()
assert err["error"]["code"] == "conflict"
assert res2.json()["error"]["code"] == "conflict"
@pytest.mark.asyncio
async def test_wrong_password_and_bad_basic_auth(client: AsyncClient):
"""Проверка ошибки авторизации 401 и корректного заголовка WWW-Authenticate."""
alice = await register_and_login(client, "auth_test")
# Неверный пароль -> 401
bad_cred = base64.b64encode(f"{alice['username']}:WrongPassword123!".encode()).decode()
res_bad = await client.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {bad_cred}"}
)
assert res_bad.status_code == 401
assert res_bad.json()["error"]["code"] == "unauthorized"
assert "basic" in res_bad.headers.get("WWW-Authenticate", "").lower()
# Несуществующий юзер -> 401
ghost_cred = base64.b64encode(b"ghost_user_123:WrongPassword123!").decode()
res_ghost = await client.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {ghost_cred}"}
)
assert res_ghost.status_code == 401
assert "basic" in res_ghost.headers.get("WWW-Authenticate", "").lower()
@pytest.mark.asyncio
async def test_logout_and_revocation(client: AsyncClient):
"""Проверка отзыва сессии (logout 204) и 401 при обращении с отозванным токеном."""
alice = await register_and_login(client, "logout_test")
# Проверяем, что токен работает
me_res = await client.get("/api/v1/users/me", headers=alice["headers"])
assert me_res.status_code == 200
# Делаем logout -> 204
logout_res = await client.delete(
"/api/v1/auth/sessions/current", headers=alice["headers"]
)
assert logout_res.status_code == 204
# Теперь тот же токен должен возвращать 401
me_after = await client.get("/api/v1/users/me", headers=alice["headers"])
assert me_after.status_code == 401
assert me_after.json()["error"]["code"] == "unauthorized"
assert "bearer" in me_after.headers.get("WWW-Authenticate", "").lower()
# Повторный logout с тем же отозванным токеном -> 401
logout_repeat = await client.delete(
"/api/v1/auth/sessions/current", headers=alice["headers"]
)
assert logout_repeat.status_code == 401
@pytest.mark.asyncio
async def test_multi_page_cursor_pagination(client: AsyncClient):
"""Проверка обхода нескольких страниц по keyset-курсору."""
user = (
await client.post(
"/api/v1/users",
json={"username": f"pag_{uuid.uuid4().hex[:8]}", "display_name": "test_user"},
)
).json()
"""Проверка обхода истории сообщений через keyset-курсор на нескольких страницах."""
alice = await register_and_login(client, "pager")
chat = (
await client.post(
"/api/v1/chats",
headers={"X-User-Id": user["id"]},
json={"title": "Pagination Chat", "member_ids": [user["id"]]},
headers=alice["headers"],
json={"title": "Pagination Chat", "member_ids": [alice["user"]["id"]]},
)
).json()
chat_id = chat["id"]
# Отправляем 5 сообщений
sent_texts = [f"Message #{i}" for i in range(1, 6)]
created_messages = []
for txt in sent_texts:
res = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={"X-User-Id": user["id"]},
json={"text": txt},
)
assert res.status_code == 201
created_messages.append(res.json())
# Отправляем 15 сообщений
sent_ids = []
for i in range(15):
msg = (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=alice["headers"],
json={"text": f"Сообщение {i:02d}"},
)
).json()
sent_ids.append(msg["id"])
# Страница 1: limit=2
p1 = (
await client.get(
f"/api/v1/chats/{chat_id}/messages?limit=2",
headers={"X-User-Id": user["id"]},
)
).json()
assert len(p1["items"]) == 2
assert p1["next_cursor"] is not None
# Читаем страницами по 4 сообщения
gathered_ids = []
cursor = None
pages_count = 0
# Страница 2: limit=2 с курсором со страницы 1
p2 = (
await client.get(
f"/api/v1/chats/{chat_id}/messages?limit=2&cursor={p1['next_cursor']}",
headers={"X-User-Id": user["id"]},
)
).json()
assert len(p2["items"]) == 2
assert p2["next_cursor"] is not None
while True:
url = f"/api/v1/chats/{chat['id']}/messages?limit=4"
if cursor:
url += f"&cursor={cursor}"
# Страница 3: limit=2 с курсором со страницы 2 -> остался 1 элемент, next_cursor == None
p3 = (
await client.get(
f"/api/v1/chats/{chat_id}/messages?limit=2&cursor={p2['next_cursor']}",
headers={"X-User-Id": user["id"]},
)
).json()
assert len(p3["items"]) == 1
assert p3["next_cursor"] is None
res = await client.get(url, headers=alice["headers"])
assert res.status_code == 200
data = res.json()
pages_count += 1
items = data["items"]
for item in items:
gathered_ids.append(item["id"])
# Проверяем, что все 5 сообщений собраны без повторов и потерь
all_retrieved = p1["items"] + p2["items"] + p3["items"]
assert len(all_retrieved) == 5
assert [m["id"] for m in all_retrieved] == [m["id"] for m in created_messages]
cursor = data.get("next_cursor")
if not cursor:
break
# Должны быть ровно 15 сообщений в строго том же порядке, без дублей и пропусков
assert len(gathered_ids) == 15
assert gathered_ids == sent_ids
assert pages_count == 4
@pytest.mark.asyncio
async def test_concurrency_race_condition(client: AsyncClient):
"""
Защита состояния от гонок:
Параллельно отправляем 100 сообщений от 10 клиентов,
затем получаем ровно 100 уникальных сообщений без повреждений.
"""
# 1. Создаём 10 клиентов
users = []
for i in range(10):
u = (
await client.post(
"/api/v1/users",
json={
"username": f"conc_{i}_{uuid.uuid4().hex[:6]}",
"display_name": f"test_user_{i}",
},
)
).json()
users.append(u)
"""Проверка устойчивости к параллельным гонкам: 10 клиентов одновременно шлют 100 сообщений."""
# Создаём 10 пользователей
users = await asyncio.gather(
*(register_and_login(client, f"u{i}") for i in range(10))
)
all_user_ids = [u["user"]["id"] for u in users]
user_ids = [u["id"] for u in users]
# 2. Создаём чат со всеми 10 участниками
# Первый пользователь создаёт общий чат со всеми 10 участниками
chat = (
await client.post(
"/api/v1/chats",
headers={"X-User-Id": user_ids[0]},
json={"title": "Highload Concurrency Chat", "member_ids": user_ids},
headers=users[0]["headers"],
json={"title": "Massive Concurrent Chat", "member_ids": all_user_ids},
)
).json()
chat_id = chat["id"]
# 3. Каждый из 10 клиентов отправляет по 10 сообщений параллельно (итого 100 сообщений)
async def send_batch(user, client_idx):
tasks = []
for msg_idx in range(10):
text = f"client-{client_idx}-msg-{msg_idx}"
tasks.append(
client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={"X-User-Id": user["id"]},
json={"text": text},
)
# Отправляем по 10 сообщений от каждого пользователя параллельно (всего 100)
async def sender(user_dict: dict, count: int):
for i in range(count):
await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers=user_dict["headers"],
json={"text": f"Msg {i} from {user_dict['username']}"},
)
return await asyncio.gather(*tasks)
# Запускаем отправку от всех 10 клиентов одновременно
batch_results = await asyncio.gather(*[send_batch(users[i], i) for i in range(10)])
await asyncio.gather(*(sender(u, 10) for u in users))
# Проверяем, что все 100 запросов завершились со статусом 201 Created
all_responses = [resp for batch in batch_results for resp in batch]
assert len(all_responses) == 100
for resp in all_responses:
assert resp.status_code == 201
# Считываем все сообщения из чата
all_msgs = []
cursor = None
while True:
url = f"/api/v1/chats/{chat_id}/messages?limit=50"
if cursor:
url += f"&cursor={cursor}"
res = await client.get(url, headers=users[0]["headers"])
assert res.status_code == 200
data = res.json()
all_msgs.extend(data["items"])
cursor = data.get("next_cursor")
if not cursor:
break
# 4. Читаем все сообщения из чата (limit=100)
history_res = await client.get(
f"/api/v1/chats/{chat_id}/messages?limit=100",
headers={"X-User-Id": user_ids[0]},
assert len(all_msgs) == 100
ids = [m["id"] for m in all_msgs]
# Все ID должны быть уникальными
assert len(ids) == len(set(ids))
@pytest.mark.asyncio
async def test_password_whitespace_rejected(client: httpx.AsyncClient):
"""Пароль из одних пробелов должен строго отклоняться с 400 Invalid Request."""
u = f"space_user_{uuid.uuid4().hex[:6]}"
res = await client.post(
"/api/v1/users",
json={"username": u, "display_name": "Test User", "password": " " * 12},
)
assert history_res.status_code == 200
history = history_res.json()
items = history["items"]
assert res.status_code == 400
data = res.json()
assert data["error"]["code"] == "invalid_request"
# параллельно отправим 100 сообщений от 10 клиентов, затем получаем ровно 100 уникальных сообщений
assert len(items) == 100, f"Expected 100 messages, received {len(items)}"
unique_ids = {m["id"] for m in items}
assert len(unique_ids) == 100, "Found duplicate message IDs"
# Проверяем монотонную сортировку (created_at, id)
for idx in range(len(items) - 1):
assert (items[idx]["created_at"], items[idx]["id"]) <= (
items[idx + 1]["created_at"],
items[idx + 1]["id"],
)
@pytest.mark.asyncio
async def test_auth_sessions_with_body_rejected(client: httpx.AsyncClient):
"""POST /api/v1/auth/sessions с телом запроса должен отклоняться с 400 Invalid Request."""
u = f"body_user_{uuid.uuid4().hex[:6]}"
p = "StrongPassword123!"
await client.post(
"/api/v1/users",
json={"username": u, "display_name": "Body Test", "password": p},
)
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
res = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {cred}"},
json={"extra": "forbidden"},
)
assert res.status_code == 400
data = res.json()
assert data["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_unsupported_media_type_415(client: httpx.AsyncClient):
"""Запрос с неподдерживаемым Content-Type (text/plain) должен возвращать 415 Unsupported Media Type."""
res = await client.post(
"/api/v1/users",
content='{"username":"ct_test","display_name":"d","password":"Password123456!"}',
headers={"Content-Type": "text/plain"},
)
assert res.status_code == 415
data = res.json()
assert data["error"]["code"] == "unsupported_media_type"
@pytest.mark.asyncio
async def test_nul_byte_in_strings_handled(client: httpx.AsyncClient):
"""Символ \\u0000 в строках не должен вызывать 500/503 и должен корректно обрабатываться."""
u = f"nul_user_{uuid.uuid4().hex[:6]}"
res = await client.post(
"/api/v1/users",
json={"username": u, "display_name": "Hello\u0000World", "password": "Password123456!"},
)
assert res.status_code == 201
data = res.json()
assert data["username"] == u
assert data["display_name"] == "HelloWorld"
@pytest.mark.asyncio
async def test_basic_auth_invalid_base64_returns_401(client: httpx.AsyncClient):
"""Authorization: Basic с битым base64 или не-ASCII символами возвращает 401, а не 500."""
res = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": b"Basic \xe9"},
)
assert res.status_code == 401
assert "Basic" in res.headers.get("www-authenticate", "")
@pytest.mark.asyncio
async def test_cross_chat_cursor_rejected_400(client: httpx.AsyncClient):
"""Курсор от одного чата при попытке использовать в другом чате должен возвращать 400."""
u = await register_and_login(client, f"cc_{uuid.uuid4().hex[:4]}")
chat1 = (await client.post("/api/v1/chats", headers=u["headers"], json={"title": "C1", "member_ids": [u["user"]["id"]]})).json()
chat2 = (await client.post("/api/v1/chats", headers=u["headers"], json={"title": "C2", "member_ids": [u["user"]["id"]]})).json()
# Отправляем 2 сообщения в чат 1
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers=u["headers"], json={"text": "m1"})
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers=u["headers"], json={"text": "m2"})
# Получаем страницу с курсором из чата 1
p1 = (await client.get(f"/api/v1/chats/{chat1['id']}/messages?limit=1", headers=u["headers"])).json()
cursor1 = p1.get("next_cursor")
assert cursor1 is not None
# Пытаемся применить курсор чата 1 к чату 2 -> 400!
res = await client.get(f"/api/v1/chats/{chat2['id']}/messages?cursor={cursor1}", headers=u["headers"])
assert res.status_code == 400
assert res.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_utf8_password_support(client: httpx.AsyncClient):
"""Пароли с символами UTF-8 и emoji корректно регистрируются и аутентифицируются."""
u = f"utf_{uuid.uuid4().hex[:6]}"
p = "СложныйПароль123!🔒"
res1 = await client.post(
"/api/v1/users",
json={"username": u, "display_name": "UTF User", "password": p},
)
assert res1.status_code == 201
cred = base64.b64encode(f"{u}:{p}".encode("utf-8")).decode("utf-8")
res2 = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {cred}"},
)
assert res2.status_code == 201
assert "token" in res2.json()
@pytest.mark.asyncio
async def test_health_readiness_and_liveness(client: httpx.AsyncClient):
"""Проверка доступности /health/live и готовности хранилищ /health/ready."""
r_live = await client.get("/health/live")
assert r_live.status_code == 200
assert r_live.json()["status"] == "ok"
r_ready = await client.get("/health/ready")
assert r_ready.status_code == 200
assert r_ready.json()["status"] == "ok"