* feat(#9): add bearer token auth for HTTP transport Adds NPM_MCP_AUTH_TOKEN env var. When set, HTTP transport requires Authorization: Bearer <token> on all requests except /health. Uses timing-safe comparison via hmac.compare_digest. Closes #9 * fix(auth): fix lifespan context and 401 status/headers spec compliance --------- Co-authored-by: b3nw <189466+b3nw@users.noreply.github.com>
This commit is contained in:
1 parent
2278c97d9d
commit
21bce2ad91
7 files changed
+135
-3
No files matched your search
@@ -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` |
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
@@ -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 = ""
|
||||
|
||||
|
||||
+19
-3
@@ -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__":
|
||||
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user