forked from mtusi2026/mtusi2026lab3
chore: перенос решения lab2 (src, миграции, student-tests, Dockerfile, compose, lock) без изменений
Исходная точка lab3: код из solution/bvt2302-bodanyuk лабы 2, коммит ef44e48 (PR mtusi2026/mtusi2026lab2#42 принят). README, COURSE, contracts/ и tests/ преподавателя не тронуты; к Makefile дописан студенческий раздел lab2, .env.example — версия lab2. Исследование трека 2 lab2 (bench/track2) не переносилось. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0ab3a341aa
commit
4f6cfda37a
@@ -0,0 +1,160 @@
|
||||
"""Server-side sessions behind an opaque Bearer token.
|
||||
|
||||
* Token: `secrets.token_urlsafe(32)` = 256 random bits. Only SHA-256(token) is
|
||||
stored, so a leaked database/AOF does not contain usable tokens. A fast hash is
|
||||
enough for a 256-bit random value; passwords need a slow KDF (passwords.py).
|
||||
* Expiry is absolute: `expires_at = login time + SESSION_TTL_SECONDS`. Every lookup
|
||||
compares it with the current time, and a restart never extends it.
|
||||
|
||||
Two interchangeable stores (SESSION_STORE):
|
||||
|
||||
* `valkey` (compose default): the ONLY copy of a session is a Valkey key with
|
||||
`PXAT expires_at`, persisted by AOF with `appendfsync always`. There is no second
|
||||
copy (no cache over PostgreSQL), so a logout cannot be "forgotten" and a revoked
|
||||
token cannot come back after Valkey fails and recovers. If Valkey is unreachable
|
||||
a session cannot be checked: protected requests and logout get 503, never access.
|
||||
* `postgres`: table `sessions` (migrations/0001_init.sql).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from typing import Protocol
|
||||
|
||||
from redis import exceptions as redis_errors
|
||||
from redis.asyncio import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.retry import Retry
|
||||
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .timefmt import UTC, from_us, to_us
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def now() -> dt.datetime:
|
||||
return dt.datetime.now(UTC)
|
||||
|
||||
|
||||
class SessionStore(Protocol):
|
||||
name: str
|
||||
|
||||
async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]: ...
|
||||
async def user_id_for(self, token: str) -> str | None: ...
|
||||
async def revoke(self, token: str) -> bool: ...
|
||||
async def ping(self) -> bool: ...
|
||||
async def close(self) -> None: ...
|
||||
|
||||
|
||||
class PostgresSessionStore:
|
||||
name = "postgres"
|
||||
|
||||
def __init__(self, db: Database):
|
||||
self.db = db
|
||||
|
||||
async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]:
|
||||
token = new_token()
|
||||
expires_at = now() + dt.timedelta(seconds=ttl_seconds)
|
||||
|
||||
async def work(conn) -> None:
|
||||
await conn.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token_hash(token), user_id, expires_at))
|
||||
# Housekeeping: drop this user's expired sessions (bounded by the user's own rows).
|
||||
await conn.execute("DELETE FROM sessions WHERE user_id = %s AND expires_at <= %s", (user_id, now()))
|
||||
await self.db.run(work)
|
||||
return token, expires_at
|
||||
|
||||
async def user_id_for(self, token: str) -> str | None:
|
||||
async def work(conn):
|
||||
cur = await conn.execute(
|
||||
"SELECT user_id FROM sessions WHERE token_hash = %s AND expires_at > %s", (token_hash(token), now()))
|
||||
return await cur.fetchone()
|
||||
row = await self.db.run(work)
|
||||
return str(row[0]) if row else None
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
async def work(conn) -> bool:
|
||||
cur = await conn.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = %s AND expires_at > %s", (token_hash(token), now()))
|
||||
return cur.rowcount == 1
|
||||
return await self.db.run(work)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
return True # covered by the database readiness check
|
||||
|
||||
async def close(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class ValkeySessionStore:
|
||||
name = "valkey"
|
||||
PREFIX = "session:"
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.timeout = settings.cache_timeout_seconds
|
||||
self.client = Redis.from_url(
|
||||
settings.cache_url,
|
||||
socket_timeout=self.timeout,
|
||||
socket_connect_timeout=self.timeout,
|
||||
retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once
|
||||
decode_responses=False,
|
||||
)
|
||||
|
||||
def _key(self, token: str) -> str:
|
||||
return self.PREFIX + token_hash(token).hex()
|
||||
|
||||
async def _call(self, coro):
|
||||
try:
|
||||
async with asyncio.timeout(self.timeout * 2):
|
||||
return await coro
|
||||
except (redis_errors.ConnectionError, redis_errors.TimeoutError, TimeoutError, OSError) as exc:
|
||||
log.warning("session_store_unavailable", extra={"fields": {"error": type(exc).__name__}})
|
||||
raise Unavailable("Хранилище сессий временно недоступно") from None
|
||||
|
||||
async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]:
|
||||
token = new_token()
|
||||
expires_at = now() + dt.timedelta(seconds=ttl_seconds)
|
||||
value = json.dumps({"user_id": user_id, "expires_at_us": to_us(expires_at)}).encode()
|
||||
# PXAT = absolute expiry time: survives restarts (AOF) without being extended.
|
||||
await self._call(self.client.set(self._key(token), value, pxat=to_us(expires_at) // 1000))
|
||||
return token, expires_at
|
||||
|
||||
async def user_id_for(self, token: str) -> str | None:
|
||||
raw = await self._call(self.client.get(self._key(token)))
|
||||
if raw is None:
|
||||
return None
|
||||
data = json.loads(raw)
|
||||
if from_us(data["expires_at_us"]) <= now():
|
||||
return None # do not rely only on Valkey's lazy expiry
|
||||
return data["user_id"]
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
return await self._call(self.client.delete(self._key(token))) == 1
|
||||
|
||||
async def ping(self) -> bool:
|
||||
try:
|
||||
return bool(await self._call(self.client.ping()))
|
||||
except Unavailable:
|
||||
return False
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
|
||||
def build_store(settings: Settings, db: Database) -> SessionStore:
|
||||
return ValkeySessionStore(settings) if settings.session_store == "valkey" else PostgresSessionStore(db)
|
||||
Reference in New Issue
Block a user