"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(api): require the configured key on loopback too (GHSA-7wgj)
Haozhe Wu2f35bce832c6
diff --git a/agent/src/api/security.py b/agent/src/api/security.pyindex c3084c2c0..ce4c17395 100644--- a/agent/src/api/security.py+++ b/agent/src/api/security.py@@ -375,23 +375,29 @@ def _validate_api_auth(query_api_key: Optional[str] = None,allow_query: bool = False,) -> None:- """Validate configured auth, preserving loopback-only dev mode."""+ """Validate configured auth, preserving loopback-only dev mode.++ Key-first precedence: when an API key is configured every peer -- including+ loopback -- must present a valid credential (GHSA-7wgj). Only when no key is+ configured does the loopback dev-trust apply. Mirrors+ :func:`require_settings_write_auth`.+ """if request.method.upper() not in _SAFE_BROWSER_METHODS:_reject_cross_site_browser_request(request)- if _is_local_client(request):- return-api_key = _configured_api_key()- if not api_key:- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail="API_AUTH_KEY is required for non-local API access",- )+ if api_key:+ token = _auth_credential_from_header_or_query(cred, query_api_key, allow_query=allow_query)+ if not token or not hmac.compare_digest(token, api_key):+ raise HTTPException(status_code=401, detail="Invalid or missing API key")+ return- token = _auth_credential_from_header_or_query(cred, query_api_key, allow_query=allow_query)- if not token or not hmac.compare_digest(token, api_key):- raise HTTPException(status_code=401, detail="Invalid or missing API key")+ if _is_local_client(request):+ return+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="API_AUTH_KEY is required for non-local API access",+ )def _is_local_client(request: Request) -> bool:@@ -483,24 +489,21 @@ async def require_event_stream_auth(if request.method.upper() not in _SAFE_BROWSER_METHODS:_reject_cross_site_browser_request(request)- if _is_local_client(request):- return-api_key = _configured_api_key()- if not api_key:- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail="API_AUTH_KEY is required for non-local API access",- )-- token = cred.credentials if (cred and cred.credentials) else ""- if token and hmac.compare_digest(token, api_key):- return+ if api_key:+ token = cred.credentials if (cred and cred.credentials) else ""+ if token and hmac.compare_digest(token, api_key):+ return+ if ticket and _consume_sse_ticket(ticket):+ return+ raise HTTPException(status_code=401, detail="Invalid or missing API key")- if ticket and _consume_sse_ticket(ticket):+ if _is_local_client(request):return-- raise HTTPException(status_code=401, detail="Invalid or missing API key")+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="API_AUTH_KEY is required for non-local API access",+ )async def require_local_or_auth(diff --git a/agent/tests/test_auth_precedence.py b/agent/tests/test_auth_precedence.pynew file mode 100644index 000000000..baee320e2--- /dev/null+++ b/agent/tests/test_auth_precedence.py@@ -0,0 +1,141 @@+"""GHSA-7wgj regression: API auth must check the configured key BEFORE trusting a loopback peer.++The bug: ``_validate_api_auth`` / ``require_event_stream_auth`` returned early on+``_is_local_client(request)`` *before* reading the configured API key, so a+loopback (or same-host reverse-proxy) peer was admitted with no credential even+when ``API_AUTH_KEY`` was set. The fix inverts to key-first precedence: when a+key is configured every peer -- loopback included -- must present a valid+credential; only in keyless dev mode does loopback trust apply.++A default FastAPI ``TestClient`` reports its peer host as ``testclient``, which+``_is_local_client`` treats as loopback -- exactly the condition that reproduced+the bug.+"""++from __future__ import annotations++import pytest+from fastapi.testclient import TestClient++import api_server+++def _loopback_client() -> TestClient:+ """TestClient whose peer host ('testclient') is treated as loopback."""+ return TestClient(api_server.app)++[email protected](autouse=True)+def clear_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ """Start every test from dev-mode auth (no configured key)."""+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.delenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", raising=False)+ monkeypatch.delenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", "")+++def _set_key(monkeypatch: pytest.MonkeyPatch, key: str = "secret") -> None:+ monkeypatch.setenv("API_AUTH_KEY", key)+ monkeypatch.setattr(api_server, "_API_KEY", key)+++# (a) Key configured + NO credential on a require_auth route -> rejected, even for a loopback peer.+def test_loopback_without_credential_rejected_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ response = _loopback_client().get("/runs")++ # The vulnerability would return 200 here; key-first precedence rejects it.+ assert response.status_code in {401, 403}+ assert response.status_code != 200+++# (b) Key configured + valid bearer -> allowed.+def test_loopback_with_valid_bearer_allowed_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ response = _loopback_client().get(+ "/runs", headers={"Authorization": "Bearer secret"}+ )++ assert response.status_code == 200+++# (b') Key configured + WRONG bearer -> rejected.+def test_loopback_with_invalid_bearer_rejected_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ response = _loopback_client().get(+ "/runs", headers={"Authorization": "Bearer wrong"}+ )++ assert response.status_code == 401+++# (c) No key (dev mode) + loopback peer -> allowed. Default local UX is unchanged.+def test_loopback_allowed_in_dev_mode_without_key() -> None:+ response = _loopback_client().get("/runs")++ assert response.status_code == 200+++# (d) Event-stream: valid single-use ticket still authenticates.+def test_event_stream_accepts_valid_ticket_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ ticket = api_server._mint_sse_ticket()+ response = _loopback_client().get(f"/sessions/missing/events?ticket={ticket}")++ # Auth passed; the 404/501 comes from the missing session / disabled runtime,+ # not from the auth layer (a 401/403 would mean auth rejected the ticket).+ assert response.status_code in {404, 501}+++# (d) Event-stream: valid bearer still authenticates.+def test_event_stream_accepts_valid_bearer_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ response = _loopback_client().get(+ "/sessions/missing/events", headers={"Authorization": "Bearer secret"}+ )++ assert response.status_code in {404, 501}+++# (d) Event-stream: missing credential on a loopback peer -> rejected when key configured.+def test_event_stream_without_credential_rejected_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ response = _loopback_client().get("/sessions/missing/events")++ assert response.status_code == 401+++# (d) Event-stream: an expired/invalid ticket is not accepted.+def test_event_stream_rejects_invalid_ticket_when_key_configured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_key(monkeypatch)++ response = _loopback_client().get("/sessions/missing/events?ticket=not-a-real-ticket")++ assert response.status_code == 401+++# Event-stream dev mode: loopback allowed without any credential (unchanged UX).+def test_event_stream_allowed_in_dev_mode_without_key() -> None:+ response = _loopback_client().get("/sessions/missing/events")++ assert response.status_code in {404, 501}diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.pyindex 449cc98f0..93c16d821 100644--- a/agent/tests/test_security_auth_api.py+++ b/agent/tests/test_security_auth_api.py@@ -129,19 +129,23 @@ def test_configured_api_key_accepts_bearer_for_sensitive_reads(assert response.status_code == 200-def test_loopback_bypasses_auth_even_when_api_key_configured(+def test_loopback_requires_auth_when_api_key_configured(monkeypatch: pytest.MonkeyPatch,) -> None:- """Loopback clients remain trusted for non-settings reads."""+ """GHSA-7wgj: a configured key gates EVERY peer, loopback included."""monkeypatch.setenv("API_AUTH_KEY", "secret")monkeypatch.setattr(api_server, "_API_KEY", "secret")local = _local_client()remote = _remote_client()- # Loopback: no bearer needed → should succeed+ # Loopback without bearer: no longer bypasses the configured key → rejectedlocal_response = local.get("/runs")- assert local_response.status_code == 200+ assert local_response.status_code == 401++ # Loopback with bearer: accepted (this is the frontend's authenticated path)+ local_bearer = local.get("/runs", headers={"Authorization": "Bearer secret"})+ assert local_bearer.status_code == 200# Remote without bearer: still rejectedremote_response = remote.get("/runs")diff --git a/agent/tests/test_settings_api.py b/agent/tests/test_settings_api.pyindex d928b14a9..98b77e57b 100644--- a/agent/tests/test_settings_api.py+++ b/agent/tests/test_settings_api.py@@ -292,7 +292,7 @@ def test_settings_reads_reject_remote_dev_mode_clients(assert "ts-s...oken" not in data_source_response.text-def test_settings_reads_allow_loopback_without_bearer_even_when_api_auth_key_configured(+def test_settings_reads_require_bearer_on_loopback_when_api_auth_key_configured(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,) -> None:env_path = tmp_path / ".env"@@ -319,7 +319,9 @@ def test_settings_reads_allow_loopback_without_bearer_even_when_api_auth_key_conheaders={"Authorization": "Bearer settings-secret"},)- assert unauthenticated_response.status_code == 200+ # GHSA-7wgj: a configured key gates settings reads even on loopback (the+ # bundled frontend sends the bearer once the key is stored in Settings).+ assert unauthenticated_response.status_code == 401assert authenticated_response.status_code == 200assert authenticated_response.json()["api_key_configured"] is Trueassert authenticated_response.json()["api_key_hint"] is Nonediff --git a/agent/tests/test_upload_api.py b/agent/tests/test_upload_api.pyindex 32cba7fa6..10f261357 100644--- a/agent/tests/test_upload_api.py+++ b/agent/tests/test_upload_api.py@@ -51,21 +51,31 @@ def test_cross_site_browser_upload_is_rejected_even_from_loopback(assert _existing_uploads(tmp_path) == []-def test_loopback_upload_without_browser_origin_still_allowed_when_key_configured(+def test_loopback_upload_requires_bearer_when_key_configured(client: TestClient,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:+ # GHSA-7wgj: a configured key gates uploads even on loopback. Without a+ # bearer the loopback upload is rejected; with the bearer it succeeds — the+ # bundled frontend sends Authorization once the key is stored in Settings.monkeypatch.setenv("API_AUTH_KEY", "secret")monkeypatch.setattr(api_server, "_API_KEY", "secret")- response = client.post(+ unauth = client.post("/upload",headers={"Host": "127.0.0.1:8899"},files={"file": ("note.txt", b"safe", "text/plain")},)+ assert unauth.status_code == 401+ assert _existing_uploads(tmp_path) == []- assert response.status_code == 200+ authed = client.post(+ "/upload",+ headers={"Host": "127.0.0.1:8899", "Authorization": "Bearer secret"},+ files={"file": ("note.txt", b"safe", "text/plain")},+ )+ assert authed.status_code == 200assert len(_existing_uploads(tmp_path)) == 1