"""The permission core — two layers. Layer 1 (`require_role`) answers "WHAT may this role do?". Layer 2 (`assert_can_*`) answers "WHOSE data may this specific user touch?". Most RBAC bugs live in the gap between those two questions: "ABM" is the stored role code for an ABM, but "ABM *of this headquarters*" is a scope. Both checks are mandatory on scoped endpoints, and every one has a negative test asserting 403 (X1-X3). """ import uuid from fastapi import Depends, Request from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.auth.security import decode_access_token from app.common.enums import Role, FIELD_ROLES from app.common.exceptions import ForbiddenError, UnauthorizedError from app.database.session import get_db from app.organization.models import AMHeadquarters from app.users.models import User bearer_scheme = HTTPBearer(auto_error=False) async def get_current_user( credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme), db: AsyncSession = Depends(get_db), ) -> User: if credentials is None: raise UnauthorizedError("Missing bearer token") payload = decode_access_token(credentials.credentials) try: user_id = uuid.UUID(payload["sub"]) except (KeyError, ValueError) as exc: raise UnauthorizedError("Malformed token subject") from exc user = await db.get(User, user_id) if user is None: raise UnauthorizedError("User no longer exists") # SEC-5: checked on EVERY request, not only at login. if not user.is_active: raise UnauthorizedError("User account is deactivated") return user def require_role(*allowed: Role): """Layer 1. Usage: `user: User = Depends(require_role(Role.MR))`.""" async def _check(user: User = Depends(get_current_user)) -> User: # Wherever an MR is allowed, an SFE is too. permitted = set(allowed) | ({Role.SFE} if Role.MR in allowed else set()) if user.role not in permitted: raise ForbiddenError( "Role not permitted for this action", {"your_role": user.role.value, "required": [r.value for r in allowed]}, ) return user return _check async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[uuid.UUID]: """Headquarters this Area Business Manager currently manages (`effective_to IS NULL`).""" stmt = select(AMHeadquarters.headquarters_id).where( AMHeadquarters.area_manager_user_id == am_user_id, AMHeadquarters.effective_to.is_(None), ) return set((await db.execute(stmt)).scalars().all()) async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None: """Headquarters the user may see. `None` means "all" (AGM and ADMIN).""" if user.role in (Role.AGM, Role.ADMIN): return None if user.role == Role.ABM: return await active_hq_ids_for_am(db, user.id) if user.role in FIELD_ROLES: return user.covered_headquarter_ids return set() async def assert_can_view_hq(db: AsyncSession, user: User, headquarters_id: uuid.UUID) -> None: allowed = await visible_hq_ids(db, user) if allowed is None or headquarters_id in allowed: return raise ForbiddenError("Headquarters outside your data scope") async def assert_can_view_dcr(db: AsyncSession, user: User, dcr) -> None: """Layer 2 for reports. ADMIN may inspect report content for support and administration, but cannot act on reports because every transition endpoint still requires the ABM role code (ABM). """ if user.role in (Role.AGM, Role.ADMIN): return if user.role in FIELD_ROLES and dcr.mr_user_id == user.id: return if user.role == Role.ABM: if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id): return raise ForbiddenError("Report outside your data scope") def client_ip(request: Request) -> str | None: forwarded = request.headers.get("x-forwarded-for") if forwarded: return forwarded.split(",")[0].strip() return request.client.host if request.client else None