Files
mtusi2026lab2/student-tests/api/test_negative.py
T
ArtyomandClaude Opus 5.5 7bf28fc6ed Make message posts idempotent with Idempotency-Key
POST /api/v1/chats/{chat_id}/messages now requires the header, checked
at the HTTP boundary (1-128 of [A-Za-z0-9._:-], else 400). The handler
keeps the lab 2 order under the chat row lock: membership, then text,
then the receipt for (chat, sender, key) younger than
IDEMPOTENCY_TTL_SECONDS. A receipt with the same fingerprint replays
the stored message, a different one is 409 conflict; without a
receipt one statement inserts the message, the key row and the chat
mark, so both commit or neither does. Concurrent retries wait on the
same row lock and then read the committed receipt. The fingerprint is
SHA-256 of the canonical JSON of the parsed body, so layout does not
matter, and only 201 answers are ever stored.

A lock timeout now counts as a dependency failure and answers 503
instead of 500, so a retry with the same key is safe.

Own tests cover replay, a different layout of the same JSON, conflict,
missing and malformed keys, rejected attempts that leave the key free,
scope by user and chat, revalidation after logout and for outsiders,
expiry, and eight concurrent retries through two app instances
sharing one PostgreSQL. Every earlier message post sends a fresh key.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 11:36:15 +03:00

197 lines
6.5 KiB
Python

from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
}
def assert_error(response, expected_status: int) -> None:
assert response.status_code == expected_status, response.text
assert response.headers.get("content-type", "").startswith("application/json")
body = response.json()
assert set(body) == {"error"}
assert set(body["error"]) == {"code", "message", "request_id"}
assert body["error"]["code"] == ERROR_CODES[expected_status]
assert body["error"]["message"]
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_malformed_json(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
content=b'{"username": ',
headers={"Content-Type": "application/json"},
)
assert_error(response, 400)
async def test_unexpected_field(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"},
)
assert_error(response, 400)
async def test_wrong_types(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234}
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"username": "Alice", "display_name": "X", "password": PASSWORD},
{"username": "ab", "display_name": "X", "password": PASSWORD},
{"username": "alice_01\n", "display_name": "X", "password": PASSWORD},
{"username": "abc_def", "display_name": "", "password": PASSWORD},
{"username": "abc_def", "display_name": " ", "password": PASSWORD},
{"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD},
{"username": "abc_def", "display_name": "X", "password": "short"},
{"username": "abc_def", "display_name": "X", "password": "x" * 129},
{"username": "abc_def", "display_name": "X", "password": " " * 20},
{"username": "abc_def", "display_name": "X"},
{"username": "abc_def", "password": PASSWORD},
],
)
async def test_invalid_registration(client: AsyncClient, body: dict) -> None:
assert_error(await client.post("/api/v1/users", json=body), 400)
async def test_duplicate_username(client: AsyncClient) -> None:
alice = await register(client, "alice")
repeat = await client.post(
"/api/v1/users",
json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD},
)
assert_error(repeat, 409)
async def test_missing_identity(client: AsyncClient) -> None:
assert_error(await client.get("/api/v1/users/me"), 401)
BAD_AUTHORIZATIONS = [
"",
"Bearer",
"Bearer ",
"Bearer not a token",
"Bearer " + "x" * 43,
"Token abcdef",
"11111111-1111-4111-8111-111111111111",
]
@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS)
async def test_invalid_bearer(client: AsyncClient, raw: str) -> None:
response = await client.get("/api/v1/users/me", headers={"Authorization": raw})
assert_error(response, 401)
assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
assert_error(response, 401)
async def test_identity_checked_before_body(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
assert_error(response, 401)
async def test_empty_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
for text in ("", " ", "\n\t"):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=keyed(alice),
)
assert_error(response, 400)
async def test_long_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "я" * 4001},
headers=keyed(alice),
)
assert_error(response, 400)
async def test_sender_id_not_accepted(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "подмена", "sender_id": bob["id"]},
headers=keyed(alice),
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"title": "Чат", "member_ids": []},
{"title": "", "member_ids": None},
{"title": " ", "member_ids": None},
{"title": "Чат", "member_ids": ["не-uuid"]},
{"title": "Чат", "member_ids": [1]},
{"title": "Чат", "member_ids": "не-список"},
],
)
async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None:
alice = await register(client, "alice")
payload = dict(body)
if payload["member_ids"] is None:
payload["member_ids"] = [alice["id"]]
response = await client.post("/api/v1/chats", json=payload, headers=actor(alice))
assert_error(response, 400)
async def test_creator_must_be_member(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [bob["id"]]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_unknown_member_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_bad_chat_id_in_path(client: AsyncClient) -> None:
alice = await register(client, "alice")
assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400)