Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(mcp): Host/Origin guard on network transports (GHSA-p3c9)

Haozhe Wue4498d403f53
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index a659a27b1..82fd52414 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -117,6 +117,130 @@ def _resolve_include_shell_tools(cli_opt_in: bool) -> bool:
return bool(cli_opt_in) or _env_shell_tools_enabled()
+# ---------------------------------------------------------------------------
+# Network-transport DNS-rebinding hardening (GHSA-p3c9)
+#
+# The stdio transport is a private parent/child pipe and needs no host guard.
+# The network transports (``--transport sse`` / ``http``) bind a TCP port, so
+# a page in the user's browser could POST to the local MCP endpoint via
+# DNS-rebinding and reach every MCP tool. fastmcp 3.2.4 ships NO host/origin
+# protection, so we wrap the ASGI app with a Host allow-list
+# (TrustedHostMiddleware) plus an Origin allow-list before the MCP session is
+# reached. Default = loopback-only, so a local HTTP/SSE MCP still works.
+# ---------------------------------------------------------------------------
+
+_DEFAULT_MCP_ALLOWED_HOSTS = ("127.0.0.1", "localhost")
+
+
+def _parse_allowed_hosts(raw: str | None) -> list[str]:
+ """Parse ``VIBE_TRADING_MCP_ALLOWED_HOSTS`` into a Host/Origin allow-list.
+
+ Args:
+ raw: Comma-separated env value (may be ``None`` / empty).
+
+ Returns:
+ The parsed host list, or the loopback-only default
+ (``127.0.0.1``, ``localhost``) when unset/blank so a local HTTP/SSE
+ MCP keeps working while DNS-rebinding hosts are rejected.
+ """
+ hosts = [h.strip() for h in (raw or "").split(",") if h.strip()]
+ return hosts or list(_DEFAULT_MCP_ALLOWED_HOSTS)
+
+
+def _host_matches(host: str, pattern: str) -> bool:
+ """Return whether ``host`` matches an allow-list ``pattern``.
+
+ Mirrors Starlette's TrustedHostMiddleware semantics: ``*`` allows any host
+ and a leading ``*.`` matches the bare domain plus any subdomain.
+ """
+ if pattern == "*":
+ return True
+ if pattern.startswith("*."):
+ return host == pattern[2:] or host.endswith(pattern[1:])
+ return host == pattern
+
+
+def _origin_allowed(origin: str | None, allowed_hosts: list[str]) -> bool:
+ """Return whether a request ``Origin`` header is trusted.
+
+ A missing/blank Origin is allowed: non-browser MCP clients (curl, the
+ Python SDK) never send one, and DNS-rebinding is a browser-only attack. A
+ present Origin is trusted only when its hostname matches the allow-list.
+
+ Args:
+ origin: The raw ``Origin`` header value, or ``None`` when absent.
+ allowed_hosts: Trusted hostnames (same list used for Host validation).
+ """
+ if not origin:
+ return True
+ from urllib.parse import urlparse
+
+ host = urlparse(origin).hostname
+ if not host:
+ return False
+ return any(_host_matches(host, pattern) for pattern in allowed_hosts)
+
+
+class _OriginGuardMiddleware:
+ """ASGI middleware rejecting untrusted cross-origin browser requests.
+
+ Complements TrustedHostMiddleware: it blocks a request whose ``Origin``
+ header names a host outside the allow-list before the MCP session handler
+ runs, returning ``403`` so a rebinding page cannot invoke MCP tools.
+ """
+
+ def __init__(self, app: Any, allowed_hosts: list[str]) -> None:
+ self.app = app
+ self.allowed_hosts = list(allowed_hosts)
+
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
+ if scope.get("type") == "http":
+ origin: str | None = None
+ for key, value in scope.get("headers", []):
+ if key == b"origin":
+ origin = value.decode("latin-1")
+ break
+ if not _origin_allowed(origin, self.allowed_hosts):
+ from starlette.responses import PlainTextResponse
+
+ await PlainTextResponse("Origin not allowed", status_code=403)(
+ scope, receive, send
+ )
+ return
+ await self.app(scope, receive, send)
+
+
+def _security_middleware(allowed_hosts: list[str]) -> list[Any]:
+ """Build the Host + Origin allow-list middleware for network MCP transports.
+
+ Args:
+ allowed_hosts: Trusted hostnames from ``_parse_allowed_hosts``.
+
+ Returns:
+ A middleware list suitable for ``FastMCP.http_app(middleware=...)``.
+ """
+ from starlette.middleware import Middleware
+ from starlette.middleware.trustedhost import TrustedHostMiddleware
+
+ return [
+ Middleware(TrustedHostMiddleware, allowed_hosts=allowed_hosts),
+ Middleware(_OriginGuardMiddleware, allowed_hosts=allowed_hosts),
+ ]
+
+
+def _build_network_app(transport: str, allowed_hosts: list[str]):
+ """Build a DNS-rebinding-hardened FastMCP ASGI app for a network transport.
+
+ Args:
+ transport: ``"sse"`` or ``"streamable-http"``.
+ allowed_hosts: Trusted Host/Origin hostnames.
+
+ Returns:
+ A Starlette ASGI app (with MCP lifespan) ready for ``uvicorn.run``.
+ """
+ return mcp.http_app(transport=transport, middleware=_security_middleware(allowed_hosts))
+
+
def _get_skills_loader():
global _skills_loader
if _skills_loader is None:
@@ -1937,7 +2061,7 @@ def main():
parser.add_argument(
"--host",
default="127.0.0.1",
- help="Streamable HTTP bind host, --transport http only (default: 127.0.0.1)",
+ help="Network bind host for --transport sse / http (default: 127.0.0.1)",
)
parser.add_argument(
"--port", type=int, default=8900, help="SSE/HTTP port (default: 8900)"
@@ -1954,13 +2078,23 @@ def main():
_registry = None
_get_registry() # pre-warm: avoids deadlock when first tools/call lazy-inits inside FastMCP worker thread
- if args.transport == "sse":
- mcp.run(transport="sse", port=args.port)
- elif args.transport == "http":
- # Streamable HTTP (MCP spec 2025-03-26+): single endpoint at /mcp that
- # accepts POST (requests) and GET (notification stream). Replaces the
- # deprecated two-endpoint SSE transport for modern clients.
- mcp.run(transport="streamable-http", host=args.host, port=args.port)
+ if args.transport in ("sse", "http"):
+ # Network transports bind a TCP port and are therefore reachable by a
+ # DNS-rebinding page in the user's browser. fastmcp 3.2.4 has no
+ # built-in host/origin guard, so wrap the ASGI app with a Host + Origin
+ # allow-list (default loopback-only) and serve via uvicorn directly.
+ # 'http' = Streamable HTTP (single /mcp endpoint, MCP spec 2025-03-26+),
+ # replacing the deprecated two-endpoint SSE transport for modern clients.
+ import uvicorn
+
+ from src.config.accessor import get_env_config
+
+ allowed_hosts = _parse_allowed_hosts(
+ get_env_config().api.vibe_trading_mcp_allowed_hosts
+ )
+ transport = "streamable-http" if args.transport == "http" else "sse"
+ app = _build_network_app(transport, allowed_hosts)
+ uvicorn.run(app, host=args.host, port=args.port)
else:
mcp.run()
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index d1775132a..3ba4a229a 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -206,6 +206,12 @@ class APIConfig(_EnvBase):
vibe_trading_api_key: str = Field(alias="VIBE_TRADING_API_KEY", default="")
cors_origins: str = Field(alias="CORS_ORIGINS", default="")
api_allowed_hosts: str = Field(alias="API_ALLOWED_HOSTS", default="")
+ # Comma-separated Host/Origin allow-list for the network MCP transports
+ # (--transport sse / http). Empty means loopback-only (127.0.0.1,
+ # localhost), which blocks DNS-rebinding while keeping local use working.
+ vibe_trading_mcp_allowed_hosts: str = Field(
+ alias="VIBE_TRADING_MCP_ALLOWED_HOSTS", default="",
+ )
enable_session_runtime: EnvBool = Field(alias="ENABLE_SESSION_RUNTIME", default=True)
vibe_trading_trust_docker_loopback: EnvBool = Field(
alias="VIBE_TRADING_TRUST_DOCKER_LOOPBACK", default=False,
diff --git a/agent/tests/test_mcp_host_origin_guard.py b/agent/tests/test_mcp_host_origin_guard.py
new file mode 100644
index 000000000..7036567cd
--- /dev/null
+++ b/agent/tests/test_mcp_host_origin_guard.py
@@ -0,0 +1,141 @@
+"""Tests for the network MCP transport DNS-rebinding guard (GHSA-p3c9).
+
+The stdio transport is a private pipe and is not touched. The network
+transports (``--transport sse`` / ``http``) bind a TCP port, so fastmcp 3.2.4
+(which ships no host/origin protection) is wrapped with a Host + Origin
+allow-list before the MCP session is reached. These tests cover:
+
+1. ``_parse_allowed_hosts`` — loopback-only default + comma parsing.
+2. ``_origin_allowed`` — the Origin allow-list helper (browser-only guard).
+3. The fully wired ASGI app rejects an untrusted Host (400) and Origin (403).
+4. A loopback Host/Origin (and a missing Origin) is accepted.
+"""
+
+from __future__ import annotations
+
+import mcp_server
+from starlette.applications import Starlette
+from starlette.responses import PlainTextResponse
+from starlette.routing import Route
+from starlette.testclient import TestClient
+
+
+# ---------------------------------------------------------------------------
+# _parse_allowed_hosts
+# ---------------------------------------------------------------------------
+
+
+def test_parse_allowed_hosts_default_is_loopback_only():
+ assert mcp_server._parse_allowed_hosts(None) == ["127.0.0.1", "localhost"]
+ assert mcp_server._parse_allowed_hosts("") == ["127.0.0.1", "localhost"]
+ assert mcp_server._parse_allowed_hosts(" ") == ["127.0.0.1", "localhost"]
+
+
+def test_parse_allowed_hosts_parses_and_trims():
+ assert mcp_server._parse_allowed_hosts("a.example.com, b.example.com") == [
+ "a.example.com",
+ "b.example.com",
+ ]
+ # Empty segments are dropped, whitespace stripped.
+ assert mcp_server._parse_allowed_hosts("mcp.local, , ") == ["mcp.local"]
+
+
+# ---------------------------------------------------------------------------
+# _origin_allowed
+# ---------------------------------------------------------------------------
+
+
+def test_origin_allowed_missing_origin_is_allowed():
+ # Non-browser MCP clients (curl / Python SDK) never send Origin.
+ hosts = ["127.0.0.1", "localhost"]
+ assert mcp_server._origin_allowed(None, hosts) is True
+ assert mcp_server._origin_allowed("", hosts) is True
+
+
+def test_origin_allowed_matches_allow_list():
+ hosts = ["127.0.0.1", "localhost"]
+ assert mcp_server._origin_allowed("http://localhost:8900", hosts) is True
+ assert mcp_server._origin_allowed("http://127.0.0.1", hosts) is True
+
+
+def test_origin_allowed_rejects_foreign_and_unparseable():
+ hosts = ["127.0.0.1", "localhost"]
+ assert mcp_server._origin_allowed("http://evil.example.com", hosts) is False
+ assert mcp_server._origin_allowed("https://attacker.test:443", hosts) is False
+ # A present-but-hostless Origin is rejected (fail closed).
+ assert mcp_server._origin_allowed("null", hosts) is False
+
+
+def test_origin_allowed_supports_wildcard():
+ hosts = ["*.example.com"]
+ assert mcp_server._origin_allowed("http://api.example.com", hosts) is True
+ assert mcp_server._origin_allowed("http://example.com", hosts) is True
+ assert mcp_server._origin_allowed("http://example.org", hosts) is False
+ assert mcp_server._origin_allowed("http://evil.test", ["*"]) is True
+
+
+# ---------------------------------------------------------------------------
+# Fully wired ASGI app (real FastMCP network transport)
+# ---------------------------------------------------------------------------
+
+
+def test_network_app_rejects_untrusted_host():
+ # Build the real hardened streamable-http app. TrustedHostMiddleware
+ # short-circuits an untrusted Host before the MCP session handler runs, so
+ # no lifespan/session-manager startup is needed to observe the rejection.
+ app = mcp_server._build_network_app("streamable-http", ["127.0.0.1", "localhost"])
+ client = TestClient(app)
+ resp = client.post("/mcp", headers={"host": "evil.example.com"})
+ assert resp.status_code == 400 # TrustedHostMiddleware "Invalid host header"
+
+
+def test_network_app_rejects_untrusted_origin():
+ app = mcp_server._build_network_app("streamable-http", ["127.0.0.1", "localhost"])
+ client = TestClient(app)
+ resp = client.post(
+ "/mcp",
+ headers={"host": "127.0.0.1:8900", "origin": "http://evil.example.com"},
+ )
+ assert resp.status_code == 403 # _OriginGuardMiddleware rejection
+
+
+# ---------------------------------------------------------------------------
+# Accepted path — exercises the exact middleware objects on a light app so a
+# valid loopback request is NOT rejected by either guard (no MCP session churn).
+# ---------------------------------------------------------------------------
+
+
+def _guarded_probe_app(allowed_hosts):
+ async def _ok(_request):
+ return PlainTextResponse("ok")
+
+ return Starlette(
+ routes=[Route("/mcp", _ok, methods=["POST"])],
+ middleware=mcp_server._security_middleware(allowed_hosts),
+ )
+
+
+def test_loopback_host_and_origin_accepted():
+ client = TestClient(_guarded_probe_app(["127.0.0.1", "localhost"]))
+ # Good host, matching origin.
+ resp = client.post(
+ "/mcp", headers={"host": "127.0.0.1:8900", "origin": "http://127.0.0.1:8900"}
+ )
+ assert resp.status_code == 200
+ assert resp.text == "ok"
+ # Good host, no origin header (non-browser client).
+ resp = client.post("/mcp", headers={"host": "localhost:8900"})
+ assert resp.status_code == 200
+
+
+def test_env_override_extends_allow_list():
+ hosts = mcp_server._parse_allowed_hosts("mcp.internal.test")
+ client = TestClient(_guarded_probe_app(hosts))
+ resp = client.post(
+ "/mcp",
+ headers={"host": "mcp.internal.test", "origin": "http://mcp.internal.test"},
+ )
+ assert resp.status_code == 200
+ # Loopback is no longer implicitly trusted once an explicit list is set.
+ resp = client.post("/mcp", headers={"host": "127.0.0.1:8900"})
+ assert resp.status_code == 400