"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(providers): log resolved dotenv source
Teerapat Vatpitak5684d5fe0993
diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 4794a3630..f607ddaef 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -3,9 +3,11 @@from __future__ import annotationsimport json+import loggingimport osfrom pathlib import Pathfrom typing import Any, Dict, Optional+from urllib.parse import urlsplittry:from dotenv import load_dotenv@@ -95,9 +97,61 @@ _ENV_CANDIDATES = [Path.cwd() / ".env",]+# Index-aligned with _ENV_CANDIDATES. CWE-209: never log the absolute+# .env path (it leaks the OS username / home / CWD). The label names+# which slot won - the entire P08 R1 signal - using compile-time+# constants only.+_ENV_LABELS = ("~/.vibe-trading/.env", "<AGENT_DIR>/.env", "<CWD>/.env")++logger = logging.getLogger(__name__)+_dotenv_loaded: bool = False+def _redact_env_source(loaded: Path | None) -> str:+ """Map a resolved `.env` candidate to a stable, leak-free label.++ Returns a symbolic slot label (never the absolute path) so a stale+ or shadowed `.env` stays diagnosable without exposing the OS+ username, home, or CWD (CWE-209). A candidate outside the fixed+ list (e.g. one injected by a test) collapses to a generic+ placeholder rather than echoing a real path.+ """+ if loaded is None:+ return "none (no .env file found)"+ for label, candidate in zip(_ENV_LABELS, _ENV_CANDIDATES):+ if loaded == candidate:+ return label+ return "<.env>"+++def _redact_base_url_for_log(raw: str | None) -> str:+ """Return a diagnostic-safe base URL label for logs."""+ if not raw or not raw.strip():+ return "(unset)"++ try:+ parsed = urlsplit(raw.strip())+ except ValueError:+ return "<base-url>"++ if not parsed.scheme or not parsed.hostname:+ return "<base-url>"++ host = parsed.hostname+ if ":" in host and not host.startswith("["):+ host = f"[{host}]"++ try:+ port = parsed.port+ except ValueError:+ port = None+ if port is not None:+ host = f"{host}:{port}"++ return f"{parsed.scheme}://{host}"++def _load_env_file(path: Path) -> None:"""Load a single .env file into os.environ (setdefault, no override)."""if load_dotenv is not None:@@ -118,11 +172,23 @@ def _ensure_dotenv() -> None:global _dotenv_loadedif _dotenv_loaded:return+ loaded = Nonefor candidate in _ENV_CANDIDATES:if candidate.exists():_load_env_file(candidate)+ loaded = candidatebreak_dotenv_loaded = True+ # P08 R1: one-time, behavior-preserving diagnostic so a stale or+ # shadowed .env is observable instead of costing hours. The path is+ # redacted to a symbolic slot label and the API key is never logged.+ logger.info(+ "dotenv resolved from %s | provider=%s model=%s base=%s",+ _redact_env_source(loaded),+ os.getenv("LANGCHAIN_PROVIDER", "(unset)"),+ os.getenv("LANGCHAIN_MODEL_NAME", "(unset)"),+ _redact_base_url_for_log(os.getenv("OPENAI_BASE_URL") or os.getenv("OPENAI_API_BASE")),+ )def _sync_provider_env() -> None:diff --git a/agent/tests/test_dotenv_observability.py b/agent/tests/test_dotenv_observability.pynew file mode 100644index 000000000..624411166--- /dev/null+++ b/agent/tests/test_dotenv_observability.py@@ -0,0 +1,92 @@+"""Regression test for P08 (R1) — .env resolution must be observable.++A stale / shadowed .env silently won the config for the whole process with+zero diagnostic, costing hours. _ensure_dotenv now emits one behavior-+preserving INFO line naming the resolved slot via a redacted symbolic+label (or "none") plus the resolved provider/model/base. The absolute+path, OS username, and API key are never logged (CWE-209).+"""++from __future__ import annotations++import getpass+import logging+from pathlib import Path++import pytest++import src.providers.llm as llm++LOGGER = "src.providers.llm"+++def fresh(monkeypatch):+ # Drop the once-per-process latch so the resolver actually runs.+ monkeypatch.setattr(llm, "_dotenv_loaded", False)+++def test_logs_redacted_label_not_path(tmp_path, fresh, monkeypatch, caplog):+ """The resolved slot is logged as a symbolic label; the absolute path+ and OS username never appear (CWE-209)."""+ env = tmp_path / ".env"+ env.write_text("FOO=bar\n", encoding="utf-8")+ monkeypatch.setattr(llm, "_ENV_CANDIDATES", [env])+ monkeypatch.setattr(llm, "_ENV_LABELS", ("<TEST_SLOT>",))+ with caplog.at_level(logging.INFO, logger=LOGGER):+ llm._ensure_dotenv()+ msg = "\n".join(r.getMessage() for r in caplog.records)+ assert "dotenv resolved from" in msg+ assert "<TEST_SLOT>" in msg # redacted slot label is logged+ assert str(env) not in msg # absolute path never logged+ assert str(tmp_path) not in msg+ assert getpass.getuser() not in msg # OS username never leaks+ assert "sk-" not in msg # key must never be logged+++def test_redact_env_source_maps_real_candidates():+ """_redact_env_source maps fixed candidates to stable leak-free+ labels, None to the no-file sentinel, and any unknown path to a+ generic placeholder (never the real path)."""+ # The home slot never collides with AGENT_DIR / CWD -> exact mapping.+ assert llm._redact_env_source(llm._ENV_CANDIDATES[0]) == llm._ENV_LABELS[0]+ # Every fixed candidate resolves to a known redacted label. When CWD+ # == AGENT_DIR the earlier slot legitimately wins (matches the+ # first-match order of _ensure_dotenv) — still leak-free.+ for candidate in llm._ENV_CANDIDATES:+ result = llm._redact_env_source(candidate)+ assert result in llm._ENV_LABELS+ assert str(candidate) not in result+ assert llm._redact_env_source(None) == "none (no .env file found)"+ unknown = Path("/some/secret/home/user/.env")+ assert llm._redact_env_source(unknown) == "<.env>"+ assert str(unknown) not in llm._redact_env_source(unknown)+++def test_logs_none_when_no_env_found(tmp_path, fresh, monkeypatch, caplog):+ monkeypatch.setattr(llm, "_ENV_CANDIDATES", [tmp_path / "does-not-exist.env"])+ with caplog.at_level(logging.INFO, logger=LOGGER):+ llm._ensure_dotenv()+ msg = "\n".join(r.getMessage() for r in caplog.records)+ assert "none (no .env file found)" in msg+++def test_logs_redacted_base_url_without_credentials(tmp_path, fresh, monkeypatch, caplog):+ monkeypatch.setattr(llm, "_ENV_CANDIDATES", [tmp_path / "does-not-exist.env"])+ monkeypatch.setenv("OPENAI_BASE_URL", "https://[email protected]:8443/v1?api_key=sk-hidden")+ with caplog.at_level(logging.INFO, logger=LOGGER):+ llm._ensure_dotenv()+ msg = "\n".join(r.getMessage() for r in caplog.records)+ assert "base=https://example.com:8443" in msg+ assert "sk-secret" not in msg+ assert "sk-hidden" not in msg+ assert "api_key" not in msg+++def test_latch_still_skips_second_call(tmp_path, fresh, monkeypatch, caplog):+ """Behavior preserved: still loads once per process (no log on re-entry)."""+ monkeypatch.setattr(llm, "_ENV_CANDIDATES", [tmp_path / "nope.env"])+ llm._ensure_dotenv()+ with caplog.at_level(logging.INFO, logger=LOGGER):+ llm._ensure_dotenv() # latched -> early return, no new log+ assert not [r for r in caplog.records if "dotenv resolved" in r.getMessage()]