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>
This commit is contained in:
2026-10-01 18:50:42 +03:00
co-authored by Claude Opus 5.5
parent ee2643d21e
commit ae4154eaf5
68 changed files with 2946 additions and 314 deletions
+106 -23
View File
@@ -1,17 +1,26 @@
"""Зависимости ручек: сессия БД, сервисы, текущий пользователь, страница."""
"""Зависимости ручек: сессия БД, сервисы, вход и текущая сессия, страница."""
import asyncio
import base64
import binascii
import re
from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, Query, Security
from fastapi.security import APIKeyHeader
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.security.http import HTTPBase
from sqlalchemy.ext.asyncio import AsyncSession
from src.config import settings
from src.core import exceptions
from src.core.services import ChatService, MessageService, UserService
from src.core.services import (
ChatService,
MessageService,
SessionService,
UserService,
)
from src.infra.db import is_db_unavailable, ping
from src.infra.db.session import engine, session_factory
from src.infra.logger import AbstractLogger, current_user_id, get_logger
@@ -20,8 +29,10 @@ from src.utils.constants import (
PAGE_LIMIT_DEFAULT,
PAGE_LIMIT_MAX,
PAGE_LIMIT_MIN,
PASSWORD_MAX_LENGTH,
PASSWORD_MIN_LENGTH,
READINESS_DB_TIMEOUT_SECONDS,
USER_ID_HEADER,
USERNAME_PATTERN,
)
logger: AbstractLogger = get_logger().bind(module="api_dependencies")
@@ -81,36 +92,108 @@ async def get_message_service(db_session: DbSessionDep) -> MessageService:
return MessageService(db_session=db_session)
async def get_session_service(db_session: DbSessionDep) -> SessionService:
return SessionService(db_session=db_session)
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
ChatServiceDep = Annotated[ChatService, Depends(get_chat_service)]
MessageServiceDep = Annotated[MessageService, Depends(get_message_service)]
SessionServiceDep = Annotated[SessionService, Depends(get_session_service)]
# схема devUser из contracts/openapi.json: кнопка Authorize в /docs.
# auto_error=False — нет заголовка даёт None, а не ошибку FastAPI: 401 в
# формате контракта бросает сервис. Типизированный `Header()` не подходит:
# он уходит в валидацию и дал бы 400 вместо 401
user_id_scheme = APIKeyHeader(
name=USER_ID_HEADER,
scheme_name="devUser",
description=(
"Только учебная lab1: существующий UUID. Не является аутентификацией."
),
# схемы basicAuth и bearerAuth из contracts/openapi.json: объявлены в
# /openapi.json и дают кнопку Authorize в /docs. auto_error=False — нет
# заголовка или схема чужая даёт None, а 401 в формате контракта бросает
# сервис. HTTPBase отдаёт credentials как есть: HTTPBasic FastAPI
# декодирует ASCII и на пароле не из ASCII сам ответил бы 401
basic_scheme = HTTPBase(
scheme="basic",
scheme_name="basicAuth",
auto_error=False,
)
bearer_scheme = HTTPBearer(
scheme_name="bearerAuth",
bearerFormat="opaque session token",
auto_error=False,
)
async def get_current_user(
raw_user_id: Annotated[str | None, Security(user_id_scheme)],
users: UserServiceDep,
) -> dataclasses.UserFullDTO:
"""Текущий пользователь по X-User-Id; иначе 401.
@dataclass(frozen=True, slots=True)
class BasicCredentials:
username: str
password: str
С лабы 2 здесь будет Bearer-сессия (своя схема безопасности).
def parse_basic(
credentials: HTTPAuthorizationCredentials | None,
) -> BasicCredentials | None:
"""username и пароль из `Authorization: Basic`; None — разбор не удался.
base64 строго, UTF-8, разделитель — первое двоеточие: в username его
не бывает, в пароле оно допустимо. Значения, которые не могут быть
верными (формат username и длина пароля публичны), отсекаются здесь:
до БД и KDF не доходит ни мусор, ни пароль в мегабайт.
"""
user = await users.identify(raw_user_id=raw_user_id)
current_user_id.set(str(user.id))
return user
if credentials is None or credentials.scheme.lower() != "basic":
return None
try:
decoded = base64.b64decode(credentials.credentials, validate=True)
username, separator, password = decoded.decode().partition(":")
except (binascii.Error, UnicodeDecodeError):
return None
if not separator or not re.fullmatch(USERNAME_PATTERN, username):
return None
if not PASSWORD_MIN_LENGTH <= len(password) <= PASSWORD_MAX_LENGTH:
return None
return BasicCredentials(username=username, password=password)
async def get_basic_credentials(
credentials: Annotated[
HTTPAuthorizationCredentials | None,
Security(basic_scheme),
],
) -> BasicCredentials:
"""Учётные данные входа; любой сбой разбора — тот же 401, что и
неверный пароль."""
parsed = parse_basic(credentials)
if parsed is None:
raise exceptions.InvalidCredentials
return parsed
BasicCredentialsDep = Annotated[
BasicCredentials,
Depends(get_basic_credentials),
]
async def get_current_session(
credentials: Annotated[
HTTPAuthorizationCredentials | None,
Security(bearer_scheme),
],
sessions: SessionServiceDep,
) -> dataclasses.CurrentSessionDTO:
"""Действующая сессия по Bearer-токену; иначе 401."""
current = await sessions.authenticate(
token=credentials.credentials if credentials else None,
)
current_user_id.set(str(current.user.id))
return current
CurrentSession = Annotated[
dataclasses.CurrentSessionDTO,
Depends(get_current_session),
]
async def get_current_user(
current: CurrentSession,
) -> dataclasses.UserFullDTO:
return current.user
CurrentUser = Annotated[dataclasses.UserFullDTO, Depends(get_current_user)]
+13 -2
View File
@@ -15,10 +15,11 @@ 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 REQUEST_ID_HEADER
from src.utils.constants import AUTH_REALM, REQUEST_ID_HEADER
DOMAIN_ERRORS: dict[type[exceptions.DomainError], tuple[int, ErrorCode]] = {
exceptions.Unidentified: (401, ErrorCode.UNAUTHORIZED),
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),
@@ -28,6 +29,14 @@ DOMAIN_ERRORS: dict[type[exceptions.DomainError], tuple[int, ErrorCode]] = {
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"),
@@ -64,11 +73,13 @@ async def handle_domain_error(
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,
)
+2
View File
@@ -10,10 +10,12 @@ from src.utils.constants import API_V1_PREFIX
from .chat import router as chat_router
from .message import router as message_router
from .session import router as session_router
from .user import router as user_router
v1_router = APIRouter(prefix=API_V1_PREFIX)
v1_router.include_router(user_router)
v1_router.include_router(session_router)
v1_router.include_router(chat_router)
v1_router.include_router(message_router)
+32
View File
@@ -0,0 +1,32 @@
from fastapi import APIRouter, Response
from src.api.dependencies import (
BasicCredentialsDep,
CurrentSession,
SessionServiceDep,
)
from src.api.schemas import Session
router = APIRouter(prefix="/auth/sessions", tags=["sessions"])
@router.post("", status_code=201, response_model=Session)
async def create_session(
credentials: BasicCredentialsDep,
sessions: SessionServiceDep,
) -> Session:
"""Вход по `Authorization: Basic`; тело запроса не читается."""
issued = await sessions.login(
username=credentials.username,
password=credentials.password,
)
return Session.model_validate(issued)
@router.delete("/current", status_code=204, response_class=Response)
async def revoke_current_session(
current: CurrentSession,
sessions: SessionServiceDep,
) -> Response:
await sessions.revoke(session_id=current.id)
return Response(status_code=204)
+1
View File
@@ -11,6 +11,7 @@ async def register_user(body: CreateUser, users: UserServiceDep) -> User:
user = await users.register(
username=body.username,
display_name=body.display_name,
password=body.password,
)
return User.model_validate(user)
+2
View File
@@ -1,6 +1,7 @@
from .chat import Chat, ChatPage, CreateChat
from .common import Error, ErrorBody, ErrorCode, Health
from .message import CreateMessage, Message, MessagePage
from .session import Session
from .user import CreateUser, User
__all__ = [
@@ -15,5 +16,6 @@ __all__ = [
"Health",
"Message",
"MessagePage",
"Session",
"User",
]
+15
View File
@@ -0,0 +1,15 @@
from typing import Literal
from pydantic import BaseModel, ConfigDict
from src.api.schemas.common import UtcDatetime
from src.api.schemas.user import User
class Session(BaseModel):
model_config = ConfigDict(from_attributes=True)
token: str
token_type: Literal["Bearer"] = "Bearer"
expires_at: UtcDatetime
user: User
+8
View File
@@ -6,6 +6,8 @@ from src.api.schemas.common import NonBlankStr, UtcDatetime
from src.utils.constants import (
DISPLAY_NAME_MAX_LENGTH,
DISPLAY_NAME_MIN_LENGTH,
PASSWORD_MAX_LENGTH,
PASSWORD_MIN_LENGTH,
USERNAME_PATTERN,
)
@@ -18,6 +20,12 @@ class CreateUser(BaseModel):
min_length=DISPLAY_NAME_MIN_LENGTH,
max_length=DISPLAY_NAME_MAX_LENGTH,
)
# длина в code points; значение не обрезается и не нормализуется
password: NonBlankStr = Field(
min_length=PASSWORD_MIN_LENGTH,
max_length=PASSWORD_MAX_LENGTH,
json_schema_extra={"writeOnly": True},
)
class User(BaseModel):