Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(api): reject untrusted loopback hosts (#242)

Hinotobie5ee704e2ed8
diff --git a/agent/api_server.py b/agent/api_server.py
index e3265478b..420d07ad8 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -479,6 +479,16 @@ _DEFAULT_CORS_ORIGINS = [
"http://127.0.0.1:8000",
]
+_DEFAULT_LOOPBACK_HOSTS = frozenset({
+ "localhost",
+ "127.0.0.1",
+ "::1",
+ "[::1]",
+ # Starlette/FastAPI TestClient default host; included so unit tests exercise
+ # the API without having to override Host on every request.
+ "testserver",
+})
+
def _parse_cors_origins(raw: Optional[str]) -> List[str]:
"""Parse CORS origins and reject credentialed wildcard configuration.
@@ -505,6 +515,37 @@ def _parse_cors_origins(raw: Optional[str]) -> List[str]:
return origins
+def _parse_extra_loopback_hosts(raw: Optional[str]) -> set[str]:
+ """Return additional trusted Host names for loopback API traffic."""
+ if raw is None or not raw.strip():
+ return set()
+ return {host.strip().lower().rstrip(".") for host in raw.split(",") if host.strip()}
+
+
+_EXTRA_LOOPBACK_HOSTS = _parse_extra_loopback_hosts(os.getenv("API_ALLOWED_HOSTS"))
+
+
+def _host_without_port(host: str) -> str:
+ """Normalize a Host header to a lowercase hostname without a port."""
+ value = host.strip().lower().rstrip(".")
+ if not value:
+ return ""
+ if value.startswith("["):
+ end = value.find("]")
+ if end != -1:
+ return value[: end + 1]
+ return value
+ if value.count(":") == 1:
+ return value.rsplit(":", 1)[0]
+ return value
+
+
+def _is_allowed_loopback_host(host: str) -> bool:
+ """Return whether ``host`` is allowed for loopback-trusted API requests."""
+ normalized = _host_without_port(host)
+ return normalized in _DEFAULT_LOOPBACK_HOSTS or normalized in _EXTRA_LOOPBACK_HOSTS
+
+
# CORS: override with CORS_ORIGINS (comma-separated explicit origins)
_CORS_ORIGINS = _parse_cors_origins(os.getenv("CORS_ORIGINS"))
@@ -517,6 +558,17 @@ app.add_middleware(
)
+async def _reject_untrusted_loopback_host(request: Request, call_next):
+ """Block DNS-rebinding Host headers before loopback auth bypasses run."""
+ if _is_local_client(request) and not _is_allowed_loopback_host(request.headers.get("host", "")):
+ return JSONResponse(
+ status_code=status.HTTP_403_FORBIDDEN,
+ content={"detail": "Untrusted local API host"},
+ )
+ return await call_next(request)
+
+
# ----------------------------------------------------------------------------
# SPA deep-link fallback
# ----------------------------------------------------------------------------
diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.py
index 4342b6115..331052ca2 100644
--- a/agent/tests/test_security_auth_api.py
+++ b/agent/tests/test_security_auth_api.py
@@ -150,6 +150,109 @@ def test_loopback_bypasses_auth_even_when_api_key_configured(
assert remote_bearer.status_code == 200
+def test_loopback_rejects_rebound_host_before_auth_bypass(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A loopback peer is not enough when Host is attacker-controlled."""
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+
+ response = _local_client().get(
+ "/runs",
+ headers={"Host": "attacker.example:8899", "Origin": "http://attacker.example:8899"},
+ )
+
+ assert response.status_code == 403
+ assert response.json()["detail"] == "Untrusted local API host"
+
+
+def test_remote_untrusted_host_still_uses_bearer_auth(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The Host gate only narrows loopback trust; remote clients still use API_AUTH_KEY."""
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+
+ response = _remote_client().get(
+ "/runs",
+ headers={"Host": "attacker.example:8899", "Origin": "http://attacker.example:8899"},
+ )
+
+ assert response.status_code == 401
+
+
+def test_rebound_host_cannot_start_live_runner(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """DNS-rebound loopback JSON requests must not reach live-runner control."""
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+ monkeypatch.setattr(api_server, "_active_mandate_state", lambda broker: SimpleNamespace(expired=False))
+
+ reached = {"factory": False}
+
+ class DummyRunner:
+ async def run_loop(self):
+ return None
+
+ def build_runner(broker: str) -> DummyRunner:
+ reached["factory"] = True
+ return DummyRunner()
+
+ monkeypatch.setattr(api_server, "_runner_factory", build_runner)
+ monkeypatch.setattr("src.trading.service.broker_supports_live_runner", lambda broker: True)
+ monkeypatch.setattr("src.live.halt.halt_flag_set", lambda broker=None: False)
+ api_server._runner_tasks.clear()
+
+ response = _local_client().post(
+ "/live/runner/start",
+ headers={
+ "Host": "attacker.example:8899",
+ "Origin": "http://attacker.example:8899",
+ "Content-Type": "application/json",
+ },
+ json={"broker": "robinhood", "session_id": "proof-session"},
+ )
+
+ assert response.status_code == 403
+ assert reached["factory"] is False
+ assert "robinhood" not in api_server._runner_tasks
+
+
+def test_allowed_loopback_host_can_start_live_runner_dev_mode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Allowed local hosts preserve the loopback dev-mode runner control path."""
+ monkeypatch.setattr(api_server, "_active_mandate_state", lambda broker: SimpleNamespace(expired=False))
+
+ reached = {"factory": False}
+
+ class DummyRunner:
+ async def run_loop(self):
+ return None
+
+ def build_runner(broker: str) -> DummyRunner:
+ reached["factory"] = True
+ return DummyRunner()
+
+ monkeypatch.setattr(api_server, "_runner_factory", build_runner)
+ monkeypatch.setattr("src.trading.service.broker_supports_live_runner", lambda broker: True)
+ monkeypatch.setattr("src.live.halt.halt_flag_set", lambda broker=None: False)
+ api_server._runner_tasks.clear()
+
+ response = _local_client().post(
+ "/live/runner/start",
+ headers={"Host": "127.0.0.1:8899", "Content-Type": "application/json"},
+ json={"broker": "robinhood", "session_id": "proof-session"},
+ )
+
+ assert response.status_code == 200
+ assert reached["factory"] is True
+ task = api_server._runner_tasks.pop("robinhood", None)
+ if task is not None and not task.done():
+ task.cancel()
+
+
def test_configured_api_key_required_for_session_event_stream(
monkeypatch: pytest.MonkeyPatch,
) -> None: