Spaces:
Paused
Paused
File size: 8,564 Bytes
56c063a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | """
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() |