Files
mtusi2026lab2/app/main.py
T
2026-10-15 18:30:21 +03:00

361 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
HTTP-слой мессенджера (lab2).
Клиент → HTTP API (этот файл) → PostgreSQL (источник истины)
↘ Redis/Valkey (кэш сессий, необязательный)
Что изменилось относительно lab1:
* регистрация принимает password, хранится только Argon2id-хэш;
* вход: POST /api/v1/auth/sessions с Authorization: Basic → Bearer-токен;
* все бизнес-запросы требуют Authorization: Bearer; X-User-Id игнорируется;
* данные и действующие сессии лежат в PostgreSQL и переживают рестарт.
"""
from __future__ import annotations
import base64
import binascii
import logging
import re
import time
import uuid
from contextlib import asynccontextmanager
import psycopg
from fastapi import Depends, FastAPI, Query, Request
from fastapi.concurrency import run_in_threadpool
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from psycopg_pool import PoolTimeout
from pydantic import BaseModel, field_validator
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import db, repo, security, sessions
from .config import settings
from .migrate import migrate
logger = logging.getLogger("messenger")
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
BEARER_CHALLENGE = 'Bearer realm="messenger"'
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
@asynccontextmanager
async def lifespan(app: FastAPI):
if settings.migrate_on_start:
try:
applied = await migrate()
logger.info("migrations: %s", applied or "up to date")
except psycopg.OperationalError as exc:
# БД ещё не готова: API всё равно стартует, /health/ready покажет 503.
logger.warning("migrations skipped, database unavailable: %s", type(exc).__name__)
await db.open_pool()
sessions.init_redis()
yield
await sessions.close_redis()
await db.close_pool()
app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan)
# ============================================================================
# 1. ЕДИНЫЙ ФОРМАТ ОШИБОК {"error":{"code","message","request_id"}}
# ============================================================================
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
def error_response(request: Request, status: int, code: str, message: str,
headers: dict | None = None) -> JSONResponse:
rid = getattr(request.state, "request_id", str(uuid.uuid4()))
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": rid}},
headers={"X-Request-Id": rid, **(headers or {})},
)
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError):
return error_response(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "invalid request body or parameters")
@app.exception_handler(StarletteHTTPException)
async def handle_http(request: Request, exc: StarletteHTTPException):
# Только коды из enum контракта (contracts/openapi.json → Error.code).
code = {401: "unauthorized", 404: "not_found", 409: "conflict",
413: "payload_too_large", 415: "unsupported_media_type",
429: "rate_limited", 503: "unavailable"}.get(
exc.status_code, "internal_error" if exc.status_code >= 500 else "invalid_request")
return error_response(request, exc.status_code, code, str(exc.detail))
@app.exception_handler(psycopg.OperationalError)
@app.exception_handler(PoolTimeout)
async def handle_db_down(request: Request, exc: Exception):
# БД недоступна или не ответила за таймаут: ограниченная ошибка, а не зависание.
logger.warning("database unavailable: %s", type(exc).__name__)
return error_response(request, 503, "unavailable", "service temporarily unavailable")
@app.exception_handler(Exception)
async def handle_unexpected(request: Request, exc: Exception):
logger.exception("unexpected error")
return error_response(request, 500, "internal_error", "internal error")
# ============================================================================
# 2. X-Request-Id + лог без тела запроса, токенов и паролей
# ============================================================================
@app.middleware("http")
async def add_request_id(request: Request, call_next):
rid = str(uuid.uuid4())
request.state.request_id = rid
start = time.monotonic()
response = await call_next(request)
response.headers["X-Request-Id"] = rid
logger.info("rid=%s %s %s -> %s %sms", rid, request.method, request.url.path,
response.status_code, round((time.monotonic() - start) * 1000, 1))
return response
# ============================================================================
# 3. АУТЕНТИФИКАЦИЯ
# Bearer — для всех бизнес-запросов. Basic — только на POST /auth/sessions.
# X-User-Id больше ничего не значит и ни на что не влияет.
# ============================================================================
def unauthorized(message: str = "invalid or missing bearer token") -> ApiError:
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": BEARER_CHALLENGE})
def _bearer_token(request: Request) -> str:
auth = request.headers.get("authorization", "")
scheme, _, token = auth.partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or not token or len(token) > 512:
raise unauthorized()
return token
async def current_user(request: Request) -> dict:
"""Зависимость FastAPI: выполняется ДО разбора тела → сначала 401, потом 400."""
token = _bearer_token(request)
user = await sessions.resolve(db.get_pool(), token, repo.get_user)
if user is None:
raise unauthorized()
request.state.token = token
return user
def _parse_basic(request: Request) -> tuple[str, str]:
bad = ApiError(401, "unauthorized", "invalid credentials", {"WWW-Authenticate": BASIC_CHALLENGE})
scheme, _, value = request.headers.get("authorization", "").partition(" ")
if scheme.lower() != "basic" or not value:
raise bad
try:
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
raise bad
username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо
if not sep or not username.isascii() or not (12 <= len(password) <= 128):
raise bad
return username, password
# ============================================================================
# 4. МОДЕЛИ ВВОДА
# ============================================================================
class CreateUser(BaseModel):
model_config = {"extra": "forbid"}
username: str
display_name: str
password: str
@field_validator("username")
@classmethod
def check_username(cls, v: str) -> str:
if not USERNAME_RE.match(v):
raise ValueError("username must match [a-z0-9_]{3,32}")
return v
@field_validator("display_name")
@classmethod
def check_display_name(cls, v: str) -> str:
if not (1 <= len(v) <= 100) or not v.strip():
raise ValueError("display_name must be 1..100 non-blank chars")
return v
@field_validator("password")
@classmethod
def check_password(cls, v: str) -> str:
if not (12 <= len(v) <= 128) or not v.strip():
raise ValueError("password must be 12..128 chars")
return v
class CreateChat(BaseModel):
model_config = {"extra": "forbid"}
title: str
member_ids: list[str]
@field_validator("title")
@classmethod
def check_title(cls, v: str) -> str:
if not (1 <= len(v) <= 100) or not v.strip():
raise ValueError("title must be 1..100 non-blank chars")
return v
class CreateMessage(BaseModel):
model_config = {"extra": "forbid"}
text: str
@field_validator("text")
@classmethod
def check_text(cls, v: str) -> str:
if not (1 <= len(v) <= 4000) or not v.strip():
raise ValueError("text must be 1..4000 non-blank chars")
return v
def parse_uuid(value: str, what: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise ApiError(400, "invalid_request", f"{what} is not a valid uuid")
# ============================================================================
# 5. ENDPOINTS
# ============================================================================
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready(request: Request):
# Критичная зависимость — только PostgreSQL. Redis — кэш: его отказ не делает API неготовым.
try:
async with db.get_pool().connection() as conn:
await conn.execute("SELECT 1 FROM schema_migrations LIMIT 1")
except (psycopg.Error, PoolTimeout):
return error_response(request, 503, "unavailable", "database is not ready")
return {"status": "ok"}
# -------- users и сессии --------
@app.post("/api/v1/users", status_code=201)
async def create_user(body: CreateUser):
# Argon2 намеренно медленный — считаем в пуле потоков, чтобы не блокировать event loop.
password_hash = await run_in_threadpool(security.hash_password, body.password)
async with db.get_pool().connection() as conn:
try:
return await repo.create_user(conn, body.username, body.display_name, password_hash)
except repo.UsernameTaken:
raise ApiError(409, "conflict", "username already taken")
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
username, password = _parse_basic(request)
async with db.get_pool().connection() as conn:
row = await repo.get_credentials(conn, username)
stored_hash = row[4] if row else None
# Проверяем хэш даже для несуществующего пользователя — одинаковое время ответа.
ok = await run_in_threadpool(security.verify_password, stored_hash, password)
if not ok:
raise ApiError(401, "unauthorized", "invalid credentials", {"WWW-Authenticate": BASIC_CHALLENGE})
user = repo.user_out(row)
async with db.get_pool().connection() as conn:
if security.needs_rehash(stored_hash):
await repo.update_password_hash(conn, row[0], await run_in_threadpool(security.hash_password, password))
token, expires_at = await sessions.create_session(conn, row[0])
return {"token": token, "token_type": "Bearer", "expires_at": repo.iso(expires_at), "user": user}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(request: Request, user: dict = Depends(current_user)):
if not await sessions.revoke(db.get_pool(), request.state.token):
raise unauthorized()
return Response(status_code=204)
@app.get("/api/v1/users/me")
async def get_me(user: dict = Depends(current_user)):
return user
# -------- chats --------
@app.post("/api/v1/chats", status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
members = body.member_ids
if not (1 <= len(members) <= 100):
raise ApiError(400, "invalid_request", "member_ids must have 1..100 items")
if len(set(members)) != len(members):
raise ApiError(400, "invalid_request", "duplicate member_ids")
ids = [parse_uuid(m, "member id") for m in members]
if uuid.UUID(user["id"]) not in ids:
raise ApiError(400, "invalid_request", "caller must be a member")
async with db.get_pool().connection() as conn:
# Одна транзакция: чат и все участники создаются вместе или не создаются вовсе.
async with conn.transaction():
if await repo.count_existing_users(conn, ids) != len(ids):
raise ApiError(400, "invalid_request", "unknown member")
return await repo.insert_chat(conn, body.title, ids, user["id"])
@app.get("/api/v1/chats")
async def list_chats(user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None, min_length=1)):
async with db.get_pool().connection() as conn:
try:
items, nxt = await repo.list_chats(conn, user["id"], limit, cursor)
except ValueError:
raise ApiError(400, "invalid_request", "bad cursor")
return {"items": items, "next_cursor": nxt}
async def accessible_chat(conn, chat_id: str, user: dict) -> dict:
"""Кривой UUID → 400. Чата нет ИЛИ ты не участник → одинаковый 404."""
cid = parse_uuid(chat_id, "chat_id")
chat = await repo.get_chat_for_member(conn, cid, user["id"])
if chat is None:
raise ApiError(404, "not_found", "chat not found")
return chat
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, user: dict = Depends(current_user)):
async with db.get_pool().connection() as conn:
return await accessible_chat(conn, chat_id, user)
# -------- messages --------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def send_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
async with db.get_pool().connection() as conn:
chat = await accessible_chat(conn, chat_id, user)
# Отправитель — из сессии, а не из тела запроса.
return await repo.insert_message(conn, chat["id"], user["id"], body.text)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None, min_length=1)):
async with db.get_pool().connection() as conn:
chat = await accessible_chat(conn, chat_id, user)
try:
items, nxt = await repo.list_messages(conn, chat["id"], limit, cursor)
except ValueError:
raise ApiError(400, "invalid_request", "bad cursor")
return {"items": items, "next_cursor": nxt}