import hashlib import json import logging import secrets import time from datetime import datetime, timedelta, timezone from typing import Optional import valkey.asyncio as valkey from app import config, repo from app.cursor import fmt from app.errors import unavailable log = logging.getLogger("messenger.sessions") REVOKED = "revoked" class SessionStore: def __init__(self, db) -> None: self.db = db self.client = None self.stats = {"hits": 0, "misses": 0, "errors": 0} self._local = {} async def open(self) -> None: if not config.CACHE_URL: log.info("session cache disabled: CACHE_URL is empty") return # lab7: rediss:// = TLS to Valkey, server verified against the lab CA (hostname "valkey"); ACL user `api`. self.client = valkey.Valkey.from_url( config.CACHE_URL, socket_timeout=config.CACHE_TIMEOUT, socket_connect_timeout=config.CACHE_TIMEOUT, decode_responses=True, ssl_ca_certs=config.TLS_CA_FILE, ssl_cert_reqs="required", ssl_check_hostname=True, ) async def close(self) -> None: if self.client is not None: await self.client.aclose() self.client = None @staticmethod def digest(token: str) -> bytes: return hashlib.sha256(token.encode("utf-8")).digest() @staticmethod def key(digest: bytes) -> str: return "session:" + digest.hex() async def create(self, user: dict) -> tuple: token = secrets.token_urlsafe(32) digest = self.digest(token) expires_at = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS) async with self.db.connection() as conn: await conn.execute( "INSERT INTO sessions (token_hash, user_id, created_at, expires_at)" " VALUES (%s, %s, clock_timestamp(), %s)", (digest, user["id"], expires_at), ) await self._cache_put(digest, user, expires_at) return token, fmt(expires_at) async def resolve(self, token: str) -> Optional[dict]: digest = self.digest(token) cached = await self._cache_get(digest) if cached == REVOKED: self.stats["hits"] += 1 return None if cached is not None: self.stats["hits"] += 1 return cached self.stats["misses"] += 1 async with self.db.connection() as conn: cur = await conn.execute( "SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at" " FROM sessions s JOIN users u ON u.id = s.user_id" " WHERE s.token_hash = %s AND s.expires_at > now()", (digest,), ) row = await cur.fetchone() if row is None: return None user = repo.public_user(row) await self._cache_put(digest, user, row["expires_at"]) return user async def revoke(self, token: str) -> None: digest = self.digest(token) await self._cache_revoke(digest) try: async with self.db.connection() as conn: await conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,)) except Exception: await self._cache_release(digest) raise async def sweep(self) -> int: async with self.db.connection() as conn: cur = await conn.execute("DELETE FROM sessions WHERE expires_at <= now()") return cur.rowcount def _cache_ttl(self, expires_at: datetime) -> int: remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) return min(config.SESSION_CACHE_TTL_SECONDS, remaining) async def _cache_get(self, digest: bytes) -> Optional[dict]: if self.client is None: return None try: raw = await self.client.get(self.key(digest)) except Exception: self._cache_failed("get") return None if not raw: return None if raw == REVOKED: return REVOKED try: return json.loads(raw) except ValueError: return None async def _cache_put(self, digest: bytes, user: dict, expires_at: datetime) -> None: if self.client is None: return ttl = self._cache_ttl(expires_at) if ttl <= 0: return payload = json.dumps(user) try: await self.client.set(self.key(digest), payload, ex=ttl, nx=True) except Exception: self._cache_failed("set") async def _cache_release(self, digest: bytes) -> None: if self.client is None: return try: await self.client.delete(self.key(digest)) except Exception: self._cache_failed("release") async def _cache_revoke(self, digest: bytes) -> None: if self.client is None: return try: await self.client.set(self.key(digest), REVOKED, ex=config.SESSION_REVOKED_TTL_SECONDS) except Exception: self._cache_failed("revoke") raise unavailable("Кэш сессий недоступен, выход из сессии не подтверждён") from None def _cache_failed(self, operation: str) -> None: self.stats["errors"] += 1 if self.stats["errors"] % 50 == 1: log.warning("session_cache_failed %s, falling back to postgres (errors=%d)", operation, self.stats["errors"]) # ------------------------------------------------------------------ lab7: shared login rate limit async def hit(self, key: str, window: int) -> tuple: """INCR a fixed-window counter shared by all replicas. Returns (count, retry_after_seconds). Valkey unavailable -> per-process fallback window (limits stay on, but are not shared).""" if self.client is not None: try: count = await self.client.incr(key) if count == 1: await self.client.expire(key, window) ttl = window else: ttl = await self.client.ttl(key) if ttl < 0: # lost EXPIRE (crash between INCR and EXPIRE): repair await self.client.expire(key, window) ttl = window return count, max(1, ttl) except Exception: self._cache_failed("ratelimit") return self._local_hit(key, window) async def peek(self, key: str) -> tuple: if self.client is not None: try: raw = await self.client.get(key) ttl = await self.client.ttl(key) if raw else 0 return int(raw or 0), max(1, ttl) except Exception: self._cache_failed("ratelimit") entry = self._local.get(key) if entry and entry[1] > time.monotonic(): return entry[0], max(1, int(entry[1] - time.monotonic())) return 0, 1 async def reset(self, key: str) -> None: self._local.pop(key, None) if self.client is not None: try: await self.client.delete(key) except Exception: self._cache_failed("ratelimit") def _local_hit(self, key: str, window: int) -> tuple: now = time.monotonic() count, until = self._local.get(key, (0, now + window)) if until <= now: count, until = 0, now + window self._local[key] = (count + 1, until) if len(self._local) > 10000: # bounded memory under a username-spraying attack self._local = {k: v for k, v in self._local.items() if v[1] > now} return count + 1, max(1, int(until - now))