""" Clerk authentication integration for the MCP AI Data Scientist system. Handles JWT validation, user context extraction, and permission checking. """ import jwt import httpx import asyncio from typing import Optional, Dict, Any, List from datetime import datetime, timezone from pydantic import BaseModel from fastapi import HTTPException, status from shared.config import settings class UserContext(BaseModel): """User context extracted from Clerk JWT token.""" user_id: str email: Optional[str] = None first_name: Optional[str] = None last_name: Optional[str] = None permissions: List[str] = [] is_authenticated: bool = True clerk_user_id: str class ClerkJWTValidator: """Handles Clerk JWT token validation and user context extraction.""" def __init__(self): self.clerk_secret_key = settings.clerk_secret_key self.clerk_publishable_key = settings.clerk_publishable_key self._jwks_cache: Optional[Dict[str, Any]] = None self._jwks_cache_expiry: Optional[datetime] = None async def get_jwks(self) -> Dict[str, Any]: """Fetch JWKS (JSON Web Key Set) from Clerk.""" # Cache JWKS for 1 hour if (self._jwks_cache and self._jwks_cache_expiry and datetime.now(timezone.utc) < self._jwks_cache_expiry): return self._jwks_cache # Extract instance ID from publishable key if not self.clerk_publishable_key.startswith('pk_'): raise ValueError("Invalid Clerk publishable key format") # Clerk JWKS endpoint format jwks_url = f"https://clerk.{self.clerk_publishable_key.split('_')[1]}.lcl.dev/.well-known/jwks.json" try: async with httpx.AsyncClient() as client: response = await client.get(jwks_url, timeout=10.0) response.raise_for_status() self._jwks_cache = response.json() # Cache for 1 hour self._jwks_cache_expiry = datetime.now(timezone.utc).replace( hour=datetime.now(timezone.utc).hour + 1 ) return self._jwks_cache except httpx.RequestError as e: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"Failed to fetch JWKS from Clerk: {str(e)}" ) except httpx.HTTPStatusError as e: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"Clerk JWKS endpoint returned error: {e.response.status_code}" ) def _get_signing_key(self, token_header: Dict[str, Any], jwks: Dict[str, Any]) -> str: """Extract the signing key from JWKS based on token header.""" kid = token_header.get('kid') if not kid: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token header missing 'kid' field" ) for key in jwks.get('keys', []): if key.get('kid') == kid: # Convert JWK to PEM format for PyJWT from jwt.algorithms import RSAAlgorithm return RSAAlgorithm.from_jwk(key) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Unable to find matching key in JWKS" ) async def validate_token(self, token: str) -> UserContext: """Validate Clerk JWT token and extract user context.""" if not token: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="No authentication token provided" ) try: # Decode token header without verification to get kid unverified_header = jwt.get_unverified_header(token) # Get JWKS and find matching key jwks = await self.get_jwks() signing_key = self._get_signing_key(unverified_header, jwks) # Verify and decode the token payload = jwt.decode( token, signing_key, algorithms=['RS256'], options={"verify_exp": True, "verify_aud": False} ) # Extract user information from payload user_id = payload.get('sub') if not user_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing user ID" ) # Extract additional user information email = payload.get('email') first_name = payload.get('given_name') last_name = payload.get('family_name') # Extract permissions (if any) permissions = payload.get('permissions', []) if isinstance(permissions, str): permissions = [permissions] return UserContext( user_id=user_id, clerk_user_id=user_id, email=email, first_name=first_name, last_name=last_name, permissions=permissions, is_authenticated=True ) except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has expired" ) except jwt.InvalidTokenError as e: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid token: {str(e)}" ) except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Token validation failed: {str(e)}" ) class PermissionChecker: """Handles permission checking for authenticated users.""" # Define available permissions PERMISSIONS = { 'read_data': 'Can read datasets and analysis results', 'write_data': 'Can upload datasets and create analyses', 'delete_data': 'Can delete datasets and analyses', 'admin': 'Full administrative access' } @staticmethod def check_permission(user_context: UserContext, required_permission: str) -> bool: """Check if user has the required permission.""" if not user_context.is_authenticated: return False # Admin users have all permissions if 'admin' in user_context.permissions: return True # Check specific permission return required_permission in user_context.permissions @staticmethod def require_permission(user_context: UserContext, required_permission: str): """Raise exception if user doesn't have required permission.""" if not PermissionChecker.check_permission(user_context, required_permission): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Insufficient permissions. Required: {required_permission}" ) @staticmethod def check_data_access(user_context: UserContext, resource_user_id: str) -> bool: """Check if user can access data belonging to another user.""" # Users can always access their own data if user_context.user_id == resource_user_id: return True # Admin users can access all data if 'admin' in user_context.permissions: return True return False @staticmethod def require_data_access(user_context: UserContext, resource_user_id: str): """Raise exception if user cannot access the specified data.""" if not PermissionChecker.check_data_access(user_context, resource_user_id): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access denied: You can only access your own data" ) # Global instances jwt_validator = ClerkJWTValidator() permission_checker = PermissionChecker()