Files
mtusi2026lab7/app/sessions.py
T
Artu-Rito ab7b467957
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Implement lab 7 security and mTLS
2026-11-26 16:55:53 +03:00

66 lines
2.0 KiB
Python

"""Opaque Bearer sessions backed by Redis/Valkey, TTL-bound, AOF-persistent."""
import json
import os
import secrets
import uuid
from datetime import datetime, timedelta, timezone
import redis.asyncio as redis
from .redis_tls import connection
_client: redis.Redis | None = None
TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
def init(url: str) -> None:
global _client
url, tls = connection(url)
_client = redis.from_url(url, decode_responses=True, socket_timeout=3, socket_connect_timeout=3, **tls)
async def close() -> None:
if _client is not None:
await _client.close()
def client() -> redis.Redis:
if _client is None:
raise RuntimeError("session store is not initialized")
return _client
async def ping() -> bool:
try:
return bool(await client().ping())
except Exception: # noqa: BLE001 - readiness probe
return False
async def create(user_id: uuid.UUID) -> tuple[str, datetime]:
token = secrets.token_urlsafe(32) # 256 bits of entropy, opaque and non-guessable
expires_at = datetime.now(timezone.utc) + timedelta(seconds=TTL_SECONDS)
payload = json.dumps({"user_id": str(user_id), "expires_at": expires_at.isoformat()})
await client().set(f"session:{token}", payload, ex=TTL_SECONDS)
return token, expires_at
async def resolve(token: str) -> uuid.UUID | None:
raw = await client().get(f"session:{token}")
if raw is None:
return None
data = json.loads(raw)
return uuid.UUID(data["user_id"])
async def revoke(token: str) -> None:
await client().delete(f"session:{token}")
async def allow_login(subject: str, window: int = 60, limit: int = 10) -> tuple[bool, int]:
"""Shared fixed-window login limiter; all API replicas use the same Redis."""
key = f"login-rate:{subject}"
count = await client().incr(key)
if count == 1:
await client().expire(key, window)
ttl = max(1, int(await client().ttl(key)))
return count <= limit, ttl