"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(api): default bind to 127.0.0.1 and warn on non-loopback without API_AUTH_KEY
Robin1987China3234a82e4575
diff --git a/agent/api_server.py b/agent/api_server.pyindex c8ba77634..caff02774 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -547,6 +547,14 @@ def _is_allowed_loopback_host(host: str) -> bool:return normalized in _DEFAULT_LOOPBACK_HOSTS or normalized in _EXTRA_LOOPBACK_HOSTS+def _is_loopback_bind_host(host: str) -> bool:+ """Return whether ``host`` resolves to a loopback interface."""+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return host == "localhost"++# CORS: override with CORS_ORIGINS (comma-separated explicit origins)_CORS_ORIGINS = _parse_cors_origins(os.getenv("CORS_ORIGINS"))@@ -3493,13 +3501,20 @@ def serve_main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description="Vibe-Trading Server")parser.add_argument("--port", type=int, default=8000, help="Listen port (default 8000)")- parser.add_argument("--host", default="0.0.0.0", help="Bind address")+ parser.add_argument("--host", default="127.0.0.1", help="Bind address")parser.add_argument("--dev", action="store_true", help="Dev mode: spawn Vite on :5173")try:args = parser.parse_args(argv)except SystemExit as exc:return int(exc.code) if isinstance(exc.code, int) else 2+ if not _is_loopback_bind_host(args.host) and not _configured_api_key():+ print(+ f"[warn] Binding to {args.host} without API_AUTH_KEY set. "+ f"Remote requests are rejected by the loopback peer-IP check, "+ f"but consider using --host 127.0.0.1 for local-only access."+ )+frontend_dist = Path(__file__).resolve().parent.parent / "frontend" / "dist"frontend_root = Path(__file__).resolve().parent.parent / "frontend"diff --git a/agent/cli/main.py b/agent/cli/main.pyindex 7449de8fa..d7d890f57 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -1314,7 +1314,7 @@ def _build_typer_app(): # type: ignore[no-untyped-def]@app.command("serve", help="Start the FastAPI server.")def _serve(- host: str = typer.Option("0.0.0.0", "--host"),+ host: str = typer.Option("127.0.0.1", "--host"),port: int = typer.Option(8000, "--port"),dev: bool = typer.Option(False, "--dev", help="Also boot the Vite dev server."),) -> None:diff --git a/agent/tests/test_serve_bind.py b/agent/tests/test_serve_bind.pynew file mode 100644index 000000000..0444030b0--- /dev/null+++ b/agent/tests/test_serve_bind.py@@ -0,0 +1,111 @@+"""Tests for the API server bind default and non-loopback warning.++Covers the secure-by-default behavior added for #333:+ - `_is_loopback_bind_host` classification (IPv4 / IPv6 / hostname / edge)+ - `serve_main` defaults the bind address to loopback (127.0.0.1)+ - binding a non-loopback address without API_AUTH_KEY emits a startup warning,+ while loopback or a configured key stays quiet++Warning assertions match the bind warning's own text rather than the bare+``[warn]`` prefix, so an unrelated startup warning (e.g. a missing frontend+build in CI) cannot satisfy or break them.+"""++from __future__ import annotations++from unittest import mock++import pytest++import api_server++# Unique substring of the non-loopback bind warning (api_server.py:3513).+_BIND_WARN = "without API_AUTH_KEY set"+++ "host, expected",+ [+ ("127.0.0.1", True),+ ("127.0.0.2", True),+ ("::1", True),+ ("0:0:0:0:0:0:0:1", True),+ ("localhost", True),+ ("0.0.0.0", False),+ ("::", False),+ ("192.168.1.5", False),+ ("", False),+ ],+)+def test_is_loopback_bind_host(host: str, expected: bool) -> None:+ assert api_server._is_loopback_bind_host(host) is expected+++def _run_serve(argv: list[str]) -> str | None:+ """Invoke serve_main with uvicorn stubbed; return the host it bound to.++ The frontend mount / static-file branches are short-circuited because+ uvicorn.run raises SystemExit before reaching the server loop.+ """+ captured: dict[str, object] = {}++ def fake_run(*args: object, **kwargs: object) -> None:+ captured["host"] = kwargs.get("host") or (args[1] if len(args) > 1 else None)+ raise SystemExit(0)++ with mock.patch("uvicorn.run", fake_run):+ try:+ api_server.serve_main(argv)+ except SystemExit:+ pass+ return captured.get("host") # type: ignore[return-value]+++def test_serve_defaults_to_loopback() -> None:+ assert _run_serve([]) == "127.0.0.1"+++def test_serve_honors_explicit_host() -> None:+ assert _run_serve(["--host", "0.0.0.0"]) == "0.0.0.0"+++def test_non_loopback_without_key_warns(+ capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", None, raising=False)++ _run_serve(["--host", "0.0.0.0"])++ out = capsys.readouterr().out+ assert _BIND_WARN in out+++def test_loopback_does_not_warn(+ capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", None, raising=False)++ _run_serve(["--host", "127.0.0.1"])++ out = capsys.readouterr().out+ assert _BIND_WARN not in out+++def test_non_loopback_with_key_does_not_warn(+ capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("API_AUTH_KEY", "secret")+ monkeypatch.setattr(api_server, "_API_KEY", "secret", raising=False)++ _run_serve(["--host", "0.0.0.0"])++ out = capsys.readouterr().out+ assert _BIND_WARN not in out