forked from mtusi2026/mtusi2026lab3
refactor code
This commit is contained in:
+17
-5
@@ -3,17 +3,30 @@ from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from secrets import token_bytes
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
_secret = token_bytes(32)
|
||||
_secret: bytes | None = None
|
||||
|
||||
|
||||
class CursorError(ValueError):
|
||||
"""Недопустимый, повреждённый или применённый не к тому ресурсу курсор."""
|
||||
|
||||
|
||||
def configure_secret(secret: bytes) -> None:
|
||||
"""Устанавливает общий для всех реплик ключ подписи курсоров."""
|
||||
global _secret
|
||||
if len(secret) < 32:
|
||||
raise ValueError("cursor secret must contain at least 32 bytes")
|
||||
_secret = secret
|
||||
|
||||
|
||||
def signing_secret() -> bytes:
|
||||
if _secret is None:
|
||||
raise RuntimeError("cursor secret has not been configured")
|
||||
return _secret
|
||||
|
||||
|
||||
def _encode_bytes(value: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(value).decode().rstrip("=")
|
||||
|
||||
@@ -37,7 +50,7 @@ def encode_cursor(scope: str, created_at: datetime, item_id: str) -> str:
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode()
|
||||
signature = hmac.new(_secret, payload, hashlib.sha256).digest()
|
||||
signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
|
||||
return _encode_bytes(payload) + "." + _encode_bytes(signature)
|
||||
|
||||
|
||||
@@ -49,7 +62,7 @@ def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, str]:
|
||||
except ValueError as error:
|
||||
raise CursorError from error
|
||||
|
||||
expected_signature = hmac.new(_secret, payload, hashlib.sha256).digest()
|
||||
expected_signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
|
||||
if not hmac.compare_digest(signature, expected_signature):
|
||||
raise CursorError
|
||||
|
||||
@@ -66,4 +79,3 @@ def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, str]:
|
||||
return created_at.astimezone(UTC), item_id
|
||||
except (TypeError, ValueError, KeyError) as error:
|
||||
raise CursorError from error
|
||||
|
||||
|
||||
Reference in New Issue
Block a user