""" Dependency injection helpers for FastAPI routes. """ from fastapi import Depends, HTTPException, status, Request from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from typing import Optional from core.database import get_db as _get_db from core.config import get_settings from models.user import User settings = get_settings() # Standard OAuth2 scheme for Swagger UI oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login") async def get_db(): """Proxy to the unified get_db in core.database.""" async for session in _get_db(): yield session async def get_arq_pool(request: Request): """ Returns the ARQ Redis pool from app state. This avoids expensive re-connections on every request. """ if hasattr(request.app.state, "arq_pool"): return request.app.state.arq_pool # Fallback for testing or misconfigured lifespan # Fallback for testing or misconfigured lifespan from arq import create_pool from core.config import get_redis_settings pool = await create_pool(get_redis_settings()) request.app.state.arq_pool = pool return pool async def get_current_user( request: Request, db: AsyncSession = Depends(get_db), token: str = Depends(oauth2_scheme) ) -> User: """ Decodes the JWT access token and fetches the current user from the database. Raises HTTPException if token is invalid or user doesn't exist. """ portal = request.headers.get("X-Nexus-Portal") return await get_current_user_from_token(token, db, portal) async def get_current_user_flexible( request: Request, db: AsyncSession = Depends(get_db) ) -> User: """ Enhanced version of get_current_user that checks both: 1. Authorization Header (Bearer Token) 2. 'token' Query Parameter (for direct browser downloads) """ token = None # 1. Check Header auth_header = request.headers.get("Authorization") if auth_header and auth_header.startswith("Bearer "): token = auth_header.split(" ")[1] # 2. Check Query Param if header missing if not token: token = request.query_params.get("token") if not token: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) portal = request.headers.get("X-Nexus-Portal") return await get_current_user_from_token(token, db, portal) async def get_current_user_from_token(token: str, db: AsyncSession, portal: Optional[str] = None) -> User: """Refactored logic from get_current_user for reuse with portal validation.""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) user_id: str = payload.get("sub") token_type: str = payload.get("type") jti: str = payload.get("jti") active_ws_id: str = payload.get("workspace_id") active_role: str = payload.get("role") if user_id is None or token_type != "access": raise credentials_exception if jti: from core.token_blocklist import is_token_blocked if await is_token_blocked(jti): raise credentials_exception except JWTError: raise credentials_exception stmt = select(User).where(User.id == user_id, User.deleted_at.is_(None)) result = await db.execute(stmt) user = result.scalar_one_or_none() if user is None or not user.is_active: raise credentials_exception from uuid import UUID # Safely parse active_ws_id, handling "null"/"undefined" strings from frontend ws_id = None if active_ws_id and active_ws_id not in ("null", "undefined"): try: ws_id = UUID(active_ws_id) except (ValueError, TypeError): pass setattr(user, "workspace_id", ws_id) setattr(user, "role", active_role or user.role) # Preserve injected role if available # --- STRICT PORTAL ISOLATION (Backend Guard) --- # We use inclusive checks to prevent cross-persona access while supporting legacy roles role_str = str(user.role).lower() if user.role else "" if portal == "internal": # Block ONLY known customer personas from the operations console if role_str.startswith("customer"): import logging logging.getLogger("security").warning(f"BLOCKED: Customer {user.email} (Role: {role_str}) attempted internal portal API access") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access Denied: Customers cannot access internal operations endpoints." ) elif portal == "customer": # Block known staff who are NOT super-admins from the customer ecosystem if role_str.startswith("3sc_") and role_str != "3sc_admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access Denied: Staff must use the Operations Console." ) return user async def get_current_staff_user( current_user: User = Depends(get_current_user) ) -> User: """ Enforces that the current user must have a staff/internal role. """ role_str = str(current_user.role).lower() if role_str.startswith("customer"): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access Denied: 3SC Internal Staff Only — Customers are restricted from system diagnostics." ) return current_user async def get_current_refresh_user( db: AsyncSession = Depends(get_db), token: str = Depends(oauth2_scheme) ) -> User: """ Decodes the JWT refresh token and fetches the current user. Resolves workspace_id and role from the UserWorkspace junction table so that refreshed access tokens contain valid context. """ credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate refresh token", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) user_id: str = payload.get("sub") token_type: str = payload.get("type") jti: str = payload.get("jti") if user_id is None or token_type != "refresh": raise credentials_exception # Check if refresh token has been revoked if jti: from core.token_blocklist import is_token_blocked if await is_token_blocked(jti): raise credentials_exception except JWTError: raise credentials_exception stmt = select(User).where( User.id == user_id, User.deleted_at.is_(None) ) result = await db.execute(stmt) user = result.scalar_one_or_none() if not user: raise credentials_exception # Resolve workspace context from the junction table (primary workspace first) from models.user_workspace import UserWorkspace ws_stmt = select(UserWorkspace).where( UserWorkspace.user_id == user.id ).order_by(UserWorkspace.is_primary.desc()) ws_result = await db.execute(ws_stmt) active_link = ws_result.scalars().first() if active_link: setattr(user, "workspace_id", active_link.workspace_id) setattr(user, "role", user.global_role or active_link.role) else: setattr(user, "workspace_id", None) setattr(user, "role", None) return user