feat: add replicated messenger and reproducible lab3 stand
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
"""Идентификация лабы 2: Bearer-сессия — до роутинга и разбора тела.
|
||||
|
||||
Работает через стандартный `AuthenticationMiddleware` Starlette.
|
||||
`BearerBackend` вызывается на каждый запрос:
|
||||
|
||||
- публичный путь (health, docs, `POST /api/v1/users`,
|
||||
`POST /api/v1/auth/sessions`) — `None`, запрос идёт дальше без
|
||||
пользователя. Вход по Basic разбирает сама ручка входа (`deps.py`);
|
||||
- защищённый путь — сессия по токену из `Authorization: Bearer <token>`
|
||||
или отказ, и middleware сразу отвечает через `on_auth_error`.
|
||||
|
||||
Поэтому 401 приходит раньше любой проверки тела, пути и query: «сначала
|
||||
аутентификация» из contracts/README.md выполняется даже для битого JSON.
|
||||
Ручки берут готовую сессию из `request.user` (`deps.current_identity`).
|
||||
|
||||
`X-User-Id` больше не читается нигде: он не даёт доступа и не меняет
|
||||
владельца сессии. Basic на бизнес-ручке — чужая схема, тот же 401 с
|
||||
вызовом Bearer. Недоступность PostgreSQL — 503, а не 401 и не анонимный
|
||||
доступ.
|
||||
"""
|
||||
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security.utils import get_authorization_scheme_param
|
||||
from starlette.authentication import (
|
||||
AuthCredentials,
|
||||
AuthenticationBackend,
|
||||
AuthenticationError,
|
||||
)
|
||||
from starlette.requests import HTTPConnection
|
||||
|
||||
from src.api.handlers import app_error_response
|
||||
from src.constants import API_PREFIX, AUTHORIZATION_HEADER, SESSIONS_PATH
|
||||
from src.domain import Identity
|
||||
from src.errors import AppError, Unauthorized
|
||||
from src.services import SessionService
|
||||
|
||||
# публичные пути внутри API_PREFIX: регистрация и вход по Basic
|
||||
PUBLIC_ENDPOINTS = frozenset(
|
||||
{
|
||||
("POST", f"{API_PREFIX}/users"),
|
||||
("POST", SESSIONS_PATH),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def requires_identity(method: str, path: str) -> bool:
|
||||
return path.startswith(f"{API_PREFIX}/") and (method, path) not in PUBLIC_ENDPOINTS
|
||||
|
||||
|
||||
def bearer_token(header: str | None) -> str | None:
|
||||
"""Токен из `Authorization: Bearer <token>`; другая схема — `None`."""
|
||||
scheme, token = get_authorization_scheme_param(header)
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
return None
|
||||
return token
|
||||
|
||||
|
||||
class AuthFailure(AuthenticationError):
|
||||
"""Отказ бэкенда с доменной ошибкой: 401 или 503 (БД недоступна)."""
|
||||
|
||||
def __init__(self, error: AppError) -> None:
|
||||
super().__init__(str(error))
|
||||
self.error = error
|
||||
|
||||
|
||||
class BearerBackend(AuthenticationBackend):
|
||||
async def authenticate(
|
||||
self,
|
||||
conn: HTTPConnection,
|
||||
) -> tuple[AuthCredentials, Identity] | None:
|
||||
if not requires_identity(conn.scope.get("method", ""), conn.scope["path"]):
|
||||
return None
|
||||
state = conn.app.state
|
||||
sessions = SessionService(
|
||||
state.storage,
|
||||
state.passwords,
|
||||
ttl=state.settings.session_ttl,
|
||||
)
|
||||
token = bearer_token(conn.headers.get(AUTHORIZATION_HEADER))
|
||||
try:
|
||||
identity = await sessions.authenticate(token=token)
|
||||
except AppError as exc:
|
||||
raise AuthFailure(exc) from exc
|
||||
return AuthCredentials(["authenticated"]), identity
|
||||
|
||||
|
||||
def on_auth_error(conn: HTTPConnection, exc: AuthenticationError) -> JSONResponse:
|
||||
error = exc.error if isinstance(exc, AuthFailure) else Unauthorized()
|
||||
return app_error_response(conn, error)
|
||||
Reference in New Issue
Block a user