diff --git a/CHANGELOG.md b/CHANGELOG.md index 376fe77..39cea54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- Fixed `/.well-known/oauth-protected-resource` advertising `http://` when TLS + ends at an ingress, which made MCP clients reject the server ("Protected + resource ... does not match expected ..."). Added `PUBLIC_URL` + (`config.publicUrl`) to set the advertised base URL explicitly and + `FORWARDED_ALLOW_IPS` (`config.forwardedAllowIps`) to trust the proxy's + `X-Forwarded-*` headers. + - Fixed the HTTP server stalling while RaaS answers slowly: the `/token` credential check and the per-request RaaS login and RPC in the dispatcher are synchronous (`httpx.Client`) but ran inside async handlers, so one slow RaaS call blocked the diff --git a/README.md b/README.md index 0a0aea0..8568036 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,8 @@ HTTPS, helper script, static token and OAuth/OIDC options, troubleshooting - is | `METRICS_PORT` | `9090` | Port for Prometheus /metrics | | `TOKEN_TTL_SECONDS` | `3600` | Bearer token lifetime | | `CORS_ALLOWED_ORIGINS` | (empty) | Comma-separated CORS origins | +| `PUBLIC_URL` | (empty) | Externally visible base URL, e.g. `https://raas-mcp.example.com`. Advertised as `resource` in `/.well-known/oauth-protected-resource`; MCP clients reject the server if it differs from the URL they connect to. Set it when TLS ends at an ingress/proxy (Helm: `config.publicUrl`) | +| `FORWARDED_ALLOW_IPS` | (empty = `127.0.0.1`) | Proxy IPs (or `*`) whose `X-Forwarded-*` headers are trusted (Helm: `config.forwardedAllowIps`) | | `KEEPALIVE_INTERVAL` | `15` | SSE keepalive interval (seconds) | | `PRESTOP_DRAIN_SECONDS` | `15` | Pre-SIGTERM drain grace period | | `TLS_ENABLED` | `false` | Direct TLS (prefer Ingress TLS) | diff --git a/helm/raas-mcp-server/templates/configmap.yaml b/helm/raas-mcp-server/templates/configmap.yaml index 19ffb26..8398255 100644 --- a/helm/raas-mcp-server/templates/configmap.yaml +++ b/helm/raas-mcp-server/templates/configmap.yaml @@ -15,6 +15,8 @@ data: KEEPALIVE_INTERVAL: {{ .Values.config.keepaliveInterval | toString | quote }} PRESTOP_DRAIN_SECONDS: {{ .Values.config.prestopDrainSeconds | toString | quote }} MAX_RAAS_TIMEOUT_SECONDS: {{ .Values.config.maxRaasTimeoutSeconds | toString | quote }} + PUBLIC_URL: {{ .Values.config.publicUrl | default "" | quote }} + FORWARDED_ALLOW_IPS: {{ .Values.config.forwardedAllowIps | default "" | quote }} ALLOWED_TOOLS: {{ .Values.config.allowedTools | quote }} APPROVAL_GATE: {{ .Values.config.approvalGate | quote }} {{- if .Values.tls.enabled }} diff --git a/helm/raas-mcp-server/values.yaml b/helm/raas-mcp-server/values.yaml index 73f1b30..1d629b4 100644 --- a/helm/raas-mcp-server/values.yaml +++ b/helm/raas-mcp-server/values.yaml @@ -57,6 +57,15 @@ config: prestopDrainSeconds: 15 maxRaasTimeoutSeconds: 60 + # Externally visible base URL (e.g. https://raas-mcp.example.com). Advertised + # as "resource" in /.well-known/oauth-protected-resource; clients reject the + # server if it differs from the URL they connect to. Set it when TLS ends at + # the ingress. Empty = derive from the request. + publicUrl: "" + # Proxy IPs (or "*") whose X-Forwarded-* headers uvicorn trusts. Empty = uvicorn + # default (127.0.0.1 only). + forwardedAllowIps: "" + # Tool filtering (comma-separated; empty = all tools allowed) allowedTools: "" # Approval gate (comma-separated; empty = no gate) diff --git a/raas_mcp/__main__.py b/raas_mcp/__main__.py index 738f4ee..b82db74 100644 --- a/raas_mcp/__main__.py +++ b/raas_mcp/__main__.py @@ -64,6 +64,9 @@ async def _run_http() -> None: host="0.0.0.0", port=cfg.mcp_port, log_level="info", + # uvicorn trusts X-Forwarded-* only from 127.0.0.1 by default; behind an + # ingress the scheme would otherwise be seen as http. + **({"forwarded_allow_ips": cfg.forwarded_allow_ips} if cfg.forwarded_allow_ips else {}), **ssl_kwargs, ) metrics_config = uvicorn.Config( diff --git a/raas_mcp/auth/protected_resource.py b/raas_mcp/auth/protected_resource.py index aab3b12..8ce947c 100644 --- a/raas_mcp/auth/protected_resource.py +++ b/raas_mcp/auth/protected_resource.py @@ -4,7 +4,8 @@ OAuth-aware tools can discover the token endpoint(s) automatically. The document contains: -- ``resource``: canonical URI of this protected resource (from ``request.base_url``) +- ``resource``: canonical URI of this protected resource (``cfg.public_url`` when set, + otherwise ``request.base_url``) - ``authorization_servers``: list of authorization server URIs; always contains ``/token`` first (opaque Basic-Auth path); when VIDB is enabled, also contains the VIDB issuer URL (OIDC SSO path). @@ -36,14 +37,14 @@ def build_protected_resource_handler( Parameters ---------- cfg: - HTTP server configuration; used to read ``vidb_issuer_url``. + HTTP server configuration; used to read ``public_url`` and ``vidb_issuer_url``. vidb_validator: Optional VIDB JWT validator; when ``_is_enabled`` and ``cfg.vidb_issuer_url`` is set, the VIDB issuer URL is appended to ``authorization_servers``. """ async def protected_resource_handler(request: Request) -> Response: - resource = str(request.base_url).rstrip("/") + resource = cfg.public_url or str(request.base_url).rstrip("/") # First entry is always the server's own opaque /token endpoint. authorization_servers = [f"{resource}/token"] diff --git a/raas_mcp/http_config.py b/raas_mcp/http_config.py index 24568a3..ddc2f3d 100644 --- a/raas_mcp/http_config.py +++ b/raas_mcp/http_config.py @@ -18,6 +18,11 @@ TLS_ENABLED "true"/"1" to enable direct TLS (default: false) TLS_CERT_PATH path to PEM certificate for direct TLS TLS_KEY_PATH path to PEM private key for direct TLS +PUBLIC_URL externally visible base URL of this server, e.g. + https://raas-mcp.example.com (default: derived from the + request). Set it when TLS ends at an ingress/proxy. +FORWARDED_ALLOW_IPS comma-separated proxy IPs (or "*") whose X-Forwarded-* + headers uvicorn trusts (default: 127.0.0.1) VIDB_ISSUER_URL VIDB OIDC issuer URL for SSO JWT validation (empty string or absent = VIDB path disabled) VIDB_JWKS_REFRESH JWKS cache TTL in seconds (default: 43200 = 12 h) @@ -27,6 +32,7 @@ import os from dataclasses import dataclass, field +from urllib.parse import urlparse @dataclass @@ -60,6 +66,12 @@ class HttpServerConfig: tls_cert_path: str | None = None tls_key_path: str | None = None + # Reverse-proxy awareness. public_url overrides the base URL advertised in + # the protected-resource metadata; forwarded_allow_ips tells uvicorn which + # proxies' X-Forwarded-Proto/Host headers to trust. + public_url: str | None = None + forwarded_allow_ips: str | None = None + # OIDC / VIDB JWT SSO authentication (optional — disabled when issuer URL absent) vidb_issuer_url: str | None = None vidb_jwks_refresh_interval_seconds: int = 43200 @@ -131,6 +143,15 @@ def load() -> HttpServerConfig: if not tls_key_path: raise ValueError("TLS_KEY_PATH must be set when TLS_ENABLED=true") + public_url: str | None = _str_env("PUBLIC_URL").rstrip("/") or None + if public_url is not None: + parsed = urlparse(public_url) + if parsed.scheme not in ("http", "https") or not parsed.netloc: + raise ValueError( + f"PUBLIC_URL must be an absolute http(s) URL; got: {public_url!r}" + ) + forwarded_allow_ips = _str_env("FORWARDED_ALLOW_IPS") or None + # VIDB / OIDC SSO configuration (optional) # Treat empty string (rendered by Helm ConfigMap when not configured) as None. vidb_issuer_url: str | None = _str_env("VIDB_ISSUER_URL") or None @@ -167,6 +188,8 @@ def load() -> HttpServerConfig: tls_enabled=tls_enabled, tls_cert_path=tls_cert_path, tls_key_path=tls_key_path, + public_url=public_url, + forwarded_allow_ips=forwarded_allow_ips, vidb_issuer_url=vidb_issuer_url, vidb_jwks_refresh_interval_seconds=vidb_jwks_refresh, ) diff --git a/tests/test_http_config.py b/tests/test_http_config.py index a848a92..8916edd 100644 --- a/tests/test_http_config.py +++ b/tests/test_http_config.py @@ -194,3 +194,28 @@ def test_vidb_issuer_url_localhost_http_accepted(monkeypatch): cfg = load() assert cfg.vidb_issuer_url == "http://localhost/oidc/t1" + + +def test_public_url_and_forwarded_ips(monkeypatch): + monkeypatch.setenv("RAAS_URL", "http://raas.test") + monkeypatch.setenv("PUBLIC_URL", "https://mcp.example.com:30443/") + monkeypatch.setenv("FORWARDED_ALLOW_IPS", "*") + cfg = load() + assert cfg.public_url == "https://mcp.example.com:30443" + assert cfg.forwarded_allow_ips == "*" + + +def test_public_url_defaults_to_none(monkeypatch): + monkeypatch.setenv("RAAS_URL", "http://raas.test") + monkeypatch.delenv("PUBLIC_URL", raising=False) + monkeypatch.delenv("FORWARDED_ALLOW_IPS", raising=False) + cfg = load() + assert cfg.public_url is None + assert cfg.forwarded_allow_ips is None + + +def test_public_url_invalid_raises(monkeypatch): + monkeypatch.setenv("RAAS_URL", "http://raas.test") + monkeypatch.setenv("PUBLIC_URL", "mcp.example.com") + with pytest.raises(ValueError, match="PUBLIC_URL"): + load() diff --git a/tests/test_protected_resource.py b/tests/test_protected_resource.py index 9f11f8b..f56d7fb 100644 --- a/tests/test_protected_resource.py +++ b/tests/test_protected_resource.py @@ -130,3 +130,15 @@ def test_returns_200_json(): # (schema validation is intentionally skipped — jsonschema not required at # test runtime; field presence is verified by the tests above) # --------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- +# f. PUBLIC_URL overrides the request-derived base URL (TLS-terminating proxy) +# --------------------------------------------------------------------------- + +def test_public_url_overrides_base_url(): + cfg = HttpServerConfig(raas_url="http://raas.test", public_url="https://mcp.example.com") + client = TestClient(_make_app(cfg)) + body = client.get("/.well-known/oauth-protected-resource").json() + assert body["resource"] == "https://mcp.example.com" + assert body["authorization_servers"] == ["https://mcp.example.com/token"]