|
9 | 9 | python server.py # stdio (default) |
10 | 10 | python server.py --transport http # streamable HTTP on $PORT |
11 | 11 | """ |
| 12 | +import json |
| 13 | +import logging |
12 | 14 | import sys |
| 15 | +from typing import Optional |
13 | 16 |
|
14 | 17 | from mcp.server.fastmcp import FastMCP |
15 | 18 | import mcp.types as types |
16 | 19 | from starlette.routing import Route |
17 | 20 | from starlette.responses import JSONResponse |
18 | 21 |
|
| 22 | +from api_client import set_request_api_key |
19 | 23 | from config import SERVER_NAME, SERVER_VERSION, TRANSPORT, HOST, PORT, MCP_AUTH_TOKEN |
20 | 24 | from tools import get_tool_schemas |
21 | 25 | from handlers import call_tool |
22 | 26 |
|
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
23 | 29 | mcp = FastMCP( |
24 | 30 | name=SERVER_NAME, |
25 | 31 | instructions=( |
@@ -62,27 +68,92 @@ async def _health(request): |
62 | 68 | return JSONResponse({"status": "ok", "server": SERVER_NAME, "version": SERVER_VERSION}) |
63 | 69 |
|
64 | 70 |
|
65 | | -def _get_http_app(): |
66 | | - """Build the Starlette app with health check + MCP endpoint.""" |
67 | | - from starlette.middleware.base import BaseHTTPMiddleware |
68 | | - from starlette.requests import Request |
| 71 | +def _extract_bearer(scope) -> Optional[str]: |
| 72 | + """Pull the Bearer token from an ASGI scope's headers, or None. |
69 | 73 |
|
70 | | - app = mcp.streamable_http_app() |
71 | | - app.routes.insert(0, Route("/health", _health, methods=["GET"])) |
| 74 | + Requires the space after 'Bearer' -- a missing space is the PR #292 bug, and a |
| 75 | + request carrying it is treated as malformed (rejected), never silently parsed. |
| 76 | + """ |
| 77 | + for name, value in scope.get("headers", []): |
| 78 | + if name == b"authorization": |
| 79 | + raw = value.decode("latin-1") |
| 80 | + if raw.startswith("Bearer "): |
| 81 | + return raw[len("Bearer "):].strip() |
| 82 | + return None |
| 83 | + return None |
| 84 | + |
| 85 | + |
| 86 | +def _key_suffix(token: str) -> str: |
| 87 | + """Last 8 chars for safe log correlation. Never log the full key (bug #7).""" |
| 88 | + return token[-8:] if len(token) >= 8 else "********" |
| 89 | + |
| 90 | + |
| 91 | +async def _send_401(send, detail: str) -> None: |
| 92 | + body = json.dumps({"error": detail}).encode() |
| 93 | + await send({ |
| 94 | + "type": "http.response.start", |
| 95 | + "status": 401, |
| 96 | + "headers": [ |
| 97 | + (b"content-type", b"application/json"), |
| 98 | + (b"www-authenticate", b"Bearer"), |
| 99 | + ], |
| 100 | + }) |
| 101 | + await send({"type": "http.response.body", "body": body}) |
| 102 | + |
| 103 | + |
| 104 | +class MCPAuthMiddleware: |
| 105 | + """Authenticate /mcp with a per-user ci_ key, forwarded to the backend. |
| 106 | +
|
| 107 | + Pure ASGI (not BaseHTTPMiddleware) on purpose: the ContextVar set here must |
| 108 | + propagate to the tool-handler task, and BaseHTTPMiddleware runs the downstream |
| 109 | + app in a separate task that breaks that propagation. |
72 | 110 |
|
73 | | - if MCP_AUTH_TOKEN: |
74 | | - class MCPAuthMiddleware(BaseHTTPMiddleware): |
75 | | - """Require Bearer token on /mcp, leave /health public.""" |
76 | | - async def dispatch(self, request: Request, call_next): |
77 | | - if request.url.path == "/health": |
78 | | - return await call_next(request) |
79 | | - auth = request.headers.get("authorization", "") |
80 | | - if not auth.startswith("Bearer ") or auth[7:] != MCP_AUTH_TOKEN: |
81 | | - return JSONResponse({"error": "Unauthorized"}, status_code=401) |
82 | | - return await call_next(request) |
| 111 | + Fails closed -- a missing or invalid credential is a 401, never a fallback to a |
| 112 | + shared identity for data calls. /health stays public. |
| 113 | + """ |
83 | 114 |
|
84 | | - app.add_middleware(MCPAuthMiddleware) |
| 115 | + def __init__(self, app): |
| 116 | + self.app = app |
85 | 117 |
|
| 118 | + async def __call__(self, scope, receive, send): |
| 119 | + if scope["type"] != "http": |
| 120 | + await self.app(scope, receive, send) |
| 121 | + return |
| 122 | + |
| 123 | + if scope.get("path") == "/health": |
| 124 | + await self.app(scope, receive, send) |
| 125 | + return |
| 126 | + |
| 127 | + token = _extract_bearer(scope) |
| 128 | + if not token: |
| 129 | + logger.warning("mcp auth: missing or malformed Authorization header") |
| 130 | + await _send_401(send, "Missing or malformed Authorization header") |
| 131 | + return |
| 132 | + |
| 133 | + if token.startswith("ci_"): |
| 134 | + # Per-user key: carry the caller's own identity to the backend. |
| 135 | + set_request_api_key(token) |
| 136 | + logger.info("mcp auth: ci_ key accepted (suffix=%s)", _key_suffix(token)) |
| 137 | + await self.app(scope, receive, send) |
| 138 | + return |
| 139 | + |
| 140 | + if MCP_AUTH_TOKEN and token == MCP_AUTH_TOKEN: |
| 141 | + # Admin path: authenticates the endpoint only. No user key is set, so |
| 142 | + # api_client uses the configured key -- the data scope is not widened. |
| 143 | + logger.info("mcp auth: admin token accepted") |
| 144 | + await self.app(scope, receive, send) |
| 145 | + return |
| 146 | + |
| 147 | + logger.warning("mcp auth: invalid token rejected (suffix=%s)", _key_suffix(token)) |
| 148 | + await _send_401(send, "Invalid API key") |
| 149 | + |
| 150 | + |
| 151 | +def _get_http_app(): |
| 152 | + """Build the Starlette app: public /health + auth-required /mcp.""" |
| 153 | + app = mcp.streamable_http_app() |
| 154 | + app.routes.insert(0, Route("/health", _health, methods=["GET"])) |
| 155 | + # Always enforce: remote /mcp requires a per-user ci_ key (or the admin token). |
| 156 | + app.add_middleware(MCPAuthMiddleware) |
86 | 157 | return app |
87 | 158 |
|
88 | 159 |
|
|
0 commit comments