forked from mtusi2026/mtusi2026lab4
add lab3
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import base64
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
_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("=")
|
||||
|
||||
|
||||
def _decode_bytes(value: str) -> bytes:
|
||||
try:
|
||||
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
||||
except (ValueError, UnicodeEncodeError) as error:
|
||||
raise CursorError from error
|
||||
|
||||
|
||||
def encode_cursor(scope: str, created_at: datetime, item_id: str) -> str:
|
||||
payload = json.dumps(
|
||||
{
|
||||
"scope": scope,
|
||||
"created_at": created_at.astimezone(UTC)
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z"),
|
||||
"id": item_id,
|
||||
},
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode()
|
||||
signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
|
||||
return _encode_bytes(payload) + "." + _encode_bytes(signature)
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, str]:
|
||||
try:
|
||||
encoded_payload, encoded_signature = cursor.split(".")
|
||||
payload = _decode_bytes(encoded_payload)
|
||||
signature = _decode_bytes(encoded_signature)
|
||||
except ValueError as error:
|
||||
raise CursorError from error
|
||||
|
||||
expected_signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
|
||||
if not hmac.compare_digest(signature, expected_signature):
|
||||
raise CursorError
|
||||
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
if set(data) != {"scope", "created_at", "id"}:
|
||||
raise CursorError
|
||||
if data["scope"] != expected_scope:
|
||||
raise CursorError
|
||||
item_id = str(UUID(data["id"]))
|
||||
created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise CursorError
|
||||
return created_at.astimezone(UTC), item_id
|
||||
except (TypeError, ValueError, KeyError) as error:
|
||||
raise CursorError from error
|
||||
Reference in New Issue
Block a user