"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(mcp): accept IPv6 and case-variant hosts in the network guard
Robin1987China63dee9a081d4
diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 82fd52414..2b7a9eb33 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -123,27 +123,62 @@ def _resolve_include_shell_tools(cli_opt_in: bool) -> bool:# 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+# DNS-rebinding and reach every MCP tool. fastmcp 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+# (_HostGuardMiddleware) 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")+_DEFAULT_MCP_ALLOWED_HOSTS = ("127.0.0.1", "::1", "localhost")+++def _normalize_host(host: str) -> str:+ """Normalize a Host header value (or allow-list entry) for comparison.++ Strips the port and any IPv6 brackets, then lowercases: ``[::1]:8900``+ becomes ``::1``, ``Example.COM:8900`` becomes ``example.com``. A value+ with more than one colon and no brackets is treated as a bare IPv6+ literal and kept whole (never split into a fake ``host:port`` pair).++ Args:+ host: Raw Host header value or allow-list entry.++ Returns:+ The comparable hostname, lowercased.+ """+ value = host.strip()+ if value.startswith("["):+ # Bracketed IPv6 literal, optionally followed by ``:port``.+ end = value.find("]")+ if end != -1:+ return value[1:end].lower()+ elif value.count(":") == 1:+ # ``name:port`` — bare IPv6 (multiple colons) is kept whole.+ value = value.rsplit(":", 1)[0]+ return value.lower()def _parse_allowed_hosts(raw: str | None) -> list[str]:"""Parse ``VIBE_TRADING_MCP_ALLOWED_HOSTS`` into a Host/Origin allow-list.+ Entries are normalized like Host header values (case-insensitive, IPv6+ brackets stripped); wildcard forms (``*``, ``*.``) pass through apart+ from lowercasing.+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()]+ (``127.0.0.1``, ``::1``, ``localhost``) when unset/blank so a local+ HTTP/SSE MCP keeps working while DNS-rebinding hosts are rejected.+ """+ hosts = []+ for entry in (raw or "").split(","):+ entry = entry.strip()+ if not entry:+ continue+ hosts.append(entry.lower() if entry.startswith("*") else _normalize_host(entry))return hosts or list(_DEFAULT_MCP_ALLOWED_HOSTS)@@ -181,6 +216,37 @@ def _origin_allowed(origin: str | None, allowed_hosts: list[str]) -> bool:return any(_host_matches(host, pattern) for pattern in allowed_hosts)+class _HostGuardMiddleware:+ """ASGI middleware rejecting requests with an untrusted Host header.++ Same role as Starlette's TrustedHostMiddleware, but normalizes the+ header first: Starlette's plain ``split(":")`` mangles bracketed IPv6+ (``[::1]:8900`` → ``"["``) and matches case-sensitively, which locked+ out ``--host ::1`` deployments and ``LOCALHOST`` clients entirely.+ """++ 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":+ host: str | None = None+ for key, value in scope.get("headers", []):+ if key == b"host":+ host = value.decode("latin-1")+ break+ normalized = _normalize_host(host) if host else ""+ if not any(_host_matches(normalized, pattern) for pattern in self.allowed_hosts):+ from starlette.responses import PlainTextResponse++ await PlainTextResponse("Invalid host header", status_code=400)(+ scope, receive, send+ )+ return+ await self.app(scope, receive, send)++class _OriginGuardMiddleware:"""ASGI middleware rejecting untrusted cross-origin browser requests.@@ -220,10 +286,9 @@ def _security_middleware(allowed_hosts: list[str]) -> list[Any]:A middleware list suitable for ``FastMCP.http_app(middleware=...)``."""from starlette.middleware import Middleware- from starlette.middleware.trustedhost import TrustedHostMiddlewarereturn [- Middleware(TrustedHostMiddleware, allowed_hosts=allowed_hosts),+ Middleware(_HostGuardMiddleware, allowed_hosts=allowed_hosts),Middleware(_OriginGuardMiddleware, allowed_hosts=allowed_hosts),]diff --git a/agent/tests/test_mcp_host_origin_guard.py b/agent/tests/test_mcp_host_origin_guard.pyindex 7036567cd..d54497cd8 100644--- a/agent/tests/test_mcp_host_origin_guard.py+++ b/agent/tests/test_mcp_host_origin_guard.py@@ -26,9 +26,9 @@ from starlette.testclient import TestClientdef 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"]+ assert mcp_server._parse_allowed_hosts(None) == ["127.0.0.1", "::1", "localhost"]+ assert mcp_server._parse_allowed_hosts("") == ["127.0.0.1", "::1", "localhost"]+ assert mcp_server._parse_allowed_hosts(" ") == ["127.0.0.1", "::1", "localhost"]def test_parse_allowed_hosts_parses_and_trims():@@ -40,6 +40,35 @@ def test_parse_allowed_hosts_parses_and_trims():assert mcp_server._parse_allowed_hosts("mcp.local, , ") == ["mcp.local"]+def test_parse_allowed_hosts_normalizes_entries():+ # Case-insensitive, IPv6 brackets stripped, wildcard forms pass through.+ assert mcp_server._parse_allowed_hosts("LOCALHOST, [::1], *.Example.COM, *") == [+ "localhost",+ "::1",+ "*.example.com",+ "*",+ ]+++# ---------------------------------------------------------------------------+# _normalize_host+# ---------------------------------------------------------------------------+++def test_normalize_host_strips_port_and_lowercases():+ assert mcp_server._normalize_host("LOCALHOST:8900") == "localhost"+ assert mcp_server._normalize_host("Example.COM") == "example.com"+ assert mcp_server._normalize_host("127.0.0.1:8900") == "127.0.0.1"+++def test_normalize_host_handles_ipv6_forms():+ assert mcp_server._normalize_host("[::1]:8900") == "::1"+ assert mcp_server._normalize_host("[::1]") == "::1"+ # Bare IPv6 (no brackets) is kept whole, never split into a fake host:port.+ assert mcp_server._normalize_host("::1") == "::1"+ assert mcp_server._normalize_host("fe80::1%eth0") == "fe80::1%eth0"++# ---------------------------------------------------------------------------# _origin_allowed# ---------------------------------------------------------------------------@@ -139,3 +168,50 @@ def test_env_override_extends_allow_list():# 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+++# ---------------------------------------------------------------------------+# IPv6 / case handling in the wired host guard+# ---------------------------------------------------------------------------+++def test_ipv6_loopback_accepted_by_default_list():+ """`--host ::1` deployments must not 400 every request (Starlette did)."""+ client = TestClient(_guarded_probe_app(mcp_server._parse_allowed_hosts(None)))+ resp = client.post("/mcp", headers={"host": "[::1]:8900"})+ assert resp.status_code == 200+ resp = client.post("/mcp", headers={"host": "::1"})+ assert resp.status_code == 200+++def test_ipv6_env_entry_accepts_bracketed_host():+ """An env entry of `[::1]` or `::1` must actually match (no `*` needed)."""+ for entry in ("[::1]", "::1"):+ hosts = mcp_server._parse_allowed_hosts(entry)+ client = TestClient(_guarded_probe_app(hosts))+ resp = client.post("/mcp", headers={"host": "[::1]:8900"})+ assert resp.status_code == 200, entry+++def test_host_matching_is_case_insensitive():+ client = TestClient(_guarded_probe_app(["127.0.0.1", "localhost"]))+ resp = client.post("/mcp", headers={"host": "LOCALHOST:8900"})+ assert resp.status_code == 200+++def test_host_guard_still_rejects_untrusted():+ client = TestClient(_guarded_probe_app(mcp_server._parse_allowed_hosts(None)))+ resp = client.post("/mcp", headers={"host": "evil.example.com"})+ assert resp.status_code == 400+ # A missing Host header fails closed.+ resp = client.post("/mcp", headers={"host": ""})+ assert resp.status_code == 400+++def test_host_guard_wildcard_semantics_unchanged():+ client = TestClient(_guarded_probe_app(["*.example.com"]))+ assert client.post("/mcp", headers={"host": "api.example.com"}).status_code == 200+ assert client.post("/mcp", headers={"host": "example.com"}).status_code == 200+ assert client.post("/mcp", headers={"host": "example.org"}).status_code == 400+ client = TestClient(_guarded_probe_app(["*"]))+ assert client.post("/mcp", headers={"host": "anything.example.org"}).status_code == 200