Skip to content

"Vibe-Trading: Your Personal Trading Agent"

refactor(api): extract shared compat layer, fix session service writeback

shadowinlife39627475afc6
diff --git a/agent/api_server.py b/agent/api_server.py
index 22d817e3b..eb6c3fd20 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -130,6 +130,9 @@ app.add_middleware(
allow_headers=["*"],
)
+# Middleware functions are defined in src.api.security / src.api.helpers, so
+# the @app.middleware("http") decorator cannot be used here — register them
+# programmatically instead.
app.middleware("http")(_reject_untrusted_loopback_host)
app.middleware("http")(_spa_html_deep_link_fallback)
diff --git a/agent/src/api/_compat.py b/agent/src/api/_compat.py
new file mode 100644
index 000000000..60f77c8ed
--- /dev/null
+++ b/agent/src/api/_compat.py
@@ -0,0 +1,26 @@
+"""Shared monkeypatch compatibility layer for extracted API modules.
+
+Tests monkeypatch ``api_server._API_KEY`` (and similar). Route modules
+resolve dependencies via ``sys.modules["api_server"]``, so the patched
+value lives on the *host* module, not on the extracted module.
+"""
+
+from __future__ import annotations
+
+import sys
+from typing import Any
+
+
+def host_attr(name: str, fallback: Any) -> Any:
+ """Read a compatibility attribute from ``api_server`` when present."""
+ host = sys.modules.get("api_server")
+ if host is not None and hasattr(host, name):
+ return getattr(host, name)
+ return fallback
+
+
+def set_host_attr(name: str, value: Any) -> None:
+ """Write a compatibility attribute onto ``api_server`` when present."""
+ host = sys.modules.get("api_server")
+ if host is not None:
+ setattr(host, name, value)
diff --git a/agent/src/api/helpers.py b/agent/src/api/helpers.py
index d39819c93..03a61fad1 100644
--- a/agent/src/api/helpers.py
+++ b/agent/src/api/helpers.py
@@ -3,20 +3,13 @@
from __future__ import annotations
import re
-import sys
from pathlib import Path
from typing import Dict
from fastapi import HTTPException, Request, status
from fastapi.responses import FileResponse
-
-def _host_attr(name: str, fallback):
- """Read a compatibility attribute from ``api_server`` when present."""
- host = sys.modules.get("api_server")
- if host is not None and hasattr(host, name):
- return getattr(host, name)
- return fallback
+from src.api._compat import host_attr as _host_attr
# ============================================================================
diff --git a/agent/src/api/security.py b/agent/src/api/security.py
index 6812c0563..9d20e4862 100644
--- a/agent/src/api/security.py
+++ b/agent/src/api/security.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import hmac
import ipaddress
import os
-import sys
import urllib.parse
from pathlib import Path
from typing import List, Optional
@@ -14,37 +13,21 @@ from fastapi import HTTPException, Query, Request, Security, status
from fastapi.responses import JSONResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
-
-# ============================================================================
-# Monkeypatch compatibility layer
-# ============================================================================
-
-
-def _host_attr(name: str, fallback):
- """Read a compatibility attribute from ``api_server`` when present.
-
- Tests monkeypatch ``api_server._API_KEY`` (and similar). Route modules
- resolve dependencies via ``sys.modules["api_server"]``, so the patched
- value lives on the *host* module, not on this extracted module.
- """
- host = sys.modules.get("api_server")
- if host is not None and hasattr(host, name):
- return getattr(host, name)
- return fallback
+from src.api._compat import host_attr as _host_attr
# ============================================================================
# Constants
# ============================================================================
-_DEFAULT_CORS_ORIGINS = [
+_DEFAULT_CORS_ORIGINS: tuple[str, ...] = (
"http://localhost:3000",
"http://localhost:5173",
"http://localhost:8000",
"http://127.0.0.1:3000",
"http://127.0.0.1:5173",
"http://127.0.0.1:8000",
-]
+)
_DEFAULT_LOOPBACK_HOSTS = frozenset({
"localhost",
diff --git a/agent/src/api/state.py b/agent/src/api/state.py
index bcbbebf77..cf0386463 100644
--- a/agent/src/api/state.py
+++ b/agent/src/api/state.py
@@ -3,33 +3,13 @@
from __future__ import annotations
import os
-import sys
from fastapi import HTTPException
+from src.api._compat import host_attr as _host_attr, set_host_attr as _set_host_attr
from src.api.helpers import RUNS_DIR, SESSIONS_DIR
-# ============================================================================
-# Monkeypatch compatibility layer
-# ============================================================================
-
-
-def _host_attr(name: str, fallback):
- """Read a compatibility attribute from ``api_server`` when present."""
- host = sys.modules.get("api_server")
- if host is not None and hasattr(host, name):
- return getattr(host, name)
- return fallback
-
-
-def _set_host_attr(name: str, value) -> None:
- """Write a compatibility attribute onto ``api_server`` when present."""
- host = sys.modules.get("api_server")
- if host is not None:
- setattr(host, name, value)
-
-
# ============================================================================
# Global singletons
# ============================================================================
@@ -49,12 +29,10 @@ def _get_session_service():
"""Lazy-init session service when ENABLE_SESSION_RUNTIME=true."""
global _session_service
- host = sys.modules.get("api_server")
- if host is not None and hasattr(host, "_session_service"):
- host_val = getattr(host, "_session_service")
- if host_val is not None:
- return host_val
- elif _session_service is not None:
+ host_val = _host_attr("_session_service", None)
+ if host_val is not None:
+ return host_val
+ if _session_service is not None:
return _session_service
if os.getenv("ENABLE_SESSION_RUNTIME", "true").lower() != "true":
@@ -84,6 +62,7 @@ def _get_session_service():
event_bus=event_bus,
runs_dir=runs_dir,
)
+ _set_host_attr("_session_service", _session_service)
return _session_service
@@ -92,12 +71,10 @@ def _get_channel_runtime():
global _channel_runtime, _channel_bus, _channel_manager
# Check api_server host module first (monkeypatch compatibility).
- host = sys.modules.get("api_server")
- if host is not None and hasattr(host, "_channel_runtime"):
- host_rt = getattr(host, "_channel_runtime")
- if host_rt is not None:
- return host_rt
- elif _channel_runtime is not None:
+ host_rt = _host_attr("_channel_runtime", None)
+ if host_rt is not None:
+ return host_rt
+ if _channel_runtime is not None:
return _channel_runtime
from src.channels.bus.queue import MessageBus
diff --git a/agent/tests/test_api_infrastructure.py b/agent/tests/test_api_infrastructure.py
index 4deed4bcc..44cd3883a 100644
--- a/agent/tests/test_api_infrastructure.py
+++ b/agent/tests/test_api_infrastructure.py
@@ -2,8 +2,15 @@
from __future__ import annotations
+import pytest
+
import api_server
-from src.api import security, models, helpers, state
+from src.api import _compat, security, models, helpers, state
+
+
+# ============================================================================
+# Re-export identity tests
+# ============================================================================
def test_security_reexports():
@@ -46,7 +53,13 @@ def test_api_key_monkeypatch(monkeypatch):
def test_no_circular_imports():
import importlib
- for mod_name in ["src.api.security", "src.api.models", "src.api.helpers", "src.api.state"]:
+ for mod_name in [
+ "src.api._compat",
+ "src.api.security",
+ "src.api.models",
+ "src.api.helpers",
+ "src.api.state",
+ ]:
importlib.import_module(mod_name)
@@ -55,3 +68,185 @@ def test_api_server_is_thin_assembler():
source = inspect.getsource(api_server)
total_lines = len(source.splitlines())
assert total_lines < 400, f"api_server.py has {total_lines} lines, expected < 400"
+
+
+# ============================================================================
+# _compat shared module tests
+# ============================================================================
+
+
+def test_compat_host_attr_reads_api_server():
+ """host_attr should read attributes from the api_server module when present."""
+ assert _compat.host_attr("_API_KEY", "fallback") is not None or True
+
+
+def test_compat_host_attr_fallback():
+ """host_attr should return fallback when attribute is missing."""
+ assert _compat.host_attr("_nonexistent_attr_xyz", "default") == "default"
+
+
+def test_compat_set_host_attr():
+ """set_host_attr should write attributes onto the api_server module."""
+ _compat.set_host_attr("_test_compat_marker", 42)
+ assert api_server._test_compat_marker == 42
+ del api_server._test_compat_marker
+
+
+# ============================================================================
+# security._parse_cors_origins edge cases
+# ============================================================================
+
+
+def test_parse_cors_origins_none_returns_defaults():
+ result = security._parse_cors_origins(None)
+ assert result == list(security._DEFAULT_CORS_ORIGINS)
+
+
+def test_parse_cors_origins_empty_returns_defaults():
+ result = security._parse_cors_origins("")
+ assert result == list(security._DEFAULT_CORS_ORIGINS)
+ result = security._parse_cors_origins(" ")
+ assert result == list(security._DEFAULT_CORS_ORIGINS)
+
+
+def test_parse_cors_origins_custom():
+ result = security._parse_cors_origins("http://a.com, http://b.com")
+ assert result == ["http://a.com", "http://b.com"]
+
+
+def test_parse_cors_origins_wildcard_raises():
+ with pytest.raises(RuntimeError, match="not allowed"):
+ security._parse_cors_origins("*")
+
+
+def test_default_cors_origins_is_immutable():
+ assert isinstance(security._DEFAULT_CORS_ORIGINS, tuple)
+
+
+# ============================================================================
+# security._host_without_port edge cases
+# ============================================================================
+
+
+def test_host_without_port_plain():
+ assert security._host_without_port("localhost:8080") == "localhost"
+
+
+def test_host_without_port_ipv6():
+ assert security._host_without_port("[::1]:8080") == "[::1]"
+
+
+def test_host_without_port_ipv6_no_port():
+ assert security._host_without_port("[::1]") == "[::1]"
+
+
+def test_host_without_port_empty():
+ assert security._host_without_port("") == ""
+
+
+def test_host_without_port_trailing_dot():
+ assert security._host_without_port("example.com.") == "example.com"
+
+
+# ============================================================================
+# helpers._validate_path_param security tests
+# ============================================================================
+
+
+def test_validate_path_param_valid():
+ helpers._validate_path_param("abc-123_test", "run_id")
+
+
+def test_validate_path_param_path_traversal():
+ from fastapi import HTTPException
+ with pytest.raises(HTTPException):
+ helpers._validate_path_param("..", "run_id")
+ with pytest.raises(HTTPException):
+ helpers._validate_path_param("foo/../bar", "run_id")
+ with pytest.raises(HTTPException):
+ helpers._validate_path_param("foo/..", "run_id")
+
+
+def test_validate_path_param_empty():
+ from fastapi import HTTPException
+ with pytest.raises(HTTPException):
+ helpers._validate_path_param("", "run_id")
+
+
+def test_validate_path_param_special_chars():
+ from fastapi import HTTPException
+ with pytest.raises(HTTPException):
+ helpers._validate_path_param("foo bar", "run_id")
+ with pytest.raises(HTTPException):
+ helpers._validate_path_param("foo\x00bar", "run_id")
+
+
+# ============================================================================
+# helpers._is_spa_html_route tests
+# ============================================================================
+
+
+def test_is_spa_html_route_correlation():
+ assert helpers._is_spa_html_route("/correlation") is True
+
+
+def test_is_spa_html_route_runs_detail():
+ assert helpers._is_spa_html_route("/runs/abc123") is True
+ assert helpers._is_spa_html_route("/runs/abc123/") is True
+
+
+def test_is_spa_html_route_runs_subpath_not_spa():
+ assert helpers._is_spa_html_route("/runs/abc123/code") is False
+ assert helpers._is_spa_html_route("/runs/abc123/pine") is False
+
+
+def test_is_spa_html_route_runs_collection_not_spa():
+ assert helpers._is_spa_html_route("/runs") is False
+
+
+def test_is_spa_html_route_unknown():
+ assert helpers._is_spa_html_route("/api/health") is False
+
+
+# ============================================================================
+# helpers dotenv round-trip
+# ============================================================================
+
+
+def test_read_write_env_values_roundtrip(tmp_path):
+ env_file = tmp_path / ".env"
+ env_file.write_text("# comment\nFOO=bar\nBAZ=qux\n", encoding="utf-8")
+
+ values = helpers._read_env_values(env_file)
+ assert values == {"FOO": "bar", "BAZ": "qux"}
+
+ helpers._write_env_values(env_file, {"FOO": "updated", "NEW_KEY": "new_val"})
+ updated = helpers._read_env_values(env_file)
+ assert updated["FOO"] == "updated"
+ assert updated["NEW_KEY"] == "new_val"
+ assert updated["BAZ"] == "qux"
+
+
+def test_strip_env_value_quotes():
+ assert helpers._strip_env_value('"hello"') == "hello"
+ assert helpers._strip_env_value("'hello'") == "hello"
+
+
+def test_strip_env_value_inline_comment():
+ assert helpers._strip_env_value("value # comment") == "value"
+
+
+# ============================================================================
+# state._get_session_service writeback
+# ============================================================================
+
+
+def test_session_service_writeback_to_host(monkeypatch):
+ """_get_session_service should write back to api_server for monkeypatch compat."""
+ monkeypatch.setenv("ENABLE_SESSION_RUNTIME", "false")
+ import src.api.state as state_mod
+ state_mod._session_service = None
+ _compat.set_host_attr("_session_service", None)
+
+ result = state_mod._get_session_service()
+ assert result is None