338 lines
13 KiB
Python
338 lines
13 KiB
Python
"""Opaque Bearer sessions: PostgreSQL is the source of truth, Valkey is a cache.
|
|
|
|
Design (see REPORT.md):
|
|
|
|
* ``sessions`` in PostgreSQL owns identity, expiry and revocation.
|
|
* Valkey stores the same session under ``session:<sha256(token)>`` for at most
|
|
``CACHE_TTL_SECONDS`` and never longer than the session's remaining lifetime.
|
|
* Revocation writes a tombstone instead of relying on ``DEL`` alone, so a stale
|
|
cache entry cannot authenticate after logout.
|
|
* When Valkey is unavailable every request falls back to PostgreSQL. A cache
|
|
error is never treated as "authenticated", and a cache hit is only trusted
|
|
because it came from a session row that PostgreSQL confirmed at login time.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import secrets
|
|
import time
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
from typing import Any
|
|
|
|
import redis.asyncio as redis
|
|
from psycopg_pool import AsyncConnectionPool
|
|
from redis.backoff import NoBackoff
|
|
from redis.retry import Retry
|
|
|
|
from . import store
|
|
from .config import DEFAULT_IDEMPOTENCY_TTL_SECONDS as IDEMPOTENCY_TTL_SECONDS
|
|
from .errors import ApiProblem
|
|
from .pagination import format_timestamp
|
|
|
|
logger = logging.getLogger("messenger.sessions")
|
|
|
|
TOKEN_BYTES = 48 # 384 bits of entropy, well above the required 256.
|
|
CACHE_PREFIX = "session:"
|
|
REVOKED = "revoked"
|
|
# After a cache error, skip Valkey for a few seconds instead of paying the
|
|
# connect timeout on every request (lookup and remember would cost two each).
|
|
FAILURE_COOLDOWN_SECONDS = 5.0
|
|
# Bound on revocations remembered while the cache cannot accept a tombstone.
|
|
MAX_PENDING_REVOCATIONS = 4096
|
|
|
|
HIT = "hit"
|
|
MISS = "miss"
|
|
TOMBSTONE = "revoked"
|
|
ERROR = "error"
|
|
|
|
|
|
def token_hash(token: str) -> str:
|
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|
|
|
|
|
class SessionCache:
|
|
"""Small, failure-tolerant Valkey client used only for session lookups."""
|
|
|
|
def __init__(self, url: str | None, *, timeout_seconds: float, ttl_cap: int) -> None:
|
|
self.ttl_cap = max(1, ttl_cap)
|
|
self.timeout_seconds = timeout_seconds
|
|
# hashed token -> epoch at which the session would be expired anyway.
|
|
# PostgreSQL already holds the authoritative revocation; this only keeps
|
|
# logout immediate for this process while the cache is unreachable.
|
|
self._pending: dict[str, float] = {}
|
|
self._disabled_until = 0.0
|
|
self._degraded = False
|
|
self.client: redis.Redis | None = None
|
|
if url:
|
|
self.client = redis.Redis.from_url(
|
|
url,
|
|
socket_timeout=timeout_seconds,
|
|
socket_connect_timeout=timeout_seconds,
|
|
decode_responses=True,
|
|
health_check_interval=30,
|
|
# A cache must fail fast: one attempt, no retry loop, so a dead
|
|
# Valkey costs at most one timeout before PostgreSQL answers.
|
|
retry=Retry(NoBackoff(), 0),
|
|
retry_on_error=[],
|
|
)
|
|
|
|
@property
|
|
def enabled(self) -> bool:
|
|
return self.client is not None
|
|
|
|
def _ready(self) -> bool:
|
|
"""True when a cache call is worth attempting right now."""
|
|
return self.client is not None and time.monotonic() >= self._disabled_until
|
|
|
|
def _unavailable(self, operation: str, exc: BaseException) -> None:
|
|
self._disabled_until = time.monotonic() + FAILURE_COOLDOWN_SECONDS
|
|
# One warning per outage, not one per request.
|
|
if not self._degraded:
|
|
self._degraded = True
|
|
logger.warning(
|
|
"cache_unavailable operation=%s error=%s cooldown_seconds=%s",
|
|
operation,
|
|
type(exc).__name__,
|
|
FAILURE_COOLDOWN_SECONDS,
|
|
)
|
|
|
|
def _ok(self) -> None:
|
|
self._degraded = False
|
|
|
|
def remember_revocation(self, hashed: str, remaining: float) -> None:
|
|
"""Ask this process to reject a token even if the cache cannot store it."""
|
|
if len(self._pending) >= MAX_PENDING_REVOCATIONS:
|
|
# Drop the entries closest to expiry: they are the least useful.
|
|
keep = len(self._pending) // 4
|
|
for key, _ in sorted(self._pending.items(), key=lambda item: item[1])[:keep]:
|
|
self._pending.pop(key, None)
|
|
self._pending[hashed] = time.time() + max(1.0, remaining)
|
|
|
|
def is_locally_revoked(self, hashed: str) -> bool:
|
|
deadline = self._pending.get(hashed)
|
|
if deadline is None:
|
|
return False
|
|
if deadline <= time.time():
|
|
self._pending.pop(hashed, None)
|
|
return False
|
|
return True
|
|
|
|
async def _flush_revocations(self) -> None:
|
|
"""Re-apply tombstones that could not be written during an outage."""
|
|
for hashed, deadline in list(self._pending.items()):
|
|
remaining = deadline - time.time()
|
|
if remaining <= 0:
|
|
self._pending.pop(hashed, None)
|
|
continue
|
|
try:
|
|
await self.client.set(self._key(hashed), REVOKED, ex=self._ttl(remaining))
|
|
except Exception as exc: # noqa: BLE001 - still revoked in PostgreSQL
|
|
self._unavailable("flush_revocation", exc)
|
|
return
|
|
self._pending.pop(hashed, None)
|
|
|
|
async def ping(self) -> bool:
|
|
if self.client is None:
|
|
return False
|
|
try:
|
|
alive = bool(await self.client.ping())
|
|
except Exception as exc: # noqa: BLE001 - any client error means "no cache"
|
|
logger.warning("cache_ping_failed error=%s", type(exc).__name__)
|
|
return False
|
|
self._disabled_until = 0.0
|
|
self._ok()
|
|
return alive
|
|
|
|
async def close(self) -> None:
|
|
if self.client is None:
|
|
return
|
|
try:
|
|
await self.client.aclose()
|
|
except Exception as exc: # noqa: BLE001 - shutdown must not fail on cache
|
|
logger.warning("cache_close_failed error=%s", type(exc).__name__)
|
|
|
|
def _key(self, hashed: str) -> str:
|
|
return CACHE_PREFIX + hashed
|
|
|
|
def _ttl(self, seconds: float) -> int:
|
|
return max(1, min(int(seconds), self.ttl_cap))
|
|
|
|
async def lookup(self, hashed: str) -> tuple[str, dict[str, Any] | None]:
|
|
"""Return (state, payload); every cache failure degrades to a DB read."""
|
|
if not self._ready():
|
|
return MISS, None
|
|
if self._pending:
|
|
await self._flush_revocations()
|
|
if not self._ready():
|
|
return MISS, None
|
|
try:
|
|
raw = await self.client.get(self._key(hashed))
|
|
self._ok()
|
|
except Exception as exc: # noqa: BLE001 - cache must never break auth
|
|
self._unavailable("lookup", exc)
|
|
return ERROR, None
|
|
if raw is None:
|
|
return MISS, None
|
|
if raw == REVOKED:
|
|
return TOMBSTONE, None
|
|
try:
|
|
payload = json.loads(raw)
|
|
user = payload["user"]
|
|
user["id"] = str(uuid.UUID(user["id"]))
|
|
payload["expires_epoch"] = float(payload["expires_epoch"])
|
|
payload["user"] = user
|
|
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
|
|
logger.warning("cache_payload_invalid")
|
|
return MISS, None
|
|
return HIT, payload
|
|
|
|
async def remember(self, hashed: str, user: dict[str, Any], expires_at: datetime) -> None:
|
|
if not self._ready():
|
|
return
|
|
remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()
|
|
if remaining <= 0:
|
|
return
|
|
# Cache the immutable public user snapshot, so a hit needs no SQL at all.
|
|
# Users cannot be renamed or deleted in the mandatory API of lab 2.
|
|
payload = {
|
|
"user": user,
|
|
"expires_epoch": expires_at.timestamp(),
|
|
}
|
|
try:
|
|
await self.client.set(
|
|
self._key(hashed),
|
|
json.dumps(payload, ensure_ascii=False),
|
|
ex=self._ttl(remaining),
|
|
)
|
|
self._ok()
|
|
except Exception as exc: # noqa: BLE001 - a missed cache write is not fatal
|
|
self._unavailable("remember", exc)
|
|
|
|
async def revoke(self, hashed: str, expires_at: datetime | None) -> None:
|
|
"""Write a tombstone so a stale entry cannot authenticate after logout."""
|
|
remaining = 60.0
|
|
if expires_at is not None:
|
|
remaining = max(1.0, (expires_at - datetime.now(timezone.utc)).total_seconds())
|
|
# PostgreSQL already revoked the session; this keeps the fast path honest
|
|
# even if the tombstone cannot be written right now.
|
|
self.remember_revocation(hashed, remaining)
|
|
if not self._ready():
|
|
return
|
|
try:
|
|
await self.client.set(self._key(hashed), REVOKED, ex=self._ttl(remaining))
|
|
self._pending.pop(hashed, None)
|
|
self._ok()
|
|
except Exception as exc: # noqa: BLE001 - PostgreSQL already revoked the session
|
|
self._unavailable("revoke", exc)
|
|
|
|
|
|
def _user_payload(row: dict[str, Any]) -> dict[str, Any]:
|
|
return {
|
|
"id": str(row["id"]),
|
|
"username": row["username"],
|
|
"display_name": row["display_name"],
|
|
"created_at": format_timestamp(row["created_at"]),
|
|
}
|
|
|
|
|
|
async def create_session(
|
|
pool: AsyncConnectionPool,
|
|
cache: SessionCache,
|
|
*,
|
|
user_id: uuid.UUID,
|
|
ttl_seconds: int,
|
|
) -> tuple[str, datetime]:
|
|
token = secrets.token_urlsafe(TOKEN_BYTES)
|
|
hashed = token_hash(token)
|
|
async with pool.connection() as connection:
|
|
async with connection.cursor() as cursor:
|
|
expires_at = await store.insert_session(
|
|
cursor, user_id=user_id, token_hash=hashed, ttl_seconds=ttl_seconds
|
|
)
|
|
user = await store.user_by_id(cursor, user_id)
|
|
if user is not None:
|
|
await cache.remember(hashed, _user_payload(user), expires_at)
|
|
return token, expires_at
|
|
|
|
|
|
async def resolve_session(
|
|
pool: AsyncConnectionPool, cache: SessionCache, token: str
|
|
) -> tuple[uuid.UUID, dict[str, Any]]:
|
|
"""Return the authenticated user or raise 401 with a Bearer challenge."""
|
|
hashed = token_hash(token)
|
|
if cache.is_locally_revoked(hashed):
|
|
raise ApiProblem(
|
|
401,
|
|
"unauthorized",
|
|
"Session token is expired or revoked",
|
|
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
)
|
|
state, _payload = await cache.lookup(hashed)
|
|
if state == TOMBSTONE:
|
|
raise ApiProblem(
|
|
401,
|
|
"unauthorized",
|
|
"Session token is expired or revoked",
|
|
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
)
|
|
|
|
# PostgreSQL is the authoritative revocation store. A cache value can only
|
|
# accelerate the immutable user snapshot; it must never be enough to grant
|
|
# access on its own. This makes logout durable across API replicas and
|
|
# Valkey outages/restores, where a tombstone may not reach shared cache.
|
|
async with pool.connection() as connection:
|
|
async with connection.cursor() as cursor:
|
|
row = await store.session_user(cursor, hashed)
|
|
if row is None:
|
|
await cache.revoke(hashed, None)
|
|
raise ApiProblem(
|
|
401,
|
|
"unauthorized",
|
|
"Session token is expired or revoked",
|
|
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
)
|
|
user = _user_payload(row)
|
|
# Refresh an old cache hit after PostgreSQL has confirmed it is still live.
|
|
await cache.remember(hashed, user, row["expires_at"])
|
|
return uuid.UUID(user["id"]), user
|
|
|
|
|
|
async def revoke_session(
|
|
pool: AsyncConnectionPool, cache: SessionCache, token: str
|
|
) -> None:
|
|
hashed = token_hash(token)
|
|
async with pool.connection() as connection:
|
|
async with connection.cursor() as cursor:
|
|
expires_at = await store.revoke_session(cursor, hashed)
|
|
if expires_at is None:
|
|
raise ApiProblem(
|
|
401,
|
|
"unauthorized",
|
|
"Session token is expired or revoked",
|
|
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
|
)
|
|
await cache.revoke(hashed, expires_at)
|
|
|
|
|
|
async def purge_expired(pool: AsyncConnectionPool) -> int:
|
|
async with pool.connection() as connection:
|
|
async with connection.cursor() as cursor:
|
|
return await store.purge_expired_sessions(cursor)
|
|
|
|
|
|
async def purge_expired_idempotency(pool: AsyncConnectionPool) -> int:
|
|
async with pool.connection() as connection:
|
|
async with connection.cursor() as cursor:
|
|
await cursor.execute(
|
|
"""
|
|
DELETE FROM idempotency_keys
|
|
WHERE created_at < now() - (%s || ' seconds')::interval
|
|
""",
|
|
(str(IDEMPOTENCY_TTL_SECONDS),),
|
|
)
|
|
return cursor.rowcount
|