diff --git a/nginx/gnexus-book.conf b/nginx/gnexus-book.conf index 0726e31..74a0876 100644 --- a/nginx/gnexus-book.conf +++ b/nginx/gnexus-book.conf @@ -9,6 +9,12 @@ try_files $uri $uri/ /index.html; } + # Service-to-service key provisioning must never be reachable from outside. + location = /internal { return 404; } + location /internal/ { return 404; } + location = /api/internal { return 404; } + location /api/internal/ { return 404; } + location /api/ { proxy_pass http://127.0.0.1:8000/; proxy_http_version 1.1; diff --git a/server/app/auth/mcp_routes.py b/server/app/auth/mcp_routes.py index d9c3c93..5e72e11 100644 --- a/server/app/auth/mcp_routes.py +++ b/server/app/auth/mcp_routes.py @@ -40,12 +40,28 @@ reissue: bool = False +def _client_host(request: Request) -> str: + peer = request.client.host if request.client else "" + forwarded = request.headers.get("x-real-ip", "").strip() + if not forwarded: + forwarded_for = request.headers.get("x-forwarded-for", "") + forwarded = forwarded_for.split(",", 1)[0].strip() if forwarded_for else "" + if peer in {"127.0.0.1", "::1"} and forwarded: + return forwarded + return peer + + def require_internal_service( request: Request, settings: Settings = Depends(get_settings) ) -> None: if not settings.internal_key_secret: raise HTTPException(status_code=503, detail="Internal key API is not configured") + host = _client_host(request) + limiter = limiter_for(settings.internal_rate_limit) + if not limiter.allow(host or "unknown"): + raise HTTPException(status_code=429, detail="Too many requests") + supplied = request.headers.get("x-service-key") if not supplied: authorization = request.headers.get("authorization", "") @@ -56,17 +72,14 @@ if not supplied or not hmac.compare_digest(supplied, settings.internal_key_secret): raise HTTPException(status_code=401, detail="Invalid service credentials") - host = request.client.host if request.client else "" allowed = set(settings.internal_allowlist) | {"127.0.0.1", "::1"} if host not in allowed: raise HTTPException(status_code=403, detail="Source address is not allowed") - limiter = limiter_for(settings.internal_rate_limit) - if not limiter.allow(host or "unknown"): - raise HTTPException(status_code=429, detail="Too many requests") - -def _require_user(request: Request, settings: Settings) -> CurrentUser: +def _require_user( + request: Request, settings: Settings, require_write: bool = False +) -> CurrentUser: if not settings.auth_enabled: raise HTTPException(status_code=400, detail="Authentication is not configured") user = getattr(request.state, "user", None) @@ -74,6 +87,10 @@ raise HTTPException(status_code=401, detail="Not authenticated") if user.is_blocked: raise HTTPException(status_code=403, detail="User is blocked") + if require_write: + scopes = getattr(request.state, "mcp_scopes", None) + if scopes is not None and "write" not in scopes: + raise HTTPException(status_code=403, detail="write scope required") return user @@ -105,7 +122,7 @@ request: Request, settings: Settings = Depends(get_settings), ): - user = _require_user(request, settings) + user = _require_user(request, settings, require_write=True) if not limiter_for(settings.mcp_key_rate_limit).allow(f"user:{user.id}"): raise HTTPException(status_code=429, detail="Too many requests") database = Database.from_settings(settings) @@ -133,7 +150,7 @@ request: Request, settings: Settings = Depends(get_settings), ): - user = _require_user(request, settings) + user = _require_user(request, settings, require_write=True) if not limiter_for(settings.mcp_key_rate_limit).allow(f"user:{user.id}"): raise HTTPException(status_code=429, detail="Too many requests") database = Database.from_settings(settings) @@ -156,7 +173,7 @@ request: Request, settings: Settings = Depends(get_settings), ) -> Response: - user = _require_user(request, settings) + user = _require_user(request, settings, require_write=True) try: revoke_key( Database.from_settings(settings), diff --git a/server/app/mcp_server.py b/server/app/mcp_server.py index 1dad639..76b4e44 100644 --- a/server/app/mcp_server.py +++ b/server/app/mcp_server.py @@ -6,6 +6,7 @@ from typing import Annotated, Any, Literal from mcp.server.fastmcp import FastMCP +from mcp.server.transport_security import TransportSecuritySettings from pydantic import Field from .auth.actor import Actor @@ -310,6 +311,9 @@ summary: str, files: list[str], details: str = "", is_user: bool = False ) -> dict[str, Any]: """Validate the repository and create a local Git commit for selected documentation files.""" + denied = mcp_write_denied() + if denied: + return denied settings = _settings() if settings.storage_backend == "db": return { @@ -393,10 +397,19 @@ ) +def build_transport_security(settings: Settings) -> TransportSecuritySettings: + return TransportSecuritySettings( + enable_dns_rebinding_protection=True, + allowed_hosts=list(settings.mcp_allowed_hosts), + allowed_origins=list(settings.mcp_allowed_origins), + ) + + mcp = FastMCP( "gnexus-book", instructions=MCP_INSTRUCTIONS, streamable_http_path="/mcp-protocol/", + transport_security=build_transport_security(Settings()), ) diff --git a/server/tests/test_mcp_keys.py b/server/tests/test_mcp_keys.py index 3d4e3b6..7714ec8 100644 --- a/server/tests/test_mcp_keys.py +++ b/server/tests/test_mcp_keys.py @@ -20,9 +20,9 @@ from app.config import Settings, get_settings from app.main import app from app.mcp_http import app as mcp_http_app -from app.mcp_server import mcp +from app.mcp_server import build_transport_security, commit_changes, mcp from app.storage.db import Database -from app.storage.models import McpToken, User +from app.storage.models import AuditLog, McpToken, User AUTH_ENV = { "GNEXUS_BOOK_STORAGE_BACKEND": "db", @@ -202,6 +202,16 @@ issued = created.json() assert issued["token"].startswith("mcp_") + with database.session() as session: + audit = session.scalars( + select(AuditLog).where( + AuditLog.entity_id == issued["key_id"], + AuditLog.action == "mcp_key.issue", + ) + ).first() + assert audit is not None + assert audit.actor_user_id == user.id + listed = client.get("/mcp-keys") assert listed.status_code == 200 assert len(listed.json()["items"]) == 1 @@ -236,9 +246,13 @@ authenticated = client.post( "/mcp-protocol/", json=payload, - headers={"Authorization": f"Bearer {token}"}, + headers={ + "Authorization": f"Bearer {token}", + "Host": "127.0.0.1:8001", + "Accept": "application/json, text/event-stream", + }, ) - assert authenticated.status_code != 401 + assert authenticated.status_code == 200 with database.session() as session: with session.begin(): @@ -290,6 +304,54 @@ assert body["scopes"] == ["read", "write"] +def test_read_only_key_cannot_mint_write_key( + key_settings: Settings, database: Database +) -> None: + user = _insert_user(database, sub="sub-read-only") + current = to_current_user(user) + issued, token = create_key(database, current, "navi", "Read-only key") + + with database.session() as session: + with session.begin(): + row = session.get(McpToken, uuid.UUID(issued["key_id"])) + assert row is not None + row.scopes = ["read"] + + client = TestClient(app) + headers = {"Authorization": f"Bearer {token}"} + + denied = client.post( + "/mcp-keys", + headers=headers, + json={"consumer": "evil", "name": "escalated"}, + ) + assert denied.status_code == 403 + assert client.get("/mcp-keys", headers=headers).status_code == 200 + + +def test_commit_changes_requires_write_scope() -> None: + reset = current_mcp_scopes.set(("read",)) + try: + result = commit_changes("denied", ["10-systems/example.md"]) + assert result == {"error": 403, "detail": "write scope required"} + finally: + current_mcp_scopes.reset(reset) + + +def test_transport_security_uses_configured_hosts( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv( + "GNEXUS_BOOK_MCP_ALLOWED_HOSTS", + "book.gnexus.space,127.0.0.1:*", + ) + + security = build_transport_security(Settings()) + + assert "book.gnexus.space" in security.allowed_hosts + assert "127.0.0.1:*" in security.allowed_hosts + + def test_guard_rate_limits_requests( key_settings: Settings, database: Database,