Реализация лабораторной 3: балансировка, отказ API-реплики, idempotency
- 2 API-реплики (api-1, api-2) с уникальным INSTANCE_ID - Nginx load balancer с health-check и failover - PostgreSQL источник истины, Valkey кэш сессий - Idempotency-Key в заголовке, replay возвращает исходное сообщение - X-Instance-Id в каждом ответе для идентификации реплики - /version и /info эндпоинты - Housekeeping-loop для очистки истёкших сессий и ключей - stop-one.sh/cmd для failover-теста, restart.sh/cmd для persistence - Исправлены импорты config/models/api/store/sessions - Добавлены миграции 004 (idempotency), 005 (indexes), 006 (message_id) - Отчёт с доказательствами критериев уровня 3 и 4 - Все тесты проходят: smoke, 26 student tests, failover, persistence, degradation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""MTUSI messenger, laboratory 3: multi-instance, sessions, idempotency."""
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
"""Routes, authentication and request validation for lab 2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated, Any, cast
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
from pydantic import ValidationError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from . import sessions as session_service
|
||||
from . import store
|
||||
from .config import DEFAULT_PAGE_SIZE, MAX_JSON_BYTES, MAX_PAGE_SIZE, IDEMPOTENCY_KEY_PATTERN
|
||||
from .db import ping
|
||||
from .errors import BASIC_CHALLENGE, BEARER_CHALLENGE, ApiProblem
|
||||
from .models import CreateChat, CreateMessage, CreateUser, StrictModel
|
||||
from .pagination import build_page, decode_cursor, format_timestamp
|
||||
from .security import hash_password, verify_password, verify_password_unknown_user
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Principal:
|
||||
"""The authenticated identity behind a Bearer token."""
|
||||
|
||||
user_id: uuid.UUID
|
||||
user: dict[str, Any]
|
||||
|
||||
|
||||
def get_pool(request: Request) -> AsyncConnectionPool:
|
||||
return cast(AsyncConnectionPool, request.app.state.pool)
|
||||
|
||||
|
||||
def get_cache(request: Request) -> session_service.SessionCache:
|
||||
return cast(session_service.SessionCache, request.app.state.cache)
|
||||
|
||||
|
||||
async def drain_body(request: Request) -> None:
|
||||
"""Consume an unwanted request body without retaining it in memory."""
|
||||
async for _chunk in request.stream():
|
||||
pass
|
||||
|
||||
|
||||
def declared_body_size(request: Request) -> int | None:
|
||||
value = request.headers.get("Content-Length")
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
size = int(value)
|
||||
except ValueError:
|
||||
raise ApiProblem(400, "invalid_request", "Content-Length is invalid") from None
|
||||
if size < 0:
|
||||
raise ApiProblem(400, "invalid_request", "Content-Length is invalid")
|
||||
return size
|
||||
|
||||
|
||||
async def read_limited_body(request: Request) -> bytes:
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
too_large = False
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size <= MAX_JSON_BYTES:
|
||||
chunks.append(chunk)
|
||||
else:
|
||||
too_large = True
|
||||
if too_large:
|
||||
raise ApiProblem(413, "payload_too_large", "Request body is too large")
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
async def parse_body(request: Request, model: type[StrictModel]) -> Any:
|
||||
content_length = declared_body_size(request)
|
||||
if content_length is not None and content_length > MAX_JSON_BYTES:
|
||||
await drain_body(request)
|
||||
raise ApiProblem(413, "payload_too_large", "Request body is too large")
|
||||
content_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip()
|
||||
if content_type.lower() != "application/json":
|
||||
await drain_body(request)
|
||||
raise ApiProblem(
|
||||
415, "unsupported_media_type", "Content-Type must be application/json"
|
||||
)
|
||||
body = await read_limited_body(request)
|
||||
try:
|
||||
decoded = json.loads(body.decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
raise ApiProblem(
|
||||
400, "invalid_request", "Request body is not valid JSON"
|
||||
) from None
|
||||
try:
|
||||
return model.model_validate(decoded)
|
||||
except ValidationError:
|
||||
raise ApiProblem(400, "invalid_request", "Request fields are invalid") from None
|
||||
|
||||
|
||||
def ensure_no_query(request: Request) -> None:
|
||||
if request.url.query:
|
||||
raise ApiProblem(400, "invalid_request", "Query parameters are not supported")
|
||||
|
||||
|
||||
def parse_pagination_request(request: Request) -> tuple[int, str | None]:
|
||||
"""Read limit/cursor only; unknown or repeated parameters are a 400."""
|
||||
parameters = request.query_params
|
||||
keys = [key for key, _ in parameters.multi_items()]
|
||||
if set(keys) - {"limit", "cursor"} or any(
|
||||
keys.count(key) != 1 for key in set(keys)
|
||||
):
|
||||
raise ApiProblem(400, "invalid_request", "Query parameters are invalid")
|
||||
limit_value = parameters.get("limit", str(DEFAULT_PAGE_SIZE))
|
||||
try:
|
||||
limit = int(limit_value)
|
||||
except (TypeError, ValueError):
|
||||
raise ApiProblem(400, "invalid_request", "limit is invalid") from None
|
||||
if not 1 <= limit <= MAX_PAGE_SIZE:
|
||||
raise ApiProblem(400, "invalid_request", "limit is invalid")
|
||||
cursor = parameters.get("cursor")
|
||||
if cursor == "":
|
||||
raise ApiProblem(400, "invalid_request", "cursor is invalid")
|
||||
return limit, cursor
|
||||
|
||||
|
||||
def require_chat_id(chat_id: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(chat_id)
|
||||
except (ValueError, AttributeError):
|
||||
raise ApiProblem(400, "invalid_request", "chat_id must be a UUID") from None
|
||||
|
||||
|
||||
def unauthorized(message: str, challenge: str) -> ApiProblem:
|
||||
return ApiProblem(401, "unauthorized", message, {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def bearer_token(request: Request) -> str:
|
||||
"""Only Bearer is accepted; Basic here is a 401, not a fallback login."""
|
||||
header = request.headers.get("Authorization")
|
||||
if header is None:
|
||||
raise unauthorized("Bearer session token is required", BEARER_CHALLENGE)
|
||||
scheme, _, value = header.partition(" ")
|
||||
if scheme.strip().lower() != "bearer" or not value.strip():
|
||||
raise unauthorized("Bearer session token is required", BEARER_CHALLENGE)
|
||||
return value.strip()
|
||||
|
||||
|
||||
def basic_credentials(request: Request) -> tuple[str, str]:
|
||||
"""Decode Basic credentials; it is an encoding, never a trusted identity."""
|
||||
header = request.headers.get("Authorization")
|
||||
if header is None:
|
||||
raise unauthorized("Basic credentials are required", BASIC_CHALLENGE)
|
||||
scheme, _, value = header.partition(" ")
|
||||
if scheme.strip().lower() != "basic" or not value.strip():
|
||||
raise unauthorized("Basic credentials are required", BASIC_CHALLENGE)
|
||||
try:
|
||||
raw = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError, ValueError):
|
||||
raise unauthorized("Basic credentials are invalid", BASIC_CHALLENGE) from None
|
||||
username, separator, password = raw.partition(":")
|
||||
if not separator or not username or not password:
|
||||
raise unauthorized("Basic credentials are invalid", BASIC_CHALLENGE)
|
||||
if USERNAME_PATTERN.fullmatch(username) is None:
|
||||
# Unknown or malformed usernames must not be distinguished from a bad password.
|
||||
raise unauthorized("Invalid username or password", BASIC_CHALLENGE)
|
||||
return username, password
|
||||
|
||||
|
||||
async def current_principal(request: Request) -> Principal:
|
||||
token = bearer_token(request)
|
||||
user_id, user = await session_service.resolve_session(
|
||||
get_pool(request), get_cache(request), token
|
||||
)
|
||||
return Principal(user_id=user_id, user=user)
|
||||
|
||||
|
||||
Actor = Annotated[Principal, Depends(current_principal)]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Health
|
||||
# --------------------------------------------------------------------------- #
|
||||
@router.get("/health/live")
|
||||
async def liveness(request: Request) -> dict[str, str]:
|
||||
ensure_no_query(request)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def readiness(request: Request) -> dict[str, str]:
|
||||
ensure_no_query(request)
|
||||
try:
|
||||
await ping(get_pool(request))
|
||||
except Exception as exc: # noqa: BLE001 - any DB failure means not ready
|
||||
request.app.state.logger.warning(
|
||||
"readiness_database_failed error=%s", type(exc).__name__
|
||||
)
|
||||
raise ApiProblem(503, "unavailable", "Database is unavailable") from None
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Users and sessions
|
||||
# --------------------------------------------------------------------------- #
|
||||
@router.post("/api/v1/users", status_code=201)
|
||||
async def register_user(request: Request) -> dict[str, Any]:
|
||||
ensure_no_query(request)
|
||||
body = await parse_body(request, CreateUser)
|
||||
assert isinstance(body, CreateUser)
|
||||
password_hash = await run_in_threadpool(hash_password, body.password)
|
||||
async with get_pool(request).connection() as connection:
|
||||
async with connection.cursor() as cursor:
|
||||
return await store.create_user(
|
||||
cursor,
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def create_session(request: Request) -> dict[str, Any]:
|
||||
ensure_no_query(request)
|
||||
await drain_body(request)
|
||||
username, password = basic_credentials(request)
|
||||
pool = get_pool(request)
|
||||
async with pool.connection() as connection:
|
||||
async with connection.cursor() as cursor:
|
||||
row = await store.user_credentials(cursor, username)
|
||||
if row is None:
|
||||
await run_in_threadpool(verify_password_unknown_user, password)
|
||||
raise unauthorized("Invalid username or password", BASIC_CHALLENGE)
|
||||
if not await run_in_threadpool(
|
||||
verify_password, password, row["password_hash"]
|
||||
):
|
||||
raise unauthorized("Invalid username or password", BASIC_CHALLENGE)
|
||||
token, expires_at = await session_service.create_session(
|
||||
pool,
|
||||
get_cache(request),
|
||||
user_id=row["id"],
|
||||
ttl_seconds=request.app.state.settings.session_ttl_seconds,
|
||||
)
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": format_timestamp(expires_at),
|
||||
"user": store.user_json(row),
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def delete_current_session(request: Request) -> Response:
|
||||
ensure_no_query(request)
|
||||
token = bearer_token(request)
|
||||
await session_service.revoke_session(get_pool(request), get_cache(request), token)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
async def current_user(request: Request, actor: Actor) -> dict[str, Any]:
|
||||
ensure_no_query(request)
|
||||
return actor.user
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Chats and messages
|
||||
# --------------------------------------------------------------------------- #
|
||||
@router.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request, actor: Actor) -> dict[str, Any]:
|
||||
ensure_no_query(request)
|
||||
body = await parse_body(request, CreateChat)
|
||||
assert isinstance(body, CreateChat)
|
||||
members = [uuid.UUID(member) for member in body.member_ids]
|
||||
async with get_pool(request).connection() as connection:
|
||||
async with connection.cursor() as cursor:
|
||||
return await store.create_chat(
|
||||
cursor, actor_id=actor.user_id, title=body.title, member_ids=members
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats")
|
||||
async def list_chats(request: Request, actor: Actor) -> dict[str, Any]:
|
||||
limit, cursor = parse_pagination_request(request)
|
||||
resource = "chats:" + str(actor.user_id)
|
||||
after = decode_cursor(cursor, resource) if cursor is not None else None
|
||||
async with get_pool(request).connection() as connection:
|
||||
async with connection.cursor() as cursor_handle:
|
||||
rows = await store.chat_page(
|
||||
cursor_handle, actor_id=actor.user_id, limit=limit, after=after
|
||||
)
|
||||
return build_page(rows, resource, limit)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(request: Request, chat_id: str, actor: Actor) -> dict[str, Any]:
|
||||
ensure_no_query(request)
|
||||
normalized = require_chat_id(chat_id)
|
||||
async with get_pool(request).connection() as connection:
|
||||
async with connection.cursor() as cursor:
|
||||
return await store.accessible_chat(
|
||||
cursor, actor_id=actor.user_id, chat_id=normalized
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def create_message(
|
||||
request: Request, chat_id: str, actor: Actor
|
||||
) -> dict[str, Any]:
|
||||
normalized = require_chat_id(chat_id)
|
||||
ensure_no_query(request)
|
||||
body = await parse_body(request, CreateMessage)
|
||||
assert isinstance(body, CreateMessage)
|
||||
pool = get_pool(request)
|
||||
request_sha256 = hashlib.sha256(
|
||||
json.dumps(body.model_dump(), sort_keys=True).encode("utf-8")
|
||||
).hexdigest()
|
||||
async with pool.connection() as connection:
|
||||
async with connection.cursor() as cursor:
|
||||
# Check membership first so non-members get 404, not 400.
|
||||
await store.require_membership(
|
||||
cursor, actor_id=actor.user_id, chat_id=normalized
|
||||
)
|
||||
key = request.headers.get("Idempotency-Key", "").strip()
|
||||
if not key or not IDEMPOTENCY_KEY_PATTERN.fullmatch(key):
|
||||
raise ApiProblem(
|
||||
400, "invalid_request", "Idempotency-Key must match "
|
||||
"^[A-Za-z0-9._:-]{1,128}$"
|
||||
)
|
||||
existing = await store.get_idempotency_key(cursor, key)
|
||||
if existing is not None:
|
||||
if existing["request_sha256"] != request_sha256:
|
||||
raise ApiProblem(409, "conflict", "Idempotency-Key was already used")
|
||||
# Replay: return the original message.
|
||||
original = await store.message_by_id(cursor, existing["message_id"])
|
||||
if original is not None:
|
||||
return original
|
||||
try:
|
||||
await store.insert_idempotency_key(
|
||||
cursor, key=key, chat_id=normalized, request_sha256=request_sha256
|
||||
)
|
||||
except ApiProblem:
|
||||
# Race: another request inserted the key first. Treat as replay.
|
||||
existing = await store.get_idempotency_key(cursor, key)
|
||||
if existing is not None and existing["request_sha256"] == request_sha256:
|
||||
original = await store.message_by_id(cursor, existing["message_id"])
|
||||
if original is not None:
|
||||
return original
|
||||
raise
|
||||
return await store.create_message(
|
||||
cursor,
|
||||
actor_id=actor.user_id,
|
||||
chat_id=normalized,
|
||||
text=body.text,
|
||||
request_sha256=request_sha256,
|
||||
key=key,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(
|
||||
request: Request, chat_id: str, actor: Actor
|
||||
) -> dict[str, Any]:
|
||||
normalized = require_chat_id(chat_id)
|
||||
limit, cursor = parse_pagination_request(request)
|
||||
resource = "messages:" + str(normalized)
|
||||
after = decode_cursor(cursor, resource) if cursor is not None else None
|
||||
async with get_pool(request).connection() as connection:
|
||||
async with connection.cursor() as cursor_handle:
|
||||
await store.require_membership(
|
||||
cursor_handle, actor_id=actor.user_id, chat_id=normalized
|
||||
)
|
||||
rows = await store.message_page(
|
||||
cursor_handle, chat_id=normalized, limit=limit, after=after
|
||||
)
|
||||
return build_page(rows, resource, limit)
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"""Executable entry point: migrations run first, then uvicorn as PID 1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
|
||||
|
||||
if __package__ in {None, ""}:
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from src.application import create_app # noqa: E402
|
||||
from src.config import load_address # noqa: E402
|
||||
|
||||
|
||||
app = create_app()
|
||||
|
||||
|
||||
def run() -> None:
|
||||
host, port = load_address()
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=host,
|
||||
port=port,
|
||||
access_log=False,
|
||||
timeout_graceful_shutdown=8,
|
||||
log_level="info",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@@ -0,0 +1,306 @@
|
||||
"""FastAPI application factory, lifespan, middleware and error mapping.
|
||||
|
||||
Beta-1 of the lab 3 daemon. It contains the required smoke bare minimums
|
||||
(the version/info routes, the X-Request-Id / X-Instance-Id headers and the
|
||||
request context) but not the full lab 3 feature set, which is implemented in
|
||||
the lab 2 package that this package now wraps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
import psycopg
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
from psycopg_pool import AsyncConnectionPool, PoolTimeout
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.responses import Response
|
||||
|
||||
from . import sessions as session_service
|
||||
from .api import router
|
||||
from .config import CONTRACT_PATH, Settings, load_settings
|
||||
from .db import create_pool
|
||||
from .errors import ApiProblem
|
||||
|
||||
|
||||
access_logger = logging.getLogger("messenger.access")
|
||||
lifecycle_logger = logging.getLogger("uvicorn.error")
|
||||
if not access_logger.handlers:
|
||||
access_handler = logging.StreamHandler(sys.stdout)
|
||||
access_handler.setFormatter(
|
||||
logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
)
|
||||
access_logger.addHandler(access_handler)
|
||||
access_logger.setLevel(logging.INFO)
|
||||
access_logger.propagate = False
|
||||
|
||||
|
||||
def request_id(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
|
||||
|
||||
def problem_response(
|
||||
request: Request,
|
||||
status: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> JSONResponse:
|
||||
current_request_id = request_id(request)
|
||||
response_headers = {"X-Request-Id": current_request_id}
|
||||
response_headers.update(headers or {})
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": current_request_id,
|
||||
}
|
||||
},
|
||||
headers=response_headers,
|
||||
)
|
||||
|
||||
|
||||
def load_contract() -> dict[str, Any]:
|
||||
with CONTRACT_PATH.open(encoding="utf-8") as contract_file:
|
||||
return json.load(contract_file)
|
||||
|
||||
|
||||
async def _purge_loop(pool: AsyncConnectionPool) -> None:
|
||||
"""Drop long-expired session and idempotency rows; TTL is also read-path."""
|
||||
while True:
|
||||
try:
|
||||
await asyncio.sleep(60)
|
||||
purged = await session_service.purge_expired(pool)
|
||||
idempotency_purged = await session_service.purge_expired_idempotency(pool)
|
||||
if purged or idempotency_purged:
|
||||
lifecycle_logger.info(
|
||||
"housekeeping sessions_purged=%s idempotency_purged=%s",
|
||||
purged,
|
||||
idempotency_purged,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - housekeeping must not stop the API
|
||||
lifecycle_logger.warning(
|
||||
"sessions_purge_failed error=%s", type(exc).__name__
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI) -> AsyncIterator[None]:
|
||||
settings: Settings = application.state.settings
|
||||
pool: AsyncConnectionPool = application.state.pool
|
||||
cache: session_service.SessionCache = application.state.cache
|
||||
lifecycle_logger.info(
|
||||
"server_starting env=%s instance_id=%s session_ttl_seconds=%s "
|
||||
"idempotency_ttl_seconds=%s cache_enabled=%s pool_max=%s "
|
||||
"statement_timeout_ms=%s",
|
||||
settings.app_env,
|
||||
settings.instance_id,
|
||||
settings.session_ttl_seconds,
|
||||
settings.idempotency_ttl_seconds,
|
||||
cache.enabled,
|
||||
settings.pool_max_size,
|
||||
settings.statement_timeout_ms,
|
||||
)
|
||||
try:
|
||||
await pool.open(wait=True, timeout=10)
|
||||
except Exception as exc: # noqa: BLE001 - start only with a usable database
|
||||
lifecycle_logger.error(
|
||||
"database_unavailable_at_startup error=%s", type(exc).__name__
|
||||
)
|
||||
raise
|
||||
lifecycle_logger.info(
|
||||
"server_started env=%s instance_id=%s", settings.app_env, settings.instance_id
|
||||
)
|
||||
if cache.enabled:
|
||||
if await cache.ping():
|
||||
lifecycle_logger.info("cache_ready")
|
||||
else:
|
||||
lifecycle_logger.warning("cache_unavailable_using_database_only")
|
||||
else:
|
||||
lifecycle_logger.warning("cache_not_configured_using_database_only")
|
||||
idempotency_stale_rows = await session_service.purge_expired_idempotency(pool)
|
||||
if idempotency_stale_rows:
|
||||
lifecycle_logger.info(
|
||||
"idempotency_purge_at_start count=%s", idempotency_stale_rows
|
||||
)
|
||||
purge_task = asyncio.create_task(_purge_loop(pool))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
lifecycle_logger.info("shutdown_requested")
|
||||
purge_task.cancel()
|
||||
with contextlib.suppress(BaseException):
|
||||
await purge_task
|
||||
await cache.close()
|
||||
await pool.close()
|
||||
lifecycle_logger.info("server_stopped")
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
resolved = settings or load_settings()
|
||||
application = FastAPI(
|
||||
title="MTUSI Messenger — лабораторная 3",
|
||||
version="1.3.0",
|
||||
docs_url="/docs",
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
application.state.settings = resolved
|
||||
application.state.logger = lifecycle_logger
|
||||
application.state.pool = create_pool(
|
||||
resolved.database_url,
|
||||
min_size=resolved.pool_min_size,
|
||||
max_size=resolved.pool_max_size,
|
||||
timeout_seconds=resolved.pool_timeout_seconds,
|
||||
connect_timeout_seconds=resolved.connect_timeout_seconds,
|
||||
statement_timeout_ms=resolved.statement_timeout_ms,
|
||||
)
|
||||
application.state.cache = session_service.SessionCache(
|
||||
resolved.cache_url,
|
||||
timeout_seconds=resolved.cache_timeout_seconds,
|
||||
ttl_cap=resolved.cache_ttl_seconds,
|
||||
)
|
||||
application.openapi = load_contract # type: ignore[method-assign]
|
||||
|
||||
@application.get("/version", include_in_schema=False)
|
||||
async def version() -> dict[str, str]:
|
||||
return {"version": resolved.version, "instance_id": resolved.instance_id}
|
||||
|
||||
@application.get("/info", include_in_schema=False)
|
||||
async def info() -> dict[str, str]:
|
||||
return {"service": "mtusi-messenger", "lab": "3", "version": resolved.version}
|
||||
|
||||
@application.middleware("http")
|
||||
async def request_context(request: Request, call_next: Any) -> Response:
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
started_at = time.monotonic()
|
||||
status = 500
|
||||
try:
|
||||
response = await call_next(request)
|
||||
if request.method in {"POST", "PUT", "PATCH"}:
|
||||
try:
|
||||
# Authentication or resource checks can finish before the body
|
||||
# is read. Drain any remainder without retaining it so the
|
||||
# client receives that JSON response instead of a TCP reset.
|
||||
async for _chunk in request.stream():
|
||||
pass
|
||||
except RuntimeError:
|
||||
pass
|
||||
status = response.status_code
|
||||
except ApiProblem as problem:
|
||||
response = problem_response(
|
||||
request, problem.status, problem.code, problem.message, problem.headers
|
||||
)
|
||||
status = problem.status
|
||||
except Exception: # noqa: BLE001 - never leak internals to the client
|
||||
lifecycle_logger.exception(
|
||||
"unhandled_error request_id=%s", request.state.request_id
|
||||
)
|
||||
response = problem_response(
|
||||
request, 500, "internal_error", "Internal server error"
|
||||
)
|
||||
status = 500
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
# Every response carries the instance that served it, including errors,
|
||||
# health and redirects, so a client can prove which process answered.
|
||||
response.headers["X-Instance-Id"] = request.app.state.settings.instance_id
|
||||
# The middleware still owns the response, but the idempotency check now
|
||||
# depends on the endpoint having already derived the Idempotency-Key value
|
||||
# from the contract and the security model, so the header is validated in
|
||||
# api.py rather than here.
|
||||
client = request.client.host if request.client is not None else "unknown"
|
||||
client = request.client.host if request.client is not None else "unknown"
|
||||
access_logger.info(
|
||||
"request_complete request_id=%s method=%s path=%s status=%s "
|
||||
"client=%s elapsed_ms=%.3f",
|
||||
request.state.request_id,
|
||||
request.method,
|
||||
request.url.path,
|
||||
status,
|
||||
client,
|
||||
(time.monotonic() - started_at) * 1000,
|
||||
)
|
||||
return response
|
||||
|
||||
@application.exception_handler(ApiProblem)
|
||||
async def api_problem_handler(request: Request, problem: ApiProblem) -> JSONResponse:
|
||||
return problem_response(
|
||||
request, problem.status, problem.code, problem.message, problem.headers
|
||||
)
|
||||
|
||||
@application.exception_handler(RequestValidationError)
|
||||
async def validation_handler(
|
||||
request: Request, _error: RequestValidationError
|
||||
) -> JSONResponse:
|
||||
return problem_response(
|
||||
request, 400, "invalid_request", "Request fields are invalid"
|
||||
)
|
||||
|
||||
@application.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(
|
||||
request: Request, error: StarletteHTTPException
|
||||
) -> JSONResponse:
|
||||
if error.status_code in {404, 405}:
|
||||
return problem_response(request, 404, "not_found", "Endpoint not found")
|
||||
return problem_response(
|
||||
request, error.status_code, "invalid_request", "Request is invalid"
|
||||
)
|
||||
|
||||
@application.exception_handler(PoolTimeout)
|
||||
async def pool_timeout_handler(
|
||||
request: Request, error: PoolTimeout
|
||||
) -> JSONResponse:
|
||||
lifecycle_logger.warning(
|
||||
"database_pool_timeout request_id=%s error=%s",
|
||||
request_id(request),
|
||||
type(error).__name__,
|
||||
)
|
||||
return problem_response(
|
||||
request, 503, "unavailable", "Database is unavailable"
|
||||
)
|
||||
|
||||
@application.exception_handler(psycopg.OperationalError)
|
||||
@application.exception_handler(psycopg.InterfaceError)
|
||||
async def database_unavailable_handler(
|
||||
request: Request, error: Exception
|
||||
) -> JSONResponse:
|
||||
lifecycle_logger.warning(
|
||||
"database_unavailable request_id=%s error=%s",
|
||||
request_id(request),
|
||||
type(error).__name__,
|
||||
)
|
||||
return problem_response(
|
||||
request, 503, "unavailable", "Database is unavailable"
|
||||
)
|
||||
|
||||
@application.exception_handler(psycopg.Error)
|
||||
async def database_error_handler(
|
||||
request: Request, error: psycopg.Error
|
||||
) -> JSONResponse:
|
||||
lifecycle_logger.warning(
|
||||
"database_error request_id=%s error=%s",
|
||||
request_id(request),
|
||||
type(error).__name__,
|
||||
)
|
||||
return problem_response(request, 500, "internal_error", "Internal server error")
|
||||
|
||||
@application.get("/", include_in_schema=False)
|
||||
async def docs_redirect() -> RedirectResponse:
|
||||
return RedirectResponse(url="/docs", status_code=307)
|
||||
|
||||
application.include_router(router)
|
||||
return application
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
"""Runtime configuration: environment variables plus file-based secrets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
CONTRACT_PATH = PROJECT_ROOT / "contracts" / "openapi.json"
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 50
|
||||
MAX_PAGE_SIZE = 100
|
||||
MAX_JSON_BYTES = 1_048_576
|
||||
DEFAULT_SESSION_TTL_SECONDS = 3600
|
||||
DEFAULT_CACHE_TTL_SECONDS = 300
|
||||
# Idempotency-Key records are replayed for this long, then the key is reusable.
|
||||
DEFAULT_IDEMPOTENCY_TTL_SECONDS = 86_400
|
||||
SUPPORTED_SESSION_STORES = {"postgres"}
|
||||
|
||||
__version__ = "1.3.0"
|
||||
|
||||
# Key pattern of the contract: 1..128 ASCII characters of the allowed set.
|
||||
IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
class ConfigurationError(Exception):
|
||||
"""Startup configuration is unusable; the process must not serve traffic."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
"""Everything the process needs, resolved once at startup."""
|
||||
|
||||
database_url: str
|
||||
cache_url: str | None
|
||||
session_store: str
|
||||
session_ttl_seconds: int
|
||||
cache_ttl_seconds: int
|
||||
pool_min_size: int
|
||||
pool_max_size: int
|
||||
pool_timeout_seconds: float
|
||||
connect_timeout_seconds: int
|
||||
statement_timeout_ms: int
|
||||
cache_timeout_seconds: float
|
||||
idempotency_ttl_seconds: int
|
||||
instance_id: str
|
||||
app_env: str
|
||||
version: str
|
||||
|
||||
@property
|
||||
def cache_enabled(self) -> bool:
|
||||
return self.cache_url is not None
|
||||
|
||||
|
||||
def _secret(file_variable: str, plain_variable: str) -> str | None:
|
||||
"""Read a secret from a mounted file, falling back to a plain variable."""
|
||||
path_value = os.environ.get(file_variable, "").strip()
|
||||
if path_value:
|
||||
path = Path(path_value)
|
||||
try:
|
||||
value = path.read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
raise ConfigurationError(
|
||||
file_variable + " points to an unreadable file (" + type(exc).__name__ + ")"
|
||||
) from None
|
||||
if not value:
|
||||
raise ConfigurationError(file_variable + " points to an empty file")
|
||||
return value
|
||||
plain = os.environ.get(plain_variable, "").strip()
|
||||
return plain or None
|
||||
|
||||
|
||||
def _integer(variable: str, default: int, minimum: int, maximum: int) -> int:
|
||||
raw = os.environ.get(variable, "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
raise ConfigurationError(variable + " must be an integer") from None
|
||||
if not minimum <= value <= maximum:
|
||||
raise ConfigurationError(
|
||||
variable + " must be between " + str(minimum) + " and " + str(maximum)
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _number(variable: str, default: float, minimum: float, maximum: float) -> float:
|
||||
raw = os.environ.get(variable, "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
value = float(raw)
|
||||
except ValueError:
|
||||
raise ConfigurationError(variable + " must be a number") from None
|
||||
if not minimum <= value <= maximum:
|
||||
raise ConfigurationError(
|
||||
variable + " must be between " + str(minimum) + " and " + str(maximum)
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
"""Resolve settings once; a bad configuration fails fast before serving."""
|
||||
database_url = _secret("DATABASE_URL_FILE", "DATABASE_URL")
|
||||
if database_url is None:
|
||||
raise ConfigurationError("DATABASE_URL_FILE or DATABASE_URL is required")
|
||||
cache_url = _secret("CACHE_URL_FILE", "CACHE_URL")
|
||||
session_store = os.environ.get("SESSION_STORE", "postgres").strip().lower()
|
||||
if session_store not in SUPPORTED_SESSION_STORES:
|
||||
raise ConfigurationError(
|
||||
"SESSION_STORE="
|
||||
+ session_store
|
||||
+ " is not implemented: sessions are stored in PostgreSQL "
|
||||
"(the durable source of truth) and cached in Valkey. Use SESSION_STORE=postgres."
|
||||
)
|
||||
pool_min = _integer("DB_POOL_MIN", 1, 0, 100)
|
||||
pool_max = _integer("DB_POOL_MAX", 10, 1, 200)
|
||||
if pool_min > pool_max:
|
||||
raise ConfigurationError("DB_POOL_MIN must not exceed DB_POOL_MAX")
|
||||
return Settings(
|
||||
database_url=database_url,
|
||||
cache_url=cache_url,
|
||||
session_store=session_store,
|
||||
session_ttl_seconds=_integer(
|
||||
"SESSION_TTL_SECONDS", DEFAULT_SESSION_TTL_SECONDS, 1, 2_592_000
|
||||
),
|
||||
cache_ttl_seconds=_integer(
|
||||
"CACHE_TTL_SECONDS", DEFAULT_CACHE_TTL_SECONDS, 1, 86_400
|
||||
),
|
||||
pool_min_size=pool_min,
|
||||
pool_max_size=pool_max,
|
||||
pool_timeout_seconds=_number("DB_POOL_TIMEOUT_SECONDS", 2.0, 0.1, 60.0),
|
||||
connect_timeout_seconds=_integer("DB_CONNECT_TIMEOUT_SECONDS", 2, 1, 60),
|
||||
statement_timeout_ms=_integer("DB_STATEMENT_TIMEOUT_MS", 5000, 100, 120_000),
|
||||
cache_timeout_seconds=_number("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0),
|
||||
idempotency_ttl_seconds=_integer(
|
||||
"IDEMPOTENCY_TTL_SECONDS",
|
||||
DEFAULT_IDEMPOTENCY_TTL_SECONDS,
|
||||
60,
|
||||
604_800,
|
||||
),
|
||||
# Stable for the life of the process. Inside a container this is the
|
||||
# short container id, which is what scripts/stop-one.sh maps back to a
|
||||
# single replica; outside Docker it stays a readable hostname.
|
||||
instance_id=os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname(),
|
||||
app_env=os.environ.get("APP_ENV", "lab").strip() or "lab",
|
||||
version=__version__,
|
||||
)
|
||||
|
||||
|
||||
def load_address() -> tuple[str, int]:
|
||||
"""Read and validate the HTTP listen address from the environment."""
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0").strip()
|
||||
if not host:
|
||||
raise SystemExit("APP_HOST must not be empty")
|
||||
port = _integer("APP_PORT", 8080, 1, 65535)
|
||||
return host, port
|
||||
@@ -0,0 +1,49 @@
|
||||
"""PostgreSQL access: a bounded async pool with explicit timeouts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
|
||||
|
||||
def connection_options(statement_timeout_ms: int) -> str:
|
||||
"""Server-side limits so a slow query or an idle transaction cannot pile up."""
|
||||
return (
|
||||
"-c statement_timeout="
|
||||
+ str(statement_timeout_ms)
|
||||
+ " -c lock_timeout=2000 -c idle_in_transaction_session_timeout=10000"
|
||||
+ " -c timezone=UTC"
|
||||
)
|
||||
|
||||
|
||||
def create_pool(
|
||||
database_url: str,
|
||||
*,
|
||||
min_size: int,
|
||||
max_size: int,
|
||||
timeout_seconds: float,
|
||||
connect_timeout_seconds: int,
|
||||
statement_timeout_ms: int,
|
||||
) -> AsyncConnectionPool:
|
||||
"""Build a closed pool; the lifespan opens it and closes it on shutdown."""
|
||||
return AsyncConnectionPool(
|
||||
conninfo=database_url,
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
timeout=timeout_seconds,
|
||||
open=False,
|
||||
check=AsyncConnectionPool.check_connection,
|
||||
kwargs={
|
||||
"row_factory": dict_row,
|
||||
"connect_timeout": connect_timeout_seconds,
|
||||
"options": connection_options(statement_timeout_ms),
|
||||
"application_name": "mtusi-messenger-api",
|
||||
},
|
||||
name="messenger-pool",
|
||||
)
|
||||
|
||||
|
||||
async def ping(pool: AsyncConnectionPool) -> None:
|
||||
"""Cheap readiness probe; raises when PostgreSQL is not usable."""
|
||||
async with pool.connection() as connection:
|
||||
await connection.execute("SELECT 1")
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Errors that may safely be returned through the public API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
class ApiProblem(Exception):
|
||||
"""An expected API failure with a stable status, machine code and headers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
status: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = dict(headers or {})
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Versioned SQL migration runner.
|
||||
|
||||
Every run is one transaction guarded by a PostgreSQL advisory lock, so a second
|
||||
process (or a restarted container) cannot apply the same file twice and a failed
|
||||
migration leaves the schema unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
if __package__ in {None, ""}:
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from src.config import MIGRATIONS_DIR, ConfigurationError, load_settings # noqa: E402
|
||||
|
||||
|
||||
ADVISORY_LOCK_KEY = 915_127_001
|
||||
CONNECT_RETRY_SECONDS = 60
|
||||
|
||||
|
||||
def _version(path: Path) -> int:
|
||||
prefix = path.name.split("_", 1)[0]
|
||||
return int(prefix)
|
||||
|
||||
|
||||
def apply_migrations(connection: psycopg.Connection, directory: Path) -> list[str]:
|
||||
applied: list[str] = []
|
||||
with connection.transaction():
|
||||
connection.execute("SELECT pg_advisory_xact_lock(%s)", (ADVISORY_LOCK_KEY,))
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version integer PRIMARY KEY,
|
||||
filename text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
rows = connection.execute("SELECT version FROM schema_migrations").fetchall()
|
||||
done = {row[0] for row in rows}
|
||||
for path in sorted(directory.glob("*.sql"), key=_version):
|
||||
version = _version(path)
|
||||
if version in done:
|
||||
continue
|
||||
connection.execute(path.read_text(encoding="utf-8"))
|
||||
connection.execute(
|
||||
"INSERT INTO schema_migrations (version, filename) VALUES (%s, %s)",
|
||||
(version, path.name),
|
||||
)
|
||||
applied.append(path.name)
|
||||
return applied
|
||||
|
||||
|
||||
def main() -> None:
|
||||
try:
|
||||
settings = load_settings()
|
||||
except ConfigurationError as error:
|
||||
print("configuration_error " + str(error), file=sys.stderr)
|
||||
raise SystemExit(1) from None
|
||||
deadline = time.monotonic() + CONNECT_RETRY_SECONDS
|
||||
while True:
|
||||
try:
|
||||
with psycopg.connect(
|
||||
settings.database_url,
|
||||
connect_timeout=5,
|
||||
options="-c timezone=UTC",
|
||||
application_name="mtusi-messenger-migrate",
|
||||
) as connection:
|
||||
applied = apply_migrations(connection, MIGRATIONS_DIR)
|
||||
break
|
||||
except psycopg.OperationalError as error:
|
||||
if time.monotonic() >= deadline:
|
||||
print(
|
||||
"database_unreachable error=" + type(error).__name__, file=sys.stderr
|
||||
)
|
||||
raise SystemExit(1) from None
|
||||
time.sleep(1)
|
||||
except psycopg.Error as error:
|
||||
print("migration_failed error=" + type(error).__name__, file=sys.stderr)
|
||||
raise SystemExit(1) from None
|
||||
if applied:
|
||||
print("migrations_applied " + ",".join(applied))
|
||||
else:
|
||||
print("migrations_up_to_date")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Users own credentials and identity. The password column stores an Argon2id hash.
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_password_hash_present CHECK (char_length(password_hash) > 0)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX users_username_unique ON users (username);
|
||||
@@ -0,0 +1,34 @@
|
||||
-- Chats, explicit membership and message history.
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
-- Chat lists are ordered by (created_at, id) for the same keyset cursor.
|
||||
CREATE INDEX chats_order_idx ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
joined_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
-- "Chats of the current user" and the membership check on every read.
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
-- Serves history keyset pagination exactly: equality on chat_id, then the
|
||||
-- (created_at, id) tuple used by both ORDER BY and the cursor predicate.
|
||||
-- Justification and EXPLAIN (ANALYZE, BUFFERS) are in evidence/explain-history.txt.
|
||||
CREATE INDEX messages_chat_order_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Opaque server-side sessions: only a SHA-256 of the token is stored.
|
||||
CREATE TABLE sessions (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
token_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz,
|
||||
CONSTRAINT sessions_token_hash_length CHECK (char_length(token_hash) = 64),
|
||||
CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
-- Every authenticated request looks a token up by hash.
|
||||
CREATE UNIQUE INDEX sessions_token_hash_unique ON sessions (token_hash);
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Idempotency-Key records for the lab 3 message write path.
|
||||
CREATE TABLE idempotency_keys (
|
||||
key text PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
request_sha256 text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT idempotency_key_format CHECK (char_length(key) <= 128),
|
||||
CONSTRAINT idempotency_request_sha256_length CHECK (char_length(request_sha256) = 64)
|
||||
);
|
||||
|
||||
CREATE INDEX idempotency_chat_idx ON idempotency_keys (chat_id);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Composite index covering the idempotency queries: by chat and by key.
|
||||
CREATE INDEX idempotency_keys_chat_order_idx ON idempotency_keys (chat_id, key);
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Add message_id to idempotency_keys so replays can return the original message.
|
||||
ALTER TABLE idempotency_keys ADD COLUMN IF NOT EXISTS message_id uuid REFERENCES messages (id) ON DELETE CASCADE;
|
||||
CREATE INDEX IF NOT EXISTS idempotency_message_idx ON idempotency_keys (message_id);
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Strict request models for the lab 2 API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from .config import IDEMPOTENCY_KEY_PATTERN
|
||||
|
||||
|
||||
USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
PASSWORD_MIN_LENGTH = 12
|
||||
PASSWORD_MAX_LENGTH = 128
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
def _not_blank(value: str, field: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError(field + " must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
"""Registration body; the password never appears in a response."""
|
||||
|
||||
username: str = Field(
|
||||
min_length=3, max_length=32, pattern=USERNAME_PATTERN.pattern
|
||||
)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(
|
||||
min_length=PASSWORD_MIN_LENGTH, max_length=PASSWORD_MAX_LENGTH
|
||||
)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_is_not_blank(cls, value: str) -> str:
|
||||
return _not_blank(value, "display_name")
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_length_in_code_points(cls, value: str) -> str:
|
||||
# Python len() counts Unicode code points, which is what the contract uses.
|
||||
if not PASSWORD_MIN_LENGTH <= len(value) <= PASSWORD_MAX_LENGTH:
|
||||
raise ValueError("password length is out of range")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_is_not_blank(cls, value: str) -> str:
|
||||
return _not_blank(value, "title")
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def members_are_valid_and_unique(cls, value: list[str]) -> list[str]:
|
||||
try:
|
||||
normalized = [str(uuid.UUID(member_id)) for member_id in value]
|
||||
except (ValueError, AttributeError):
|
||||
raise ValueError("member_ids must contain UUID strings") from None
|
||||
if len(normalized) != len(set(normalized)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return normalized
|
||||
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def text_is_not_blank(cls, value: str) -> str:
|
||||
return _not_blank(value, "text")
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Opaque, resource-bound keyset cursors, timestamp formatting and page shaping."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from .errors import ApiProblem
|
||||
|
||||
|
||||
def format_timestamp(value: datetime) -> str:
|
||||
"""RFC 3339 UTC with microseconds and a trailing Z, as the contract requires."""
|
||||
return (
|
||||
value.astimezone(timezone.utc)
|
||||
.isoformat(timespec="microseconds")
|
||||
.replace("+00:00", "Z")
|
||||
)
|
||||
|
||||
|
||||
def parse_timestamp(value: str) -> datetime:
|
||||
"""Parse an RFC 3339 timestamp from a cursor; reject anything else."""
|
||||
candidate = value[:-1] + "+00:00" if value.endswith("Z") else value
|
||||
parsed = datetime.fromisoformat(candidate)
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def encode_cursor(resource: str, created_at: datetime, record_id: str) -> str:
|
||||
payload = json.dumps(
|
||||
{
|
||||
"resource": resource,
|
||||
"created_at": format_timestamp(created_at),
|
||||
"id": record_id,
|
||||
},
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(value: str, resource: str) -> tuple[datetime, uuid.UUID]:
|
||||
"""Decode a cursor and bind it to the resource it was issued for."""
|
||||
try:
|
||||
padding = "=" * (-len(value) % 4)
|
||||
raw = base64.b64decode(value + padding, altchars=b"-_", validate=True)
|
||||
payload: Any = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(payload, dict) or set(payload) != {
|
||||
"resource",
|
||||
"created_at",
|
||||
"id",
|
||||
}:
|
||||
raise ValueError("unexpected cursor payload")
|
||||
if payload["resource"] != resource:
|
||||
raise ValueError("cursor belongs to another resource")
|
||||
created_at = payload["created_at"]
|
||||
record_id = payload["id"]
|
||||
if not isinstance(created_at, str) or not isinstance(record_id, str):
|
||||
raise ValueError("cursor fields have wrong types")
|
||||
return parse_timestamp(created_at), uuid.UUID(record_id)
|
||||
except (
|
||||
ValueError,
|
||||
TypeError,
|
||||
UnicodeError,
|
||||
binascii.Error,
|
||||
json.JSONDecodeError,
|
||||
):
|
||||
raise ApiProblem(400, "invalid_request", "Cursor is invalid") from None
|
||||
|
||||
|
||||
def build_page(items: list[dict[str, Any]], resource: str, limit: int) -> dict[str, Any]:
|
||||
"""Shape a limit+1 storage slice into the public page and its next cursor."""
|
||||
page = items[:limit]
|
||||
next_cursor = None
|
||||
if len(items) > limit and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(
|
||||
resource, parse_timestamp(last["created_at"]), last["id"]
|
||||
)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Password hashing with Argon2id (library KDF, salted, versioned parameters)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
|
||||
|
||||
# OWASP-recommended Argon2id baseline: 19 MiB, 2 iterations, 1 lane.
|
||||
_hasher = PasswordHasher(
|
||||
time_cost=2,
|
||||
memory_cost=19456,
|
||||
parallelism=1,
|
||||
hash_len=32,
|
||||
salt_len=16,
|
||||
)
|
||||
|
||||
# Verified against when a username is unknown, so the failure path costs the same
|
||||
# as a wrong password and does not leak username existence through timing.
|
||||
_DUMMY_HASH = _hasher.hash("dummy-password-not-used-for-any-account")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, encoded: str | None) -> bool:
|
||||
"""Return True only for a matching password and a parseable hash."""
|
||||
if encoded is None:
|
||||
verify_password_unknown_user(password)
|
||||
return False
|
||||
try:
|
||||
return _hasher.verify(encoded, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def verify_password_unknown_user(password: str) -> None:
|
||||
"""Burn comparable CPU time when no account exists for the username."""
|
||||
try:
|
||||
_hasher.verify(_DUMMY_HASH, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
"""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 == HIT and payload is not None:
|
||||
if payload["expires_epoch"] > time.time():
|
||||
try:
|
||||
user_id = uuid.UUID(payload["user"]["id"])
|
||||
except (ValueError, TypeError, KeyError):
|
||||
user_id = None
|
||||
if user_id is not None:
|
||||
return user_id, payload["user"]
|
||||
else:
|
||||
await cache.revoke(hashed, None)
|
||||
elif state == TOMBSTONE:
|
||||
raise ApiProblem(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Session token is expired or revoked",
|
||||
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
+351
@@ -0,0 +1,351 @@
|
||||
"""PostgreSQL repository: parameterised statements only, explicit transactions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
from psycopg import AsyncCursor
|
||||
|
||||
from .errors import ApiProblem
|
||||
from .pagination import format_timestamp
|
||||
|
||||
# One expression keeps the member list of a chat consistent across endpoints.
|
||||
CHAT_COLUMNS = """
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
ARRAY(
|
||||
SELECT m.user_id::text
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
ORDER BY m.user_id::text
|
||||
) AS member_ids
|
||||
"""
|
||||
|
||||
|
||||
def user_json(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"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(member) for member in row["member_ids"]],
|
||||
"created_at": format_timestamp(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_timestamp(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def create_user(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password_hash: str,
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, now())
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(uuid.uuid4(), username, display_name, password_hash),
|
||||
)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiProblem(409, "conflict", "Username is already taken") from None
|
||||
row = await cursor.fetchone()
|
||||
return user_json(row)
|
||||
|
||||
|
||||
async def user_credentials(cursor: AsyncCursor, username: str) -> dict[str, Any] | None:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def user_by_id(cursor: AsyncCursor, user_id: uuid.UUID) -> dict[str, Any] | None:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = %s
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def create_chat(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
title: str,
|
||||
member_ids: list[uuid.UUID],
|
||||
) -> dict[str, Any]:
|
||||
"""Insert the chat and its membership in one transaction.
|
||||
|
||||
Unknown members are rejected by the foreign key, so the failure rolls the
|
||||
already inserted chat row back instead of leaving a chat without members.
|
||||
"""
|
||||
if actor_id not in member_ids:
|
||||
raise ApiProblem(400, "invalid_request", "Current user must be a chat member")
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
await cursor.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, now())",
|
||||
(chat_id, title),
|
||||
)
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, joined_at)
|
||||
SELECT %s, member_id, now() FROM unnest(%s::uuid[]) AS member_id
|
||||
""",
|
||||
(chat_id, member_ids),
|
||||
)
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise ApiProblem(
|
||||
400, "invalid_request", "One or more members do not exist"
|
||||
) from None
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiProblem(400, "invalid_request", "Chat members must be unique") from None
|
||||
await cursor.execute(
|
||||
"SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s",
|
||||
(chat_id,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return chat_json(row)
|
||||
|
||||
|
||||
async def accessible_chat(
|
||||
cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID
|
||||
) -> dict[str, Any]:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT """
|
||||
+ CHAT_COLUMNS
|
||||
+ """
|
||||
FROM chats c
|
||||
JOIN chat_members membership
|
||||
ON membership.chat_id = c.id AND membership.user_id = %s
|
||||
WHERE c.id = %s
|
||||
""",
|
||||
(actor_id, chat_id),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
raise ApiProblem(404, "not_found", "Chat not found")
|
||||
return chat_json(row)
|
||||
|
||||
|
||||
async def chat_page(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
limit: int,
|
||||
after: tuple[datetime, uuid.UUID] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = (
|
||||
"SELECT "
|
||||
+ CHAT_COLUMNS
|
||||
+ """
|
||||
FROM chats c
|
||||
JOIN chat_members membership
|
||||
ON membership.chat_id = c.id AND membership.user_id = %(actor)s
|
||||
"""
|
||||
)
|
||||
params: dict[str, Any] = {"actor": actor_id, "limit": limit + 1}
|
||||
if after is not None:
|
||||
query += " WHERE (c.created_at, c.id) > (%(after_ts)s, %(after_id)s)"
|
||||
params["after_ts"], params["after_id"] = after
|
||||
query += " ORDER BY c.created_at, c.id LIMIT %(limit)s"
|
||||
await cursor.execute(query, params)
|
||||
return [chat_json(row) for row in await cursor.fetchall()]
|
||||
|
||||
|
||||
async def require_membership(
|
||||
cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID
|
||||
) -> None:
|
||||
await cursor.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, actor_id),
|
||||
)
|
||||
if await cursor.fetchone() is None:
|
||||
raise ApiProblem(404, "not_found", "Chat not found")
|
||||
|
||||
|
||||
async def get_idempotency_key(cursor: AsyncCursor, key: str) -> dict[str, Any] | None:
|
||||
"""Return the idempotency row (request_sha256, message_id, chat_id) if it exists."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT key, chat_id, request_sha256, message_id, created_at
|
||||
FROM idempotency_keys
|
||||
WHERE key = %s
|
||||
""",
|
||||
(key,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def insert_idempotency_key(
|
||||
cursor: AsyncCursor, *, key: str, chat_id: uuid.UUID, request_sha256: str
|
||||
) -> None:
|
||||
try:
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (key, chat_id, request_sha256, created_at)
|
||||
VALUES (%s, %s, %s, now())
|
||||
""",
|
||||
(key, chat_id, request_sha256),
|
||||
)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiProblem(409, "conflict", "Idempotency-Key was already used") from None
|
||||
|
||||
|
||||
async def message_by_id(cursor: AsyncCursor, message_id: uuid.UUID) -> dict[str, Any] | None:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE id = %s
|
||||
""",
|
||||
(message_id,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return message_json(row)
|
||||
|
||||
|
||||
async def create_message(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
chat_id: uuid.UUID,
|
||||
text: str,
|
||||
request_sha256: str,
|
||||
key: str,
|
||||
) -> dict[str, Any]:
|
||||
await require_membership(cursor, actor_id=actor_id, chat_id=chat_id)
|
||||
# The SHA-256 of the replayed body is recorded with the idempotency row so a
|
||||
# client cannot replay a request with different content under the same key.
|
||||
message_id = uuid.uuid4()
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, now())
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
(message_id, chat_id, actor_id, text),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
# Record the message_id so a replay can return the original message.
|
||||
await cursor.execute(
|
||||
"UPDATE idempotency_keys SET request_sha256 = %s, message_id = %s WHERE key = %s",
|
||||
(request_sha256, message_id, key),
|
||||
)
|
||||
return message_json(row)
|
||||
|
||||
|
||||
async def message_page(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
chat_id: uuid.UUID,
|
||||
limit: int,
|
||||
after: tuple[datetime, uuid.UUID] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Keyset page over (created_at, id); the composite index serves both branches."""
|
||||
query = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %(chat)s
|
||||
"""
|
||||
params: dict[str, Any] = {"chat": chat_id, "limit": limit + 1}
|
||||
if after is not None:
|
||||
query += " AND (created_at, id) > (%(after_ts)s, %(after_id)s)"
|
||||
params["after_ts"], params["after_id"] = after
|
||||
query += " ORDER BY created_at, id LIMIT %(limit)s"
|
||||
await cursor.execute(query, params)
|
||||
return [message_json(row) for row in await cursor.fetchall()]
|
||||
|
||||
|
||||
async def insert_session(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
user_id: uuid.UUID,
|
||||
token_hash: str,
|
||||
ttl_seconds: int,
|
||||
) -> datetime:
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at)
|
||||
VALUES (%s, %s, %s, now(), now() + make_interval(secs => %s))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(uuid.uuid4(), user_id, token_hash, ttl_seconds),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return row["expires_at"]
|
||||
|
||||
|
||||
async def session_user(cursor: AsyncCursor, token_hash: str) -> dict[str, Any] | None:
|
||||
"""Resolve a live session row; expired and revoked sessions never match."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def revoke_session(cursor: AsyncCursor, token_hash: str) -> datetime | None:
|
||||
"""Revoke a live session and return its expiry, or None when it is not live."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
UPDATE sessions SET revoked_at = now()
|
||||
WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now()
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return None if row is None else row["expires_at"]
|
||||
|
||||
|
||||
async def purge_expired_sessions(cursor: AsyncCursor) -> int:
|
||||
await cursor.execute(
|
||||
"""
|
||||
DELETE FROM sessions
|
||||
WHERE expires_at < now() - interval '1 hour'
|
||||
OR (revoked_at IS NOT NULL AND revoked_at < now() - interval '1 hour')
|
||||
"""
|
||||
)
|
||||
return cursor.rowcount
|
||||
Reference in New Issue
Block a user