test: cover tampered cursors and UUID input forms

Add black-box tests for the strict-id-validation change: a server-issued
cursor with one field changed (non-string or non-canonical item id,
v=true, extra field) on both lists, member_ids with values of other JSON
types, a non-array member_ids and other UUID notations, and chat_id in
the path of the three chat endpoints. Sync the change's delta specs into
api-conventions, chats and pagination so the coverage check knows the
new scenarios.

The cursor and UUID-notation tests fail on the current code by design;
the fix follows in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 12:51:16 +03:00
co-authored by Claude Opus 5.5
parent 40f470f5b4
commit c5d5a1ab25
14 changed files with 1032 additions and 10 deletions
+18 -1
View File
@@ -2,7 +2,7 @@
import json
import re
from collections.abc import Iterable
from collections.abc import Iterable, Mapping
from datetime import datetime, timedelta
from functools import cache
from pathlib import Path
@@ -143,6 +143,23 @@ def assert_error(resp: httpx.Response, status: int) -> dict[str, Any]:
return error
def assert_errors(
responses: Mapping[str, httpx.Response],
status: int,
) -> None:
"""Каждый вариант запроса — ошибка `status` в формате контракта.
Статусы сверяются все разом: при падении видно, что ответил каждый
вариант, а не только первый.
"""
statuses = {name: resp.status_code for name, resp in responses.items()}
assert set(statuses.values()) == {status}, (
f"expected {status} for every variant, got {statuses}"
)
for resp in responses.values():
assert_error(resp, status)
def assert_unauthorized(
resp: httpx.Response,
challenge: str,
+130
View File
@@ -2,6 +2,8 @@
форматы."""
import json
import urllib.parse
import uuid
from collections import Counter
from typing import Any
@@ -19,6 +21,7 @@ from api_client import (
from contract import (
assert_created_at,
assert_error,
assert_errors,
assert_instance_id,
assert_ok,
assert_uuid,
@@ -26,6 +29,10 @@ from contract import (
)
UNICODE_TEXT = "Привет, мир 👋"
# не UUID в пути: типы JSON, записанные строкой URL
NOT_UUID_PATHS = ("123", "false", "[]", "{}")
# не UUID в элементе member_ids: значения других типов JSON
NOT_UUID_VALUES: tuple[Any, ...] = ([], {}, 123, False)
@pytest.mark.spec("api-conventions", "Unicode сохраняется")
@@ -259,3 +266,126 @@ def test_id_and_created_at_format(
assert_uuid(member_id)
assert_uuid(message["chat_id"])
assert_uuid(message["sender_id"])
def other_uuid_forms(value: str) -> dict[str, str]:
"""Тот же UUID в записях, которых нет в `format: uuid` контракта."""
return {
"no hyphens": value.replace("-", ""),
"urn": f"urn:uuid:{value}",
"braces": f"{{{value}}}",
}
def chat_id_requests(
api: Api,
actor: Actor,
chat_id: str,
) -> dict[str, httpx.Response]:
"""Три ручки с `chat_id` в пути; значение кодируется для URL явно."""
quoted = urllib.parse.quote(chat_id, safe="")
return {
"GET chat": api.request("GET", f"{API}/chats/{quoted}", actor=actor),
"GET history": api.messages_page(actor, quoted),
"POST message": api.post_message(
actor,
quoted,
json={"text": "path"},
),
}
def post_chat(
api: Api,
actor: Actor,
title: str,
member_ids: list[Any],
) -> httpx.Response:
return api.request(
"POST",
f"{API}/chats",
actor=actor,
json={"title": title, "member_ids": member_ids},
)
def chat_titles(api: Api, actor: Actor) -> set[str]:
return {
chat["title"]
for page in api.chat_pages(actor)
for chat in page["items"]
}
@pytest.mark.spec("api-conventions", "UUID другого типа в теле")
def test_uuid_of_other_type_in_body(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
# рядом с id Алисы: иначе 400 дала бы и проверка «вызывающий в списке»
assert_errors(
{
repr(value): post_chat(api, alice, title, [alice.id, value])
for value in NOT_UUID_VALUES
},
400,
)
assert title not in chat_titles(api, alice)
@pytest.mark.spec("api-conventions", "Не UUID в пути")
def test_not_uuid_in_path(api: Api, alice: Actor) -> None:
assert_errors(
{
f"{name} {value}": resp
for value in NOT_UUID_PATHS
for name, resp in chat_id_requests(api, alice, value).items()
},
400,
)
@pytest.mark.spec("api-conventions", "Другая запись UUID")
def test_other_uuid_forms(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
history = api.all_messages(alice, chat["id"])
title = f"rejected-{uuid.uuid4().hex}"
responses = {
f"{name} / {form}": resp
for form, value in other_uuid_forms(chat["id"]).items()
for name, resp in chat_id_requests(api, alice, value).items()
}
responses |= {
f"member_ids / {form}": post_chat(api, alice, title, [alice.id, value])
for form, value in other_uuid_forms(bob.id).items()
}
assert_errors(responses, 400)
assert api.all_messages(alice, chat["id"]) == history
assert title not in chat_titles(api, alice)
@pytest.mark.spec("api-conventions", "UUID в верхнем регистре в пути")
def test_upper_case_uuid_in_path(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
upper = chat["id"].upper()
got = api.request("GET", f"{API}/chats/{upper}", actor=alice)
# assert_ok проверяет и формат: id и chat_id в ответах — нижний регистр
assert assert_ok(got, 200, "Chat") == chat
sent = assert_ok(
api.post_message(alice, upper, json={"text": "upper"}),
201,
"Message",
)
assert sent["chat_id"] == chat["id"]
upper_page = assert_ok(api.messages_page(alice, upper), 200, "MessagePage")
lower_page = assert_ok(
api.messages_page(alice, chat["id"]),
200,
"MessagePage",
)
assert upper_page == lower_page == {"items": [sent], "next_cursor": None}
+31 -2
View File
@@ -7,14 +7,14 @@ import httpx
import pytest
from api_client import API, Actor, Api
from contract import assert_error, assert_ok
from contract import assert_error, assert_errors, assert_ok
def create_raw(
api: Api,
actor: Actor,
title: str,
member_ids: list[str],
member_ids: Any,
) -> httpx.Response:
return api.request(
"POST",
@@ -78,6 +78,35 @@ def test_empty_members(api: Api, alice: Actor) -> None:
assert_error(create_raw(api, alice, "Empty", []), 400)
@pytest.mark.spec("chats", "Участник в верхнем регистре")
def test_member_in_upper_case(api: Api, alice: Actor, bob: Actor) -> None:
resp = create_raw(api, alice, "Upper", [alice.id, bob.id.upper()])
chat = assert_ok(resp, 201, "Chat")
assert chat["member_ids"] == [alice.id, bob.id]
assert chat["id"] in listed_ids(api, bob)
@pytest.mark.spec("chats", "Повтор участника в другом регистре")
def test_duplicate_member_other_case(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
member_ids = [alice.id, alice.id.upper()]
assert_error(create_raw(api, alice, title, member_ids), 400)
assert title not in listed_titles(api, alice)
@pytest.mark.spec("chats", "member_ids не массив")
def test_member_ids_not_array(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
assert_errors(
{
repr(member_ids): create_raw(api, alice, title, member_ids)
for member_ids in ({}, 123, False, alice.id)
},
400,
)
assert title not in listed_titles(api, alice)
@pytest.mark.spec("chats", "Участник")
def test_member_reads_chat(
api: Api,
+86 -1
View File
@@ -1,5 +1,7 @@
"""Спек `pagination`: `limit`, `next_cursor`, курсоры обоих списков."""
import base64
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
@@ -8,7 +10,23 @@ import httpx
import pytest
from api_client import Actor, Api, order_key
from contract import assert_error, assert_ok
from contract import assert_error, assert_errors, assert_ok
# подмена в содержимом курсора: какие поля заменить
type Change = Callable[[dict[str, Any]], dict[str, Any]]
# подмены выданного курсора (сценарий «Изменённый курсор»): ключ элемента
# не строка, тот же id в другой записи, версия true, лишнее поле
CURSOR_CHANGES: dict[str, Change] = {
"i=[]": lambda _: {"i": []},
"i={}": lambda _: {"i": {}},
"i=123": lambda _: {"i": 123},
"i=false": lambda _: {"i": False},
"i without hyphens": lambda payload: {"i": payload["i"].replace("-", "")},
"i upper case": lambda payload: {"i": payload["i"].upper()},
"v=true": lambda _: {"v": True},
"extra field": lambda _: {"x": 1},
}
@dataclass(frozen=True)
@@ -161,3 +179,70 @@ def test_garbage_cursor(listing: Listing) -> None:
# eyJ4IjoxfQ — корректный base64 от {"x":1}, но не курсор сервиса
for cursor in ("garbage", "eyJ4IjoxfQ", "!!!"):
assert_error(listing.page(cursor=cursor), 400)
def cursor_payload(cursor: str) -> dict[str, Any]:
"""Содержимое курсора сервиса: base64url без `=` от JSON."""
padded = cursor + "=" * (-len(cursor) % 4)
return json.loads(base64.urlsafe_b64decode(padded))
def encode_payload(payload: dict[str, Any]) -> str:
"""Курсор из содержимого — так же, как его кодирует сервис."""
raw = json.dumps(payload, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def tamper(cursor: str, change: Change) -> str:
"""Выданный курсор с одной подменой в содержимом.
Без подмены перекодирование обязано вернуть ту же строку: иначе формат
курсора изменился, и 400 на подмену ничего бы не доказывал.
"""
payload = cursor_payload(cursor)
assert encode_payload(payload) == cursor, (
f"cursor format changed, re-encoded payload differs: {payload}"
)
return encode_payload(payload | change(payload))
@dataclass(frozen=True)
class IssuedCursor:
"""Список и курсор его второй страницы, выданный сервером."""
listing: Listing
cursor: str
@pytest.fixture
def issued(
listing: Listing,
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> IssuedCursor:
"""В истории два сообщения, у Алисы два чата: у обоих списков есть
вторая страница при `limit=1`."""
fill(api, alice, chat["id"], 2)
api.create_chat(alice, bob, title="second")
first = assert_ok(listing.page(limit=1), 200, listing.schema)
assert first["next_cursor"], "no second page"
return IssuedCursor(listing=listing, cursor=first["next_cursor"])
@pytest.mark.spec("pagination", "Изменённый курсор")
def test_tampered_cursor(issued: IssuedCursor) -> None:
"""Курсор не собирается с нуля: с чужими `v` или `s` его отсекла бы
проверка версии или области раньше разбора ключа."""
page = issued.listing.page
# контроль: тот же курсор, перекодированный без подмены, принимается
unchanged = tamper(issued.cursor, lambda _: {})
assert_ok(page(cursor=unchanged), 200, issued.listing.schema)
assert_errors(
{
name: page(cursor=tamper(issued.cursor, change))
for name, change in CURSOR_CHANGES.items()
},
400,
)