diff --git a/README.md b/README.md index 71300ba..66773c3 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ NPM_PROXY_DEFAULTS='{"certificate_id": 24, "ssl_forced": true}' | `NPM_MCP_PORT` | No | `8000` | MCP server port | | `NPM_MCP_TRANSPORT` | No | `stdio` | Transport mode (`stdio` or `http`) | | `NPM_MCP_ENABLE_DESTRUCTIVE_TOOLS` | No | `false` | Enable write/destructive tools (create, update, delete, enable, disable) | +| `NPM_MCP_AUTH_TOKEN` | No | - | Bearer token required for HTTP transport clients | | `NPM_LOG_DIR` | No | - | Path to mounted NPM log directory (enables `get_proxy_host_logs`) | | `NPM_PROXY_DEFAULTS` | No | `{}` | JSON defaults for `create_proxy_host` | diff --git a/compose.yaml b/compose.yaml index 39ea41b..1e95107 100644 --- a/compose.yaml +++ b/compose.yaml @@ -18,6 +18,8 @@ services: - NPM_MCP_PORT=8000 # Optional: Enable write/destructive operations (default: disabled) # - NPM_MCP_ENABLE_DESTRUCTIVE_TOOLS=true + # Optional: Require bearer token for MCP HTTP clients + # - NPM_MCP_AUTH_TOKEN=your-secret-token-here # Optional: Log access (requires volume mount below) # - NPM_LOG_DIR=/data/npm-logs # volumes: diff --git a/env.example b/env.example index 41c7c73..120f878 100644 --- a/env.example +++ b/env.example @@ -11,6 +11,9 @@ NPM_MCP_TRANSPORT=stdio # stdio or http # Enable destructive/write operations (create, update, delete, enable, disable) # NPM_MCP_ENABLE_DESTRUCTIVE_TOOLS=true +# Optional: Require bearer token for MCP HTTP clients +# NPM_MCP_AUTH_TOKEN=your-secret-token-here + # Log Access (optional) # Mount NPM's /data/logs directory and set this to the mount path. # Enables the get_proxy_host_logs tool for reading nginx access/error logs. diff --git a/src/npm_mcp/auth.py b/src/npm_mcp/auth.py new file mode 100644 index 0000000..4abac2c --- /dev/null +++ b/src/npm_mcp/auth.py @@ -0,0 +1,49 @@ +"""Bearer token authentication middleware for HTTP transport.""" + +import hmac + +from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint +from starlette.requests import Request +from starlette.responses import JSONResponse, Response +from starlette.types import ASGIApp + +_AUTH_HEADERS = {"WWW-Authenticate": "Bearer"} + + +class BearerAuthMiddleware(BaseHTTPMiddleware): + """Reject HTTP requests missing a valid Authorization: Bearer *** header.""" + + def __init__(self, app: ASGIApp, token: str): + super().__init__(app) + self._token = token + + async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: + if request.url.path == "/health": + return await call_next(request) + + auth = request.headers.get("authorization", "") + # RFC 7235 §2.1: auth scheme is case-insensitive + if auth[:7].lower() != "bearer ": + return JSONResponse( + {"error": "Missing bearer token"}, status_code=401, headers=_AUTH_HEADERS + ) + + supplied = auth[7:] + try: + # hmac.compare_digest raises TypeError if either operand is non-ASCII; + # encoding to bytes prevents this crash and is side-channel safe. + supplied_bytes = supplied.encode("utf-8", "surrogateescape") + token_bytes = self._token.encode("utf-8", "surrogateescape") + is_valid = hmac.compare_digest(supplied_bytes, token_bytes) + except (TypeError, UnicodeEncodeError): + is_valid = False + + if not is_valid: + # RFC 6750 §3: invalid token should yield 401 with error="invalid_token" + return JSONResponse( + {"error": "Invalid bearer token"}, + status_code=401, + headers={"WWW-Authenticate": 'Bearer error="invalid_token"'}, + ) + + return await call_next(request) diff --git a/src/npm_mcp/config.py b/src/npm_mcp/config.py index b0d5f83..1e3dc2e 100644 --- a/src/npm_mcp/config.py +++ b/src/npm_mcp/config.py @@ -45,6 +45,9 @@ class Settings(BaseSettings): # Runtime guard for destructive/write operations mcp_enable_destructive_tools: bool = False + # Optional bearer token for authenticating MCP clients over HTTP + mcp_auth_token: str = "" + # Path to NPM log directory (mount NPM's /data/logs here) log_dir: str = "" diff --git a/src/npm_mcp/main.py b/src/npm_mcp/main.py index 72da8de..c612870 100644 --- a/src/npm_mcp/main.py +++ b/src/npm_mcp/main.py @@ -48,9 +48,25 @@ def main() -> None: logger.info("Starting MCP server in stdio mode") mcp.run(transport="stdio") else: - logger.info(f"Starting MCP server in HTTP mode on {settings.mcp_host}:{settings.mcp_port}") - # Use FastMCP's native streamable-http transport (host/port configured in server.py) - mcp.run(transport="streamable-http") + logger.info(f"Starting MCP server in HTTP mode on {args.host}:{args.port}") + + # Always construct the HTTP app using the same FastMCP.streamable_http_app() + # so that its lifespan (StreamableHTTPSessionManager background task) runs correctly. + app = mcp.streamable_http_app() + + # Mount /health directly on the inner router + from starlette.responses import PlainTextResponse + from starlette.routing import Route + app.router.routes.insert(0, Route("/health", lambda r: PlainTextResponse("ok"))) + + if settings.mcp_auth_token: + logger.info("Bearer token authentication enabled") + from .auth import BearerAuthMiddleware + app.add_middleware(BearerAuthMiddleware, token=settings.mcp_auth_token) + + import uvicorn + + uvicorn.run(app, host=args.host, port=args.port) if __name__ == "__main__": diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..5609866 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,58 @@ +"""Tests for bearer token authentication middleware.""" + +import pytest +from starlette.applications import Starlette +from starlette.requests import Request +from starlette.responses import PlainTextResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from npm_mcp.auth import BearerAuthMiddleware + +TOKEN = "test-secret-token" + + +async def echo(request: Request): + return PlainTextResponse("ok") + + +async def health(request: Request): + return PlainTextResponse("healthy") + + +@pytest.fixture +def app(): + a = Starlette(routes=[Route("/mcp", echo), Route("/health", health)]) + a.add_middleware(BearerAuthMiddleware, token=TOKEN) + return a + + +@pytest.fixture +def client(app): + return TestClient(app, raise_server_exceptions=False) + + +class TestBearerAuth: + def test_missing_token_returns_401(self, client): + r = client.get("/mcp") + assert r.status_code == 401 + assert r.headers["WWW-Authenticate"] == "Bearer" + + def test_wrong_token_returns_401(self, client): + r = client.get("/mcp", headers={"Authorization": "Bearer wrong"}) + assert r.status_code == 401 + assert r.headers["WWW-Authenticate"] == 'Bearer error="invalid_token"' + + def test_valid_token_passes(self, client): + r = client.get("/mcp", headers={"Authorization": f"Bearer {TOKEN}"}) + assert r.status_code == 200 + assert r.text == "ok" + + def test_bearer_scheme_case_insensitive(self, client): + r = client.get("/mcp", headers={"Authorization": f"bearer {TOKEN}"}) + assert r.status_code == 200 + + def test_health_bypasses_auth(self, client): + r = client.get("/health") + assert r.status_code == 200 + assert r.text == "healthy"