fix: check cursor fields instead of re-encoding

628b5f2 accepted a cursor only if re-encoding the parsed key gave the
same string. That closed the format both ways: any encoding change, even
a compatible one (an optional field, key order, to_rfc3339 shared with
API responses), would turn cursors issued by a replica of the other
version into 400 during make rolling_update, which the tests cannot see.

decode_cursor now checks the fields one by one: v must be exactly the
integer 1, t and i must be strings, i must be in the server's notation
(lowercase 8-4-4-4-12). Unknown fields are ignored, so a tampered cursor
is still a 400 while the format stays open for compatible changes. The
rule records how to change the format: a new CURSOR_VERSION, with both
versions accepted while replicas are replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 13:11:57 +03:00
co-authored by Claude Opus 5.5
parent 628b5f2278
commit 8fe467ace0
8 changed files with 170 additions and 76 deletions
+14 -11
View File
@@ -5,10 +5,12 @@
привязывает курсор к конкретному списку: курсор чужого чата или списка
чатов другого пользователя не разбирается.
Принимается только та запись, которую выдал сервер: после разбора курсор
собирается заново и сравнивается с полученной строкой. Так изменённый
клиентом курсор (`"v": true`, лишнее поле, id или время в другой записи)
— ошибка, а не страница.
Поля проверяются по отдельности: `v` — ровно целое 1, `t` и `i` — строки,
`i` — в записи сервера (8-4-4-4-12, нижний регистр). Так изменённый
клиентом курсор — ошибка, а не 500 и не страница. Незнакомые поля
игнорируются: необязательное поле можно добавить, не ломая курсоры реплик
прежней версии при поочерёдной замене. Формат, который прежний код не
прочтёт, — новая `v`, и на время замены сервер принимает обе.
"""
import base64
@@ -53,8 +55,8 @@ def decode_cursor(cursor: str, *, scope: str) -> CursorKey:
"""Ключ последнего элемента предыдущей страницы.
Бросает `CursorError`, если курсор не разбирается, другой версии,
выдан для другой области или отличается от записи, которую выдал бы
`encode_cursor` для того же ключа.
выдан для другой области или его поля не того типа и не в той
записи, в которой их пишет `encode_cursor`.
"""
try:
padded = cursor + "=" * (-len(cursor) % 4)
@@ -64,7 +66,9 @@ def decode_cursor(cursor: str, *, scope: str) -> CursorKey:
if not isinstance(payload, dict):
raise CursorError("malformed cursor")
if payload.get("v") != CURSOR_VERSION:
version = payload.get("v")
# bool — подкласс int: без проверки типа true прошло бы как 1
if type(version) is not int or version != CURSOR_VERSION:
raise CursorError("unsupported cursor version")
if payload.get("s") != scope:
raise CursorError("cursor belongs to another list")
@@ -78,8 +82,7 @@ def decode_cursor(cursor: str, *, scope: str) -> CursorKey:
item_id = UUID(raw_id)
except ValueError as e:
raise CursorError("malformed cursor") from e
issued = encode_cursor(scope=scope, created_at=created_at, item_id=item_id)
if issued != cursor:
raise CursorError("cursor was changed")
# UUID() принимает и запись без дефисов, в верхнем регистре, с urn:uuid:
if str(item_id) != raw_id:
raise CursorError("malformed cursor")
return created_at, item_id