"""A01-A03: opaque sessions, bounded login admission, and synchronizer CSRF.""" from collections import deque import time from threading import Lock, BoundedSemaphore from typing import Annotated from fastapi import APIRouter, Depends, Request, Response from pydantic import BaseModel, ConfigDict, Field from app.api.v1.dependencies import get_auth_service, get_current_user, get_voice_settings, require_origin, error from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, generate_csrf_token, verify_csrf_token from app.modules.voice.configuration import VoiceSettings router = APIRouter(prefix='/auth', tags=['Authentication']) identity_router = APIRouter(tags=['Authentication']) _ATTEMPTS = deque(maxlen=120) _LOCK = Lock() _LOGINS = BoundedSemaphore(2) class LoginRequest(BaseModel): model_config = ConfigDict(extra='forbid', strict=True) username: str = Field(min_length=1, max_length=120) password: str = Field(min_length=1, max_length=1024) class UserDTO(BaseModel): id: str username: str role: str organization_id: str class AuthResponse(BaseModel): user: UserDTO csrf_token: str expires_at: str @router.post( '/login', response_model=AuthResponse, summary='User Login', description='Authenticate with username and password. On success, issues a secure HTTP-only rag_session cookie and returns user context with CSRF token.', ) def login(req: LoginRequest, request: Request, response: Response, auth_service: Annotated[AuthService, Depends(get_auth_service)], config: Annotated[VoiceSettings, Depends(get_voice_settings)]): require_origin(request, config) stamp = time.monotonic() with _LOCK: while _ATTEMPTS and stamp - _ATTEMPTS[0] >= 60: _ATTEMPTS.popleft() if len(_ATTEMPTS) >= config.login_attempts_per_minute: raise error('SERVICE_BUSY') _ATTEMPTS.append(stamp) if not _LOGINS.acquire(blocking=False): raise error('SERVICE_BUSY') try: user, token, csrf, expiry = auth_service.login(req.username, req.password) except ValueError as exc: raise error(str(exc)) from None finally: _LOGINS.release() response.set_cookie(COOKIE_NAME, token, httponly=True, secure=config.cookie_secure, samesite='lax', expires=expiry, path='/') return AuthResponse(user=UserDTO(**user), csrf_token=csrf, expires_at=expiry.isoformat()) @router.post( '/logout', status_code=204, summary='User Logout', description='Revoke the active authentication session and clear the session cookie.', ) def logout(request: Request, response: Response, auth_service: Annotated[AuthService, Depends(get_auth_service)], config: Annotated[VoiceSettings, Depends(get_voice_settings)]): require_origin(request, config) token = request.cookies.get(COOKIE_NAME) try: auth_service.get_current_user(token) except ValueError: pass else: if not verify_csrf_token(token, request.headers.get('x-csrf-token')): raise error('CSRF_TOKEN_INVALID') auth_service.logout(token) response.delete_cookie(COOKIE_NAME, path='/', secure=config.cookie_secure, httponly=True, samesite='lax') response.status_code = 204 return response @identity_router.get( '/me', response_model=AuthResponse, summary='Get Current Identity', description='Retrieve identity and session expiry for the currently authenticated user.', ) @router.get('/me', response_model=AuthResponse, include_in_schema=False) def get_me(request: Request, user: Annotated[UserContext, Depends(get_current_user)]): return AuthResponse(user=UserDTO(id=str(user.id), organization_id=str(user.organization_id), username=user.username, role=user.role), csrf_token=generate_csrf_token(request.cookies.get(COOKIE_NAME)), expires_at=user.expires_at.isoformat())