|
| 1 | +"""JumpServer authentication provider for FastMCP. |
| 2 | +
|
| 3 | +Simple bearer token authentication using JumpServer session IDs. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import os |
| 9 | + |
| 10 | +from fastmcp.server.dependencies import get_http_headers |
| 11 | +import httpx |
| 12 | +import dotenv |
| 13 | +from pydantic import AnyHttpUrl |
| 14 | + |
| 15 | +from fastmcp.server.auth import TokenVerifier |
| 16 | +from fastmcp.server.auth.auth import AccessToken |
| 17 | +from fastmcp.utilities.logging import get_logger |
| 18 | +from starlette.responses import JSONResponse |
| 19 | +from starlette.routing import Route |
| 20 | +from starlette.requests import Request |
| 21 | + |
| 22 | +logger = get_logger(__name__) |
| 23 | +dotenv.load_dotenv() |
| 24 | + |
| 25 | + |
| 26 | +class JumpServerAuthProvider(TokenVerifier): |
| 27 | + """Simple JumpServer session token authentication. |
| 28 | + |
| 29 | + Validates bearer tokens in format `jms-<sessionid>` by calling |
| 30 | + JumpServer's profile API with the session cookie. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + *, |
| 36 | + jumpserver_host: str | None = None, |
| 37 | + timeout_seconds: int = 10, |
| 38 | + base_url: AnyHttpUrl | str | None = None, |
| 39 | + ): |
| 40 | + """Initialize JumpServer authentication provider. |
| 41 | +
|
| 42 | + Args: |
| 43 | + jumpserver_host: JumpServer host URL (defaults to JUMPSERVER_HOST env var) |
| 44 | + timeout_seconds: HTTP request timeout (default: 10) |
| 45 | + base_url: Base URL of this server (optional) |
| 46 | + """ |
| 47 | + super().__init__(base_url=base_url) |
| 48 | + |
| 49 | + jumpserver_host_final = jumpserver_host or os.getenv("CORE_HOST") or "http://core:8080" |
| 50 | + logger.info(f"CORE_HOST: {jumpserver_host_final}") |
| 51 | + if jumpserver_host_final: |
| 52 | + jumpserver_host_final = jumpserver_host_final.rstrip("/") |
| 53 | + |
| 54 | + if not jumpserver_host_final: |
| 55 | + raise ValueError( |
| 56 | + "jumpserver_host is required - set via parameter or JUMPSERVER_HOST env var" |
| 57 | + ) |
| 58 | + |
| 59 | + self.jumpserver_host = jumpserver_host_final |
| 60 | + self.timeout_seconds = timeout_seconds |
| 61 | + |
| 62 | + logger.info(f"Initialized JumpServer auth provider for {jumpserver_host_final}") |
| 63 | + |
| 64 | + async def verify_token(self, token: str) -> AccessToken | None: |
| 65 | + """Verify JumpServer session token.""" |
| 66 | + |
| 67 | + headers = get_http_headers() |
| 68 | + headers['Accept'] = 'application/json' |
| 69 | + |
| 70 | + if token and token.startswith('jms'): |
| 71 | + headers.pop('authorization', '') |
| 72 | + |
| 73 | + try: |
| 74 | + # Request user profile with session cookie |
| 75 | + async with httpx.AsyncClient(timeout=self.timeout_seconds) as client: |
| 76 | + response = await client.get( |
| 77 | + f"{self.jumpserver_host}/api/v1/users/profile/", |
| 78 | + headers=headers, |
| 79 | + ) |
| 80 | + if response.status_code != 200: |
| 81 | + logger.debug(f"Profile API failed: {response.status_code}") |
| 82 | + return None |
| 83 | + |
| 84 | + user_data = response.json() |
| 85 | + logger.info(f"Authenticated user: {user_data.get('username', 'unknown')}") |
| 86 | + |
| 87 | + return AccessToken( |
| 88 | + token=token, |
| 89 | + client_id="jumpserver", |
| 90 | + scopes=[], |
| 91 | + expires_at=None, |
| 92 | + claims={ |
| 93 | + "sub": str(user_data.get("id", "unknown")), |
| 94 | + "username": user_data.get("username"), |
| 95 | + "name": user_data.get("name"), |
| 96 | + "email": user_data.get("email"), |
| 97 | + "is_active": user_data.get("is_active"), |
| 98 | + "is_org_admin": user_data.get("is_org_admin", False), |
| 99 | + "is_superuser": user_data.get("is_superuser", False), |
| 100 | + "jumpserver_user_data": user_data, # Contains full user data including roles |
| 101 | + }, |
| 102 | + ) |
| 103 | + |
| 104 | + except Exception as e: |
| 105 | + logger.debug(f"Token verification error: {e}") |
| 106 | + return None |
| 107 | + |
| 108 | + def get_routes(self, mcp_path: str | None = None, **kwargs) -> list[Route]: |
| 109 | + """Handle /register requests (MCP clients may try to register).""" |
| 110 | + async def handle_register(request: Request): |
| 111 | + return JSONResponse( |
| 112 | + status_code=400, |
| 113 | + content={ |
| 114 | + "error": "client_registration_not_supported", |
| 115 | + "error_description": ( |
| 116 | + "This server uses simple bearer token authentication. " |
| 117 | + "No client registration needed. Use: Authorization: Bearer jms-<sessionid>" |
| 118 | + ), |
| 119 | + }, |
| 120 | + ) |
| 121 | + |
| 122 | + return [Route("/mcp/register", handle_register, methods=["POST"])] |
0 commit comments