"""Keyset-курсор: подписан ключом процесса и привязан к ресурсу (kind + scope).""" from __future__ import annotations import base64 import binascii import hashlib import hmac import json import secrets from dataclasses import dataclass from uuid import UUID from .domain import Position, parse_rfc3339_z CURSOR_VERSION = 1 SIGNATURE_BYTES = 16 SEPARATOR = "." KIND_CHATS = "chats" KIND_MESSAGES = "messages" class InvalidCursor(ValueError): """Курсор повреждён, подделан или выпущен для другого ресурса.""" def _b64encode(raw: bytes) -> str: return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") def _b64decode(value: str) -> bytes: return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) def _parse_timestamp(value: object) -> str: """Проверяет, что метка времени — RFC 3339 UTC с суффиксом Z.""" if not isinstance(value, str): raise InvalidCursor("cursor timestamp is not a string") try: parse_rfc3339_z(value) except ValueError: raise InvalidCursor("cursor timestamp is not RFC 3339 UTC with Z suffix") from None return value @dataclass(frozen=True) class Cursor: """Позиция последнего отданного элемента выборки.""" kind: str scope: str created_at: str item_id: str @property def position(self) -> Position: """Место в порядке (created_at, id), с которого продолжается выборка.""" return (parse_rfc3339_z(self.created_at), UUID(self.item_id)) class CursorCodec: """Кодирует и проверяет курсоры ключом, известным только процессу.""" def __init__(self, key: bytes | None = None) -> None: self._key = secrets.token_bytes(32) if key is None else key def encode(self, kind: str, scope: str, created_at: str, item_id: str) -> str: payload = json.dumps( { "v": CURSOR_VERSION, "kind": kind, "scope": scope, "created_at": created_at, "id": item_id, }, ensure_ascii=False, separators=(",", ":"), sort_keys=True, ).encode("utf-8") signature = hmac.new(self._key, payload, hashlib.sha256).digest()[:SIGNATURE_BYTES] return _b64encode(payload) + SEPARATOR + _b64encode(signature) def decode(self, token: str, *, kind: str, scope: str) -> Cursor: """Разбирает курсор или поднимает InvalidCursor — наружу это всегда 400.""" if not isinstance(token, str) or not token: raise InvalidCursor("cursor is empty") encoded_payload, separator, encoded_signature = token.partition(SEPARATOR) if not separator: raise InvalidCursor("cursor has no signature part") try: payload = _b64decode(encoded_payload) signature = _b64decode(encoded_signature) except (binascii.Error, ValueError): raise InvalidCursor("cursor is not valid base64url") from None expected = hmac.new(self._key, payload, hashlib.sha256).digest()[:SIGNATURE_BYTES] if not hmac.compare_digest(signature, expected): raise InvalidCursor("cursor signature mismatch") try: data = json.loads(payload.decode("utf-8")) except (UnicodeDecodeError, ValueError): raise InvalidCursor("cursor payload is not valid JSON") from None if not isinstance(data, dict) or data.get("v") != CURSOR_VERSION: raise InvalidCursor("unsupported cursor version") cursor = Cursor( kind=str(data.get("kind", "")), scope=str(data.get("scope", "")), created_at=_parse_timestamp(data.get("created_at")), item_id=str(data.get("id", "")), ) try: UUID(cursor.item_id) except ValueError: raise InvalidCursor("cursor id is not a UUID") from None if cursor.kind != kind or cursor.scope != scope: raise InvalidCursor("cursor belongs to another resource") return cursor