Skip to content

"Vibe-Trading: Your Personal Trading Agent"

[security] fix(api): require auth for settings writes (#245)

Hinotobi97c67c9bb5d9
diff --git a/agent/api_server.py b/agent/api_server.py
index a23a15d94..f602b5b13 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -870,6 +870,31 @@ async def require_local_or_auth(
)
+async def require_settings_write_auth(
+ request: Request,
+ cred: Optional[HTTPAuthorizationCredentials] = Security(_security),
+) -> None:
+ """Require explicit authorization before changing credential-routing settings.
+
+ Settings writes can redirect stored provider credentials to a different
+ endpoint. When an API key is configured, loopback peer IP alone is not a
+ sufficient user-intent signal because a browser can reach local APIs after
+ DNS rebinding.
+ """
+ api_key = _configured_api_key()
+ if api_key:
+ token = _auth_credential_from_header_or_query(cred, None, allow_query=False)
+ if not token or not hmac.compare_digest(token, api_key):
+ raise HTTPException(status_code=401, detail="Invalid or missing API key")
+ return
+
+ if not _is_local_client(request):
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Settings writes require API_AUTH_KEY or a local loopback client",
+ )
+
+
# ============================================================================
# Workflow Factory
# ============================================================================
@@ -1525,7 +1550,7 @@ async def get_llm_settings():
return _build_llm_settings_response()
[email protected]("/settings/llm", response_model=LLMSettingsResponse, dependencies=[Depends(require_local_or_auth)])
[email protected]("/settings/llm", response_model=LLMSettingsResponse, dependencies=[Depends(require_settings_write_auth)])
async def update_llm_settings(payload: UpdateLLMSettingsRequest):
"""Persist project-local LLM settings and update the running process."""
provider_name = payload.provider.strip().lower()
@@ -1596,7 +1621,7 @@ async def get_data_source_settings():
@app.put(
"/settings/data-sources",
response_model=DataSourceSettingsResponse,
- dependencies=[Depends(require_local_or_auth)],
+ dependencies=[Depends(require_settings_write_auth)],
)
async def update_data_source_settings(payload: UpdateDataSourceSettingsRequest):
"""Persist project-local data source credentials and update the running process."""
diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.py
index 55bd97e3c..aaa791f65 100644
--- a/agent/tests/test_security_auth_api.py
+++ b/agent/tests/test_security_auth_api.py
@@ -130,7 +130,7 @@ def test_configured_api_key_accepts_bearer_for_sensitive_reads(
def test_loopback_bypasses_auth_even_when_api_key_configured(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Loopback clients are always trusted — the API key only gates remote access."""
+ """Loopback clients remain trusted for non-settings reads."""
monkeypatch.setenv("API_AUTH_KEY", "secret")
monkeypatch.setattr(api_server, "_API_KEY", "secret")
@@ -150,6 +150,91 @@ def test_loopback_bypasses_auth_even_when_api_key_configured(
assert remote_bearer.status_code == 200
+def _llm_settings_payload(base_url: str = "https://api.openai.com/v1") -> dict[str, object]:
+ return {
+ "provider": "openai",
+ "model_name": "gpt-4o-mini",
+ "base_url": base_url,
+ "temperature": 0,
+ "timeout_seconds": 120,
+ "max_retries": 2,
+ }
+
+
+def test_dns_rebound_loopback_cannot_write_llm_settings_without_bearer(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ """Configured API keys must gate credential-routing settings writes."""
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+ env_path = tmp_path / ".env"
+ env_path.write_text(
+ "\n".join(
+ [
+ "LANGCHAIN_PROVIDER=openai",
+ "LANGCHAIN_MODEL_NAME=gpt-4o-mini",
+ "OPENAI_BASE_URL=https://api.openai.com/v1",
+ "OPENAI_API_KEY=sk-existing-test-key",
+ "",
+ ]
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(api_server, "ENV_PATH", env_path)
+
+ response = _local_client().put(
+ "/settings/llm",
+ headers={"host": "attacker.example:8899", "origin": "http://attacker.example:8899"},
+ json=_llm_settings_payload("https://attacker.example/openai-compatible/v1"),
+ )
+
+ # The rebound-host middleware (#242) rejects this loopback request with an
+ # attacker-controlled Host before the settings-write auth layer is reached;
+ # either layer must prevent the credential-routing write from persisting.
+ assert response.status_code == 403
+ saved = env_path.read_text(encoding="utf-8")
+ assert "https://attacker.example/openai-compatible/v1" not in saved
+ assert "OPENAI_BASE_URL=https://api.openai.com/v1" in saved
+ assert "OPENAI_API_KEY=sk-existing-test-key" in saved
+
+
+def test_authorized_client_can_write_llm_settings_when_api_key_configured(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+ env_path = tmp_path / ".env"
+ env_path.write_text("", encoding="utf-8")
+ monkeypatch.setattr(api_server, "ENV_PATH", env_path)
+
+ response = _remote_client().put(
+ "/settings/llm",
+ headers={"Authorization": "Bearer secret"},
+ json=_llm_settings_payload("https://api.openai.com/v1"),
+ )
+
+ assert response.status_code == 200
+ assert "OPENAI_BASE_URL=https://api.openai.com/v1" in env_path.read_text(encoding="utf-8")
+
+
+def test_local_dev_can_write_llm_settings_when_api_key_unset(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ env_path = tmp_path / ".env"
+ monkeypatch.setattr(api_server, "ENV_PATH", env_path)
+
+ response = _local_client().put(
+ "/settings/llm",
+ json=_llm_settings_payload("https://api.openai.com/v1"),
+ )
+
+ assert response.status_code == 200
+ assert "OPENAI_BASE_URL=https://api.openai.com/v1" in env_path.read_text(encoding="utf-8")
+
+
def test_loopback_rejects_rebound_host_before_auth_bypass(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -328,8 +413,11 @@ def test_dns_rebound_swarm_run_does_not_enable_shell_tools_by_default(
},
)
- assert response.status_code == 200
- assert captured["include_shell_tools"] is False
+ # The rebound-host middleware (#242) rejects the attacker-controlled Host
+ # before /swarm/runs runs, so the request never reaches the point where shell
+ # tools would be granted — the swarm runtime is never invoked.
+ assert response.status_code == 403
+ assert "include_shell_tools" not in captured
def test_dns_rebound_session_message_does_not_enable_shell_tools_by_default(
@@ -357,10 +445,11 @@ def test_dns_rebound_session_message_does_not_enable_shell_tools_by_default(
json={"content": "SESSION_DNS_REBIND_PROOF_PAYLOAD"},
)
- assert response.status_code == 200
- assert captured["session_id"] == "abcdef012345"
- assert captured["content"] == "SESSION_DNS_REBIND_PROOF_PAYLOAD"
- assert captured["include_shell_tools"] is False
+ # The rebound-host middleware (#242) rejects the attacker-controlled Host
+ # before /sessions/{id}/messages runs, so the session service is never
+ # invoked and shell tools can never be granted via a DNS-rebound request.
+ assert response.status_code == 403
+ assert "include_shell_tools" not in captured
def test_default_cors_origins_are_loopback_only() -> None: