"""Idempotency-Key отправки сообщения (лаба 3, contracts/README.md). Повтор того же тела с тем же ключом — тот же 201 и то же `Message`, в истории одно сообщение; другое тело — 409; область ключа — автор, чат и ключ; повтор заново проверяет сессию и доступ; порядок кодов 401 → 400 → 404 → 409. Гонка одного ключа — `test_race.py`; сбой записи, отказ БД и срок ключа — проверки отказов (`test_failures.py`). Повтору через другую реплику нужны ≥ 2 реплики за `BASE_URL` (фикстура `replicas`). """ from typing import Any import httpx import pytest from helpers import ( BEARER_CHALLENGE, CHATS, IDEMPOTENCY_KEY, assert_error, assert_replicas, assert_unauthorized, create_chat, headers, instance_id, login, logout, messages_path, new_key, read_history, register, send, ) # 128 символов, в том числе все допустимые знаки, кроме букв и цифр LONGEST_KEY = "a1.B_:-Z" * 16 def texts(client: httpx.Client, actor: dict[str, Any], chat: dict[str, Any]) -> list: items, _ = read_history(client, actor, chat, limit=100) return [item["text"] for item in items] @pytest.fixture def pair(client: httpx.Client) -> tuple[dict[str, Any], dict[str, Any], dict]: """Алиса, Боб и их общий чат.""" alice, bob = register(client, "alice"), register(client, "bob") return alice, bob, create_chat(client, alice, bob) def test_missing_key_is_400(client: httpx.Client, pair: tuple) -> None: alice, _, chat = pair assert_error( send(client, alice, chat, "без ключа", key=None), 400, "invalid_request" ) assert texts(client, alice, chat) == [] @pytest.mark.parametrize( "key", [b"", b"a" * 129, b"a b", b"a/b", "ключ".encode()], ids=["empty", "too-long", "space", "slash", "non-ascii"], ) def test_invalid_key_is_400(client: httpx.Client, pair: tuple, key: bytes) -> None: alice, _, chat = pair response = send(client, alice, chat, "x", key=key) assert_error(response, 400, "invalid_request") # значение ключа в ответ не попадает if len(key) > 1: assert key.decode(errors="replace") not in response.text assert texts(client, alice, chat) == [] def test_longest_key_is_accepted(client: httpx.Client, pair: tuple) -> None: alice, _, chat = pair assert len(LONGEST_KEY) == 128 response = send(client, alice, chat, "длинный ключ", key=LONGEST_KEY) assert response.status_code == 201, response.text assert texts(client, alice, chat) == ["длинный ключ"] def test_replay_returns_same_message(client: httpx.Client, pair: tuple) -> None: alice, bob, chat = pair key = new_key() first = send(client, alice, chat, "Привет, мир 👋", key=key) again = send(client, alice, chat, "Привет, мир 👋", key=key) assert first.status_code == again.status_code == 201 # тот же id, created_at до микросекунды, тот же текст assert again.json() == first.json() assert texts(client, bob, chat) == ["Привет, мир 👋"] def test_same_json_in_other_spelling_is_replay( client: httpx.Client, pair: tuple, ) -> None: """Пробелы и \\u-экранирование вместо UTF-8 — тот же JSON.""" alice, _, chat = pair key = new_key() first = send(client, alice, chat, "Привет", key=key).json() raw = b'{ "text" :\n "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }' response = client.post( messages_path(chat), content=raw, headers={ **headers(alice), IDEMPOTENCY_KEY: key, "Content-Type": "application/json", }, ) assert response.status_code == 201, response.text assert response.json() == first assert texts(client, alice, chat) == ["Привет"] def test_other_body_is_409(client: httpx.Client, pair: tuple) -> None: alice, _, chat = pair key = new_key() first = send(client, alice, chat, "первое", key=key).json() assert_error(send(client, alice, chat, "второе", key=key), 409, "conflict") assert texts(client, alice, chat) == ["первое"] # 409 ключ не портит: прежнее тело по-прежнему повторяется assert send(client, alice, chat, "первое", key=key).json() == first def test_same_key_other_user_is_new_message(client: httpx.Client, pair: tuple) -> None: alice, bob, chat = pair key = new_key() from_alice = send(client, alice, chat, "от Алисы", key=key).json() from_bob = send(client, bob, chat, "от Боба", key=key).json() assert from_alice["id"] != from_bob["id"] assert sorted(texts(client, alice, chat)) == ["от Алисы", "от Боба"] def test_same_key_other_chat_is_new_message(client: httpx.Client, pair: tuple) -> None: alice, bob, chat = pair other = create_chat(client, alice, bob, title="Второй чат") key = new_key() first = send(client, alice, chat, "одно и то же", key=key).json() second = send(client, alice, other, "одно и то же", key=key).json() assert first["id"] != second["id"] assert second["chat_id"] == other["id"] for target in (chat, other): assert texts(client, alice, target) == ["одно и то же"] def test_key_on_other_post_is_ignored(client: httpx.Client, pair: tuple) -> None: """Ключ обязателен только для сообщений: создание чата он не защищает.""" alice, bob, _ = pair key = new_key() created = [] for _ in range(2): response = client.post( CHATS, json={"title": "Тот же ключ", "member_ids": [alice["id"], bob["id"]]}, headers={**headers(alice), IDEMPOTENCY_KEY: key}, ) assert response.status_code == 201, response.text created.append(response.json()["id"]) assert created[0] != created[1] def test_replay_with_revoked_token_is_401(client: httpx.Client, pair: tuple) -> None: alice, _, chat = pair key = new_key() assert send(client, alice, chat, "до выхода", key=key).status_code == 201 assert logout(client, alice).status_code == 204 assert_unauthorized( send(client, alice, chat, "до выхода", key=key), BEARER_CHALLENGE ) def test_replay_with_new_session_of_same_user( client: httpx.Client, pair: tuple ) -> None: alice, _, chat = pair key = new_key() first = send(client, alice, chat, "одна сессия", key=key).json() again = {**alice, "token": login(client, alice)} assert again["token"] != alice["token"] assert send(client, again, chat, "одна сессия", key=key).json() == first def test_outsider_with_members_key_is_404(client: httpx.Client, pair: tuple) -> None: alice, _, chat = pair eve = register(client, "eve") key = new_key() first = send(client, alice, chat, "только участникам", key=key).json() assert_error( send(client, eve, chat, "только участникам", key=key), 404, "not_found" ) assert send(client, alice, chat, "только участникам", key=key).json() == first assert texts(client, alice, chat) == ["только участникам"] def test_codes_order_401_400_404_409(client: httpx.Client, pair: tuple) -> None: """Сначала сессия, затем ключ и тело, затем доступ, затем ключ занят.""" alice, _, chat = pair eve = register(client, "eve") no_session = client.post(messages_path(chat), json={"text": "x"}) assert_unauthorized(no_session, BEARER_CHALLENGE) # посторонний без ключа: 400 раньше 404 assert_error(send(client, eve, chat, "x", key=None), 400, "invalid_request") # невалидное тело с занятым ключом: 400 раньше 409 key = new_key() assert send(client, alice, chat, "первое", key=key).status_code == 201 assert_error(send(client, alice, chat, "", key=key), 400, "invalid_request") # посторонний с чужим занятым ключом и другим телом: 404 раньше 409 assert_error(send(client, eve, chat, "другое", key=key), 404, "not_found") assert_error(send(client, alice, chat, "другое", key=key), 409, "conflict") def test_invalid_request_keeps_key_free(client: httpx.Client, pair: tuple) -> None: alice, _, chat = pair key = new_key() assert_error(send(client, alice, chat, "", key=key), 400, "invalid_request") response = send(client, alice, chat, "теперь валидно", key=key) assert response.status_code == 201, response.text assert texts(client, alice, chat) == ["теперь валидно"] def test_replay_through_other_replica( client: httpx.Client, pair: tuple, replicas: int, ) -> None: """Повтор, который обслужила другая реплика, — тот же `Message`; 409 — от разных реплик: ключ живёт в PostgreSQL, а не в памяти процесса.""" alice, _, chat = pair key = new_key() response = send(client, alice, chat, "повтор через реплики", key=key) first = response.json() origin = instance_id(response) replays: dict[str, Any] = {} for _ in range(2 * replicas): response = send(client, alice, chat, "повтор через реплики", key=key) assert response.status_code == 201, response.text replays[instance_id(response)] = response.json() print(f"sent via {origin}, replayed via {sorted(replays)}") assert_replicas({origin, *replays}, replicas) assert all(message == first for message in replays.values()) conflicts = set() for _ in range(2 * replicas): response = send(client, alice, chat, "другое тело", key=key) assert_error(response, 409, "conflict") conflicts.add(instance_id(response)) print(f"409 via {sorted(conflicts)}") assert_replicas(conflicts, replicas) assert texts(client, alice, chat) == ["повтор через реплики"]