Files
mtusi2026lab2/src/messenger/messaging/infrastructure/cursor.py
T
ArtyomandClaude Opus 5.5 bf8e4e3cd1 Carry over the lab 3 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy and k6 configuration, migrations, hooks, evidence and level 4
scripts and the CI job from the lab 3 solution commit 61c0c28, merge
the lab 3 Makefile targets into the lab 4 skeleton Makefile without
touching its targets, and append the lab 3 solution variables to the
skeleton .env.example. The package and the application follow the
contract version 1.4.0, and the image and the throwaway test containers
are tagged lab4 so they do not collide with a lab 3 stand on the same
host.

This is the starting point of the lab 4 cycle: lint, own tests and the
offline skeleton check pass before any lab 4 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:17:51 +03:00

60 lines
2.2 KiB
Python

import hmac
from base64 import urlsafe_b64decode, urlsafe_b64encode
from datetime import UTC, datetime, timedelta
from hashlib import sha256
from messenger.messaging.domain.errors import InvalidPageRequest
from messenger.messaging.domain.keys import HistoryKey
VERSION = "1"
SIGNATURE_BYTES = 12
EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
PARTS = 4
def _encode_part(value: bytes) -> str:
return urlsafe_b64encode(value).decode("ascii").rstrip("=")
def _decode_part(value: str) -> bytes:
padding = "=" * (-len(value) % 4)
try:
return urlsafe_b64decode(value + padding)
except (ValueError, TypeError) as error:
raise InvalidPageRequest("параметр cursor повреждён") from error
class SignedCursorCodec:
__slots__ = ("_secret",)
def __init__(self, secret: bytes) -> None:
self._secret = secret
def encode(self, scope: str, key: HistoryKey) -> str:
moment, identifier = key
micros = (moment - EPOCH) // timedelta(microseconds=1)
body = f"{VERSION}.{micros}.{identifier:032x}"
return f"{body}.{_encode_part(self._sign(scope, body))}"
def decode(self, scope: str, raw: str) -> HistoryKey:
parts = raw.split(".")
if len(parts) != PARTS or parts[0] != VERSION:
raise InvalidPageRequest("параметр cursor не распознан")
body = ".".join(parts[:3])
if not hmac.compare_digest(self._sign(scope, body), _decode_part(parts[3])):
raise InvalidPageRequest("параметр cursor недействителен для этого запроса")
try:
micros = int(parts[1])
identifier = int(parts[2], 16)
except ValueError as error:
raise InvalidPageRequest("параметр cursor повреждён") from error
try:
moment = EPOCH + timedelta(microseconds=micros)
except (OverflowError, ValueError) as error:
raise InvalidPageRequest("параметр cursor повреждён") from error
return (moment, identifier)
def _sign(self, scope: str, body: str) -> bytes:
payload = f"{scope}|{body}".encode()
return hmac.new(self._secret, payload, sha256).digest()[:SIGNATURE_BYTES]