Files
mtusi2026lab2/src/api/errors.py
T
ricoromaandClaude Opus 5.5 ae4154eaf5 feat: add password login and bearer sessions
- Argon2id password hashes, KDF in a thread with its own limit
- POST /auth/sessions with Basic, DELETE /auth/sessions/current
- Bearer sessions in PostgreSQL, X-User-Id ignored
- migration drops lab 1 data without passwords
- student-tests on tokens, sessions spec and synced specs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:50:42 +03:00

140 lines
4.9 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.
"""Перевод исключений в формат ошибки контракта.
Одна таблица «доменное исключение → статус, code». Ошибки валидации
FastAPI отдаются как 400, а не 422 (согласовано с преподавателем,
`.claude/rules/api-contract.md`). Непредвиденную ошибку логирует uvicorn:
Starlette повторно бросает её после ответа 500.
"""
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from src.api.schemas import Error, ErrorBody, ErrorCode
from src.core import exceptions
from src.utils.constants import AUTH_REALM, REQUEST_ID_HEADER
DOMAIN_ERRORS: dict[type[exceptions.DomainError], tuple[int, ErrorCode]] = {
exceptions.InvalidCredentials: (401, ErrorCode.UNAUTHORIZED),
exceptions.Unauthenticated: (401, ErrorCode.UNAUTHORIZED),
exceptions.UsernameTaken: (409, ErrorCode.CONFLICT),
exceptions.ChatNotFound: (404, ErrorCode.NOT_FOUND),
exceptions.InvalidChatMembers: (400, ErrorCode.INVALID_REQUEST),
exceptions.InvalidCursor: (400, ErrorCode.INVALID_REQUEST),
exceptions.ServiceUnavailable: (503, ErrorCode.UNAVAILABLE),
# доменная ошибка без своей строки — некорректный запрос
exceptions.DomainError: (400, ErrorCode.INVALID_REQUEST),
}
# вызов в WWW-Authenticate у 401: какой схемой повторить запрос
CHALLENGES: dict[type[exceptions.DomainError], str] = {
exceptions.InvalidCredentials: (
f'Basic realm="{AUTH_REALM}", charset="UTF-8"'
),
exceptions.Unauthenticated: f'Bearer realm="{AUTH_REALM}"',
}
HTTP_ERRORS: dict[int, tuple[ErrorCode, str]] = {
404: (ErrorCode.NOT_FOUND, "Not found"),
405: (ErrorCode.INVALID_REQUEST, "Method not allowed"),
}
def _request_id(request: Request) -> str:
# ставит request-id middleware; запасной id — на случай ошибки до него
return getattr(request.state, "request_id", None) or uuid4().hex
def error_response(
*,
request_id: str,
status_code: int,
code: ErrorCode,
message: str,
headers: dict[str, str] | None = None,
) -> JSONResponse:
body = Error(
error=ErrorBody(code=code, message=message, request_id=request_id),
)
return JSONResponse(
status_code=status_code,
content=body.model_dump(mode="json"),
headers=headers,
)
async def handle_domain_error(
request: Request,
exc: exceptions.DomainError,
) -> JSONResponse:
status_code, code = next(
DOMAIN_ERRORS[cls] for cls in type(exc).__mro__ if cls in DOMAIN_ERRORS
)
challenge = CHALLENGES.get(type(exc))
return error_response(
request_id=_request_id(request),
status_code=status_code,
code=code,
message=str(exc),
headers={"WWW-Authenticate": challenge} if challenge else None,
)
async def handle_validation_error(
request: Request,
exc: RequestValidationError,
) -> JSONResponse:
# первая ошибка: где и что не так, без входного значения
first = exc.errors()[0] if exc.errors() else {}
location = ".".join(str(part) for part in first.get("loc", ()))
detail = first.get("msg", "Invalid request")
return error_response(
request_id=_request_id(request),
status_code=400,
code=ErrorCode.INVALID_REQUEST,
message=f"{location}: {detail}" if location else detail,
)
async def handle_http_error(
request: Request,
exc: StarletteHTTPException,
) -> JSONResponse:
code, message = HTTP_ERRORS.get(
exc.status_code,
(ErrorCode.INVALID_REQUEST, "Invalid request"),
)
return error_response(
request_id=_request_id(request),
status_code=exc.status_code,
code=code,
message=message,
headers=exc.headers,
)
async def handle_unexpected_error(
request: Request,
exc: Exception, # noqa: ARG001
) -> JSONResponse:
# ответ формирует ServerErrorMiddleware снаружи request-id middleware,
# поэтому заголовок ставим сами
request_id = _request_id(request)
return error_response(
request_id=request_id,
status_code=500,
code=ErrorCode.INTERNAL_ERROR,
message="Internal server error",
headers={REQUEST_ID_HEADER: request_id},
)
def register(app: FastAPI) -> None:
app.add_exception_handler(exceptions.DomainError, handle_domain_error)
app.add_exception_handler(RequestValidationError, handle_validation_error)
app.add_exception_handler(StarletteHTTPException, handle_http_error)
app.add_exception_handler(Exception, handle_unexpected_error)