forked from mtusi2026/mtusi2026lab3
feat: ЛР3 - Nginx балансировка, идемпотентность сообщений и failover
This commit is contained in:
+309
-8
@@ -121,7 +121,7 @@ async def test_outsider_chat_access_is_404(client: AsyncClient):
|
||||
# Ева пытается отправить сообщение в чужой чат -> 404
|
||||
res_send = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers=eve["headers"],
|
||||
headers={**eve["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||||
json={"text": "Шпионское сообщение"},
|
||||
)
|
||||
assert res_send.status_code == 404
|
||||
@@ -150,7 +150,7 @@ async def test_empty_and_whitespace_message(client: AsyncClient):
|
||||
# Пустая строка -> 400
|
||||
res_empty = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=alice["headers"],
|
||||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||||
json={"text": ""},
|
||||
)
|
||||
assert res_empty.status_code == 400
|
||||
@@ -159,7 +159,7 @@ async def test_empty_and_whitespace_message(client: AsyncClient):
|
||||
# Одни пробелы и переводы строк -> 400
|
||||
res_whitespace = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=alice["headers"],
|
||||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||||
json={"text": " \n\t "},
|
||||
)
|
||||
assert res_whitespace.status_code == 400
|
||||
@@ -260,7 +260,7 @@ async def test_multi_page_cursor_pagination(client: AsyncClient):
|
||||
msg = (
|
||||
await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=alice["headers"],
|
||||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||||
json={"text": f"Сообщение {i:02d}"},
|
||||
)
|
||||
).json()
|
||||
@@ -319,7 +319,7 @@ async def test_concurrency_race_condition(client: AsyncClient):
|
||||
for i in range(count):
|
||||
await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers=user_dict["headers"],
|
||||
headers={**user_dict["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||||
json={"text": f"Msg {i} from {user_dict['username']}"},
|
||||
)
|
||||
|
||||
@@ -397,7 +397,11 @@ async def test_nul_byte_in_strings_handled(client: httpx.AsyncClient):
|
||||
usr = await register_and_login(client, f"nul_msg_{uuid.uuid4().hex[:4]}")
|
||||
chat = (await client.post("/api/v1/chats", headers=usr["headers"], json={"title": "NulChat", "member_ids": [usr["user"]["id"]]})).json()
|
||||
test_text = "left\u0000right"
|
||||
msg_res = await client.post(f"/api/v1/chats/{chat['id']}/messages", headers=usr["headers"], json={"text": test_text})
|
||||
msg_res = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={**usr["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||||
json={"text": test_text},
|
||||
)
|
||||
assert msg_res.status_code == 201
|
||||
assert msg_res.json()["text"] == test_text
|
||||
|
||||
@@ -425,8 +429,8 @@ async def test_cross_chat_cursor_rejected_400(client: httpx.AsyncClient):
|
||||
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"})
|
||||
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers={**u["headers"], "Idempotency-Key": uuid.uuid4().hex}, json={"text": "m1"})
|
||||
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers={**u["headers"], "Idempotency-Key": uuid.uuid4().hex}, json={"text": "m2"})
|
||||
|
||||
# Получаем страницу с курсором из чата 1
|
||||
p1 = (await client.get(f"/api/v1/chats/{chat1['id']}/messages?limit=1", headers=u["headers"])).json()
|
||||
@@ -469,3 +473,300 @@ async def test_health_readiness_and_liveness(client: httpx.AsyncClient):
|
||||
r_ready = await client.get("/health/ready")
|
||||
assert r_ready.status_code == 200
|
||||
assert r_ready.json()["status"] == "ok"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_instance_id_header_present(client: httpx.AsyncClient):
|
||||
"""Каждый ответ обязан содержать непустой заголовок X-Instance-Id."""
|
||||
res = await client.get("/health/live")
|
||||
assert res.status_code == 200
|
||||
assert "x-instance-id" in res.headers
|
||||
assert len(res.headers["x-instance-id"]) > 0
|
||||
|
||||
res_err = await client.get("/api/v1/users/me")
|
||||
assert res_err.status_code == 401
|
||||
assert "x-instance-id" in res_err.headers
|
||||
assert len(res_err.headers["x-instance-id"]) > 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idempotency_key_validation(client: httpx.AsyncClient):
|
||||
"""POST /messages без Idempotency-Key или с некорректным форматом возвращает 400."""
|
||||
alice = await register_and_login(client, f"idem_{uuid.uuid4().hex[:6]}")
|
||||
chat = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "IdemChat", "member_ids": [alice["user"]["id"]]})).json()
|
||||
chat_id = chat["id"]
|
||||
|
||||
# Без заголовка
|
||||
res1 = await client.post(f"/api/v1/chats/{chat_id}/messages", headers=alice["headers"], json={"text": "Тест"})
|
||||
assert res1.status_code == 400
|
||||
assert res1.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
# С некорректным форматом
|
||||
res2 = await client.post(f"/api/v1/chats/{chat_id}/messages", headers={**alice["headers"], "Idempotency-Key": "invalid key with spaces"}, json={"text": "Тест"})
|
||||
assert res2.status_code == 400
|
||||
assert res2.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idempotency_replay_and_conflict(client: httpx.AsyncClient):
|
||||
"""Повтор с тем же телом возвращает исходный 201; с другим телом возвращает 409."""
|
||||
alice = await register_and_login(client, f"idem2_{uuid.uuid4().hex[:6]}")
|
||||
chat = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "IdemChat2", "member_ids": [alice["user"]["id"]]})).json()
|
||||
chat_id = chat["id"]
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
# Первый запрос -> 201
|
||||
res1 = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": key},
|
||||
json={"text": "Первое сообщение"},
|
||||
)
|
||||
assert res1.status_code == 201
|
||||
msg1 = res1.json()
|
||||
|
||||
# Повтор с тем же телом -> 201 и то же сообщение
|
||||
res2 = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": key},
|
||||
json={"text": "Первое сообщение"},
|
||||
)
|
||||
assert res2.status_code == 201
|
||||
assert res2.json() == msg1
|
||||
|
||||
# Повтор с тем же ключом, но другим телом -> 409 Conflict
|
||||
res3 = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": key},
|
||||
json={"text": "Другое сообщение с тем же ключом"},
|
||||
)
|
||||
assert res3.status_code == 409
|
||||
assert res3.json()["error"]["code"] == "conflict"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idempotency_acl_check_on_replay(client: httpx.AsyncClient):
|
||||
"""
|
||||
Проверка ACL перед возвратом сохранённого результата идемпотентности.
|
||||
Если пользователь удалён из участников чата, повторный POST с тем же Idempotency-Key
|
||||
и тем же телом обязан вернуть 404 (а не 201).
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
alice = await register_and_login(client, f"acl_{uuid.uuid4().hex[:6]}")
|
||||
chat = (
|
||||
await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=alice["headers"],
|
||||
json={"title": "ACL Test Chat", "member_ids": [alice["user"]["id"]]},
|
||||
)
|
||||
).json()
|
||||
chat_id = chat["id"]
|
||||
user_id = alice["user"]["id"]
|
||||
key = f"acl_key_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
# 1. Отправляем сообщение первый раз -> 201
|
||||
res1 = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": key},
|
||||
json={"text": "Тест проверки ACL"},
|
||||
)
|
||||
assert res1.status_code == 201
|
||||
|
||||
# 2. Удаляем членство отправителя напрямую в БД (изолированная инъекция проверки ACL)
|
||||
cmd = [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"postgres",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-c",
|
||||
f"DELETE FROM chat_members WHERE chat_id = '{chat_id}' AND user_id = '{user_id}';",
|
||||
]
|
||||
sub_res = subprocess.run(cmd, capture_output=True, text=True)
|
||||
assert sub_res.returncode == 0, f"Ошибка удаления членства: {sub_res.stderr}"
|
||||
|
||||
# 3. GET истории уже обязан возвращать 404
|
||||
res_get = await client.get(f"/api/v1/chats/{chat_id}/messages", headers=alice["headers"])
|
||||
assert res_get.status_code == 404
|
||||
|
||||
# 4. Повтор POST с тем же телом и тем же ключом ОБЯЗАН вернуть 404 (ACL проверяется до возврата из idempotency_keys)
|
||||
res_repeat = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": key},
|
||||
json={"text": "Тест проверки ACL"},
|
||||
)
|
||||
assert res_repeat.status_code == 404, f"Ожидался 404, получен {res_repeat.status_code}: {res_repeat.text}"
|
||||
assert res_repeat.json()["error"]["code"] == "not_found"
|
||||
|
||||
# 5. Повтор POST с тем же ключом и ДРУГИМ телом: ACL проверяется до сравнения тела -> обязан вернуть 404 (а не 409)
|
||||
res_repeat_diff = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": key},
|
||||
json={"text": "Другой текст сообщения"},
|
||||
)
|
||||
assert res_repeat_diff.status_code == 404, f"Ожидался 404, получен {res_repeat_diff.status_code}: {res_repeat_diff.text}"
|
||||
assert res_repeat_diff.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_cursor_date_returns_400(client: httpx.AsyncClient):
|
||||
"""
|
||||
Некорректная дата курсора (например, 13-й месяц 2026-13-01T00:00:00.000000Z)
|
||||
обязана возвращать 400 invalid_request (а не 500 internal_error).
|
||||
"""
|
||||
from app.storage import encode_cursor
|
||||
|
||||
alice = await register_and_login(client, f"bad_cur_{uuid.uuid4().hex[:6]}")
|
||||
chat = (
|
||||
await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=alice["headers"],
|
||||
json={"title": "CurChat", "member_ids": [alice["user"]["id"]]},
|
||||
)
|
||||
).json()
|
||||
chat_id = chat["id"]
|
||||
|
||||
# 1. Курсор сообщений с невалидной датой (месяц 13)
|
||||
bad_cur_msg = encode_cursor(
|
||||
{
|
||||
"type": "messages",
|
||||
"chat_id": chat_id,
|
||||
"created_at": "2026-13-01T00:00:00.000000Z",
|
||||
"id": str(uuid.uuid4()),
|
||||
}
|
||||
)
|
||||
res_m = await client.get(
|
||||
f"/api/v1/chats/{chat_id}/messages?cursor={bad_cur_msg}",
|
||||
headers=alice["headers"],
|
||||
)
|
||||
assert res_m.status_code == 400
|
||||
assert res_m.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
# 2. Невалидная строка формата m|chat_id|... в base64
|
||||
raw_str = f"m|{chat_id}|2026-13-01T00:00:00.000000Z|"
|
||||
raw_cur = base64.urlsafe_b64encode(raw_str.encode()).decode()
|
||||
res_raw = await client.get(
|
||||
f"/api/v1/chats/{chat_id}/messages?cursor={raw_cur}",
|
||||
headers=alice["headers"],
|
||||
)
|
||||
assert res_raw.status_code == 400
|
||||
assert res_raw.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strict_types_and_json_parsing(client: httpx.AsyncClient):
|
||||
"""
|
||||
Запрет преобразования неверных типов ({"text": 123} -> 400)
|
||||
и требование полного разбора JSON ({"text":"x"}garbage -> 400).
|
||||
"""
|
||||
alice = await register_and_login(client, f"strict_{uuid.uuid4().hex[:6]}")
|
||||
chat = (
|
||||
await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=alice["headers"],
|
||||
json={"title": "StrictChat", "member_ids": [alice["user"]["id"]]},
|
||||
)
|
||||
).json()
|
||||
chat_id = chat["id"]
|
||||
|
||||
# 1. {"text": 123} вместо строки -> 400
|
||||
res_num = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex, "Content-Type": "application/json"},
|
||||
content='{"text": 123}',
|
||||
)
|
||||
assert res_num.status_code == 400
|
||||
assert res_num.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
# 2. {"text": "x"}garbage -> 400
|
||||
res_garbage = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex, "Content-Type": "application/json"},
|
||||
content='{"text": "x"}garbage',
|
||||
)
|
||||
assert res_garbage.status_code == 400
|
||||
assert res_garbage.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_create_rejects_non_empty_body(client: httpx.AsyncClient):
|
||||
"""POST /api/v1/auth/sessions с непустым телом {"unexpected":true} отклоняется с 400."""
|
||||
alice = await register_and_login(client, f"no_body_{uuid.uuid4().hex[:6]}")
|
||||
cred = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode()
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers={"Authorization": f"Basic {cred}", "Content-Type": "application/json"},
|
||||
content='{"unexpected": true}',
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert res.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_creation_with_unknown_participant_is_400(client: httpx.AsyncClient):
|
||||
"""Неизвестный участник при создании чата обязан возвращать 400 (не 404)."""
|
||||
alice = await register_and_login(client, f"unk_{uuid.uuid4().hex[:6]}")
|
||||
non_existent_uuid = str(uuid.uuid4())
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=alice["headers"],
|
||||
json={"title": "Chat With Ghost", "member_ids": [alice["user"]["id"], non_existent_uuid]},
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert res.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_password_with_colons_and_utf8(client: httpx.AsyncClient):
|
||||
"""Пароль с двоеточиями и UTF-8 символами работает при регистрации и входе."""
|
||||
username = f"col_{uuid.uuid4().hex[:8]}"
|
||||
password = "Пример:пароля-12345:секрет:🔒"
|
||||
|
||||
res_reg = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": username, "display_name": "Colon User", "password": password},
|
||||
)
|
||||
assert res_reg.status_code == 201
|
||||
|
||||
cred = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
|
||||
res_login = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers={"Authorization": f"Basic {cred}"},
|
||||
)
|
||||
assert res_login.status_code == 201
|
||||
assert "token" in res_login.json()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyset_pagination_returns_next_cursor(client: httpx.AsyncClient):
|
||||
"""
|
||||
При наличии записей за пределами limit возвращается next_cursor.
|
||||
Повторный запрос с cursor возвращает следующие элементы.
|
||||
"""
|
||||
alice = await register_and_login(client, f"page_{uuid.uuid4().hex[:6]}")
|
||||
c1 = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "Chat1", "member_ids": [alice["user"]["id"]]})).json()
|
||||
c2 = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "Chat2", "member_ids": [alice["user"]["id"]]})).json()
|
||||
|
||||
# Запрос с limit=1 обязан вернуть первый чат и НЕПУСТОЙ next_cursor
|
||||
res_p1 = await client.get("/api/v1/chats?limit=1", headers=alice["headers"])
|
||||
assert res_p1.status_code == 200
|
||||
data_p1 = res_p1.json()
|
||||
assert len(data_p1["items"]) == 1
|
||||
cursor = data_p1["next_cursor"]
|
||||
assert cursor is not None and len(cursor) > 0
|
||||
|
||||
# Запрос со вторым курсором обязан вернуть второй чат
|
||||
res_p2 = await client.get(f"/api/v1/chats?limit=1&cursor={cursor}", headers=alice["headers"])
|
||||
assert res_p2.status_code == 200
|
||||
data_p2 = res_p2.json()
|
||||
assert len(data_p2["items"]) == 1
|
||||
assert data_p2["items"][0]["id"] != data_p1["items"][0]["id"]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user