Проверять формат cursor: неверный cursor даёт 400

This commit is contained in:
2026-10-09 13:55:19 +03:00
parent cd66e8cd53
commit 31530fcf57
3 changed files with 63 additions and 10 deletions
+15 -8
View File
@@ -22,7 +22,7 @@ import security
from errors import ApiError, bad_credentials, error_response, invalid, not_found, unauthorized from errors import ApiError, bad_credentials, error_response, invalid, not_found, unauthorized
from schemas import CreateChat, CreateMessage, CreateUser from schemas import CreateChat, CreateMessage, CreateUser
from sessions import Sessions from sessions import Sessions
from store import Store, UnknownMember, UsernameTaken, timestamp from store import TIME_FORMAT, Store, UnknownMember, UsernameTaken, timestamp
logging.basicConfig( logging.basicConfig(
level=config.LOG_LEVEL.upper(), level=config.LOG_LEVEL.upper(),
@@ -129,8 +129,8 @@ def current_session(request: Request) -> Session:
return Session(user_id, token) return Session(user_id, token)
def encode_cursor(scope: str, item: dict) -> str: def encode_cursor(scope: str, created_at: str, item_id: str) -> str:
raw = json.dumps([scope, item["created_at"], item["id"]]) raw = json.dumps([scope, created_at, item_id])
return base64.urlsafe_b64encode(raw.encode()).decode() return base64.urlsafe_b64encode(raw.encode()).decode()
@@ -139,18 +139,25 @@ def decode_cursor(scope: str, cursor):
if cursor is None: if cursor is None:
return None return None
try: try:
cursor_scope, created_at, item_id = json.loads(base64.urlsafe_b64decode(cursor.encode())) # validate=True: символ вне алфавита base64 — ошибка, а не пропускается молча
key = [datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc), str(UUID(item_id))] cursor_scope, created_at, item_id = json.loads(base64.b64decode(cursor, altchars=b"-_", validate=True))
# время и id принимаются только в том виде, в котором их выдаёт сам сервер
moment = datetime.strptime(created_at, TIME_FORMAT).replace(tzinfo=timezone.utc)
time_ok = moment.strftime(TIME_FORMAT) == created_at
id_ok = str(UUID(item_id)) == item_id
except (TypeError, ValueError, AttributeError): except (TypeError, ValueError, AttributeError):
raise invalid("Некорректный cursor") raise invalid("Некорректный cursor")
# cursor действует только для того списка, в котором был выдан # cursor действует только для того списка, в котором был выдан
if cursor_scope != scope: if cursor_scope != scope or not time_ok or not id_ok:
raise invalid("Некорректный cursor") raise invalid("Некорректный cursor")
return key # у одной позиции есть ровно одна запись cursor: другое оформление JSON или base64 не принимается
if encode_cursor(scope, created_at, item_id) != cursor:
raise invalid("Некорректный cursor")
return [moment, item_id]
def page(scope: str, items: list, has_more: bool) -> dict: def page(scope: str, items: list, has_more: bool) -> dict:
next_cursor = encode_cursor(scope, items[-1]) if has_more else None next_cursor = encode_cursor(scope, items[-1]["created_at"], items[-1]["id"]) if has_more else None
return {"items": items, "next_cursor": next_cursor} return {"items": items, "next_cursor": next_cursor}
+5 -2
View File
@@ -15,9 +15,12 @@ class UnknownMember(Exception):
pass pass
# ширина строки фиксированная: 6 знаков микросекунд, столько же хранит timestamptz
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
def timestamp(value) -> str: def timestamp(value) -> str:
# ширина строки фиксированная: 6 знаков микросекунд, столько же хранит timestamptz return value.astimezone(timezone.utc).strftime(TIME_FORMAT)
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def user_json(row) -> dict: def user_json(row) -> dict:
+43
View File
@@ -1,3 +1,5 @@
import base64
import json
import unittest import unittest
import urllib.parse import urllib.parse
@@ -49,6 +51,47 @@ class MessagePaginationTest(unittest.TestCase):
with self.subTest(cursor=cursor): with self.subTest(cursor=cursor):
self.assertEqual(call("GET", self.path + "?cursor=" + cursor, user=self.user)[0], 400) self.assertEqual(call("GET", self.path + "?cursor=" + cursor, user=self.user)[0], 400)
def test_cursor_format_is_checked(self):
_, first, _ = call("GET", self.path + "?limit=3", user=self.user)
good = first["next_cursor"]
scope, created_at, item_id = json.loads(base64.urlsafe_b64decode(good))
def encode(value, **options):
return base64.urlsafe_b64encode(json.dumps(value, **options).encode()).decode()
# тест знает внутренний формат cursor: собранный заново правильный cursor совпадает с выданным
self.assertEqual(encode([scope, created_at, item_id]), good)
bad = {
"посторонний символ внутри base64": good[:5] + "!" + good[5:],
"пробел внутри base64": good[:5] + " " + good[5:],
"перевод строки в конце": good + "\n",
"лишний знак =": good + "=",
"обрезанный": good[:-4],
"время не в формате сервера": encode([scope, "вчера", item_id]),
"время без микросекунд": encode([scope, created_at[:19] + "Z", item_id]),
"время с неполными микросекундами": encode([scope, created_at[:21] + "Z", item_id]),
"время со смещением вместо Z": encode([scope, created_at[:-1] + "+00:00", item_id]),
"несуществующая дата": encode([scope, "2026-13-45T25:61:61.000000Z", item_id]),
"число вместо времени": encode([scope, 1234567890, item_id]),
"id не UUID": encode([scope, created_at, "abc"]),
"UUID в верхнем регистре": encode([scope, created_at, item_id.upper()]),
"UUID без дефисов": encode([scope, created_at, item_id.replace("-", "")]),
"null вместо id": encode([scope, created_at, None]),
"лишний элемент": encode([scope, created_at, item_id, "x"]),
"не хватает элемента": encode([scope, created_at]),
"объект вместо списка": encode({"scope": scope, "created_at": created_at, "id": item_id}),
"тот же JSON без пробелов": encode([scope, created_at, item_id], separators=(",", ":")),
"пустой список": encode([]),
}
for name, cursor in bad.items():
with self.subTest(name):
path = self.path + "?cursor=" + urllib.parse.quote(cursor, safe="")
status, body, _ = call("GET", path, user=self.user)
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
# правильный cursor при этом продолжает работать
self.assertEqual(call("GET", self.path + "?cursor=" + urllib.parse.quote(good, safe=""), user=self.user)[0], 200)
def test_cursor_from_another_chat(self): def test_cursor_from_another_chat(self):
other = new_chat(self.user, title="Другой чат") other = new_chat(self.user, title="Другой чат")
send(self.user, other, "раз") send(self.user, other, "раз")