Files

257 lines
12 KiB
Python

"""Мессенджер, лабораторная 2: PostgreSQL + сессии (Bearer) + Valkey/Redis как кэш сессий.
Развитие main.py из lab1 (FastAPI/Uvicorn): те же маршруты, тот же формат ошибок, middleware X-Request-Id.
Изменилось: вместо словарей в памяти — PostgreSQL (app/repo.py), вместо X-User-Id — Bearer-сессия
(app/sessions.py), вход — Basic на POST /auth/sessions, пароли — Argon2id (app/security.py).
"""
import logging
import re
import uuid
from contextlib import asynccontextmanager
from typing import NamedTuple
import anyio.to_thread
import psycopg
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from starlette.exceptions import HTTPException as StarletteHTTPException
from app import config, cursor, db, repo, security, sessions, validation
from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, ApiError, bad_request, not_found, unauthorized
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("api")
_REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
@asynccontextmanager
async def lifespan(_app):
# Sync-обработчики FastAPI идут в пул потоков; ограничиваем его, чтобы очередь ждала в потоках, а не в пуле БД.
anyio.to_thread.current_default_thread_limiter().total_tokens = config.THREAD_LIMIT
yield
db.close() # SIGTERM: корректно закрываем соединения PostgreSQL
# Автодокументация FastAPI отключена: контракт — contracts/openapi.json.
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
# ---------- X-Request-Id, ошибки (как в lab1) ----------
def make_error(code, message, request_id):
return {"error": {"code": code, "message": message, "request_id": request_id}}
def _rid(request):
return getattr(request.state, "request_id", None) or uuid.uuid4().hex
def error_response(request, status, code, message, headers=None):
rid = _rid(request)
out = {"X-Request-Id": rid, "Cache-Control": "no-store"} # заголовок и в ответах, минующих middleware (500)
out.update(headers or {})
return JSONResponse(status_code=status, content=make_error(code, message, rid), headers=out)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
incoming = request.headers.get("X-Request-Id", "")
rid = incoming if _REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex # чужое значение — только безопасное
request.state.request_id = rid
response = await call_next(request)
response.headers["X-Request-Id"] = rid
response.headers["Cache-Control"] = "no-store"
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return error_response(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc):
return error_response(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(StarletteHTTPException)
async def http_exc_handler(request: Request, exc: StarletteHTTPException):
mapping = {404: ("not_found", "Объект не найден"), 405: ("invalid_request", "Метод не поддерживается")}
code, message = mapping.get(exc.status_code, ("invalid_request", "Ошибка запроса"))
return error_response(request, exc.status_code, code, message)
@app.exception_handler(Exception)
async def generic_handler(request: Request, exc: Exception):
if isinstance(exc, db.TRANSIENT):
# PostgreSQL недоступен/перегружен: ограниченный ответ без деталей.
log.warning("dependency unavailable [%s]: %s", _rid(request), type(exc).__name__)
return error_response(request, 503, "unavailable", "Сервис временно недоступен")
log.error("unhandled error [%s]", _rid(request), exc_info=exc) # стек — только в серверный лог
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
# ---------- аутентификация (вместо X-User-Id из lab1) ----------
class Auth(NamedTuple):
user: dict
user_id: uuid.UUID
digest: bytes
def authenticated(request: Request) -> Auth:
"""Bearer-токен -> сессия -> пользователь. Basic, X-User-Id и любые другие схемы дают 401."""
token = security.parse_bearer(request.headers.get("Authorization"))
if token is None:
raise unauthorized(BEARER_CHALLENGE)
found = sessions.lookup(token) # Valkey -> PostgreSQL; БД недоступна -> 503 в generic_handler
if found is None:
raise unauthorized(BEARER_CHALLENGE)
return Auth(found["user"], uuid.UUID(found["user"]["id"]), found["digest"])
class RawBody(NamedTuple):
content_type: str
data: bytes
async def raw_body(request: Request) -> RawBody:
"""Читает тело с жёстким лимитом (в т.ч. для chunked) -> 413. Разбор JSON — позже, после проверки доступа."""
declared = request.headers.get("content-length")
if declared is not None and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
chunks, size = [], 0
async for chunk in request.stream():
size += len(chunk)
if size > config.MAX_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
chunks.append(chunk)
return RawBody(request.headers.get("content-type", ""), b"".join(chunks))
# ---------- health ----------
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready():
db.ping() # критичная зависимость — PostgreSQL; недоступность кэша НЕ делает сервис неготовым
return {"status": "ok"}
# ---------- пользователи ----------
@app.post("/api/v1/users", status_code=201)
def create_user(body: RawBody = Depends(raw_body)):
data = validation.json_body(body.content_type, body.data,
{"username", "display_name", "password"}, {"username", "display_name", "password"})
username = validation.username_field(data["username"])
display_name = validation.text_field(data["display_name"], "display_name", 1, 100)
password = validation.text_field(data["password"], "password", 12, 128)
with db.connection() as conn: # быстрый путь: не тратим Argon2 на заведомый дубль
if repo.username_exists(conn, username):
raise ApiError(409, "conflict", "Имя пользователя занято")
password_hash = security.hash_password(password) # тяжёлая CPU-операция — вне транзакции и без занятого соединения
try:
with db.connection() as conn:
row = repo.insert_user(conn, username, display_name, password_hash)
except psycopg.errors.UniqueViolation: # гонку двух регистраций решает UNIQUE в БД, а не проверка выше
raise ApiError(409, "conflict", "Имя пользователя занято")
return sessions.user_json(row)
@app.get("/api/v1/users/me")
def get_me(auth: Auth = Depends(authenticated)):
return auth.user
# ---------- сессии ----------
@app.post("/api/v1/auth/sessions", status_code=201)
def login(request: Request):
creds = security.parse_basic(request.headers.get("Authorization"))
if creds is None:
raise unauthorized(BASIC_CHALLENGE)
username, password = creds
with db.connection() as conn:
user = repo.user_for_login(conn, username) if validation._USERNAME_RE.fullmatch(username) else None
if user is None:
security.burn_verify(password) # время ответа не выдаёт, существует ли логин
raise unauthorized(BASIC_CHALLENGE)
ok, new_hash = security.verify_password(user["password_hash"], password)
if not ok:
raise unauthorized(BASIC_CHALLENGE)
with db.connection() as conn:
if new_hash:
repo.update_password_hash(conn, user["id"], new_hash)
token, expires_at = sessions.create(conn, user)
user_json = sessions.user_json(user)
sessions.warm(token, user_json, expires_at) # кэш наполняется после commit
return {"token": token, "token_type": "Bearer", "expires_at": sessions.fmt_ts(expires_at), "user": user_json}
@app.delete("/api/v1/auth/sessions/current")
def logout(auth: Auth = Depends(authenticated)):
sessions.revoke(auth.digest)
return Response(status_code=204)
# ---------- чаты ----------
@app.post("/api/v1/chats", status_code=201)
def create_chat(auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)):
data = validation.json_body(body.content_type, body.data, {"title", "member_ids"}, {"title", "member_ids"})
title = validation.text_field(data["title"], "title", 1, 100)
raw = data["member_ids"]
if not isinstance(raw, list) or not 1 <= len(raw) <= 100:
raise bad_request("member_ids: от 1 до 100 элементов")
members = [validation.require_uuid(x, "member_id") for x in raw]
if len(set(members)) != len(members) or auth.user_id not in members:
raise bad_request("member_ids должны быть уникальны и включать вызывающего")
with db.connection() as conn: # одна транзакция: либо чат целиком, либо ничего
chat = repo.create_chat(conn, auth.user_id, title, members)
return repo.chat_json(chat)
@app.get("/api/v1/chats")
def list_chats(request: Request, auth: Auth = Depends(authenticated)):
limit = validation.limit_param(request.query_params)
raw = request.query_params.get("cursor")
after = cursor.decode(raw, "chats", auth.user_id) if raw is not None else None
with db.connection() as conn:
items, nxt = repo.list_chats(conn, auth.user_id, after, limit)
return {"items": items, "next_cursor": nxt}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, auth: Auth = Depends(authenticated)):
cid = validation.require_uuid(chat_id, "chat_id")
with db.connection() as conn:
chat = repo.get_chat(conn, cid, auth.user_id)
if chat is None:
raise not_found()
return repo.chat_json(chat)
# ---------- сообщения ----------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(chat_id: str, auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)):
cid = validation.require_uuid(chat_id, "chat_id")
with db.connection() as conn:
if not repo.is_member(conn, cid, auth.user_id): # сначала доступ (404), потом валидация тела
raise not_found()
data = validation.json_body(body.content_type, body.data, {"text"}, {"text"})
text = validation.text_field(data["text"], "text", 1, 4000)
with db.connection() as conn:
row = repo.insert_message(conn, cid, auth.user_id, text) # sender_id — только из сессии
return repo.message_json(row)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request, auth: Auth = Depends(authenticated)):
cid = validation.require_uuid(chat_id, "chat_id")
limit = validation.limit_param(request.query_params)
raw = request.query_params.get("cursor")
after = cursor.decode(raw, "messages", cid) if raw is not None else None
with db.connection() as conn:
if not repo.is_member(conn, cid, auth.user_id):
raise not_found()
items, nxt = repo.list_messages(conn, cid, after, limit)
return {"items": items, "next_cursor": nxt}