|
| 1 | +"""Per-request authentication for the streamable HTTP transport.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import os |
| 5 | +from typing import Optional, Protocol, runtime_checkable |
| 6 | + |
| 7 | +from mcp.server.fastmcp import Context, FastMCP |
| 8 | +from starlette.requests import Request |
| 9 | +from starlette.responses import JSONResponse |
| 10 | +from starlette.types import ASGIApp, Receive, Scope, Send |
| 11 | + |
| 12 | +from config.perfecto import PERFECTO_CLOUD_NAME_ENV_NAME |
| 13 | +from config.token import PerfectoToken, PerfectoTokenError |
| 14 | + |
| 15 | +PERFECTO_TOKEN_STATE_ATTR = "token" |
| 16 | +PERFECTO_USER_CONFIG_STATE_ATTR = "user_config" |
| 17 | +PERFECTO_CLOUD_NAME_HEADER = "perfecto-cloud-name" |
| 18 | + |
| 19 | +# Unauthenticated probe paths for orchestrators / load balancers. |
| 20 | +HEALTH_PATHS = frozenset({"/health", "/healthz"}) |
| 21 | + |
| 22 | + |
| 23 | +class AuthError(Exception): |
| 24 | + """Raised when Authorization cannot be parsed into credentials.""" |
| 25 | + |
| 26 | + |
| 27 | +@runtime_checkable |
| 28 | +class AuthPort(Protocol): |
| 29 | + """Resolves the Perfecto security token for the current tool invocation.""" |
| 30 | + |
| 31 | + def get_token(self, ctx: Context) -> Optional[PerfectoToken]: |
| 32 | + ... |
| 33 | + |
| 34 | + |
| 35 | +class StdioAuthProvider: |
| 36 | + """Process-lifetime token from env / token file / Docker secrets.""" |
| 37 | + |
| 38 | + def __init__(self, token: Optional[PerfectoToken]): |
| 39 | + self._token = token |
| 40 | + |
| 41 | + def get_token(self, ctx: Context) -> Optional[PerfectoToken]: |
| 42 | + return self._token |
| 43 | + |
| 44 | + |
| 45 | +class HttpAuthProvider: |
| 46 | + """Per-request token attached by Bearer auth middleware to request.state.""" |
| 47 | + |
| 48 | + def get_token(self, ctx: Context) -> Optional[PerfectoToken]: |
| 49 | + request = ctx.request_context.request |
| 50 | + if request is None: |
| 51 | + return None |
| 52 | + return getattr(request.state, PERFECTO_TOKEN_STATE_ATTR, None) |
| 53 | + |
| 54 | + |
| 55 | +def resolve_cloud_name(header_value: Optional[str] = None) -> Optional[str]: |
| 56 | + """ |
| 57 | + Resolve the Perfecto cloud for a request. |
| 58 | +
|
| 59 | + Precedence: ``Perfecto-Cloud-Name`` header > PERFECTO_CLOUD_NAME env var. |
| 60 | + """ |
| 61 | + candidate = (header_value or "").strip() |
| 62 | + if candidate: |
| 63 | + return candidate |
| 64 | + return os.getenv(PERFECTO_CLOUD_NAME_ENV_NAME, "").strip() or None |
| 65 | + |
| 66 | + |
| 67 | +def parse_authorization_header(value: Optional[str], cloud_name: Optional[str] = None) -> PerfectoToken: |
| 68 | + """ |
| 69 | + Parse ``Authorization: Bearer <security-token>`` into a PerfectoToken. |
| 70 | +
|
| 71 | + The cloud name is not carried in the credentials; it comes from the |
| 72 | + ``Perfecto-Cloud-Name`` header or PERFECTO_CLOUD_NAME. Does not call the |
| 73 | + Perfecto API — parse only. |
| 74 | + """ |
| 75 | + if not value or not value.strip(): |
| 76 | + raise AuthError("Missing Authorization header") |
| 77 | + |
| 78 | + scheme, _, credentials = value.strip().partition(" ") |
| 79 | + if scheme.lower() != "bearer" or not credentials.strip(): |
| 80 | + raise AuthError("Authorization header must use Bearer scheme") |
| 81 | + |
| 82 | + try: |
| 83 | + return PerfectoToken.from_bearer_credentials(credentials.strip(), cloud_name) |
| 84 | + except PerfectoTokenError as exc: |
| 85 | + raise AuthError("Unparseable Bearer credentials") from exc |
| 86 | + |
| 87 | + |
| 88 | +class BearerAuthMiddleware: |
| 89 | + """ |
| 90 | + HTTP gate: require a parseable Bearer token on every request. |
| 91 | +
|
| 92 | + Attaches PerfectoToken to ``request.state``; does not validate against Perfecto. |
| 93 | + A missing cloud name is not rejected here — tools surface it as a |
| 94 | + configuration error, the same way stdio does. |
| 95 | + """ |
| 96 | + |
| 97 | + def __init__(self, app: ASGIApp): |
| 98 | + self.app = app |
| 99 | + |
| 100 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 101 | + if scope["type"] != "http": |
| 102 | + await self.app(scope, receive, send) |
| 103 | + return |
| 104 | + |
| 105 | + if scope.get("method") == "OPTIONS": |
| 106 | + await self.app(scope, receive, send) |
| 107 | + return |
| 108 | + |
| 109 | + path = scope.get("path", "") or "" |
| 110 | + if path in HEALTH_PATHS: |
| 111 | + await self.app(scope, receive, send) |
| 112 | + return |
| 113 | + |
| 114 | + request = Request(scope, receive) |
| 115 | + cloud_name = resolve_cloud_name(request.headers.get(PERFECTO_CLOUD_NAME_HEADER)) |
| 116 | + try: |
| 117 | + token = parse_authorization_header( |
| 118 | + request.headers.get("authorization"), |
| 119 | + cloud_name, |
| 120 | + ) |
| 121 | + except AuthError: |
| 122 | + response = JSONResponse( |
| 123 | + {"error": "Unauthorized"}, |
| 124 | + status_code=401, |
| 125 | + headers={"WWW-Authenticate": "Bearer"}, |
| 126 | + ) |
| 127 | + await response(scope, receive, send) |
| 128 | + return |
| 129 | + |
| 130 | + setattr(request.state, PERFECTO_TOKEN_STATE_ATTR, token) |
| 131 | + setattr( |
| 132 | + request.state, |
| 133 | + PERFECTO_USER_CONFIG_STATE_ATTR, |
| 134 | + {"token": token, "cloud_name": token.cloud_name}, |
| 135 | + ) |
| 136 | + await self.app(scope, receive, send) |
| 137 | + |
| 138 | + |
| 139 | +def register_health_routes(mcp: FastMCP) -> None: |
| 140 | + """Register unauthenticated health probes on the FastMCP ASGI app.""" |
| 141 | + |
| 142 | + @mcp.custom_route("/health", methods=["GET"]) |
| 143 | + async def health(_request: Request) -> JSONResponse: |
| 144 | + return JSONResponse({"status": "ok"}) |
| 145 | + |
| 146 | + @mcp.custom_route("/healthz", methods=["GET"]) |
| 147 | + async def healthz(_request: Request) -> JSONResponse: |
| 148 | + return JSONResponse({"status": "ok"}) |
| 149 | + |
| 150 | + |
| 151 | +def run_streamable_http(mcp: FastMCP) -> None: |
| 152 | + """Serve FastMCP over streamable HTTP with Bearer auth middleware.""" |
| 153 | + import anyio |
| 154 | + import uvicorn |
| 155 | + |
| 156 | + register_health_routes(mcp) |
| 157 | + |
| 158 | + async def _serve() -> None: |
| 159 | + app = BearerAuthMiddleware(mcp.streamable_http_app()) |
| 160 | + config = uvicorn.Config( |
| 161 | + app, |
| 162 | + host=mcp.settings.host, |
| 163 | + port=mcp.settings.port, |
| 164 | + log_level=mcp.settings.log_level.lower(), |
| 165 | + ) |
| 166 | + await uvicorn.Server(config).serve() |
| 167 | + |
| 168 | + anyio.run(_serve) |
0 commit comments