Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): widen transport_security to match --host (#1737)
Nathan Prideef36becff68f
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex 2ca988694..c2876c90e 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -9,6 +9,7 @@ from contextlib import asynccontextmanagerfrom typing import Anyfrom mcp.server.fastmcp import FastMCP+from mcp.server.transport_security import TransportSecuritySettingsfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom repowise.core.persistence.database import (@@ -573,6 +574,75 @@ def create_mcp_server(#: two deep in practice; the cap only stops a pathological cycle from hanging._MAX_GROUP_DEPTH = 10+#: Host values FastMCP's own default construction already treats as local.+_LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")++#: ``allowed_hosts``/``allowed_origins`` patterns for the loopback callers a+#: non-loopback bind should still accept (e.g. an SSH tunnel or a client+#: running on the same box as the server).+_LOOPBACK_ALLOWLIST_PATTERNS = ("127.0.0.1:*", "localhost:*", "[::1]:*")+++def _bracket_if_ipv6(host: str) -> str:+ """Bracket a bare IPv6 literal to match the ``Host``/``Origin`` header shape a client sends.++ ``TransportSecurityMiddleware`` matches by ``host.startswith(base + ":")``+ (see ``mcp/server/transport_security.py``), so an allowlist entry has to+ be shaped exactly like the wire value. A client connecting to an IPv6+ literal sends a bracketed Host header (``[2001:db8::1]:7338``), which+ never starts with a bare ``2001:db8::1:`` — hostnames and IPv4 addresses+ never contain a colon, so any colon in ``host`` here means IPv6.+ """+ if ":" in host and not host.startswith("["):+ return f"[{host}]"+ return host+++def _configure_transport_security(host: str) -> None:+ """Widen the DNS-rebinding ``Host`` allowlist to match ``--host``.++ ``FastMCP`` builds ``mcp.settings.transport_security`` at import time,+ before any CLI ``--host`` is known, so it bakes in an allowlist scoped to+ loopback only. ``run_mcp`` rebinds the socket via ``mcp.settings.host``+ later, but nothing updated the allowlist to match — so every request to a+ non-loopback ``--host`` failed ``Host`` header validation with+ ``421 Misdirected Request`` no matter what host was actually given.++ A loopback host needs no change (FastMCP's default already covers it).+ Anything else — including a concrete IPv6 literal, bracketed to match the+ header shape — gets an allowlist scoped to that host plus loopback.++ A wildcard bind (``0.0.0.0``/``::``) can't be matched by any single+ ``Host`` value, so the check is disabled rather than left permanently+ failing. That trades DNS-rebinding protection for reachability on a+ wildcard bind; the startup security warning logged elsewhere in+ ``run_mcp`` for an unauthenticated wide bind is, until #1400 lands, the+ only remaining gate on that surface — this fix is what makes it live+ traffic instead of traffic that already 421'd.+ """+ if host in _LOOPBACK_HOSTS:+ return+ if host in ("0.0.0.0", "::"):+ mcp.settings.transport_security = TransportSecuritySettings(+ enable_dns_rebinding_protection=False,+ )+ return+ base = _bracket_if_ipv6(host)+ # allowed_origins inherits the SDK's same startswith(base + ":") prefix+ # match as allowed_hosts (see _validate_origin), so e.g.+ # "http://172.21.12.48:*" also technically accepts an Origin like+ # "http://172.21.12.48:8080.evil.com". Pre-existing SDK behavior — the+ # loopback defaults FastMCP bakes in have the identical looseness — not+ # something introduced or worsened here.+ mcp.settings.transport_security = TransportSecuritySettings(+ enable_dns_rebinding_protection=True,+ allowed_hosts=[f"{base}:*", *_LOOPBACK_ALLOWLIST_PATTERNS],+ allowed_origins=[+ f"http://{base}:*",+ *(f"http://{p}" for p in _LOOPBACK_ALLOWLIST_PATTERNS),+ ],+ )+def _run_transport(transport: str) -> None:"""Run the server, raising the cause of a task-group failure rather than the group.@@ -623,6 +693,7 @@ def run_mcp(if transport == "sse":mcp.settings.host = hostmcp.settings.port = port+ _configure_transport_security(host)if host in ("0.0.0.0", "::") and not os.environ.get("REPOWISE_API_KEY"):_log.warning("SECURITY WARNING: MCP server (sse) is binding to %s without "@@ -634,6 +705,7 @@ def run_mcp(elif transport == "streamable-http":mcp.settings.host = hostmcp.settings.port = port+ _configure_transport_security(host)if host in ("0.0.0.0", "::") and not os.environ.get("REPOWISE_API_KEY"):_log.warning("SECURITY WARNING: MCP server (streamable-http) is binding to %s without "diff --git a/tests/unit/server/test_mcp_transport_security.py b/tests/unit/server/test_mcp_transport_security.pynew file mode 100644index 000000000..2e6f7c912--- /dev/null+++ b/tests/unit/server/test_mcp_transport_security.py@@ -0,0 +1,164 @@+"""Tests for the MCP HTTP/SSE transport_security host allowlist.++``repowise mcp --transport streamable-http --host <non-loopback>`` failed+every request with ``421 Misdirected Request`` / ``Invalid Host header``,+regardless of the ``--host`` value given. ``FastMCP`` builds+``mcp.settings.transport_security`` at import time, before any CLI ``--host``+is known, so it bakes in a DNS-rebinding ``Host`` allowlist scoped to+loopback only; ``run_mcp`` later rebinds the socket via ``mcp.settings.host``+but never updated the allowlist to match.++``_configure_transport_security`` rebuilds the allowlist around the actual+bind host (or disables the now-unsatisfiable check for a wildcard bind).+"""++from __future__ import annotations++import pytest+from mcp.server.transport_security import TransportSecurityMiddleware++from repowise.server.mcp_server import _server++[email protected](autouse=True)+def _restore_transport_security():+ """Isolate mcp.settings.transport_security across tests."""+ original = _server.mcp.settings.transport_security+ yield+ _server.mcp.settings.transport_security = original+++def test_loopback_host_is_left_alone() -> None:+ """127.0.0.1/localhost/::1 already work under FastMCP's default — no-op."""+ before = _server.mcp.settings.transport_security++ for host in ("127.0.0.1", "localhost", "::1"):+ _server.mcp.settings.transport_security = before+ _server._configure_transport_security(host)+ assert _server.mcp.settings.transport_security is before+++def test_wildcard_bind_disables_the_host_check() -> None:+ """0.0.0.0/:: can't be matched by any single Host value, so it's disabled."""+ for host in ("0.0.0.0", "::"):+ _server._configure_transport_security(host)+ settings = _server.mcp.settings.transport_security+ assert settings.enable_dns_rebinding_protection is False+++def test_lan_host_gets_widened_to_that_host_plus_loopback() -> None:+ _server._configure_transport_security("172.21.12.48")+ settings = _server.mcp.settings.transport_security++ assert settings.enable_dns_rebinding_protection is True+ assert "172.21.12.48:*" in settings.allowed_hosts+ assert "127.0.0.1:*" in settings.allowed_hosts+ assert "localhost:*" in settings.allowed_hosts+ assert "[::1]:*" in settings.allowed_hosts+ assert "http://172.21.12.48:*" in settings.allowed_origins+++def test_hostname_bind_gets_widened_too() -> None:+ _server._configure_transport_security("my-machine.lan")+ settings = _server.mcp.settings.transport_security++ assert "my-machine.lan:*" in settings.allowed_hosts+ assert "http://my-machine.lan:*" in settings.allowed_origins+++def test_ipv6_host_gets_bracketed_in_the_allowlist() -> None:+ """A bare IPv6 --host must be bracketed to match the Host header shape a+ client actually sends (``[2001:db8::1]:7338``, not ``2001:db8::1:7338``).+ """+ _server._configure_transport_security("2001:db8::1")+ settings = _server.mcp.settings.transport_security++ assert settings.enable_dns_rebinding_protection is True+ assert "[2001:db8::1]:*" in settings.allowed_hosts+ assert "http://[2001:db8::1]:*" in settings.allowed_origins+++ ("host", "expected"),+ [+ ("172.21.12.48", "172.21.12.48"),+ ("my-machine.lan", "my-machine.lan"),+ ("2001:db8::1", "[2001:db8::1]"),+ ("[2001:db8::1]", "[2001:db8::1]"), # already bracketed — left alone+ ("::1", "[::1]"),+ ],+)+def test_bracket_if_ipv6(host: str, expected: str) -> None:+ assert _server._bracket_if_ipv6(host) == expected+++ ("header_host", "expected"),+ [+ ("172.21.12.48:7338", True),+ ("localhost:7338", True),+ ("127.0.0.1:7338", True),+ ("172.21.12.48", False), # bare host, no port — not in the allowlist+ ("evil.com:7338", False),+ ],+)+def test_real_middleware_validates_reported_host_header(header_host: str, expected: bool) -> None:+ """Exercise the actual SDK middleware, not just our settings object."""+ _server._configure_transport_security("172.21.12.48")+ middleware = TransportSecurityMiddleware(_server.mcp.settings.transport_security)++ assert middleware._validate_host(header_host) is expected+++ ("header_host", "expected"),+ [+ ("[2001:db8::1]:7338", True), # bracketed, as a real client sends it+ ("2001:db8::1:7338", False), # unbracketed — not the wire shape, must not match+ ("[::1]:7338", True), # loopback pattern still allowed alongside it+ ("[2001:db8::2]:7338", False), # a different IPv6 host+ ],+)+def test_real_middleware_validates_ipv6_host_header(header_host: str, expected: bool) -> None:+ """The gap a prior review caught: an unbracketed allowlist entry never+ matches the bracketed Host header a client sends for an IPv6 literal.+ """+ _server._configure_transport_security("2001:db8::1")+ middleware = TransportSecurityMiddleware(_server.mcp.settings.transport_security)++ assert middleware._validate_host(header_host) is expected+++def test_run_mcp_applies_transport_security_for_streamable_http(monkeypatch) -> None:+ calls: list[dict] = []+ monkeypatch.setattr(_server.mcp, "run", lambda **kw: calls.append(kw))+ monkeypatch.delenv("REPOWISE_API_KEY", raising=False)++ _server.run_mcp(transport="streamable-http", host="172.21.12.48", port=7338)++ settings = _server.mcp.settings.transport_security+ assert settings.enable_dns_rebinding_protection is True+ assert "172.21.12.48:*" in settings.allowed_hosts+++def test_run_mcp_applies_transport_security_for_sse(monkeypatch) -> None:+ calls: list[dict] = []+ monkeypatch.setattr(_server.mcp, "run", lambda **kw: calls.append(kw))+ monkeypatch.delenv("REPOWISE_API_KEY", raising=False)++ _server.run_mcp(transport="sse", host="172.21.12.48", port=7338)++ settings = _server.mcp.settings.transport_security+ assert settings.enable_dns_rebinding_protection is True+ assert "172.21.12.48:*" in settings.allowed_hosts+++def test_run_mcp_stdio_does_not_touch_transport_security(monkeypatch) -> None:+ """stdio never binds a socket — there's nothing for the allowlist to gate."""+ before = _server.mcp.settings.transport_security+ monkeypatch.setattr(_server.mcp, "run", lambda **kw: None)+ monkeypatch.setattr("repowise.server.mcp_server._watchdog.start_parent_watchdog", lambda: None)++ _server.run_mcp(transport="stdio")++ assert _server.mcp.settings.transport_security is before