132 lines
5.1 KiB
Python
132 lines
5.1 KiB
Python
"""Сессии: PostgreSQL — источник истины; Valkey — кэш с TTL (read-through).
|
||
|
||
Политики:
|
||
* токен — 256 бит из secrets; в БД и Valkey хранится только SHA-256 токена;
|
||
* expiry: expires_at в БД (по часам БД). В кэше TTL = min(остаток жизни, SESSION_CACHE_TTL_SECONDS);
|
||
* инвалидация: logout помечает revoked_at в БД и удаляет ключ в Valkey;
|
||
* Valkey недоступен -> кэш обходится (чтение из БД), анонимный запрос никогда не считается доверенным;
|
||
circuit breaker не даёт каждому запросу ждать таймаут;
|
||
* окно устаревания: если Valkey был недоступен во время logout, ключ может прожить до SESSION_CACHE_TTL_SECONDS.
|
||
"""
|
||
import hashlib
|
||
import secrets
|
||
import time
|
||
|
||
from . import config
|
||
from .web import log
|
||
|
||
try:
|
||
import redis.asyncio as aioredis
|
||
except ImportError: # кэш опционален
|
||
aioredis = None
|
||
|
||
|
||
def token_hash(token):
|
||
return hashlib.sha256(token.encode("ascii")).digest()
|
||
|
||
|
||
class SessionCache:
|
||
def __init__(self):
|
||
self.client = None
|
||
self.down_until = 0.0
|
||
self.stats = {"hit": 0, "miss": 0, "error": 0}
|
||
|
||
async def start(self):
|
||
if config.VALKEY_URL and aioredis:
|
||
self.client = aioredis.Redis.from_url(config.VALKEY_URL, socket_timeout=config.VALKEY_TIMEOUT,
|
||
socket_connect_timeout=config.VALKEY_TIMEOUT)
|
||
|
||
async def stop(self):
|
||
if self.client:
|
||
await self.client.aclose()
|
||
|
||
def _usable(self):
|
||
return self.client is not None and time.monotonic() >= self.down_until
|
||
|
||
def _fail(self, exc):
|
||
self.stats["error"] += 1
|
||
if time.monotonic() >= self.down_until:
|
||
log("warning", "session_cache_unavailable", error_type=type(exc).__name__)
|
||
self.down_until = time.monotonic() + config.VALKEY_BREAKER_SECONDS
|
||
|
||
async def get(self, key):
|
||
if not self._usable():
|
||
return None
|
||
try:
|
||
value = await self.client.get(b"s:" + key)
|
||
except Exception as exc:
|
||
self._fail(exc)
|
||
return None
|
||
self.stats["hit" if value is not None else "miss"] += 1
|
||
return value
|
||
|
||
async def put(self, key, value, ttl):
|
||
if not self._usable() or ttl <= 0:
|
||
return
|
||
try:
|
||
await self.client.set(b"s:" + key, value, ex=max(1, int(ttl)))
|
||
except Exception as exc:
|
||
self._fail(exc)
|
||
|
||
async def delete(self, key):
|
||
if not self._usable():
|
||
return
|
||
try:
|
||
await self.client.delete(b"s:" + key)
|
||
except Exception as exc:
|
||
self._fail(exc)
|
||
|
||
async def ping(self):
|
||
if self.client is None:
|
||
return None
|
||
try:
|
||
return bool(await self.client.ping())
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
class Sessions:
|
||
def __init__(self, db, cache):
|
||
self.db, self.cache = db, cache
|
||
|
||
@staticmethod
|
||
def _cache_value(user_id, expires_at):
|
||
return ("%s|%d" % (user_id, int(expires_at.timestamp() * 1000))).encode()
|
||
|
||
async def create(self, user_id):
|
||
token = secrets.token_urlsafe(32) # 256 бит энтропии
|
||
digest = token_hash(token)
|
||
row = await self.db.fetchrow(
|
||
"INSERT INTO sessions (token_hash, user_id, expires_at) "
|
||
"VALUES ($1, $2, now() + make_interval(secs => $3)) RETURNING expires_at",
|
||
digest, user_id, float(config.SESSION_TTL_SECONDS))
|
||
remaining = row["expires_at"].timestamp() - time.time()
|
||
await self.cache.put(digest, self._cache_value(user_id, row["expires_at"]),
|
||
min(remaining, config.SESSION_CACHE_TTL_SECONDS))
|
||
return token, row["expires_at"]
|
||
|
||
async def resolve(self, token):
|
||
"""token -> user_id (str) либо None, если сессии нет/истекла/отозвана."""
|
||
digest = token_hash(token)
|
||
cached = await self.cache.get(digest)
|
||
if cached is not None:
|
||
user_id, _, expires_ms = cached.decode().partition("|")
|
||
if int(expires_ms) > time.time() * 1000:
|
||
return user_id
|
||
await self.cache.delete(digest)
|
||
row = await self.db.fetchrow(
|
||
"SELECT user_id, expires_at FROM sessions "
|
||
"WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > now()", digest)
|
||
if row is None:
|
||
return None
|
||
user_id = str(row["user_id"])
|
||
remaining = row["expires_at"].timestamp() - time.time()
|
||
await self.cache.put(digest, self._cache_value(user_id, row["expires_at"]),
|
||
min(remaining, config.SESSION_CACHE_TTL_SECONDS))
|
||
return user_id
|
||
|
||
async def revoke(self, token):
|
||
digest = token_hash(token)
|
||
await self.db.execute("UPDATE sessions SET revoked_at = now() WHERE token_hash = $1 AND revoked_at IS NULL", digest)
|
||
await self.cache.delete(digest)
|