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
+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,
)