Source code for s365b.api.deps

"""Shared FastAPI dependencies: services, the signed-in user, roles and CSRF."""

from __future__ import annotations

from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Annotated

from fastapi import Depends, HTTPException, Request, status

from s365b.auth.sessions import COOKIE_NAME, load_session
from s365b.core.services import Services
from s365b.db.models import AuthSource, UserRole

[docs] SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
[docs] CSRF_HEADER = "X-CSRF-Token"
[docs] def get_services(request: Request) -> Services: """Return the services created at application startup. Args: request: Current request. Returns: The services. """ services: Services = request.app.state.services return services
[docs] ServicesDep = Annotated[Services, Depends(get_services)]
[docs] def client_ip(request: Request) -> str | None: """Return the client's IP address (Caddy's ``X-Forwarded-For`` is honoured by uvicorn). Args: request: Current request. Returns: The address, if known. """ return request.client.host if request.client else None
@dataclass(frozen=True, slots=True)
[docs] class Principal: """The signed-in user for the current request. Attributes: user_id: User ID. username: Username (UPN for Entra users). display_name: Display name. role: Role for this session. method: How they signed in. csrf_token: Token state-changing requests must send back. """
[docs] user_id: int
[docs] username: str
[docs] display_name: str
[docs] role: UserRole
[docs] method: AuthSource
[docs] csrf_token: str
@property
[docs] def is_break_glass(self) -> bool: """Return whether this is a local break-glass session.""" return self.method is AuthSource.LOCAL
[docs] async def current_principal(request: Request, services: ServicesDep) -> Principal: """Return the signed-in user, enforcing CSRF on state-changing requests. Args: request: Current request. services: Process services. Returns: The principal. Raises: HTTPException: 401 if not signed in, 403 if the CSRF token is missing or wrong. """ token = request.cookies.get(COOKIE_NAME) if not token: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "not signed in") async with services.db.session() as s: row = await load_session(s, token) if row is None: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired; sign in again") principal = Principal( row.user_fk, row.user.username, row.user.display_name, row.role, row.auth_method, row.csrf_token, ) if ( request.method not in SAFE_METHODS and request.headers.get(CSRF_HEADER) != principal.csrf_token ): raise HTTPException(status.HTTP_403_FORBIDDEN, "missing or invalid CSRF token") return principal
[docs] PrincipalDep = Annotated[Principal, Depends(current_principal)]
[docs] def require_roles(*roles: UserRole) -> Callable[[Principal], Awaitable[Principal]]: """Build a dependency that allows only the given roles (admins always pass). Args: *roles: Roles allowed in addition to admin. Returns: A FastAPI dependency returning the principal. """ allowed = {UserRole.ADMIN, *roles} async def dependency(principal: PrincipalDep) -> Principal: """Check the principal's role.""" if principal.role not in allowed: raise HTTPException(status.HTTP_403_FORBIDDEN, "your role does not allow this") return principal return dependency
[docs] AdminDep = Annotated[Principal, Depends(require_roles())]
[docs] ViewerDep = Annotated[ Principal, Depends(require_roles(UserRole.OPERATOR, UserRole.RESTORE_OPERATOR, UserRole.AUDITOR)), ]
[docs] OperatorDep = Annotated[Principal, Depends(require_roles(UserRole.OPERATOR))]
[docs] RestoreDep = Annotated[ Principal, Depends(require_roles(UserRole.OPERATOR, UserRole.RESTORE_OPERATOR)) ]