Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(security): enforce path containment in safe_path + sandbox journal/shadow tools

warren6180a38ba5ef063
diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.py
index a73c1ff22..f1d3340e0 100644
--- a/agent/src/tools/path_utils.py
+++ b/agent/src/tools/path_utils.py
@@ -1,18 +1,81 @@
-"""Shared path utilities for tools."""
+"""Path safety helpers used by file-access tools.
+
+Two helpers, two threat models:
+
+* `safe_path(p, workdir)` — tool-controlled sandbox. Resolves `p` under
+ `workdir` and rejects any escape. Used by `read_file` / `write_file` /
+ `edit_file` where the LLM must stay inside the current run dir.
+
+* `safe_user_path(p)` — user-supplied broker files. Accepts any path inside
+ the user's home directory or the project CWD, rejects UNC and system
+ paths. Used by `analyze_trade_journal` and the Shadow Account tools
+ where the journal CSV is legitimately anywhere in the user's filesystem.
+
+Both raise ``ValueError`` on rejection — callers already expect this.
+"""
from __future__ import annotations
from pathlib import Path
+def _rejects_unc(p: str) -> None:
+ """Raise ValueError if `p` starts with a UNC share prefix."""
+ if p.startswith("\\\\") or p.startswith("//"):
+ raise ValueError(f"UNC paths are not allowed: {p!r}")
+
+
def safe_path(p: str, workdir: Path) -> Path:
- """Resolve a path relative to the workspace root.
+ """Resolve `p` under `workdir` and ensure it stays inside.
Args:
- p: Relative or absolute path.
- workdir: Workspace root directory.
+ p: User-supplied path (relative or absolute).
+ workdir: Workspace root. `p` must resolve to a location inside.
Returns:
- Resolved absolute path.
+ Absolute resolved path inside `workdir`.
+
+ Raises:
+ ValueError: If `p` uses a UNC share, or its resolved form escapes
+ `workdir`. Callers surface this back to the LLM as a tool error.
"""
- return (workdir / p).resolve()
+ _rejects_unc(p)
+ base = Path(workdir).resolve()
+ resolved = (base / p).resolve()
+ try:
+ resolved.relative_to(base)
+ except ValueError as exc:
+ raise ValueError(f"Path {p!r} escapes workspace {base}") from exc
+ return resolved
+
+
+def safe_user_path(p: str) -> Path:
+ """Validate a user-supplied absolute file path.
+
+ Used when the LLM passes a broker-export path the user referenced in
+ natural language. The path may legitimately live anywhere the user
+ keeps files (Desktop, Downloads, a project subdirectory), so the
+ envelope is HOME ∪ CWD rather than a tight sandbox.
+
+ Args:
+ p: User-supplied path. `~` expansion supported.
+
+ Returns:
+ Absolute resolved path.
+
+ Raises:
+ ValueError: If `p` is a UNC share, or resolves outside both the
+ user's home directory and the current working directory.
+ """
+ _rejects_unc(p)
+ resolved = Path(p).expanduser().resolve()
+
+ home = Path.home().resolve()
+ cwd = Path.cwd().resolve()
+
+ if resolved.is_relative_to(home) or resolved.is_relative_to(cwd):
+ return resolved
+
+ raise ValueError(
+ f"Path {p!r} is outside the user home directory and project directory"
+ )
diff --git a/agent/src/tools/shadow_account_tool.py b/agent/src/tools/shadow_account_tool.py
index be168b331..71060be73 100644
--- a/agent/src/tools/shadow_account_tool.py
+++ b/agent/src/tools/shadow_account_tool.py
@@ -17,6 +17,7 @@ from pathlib import Path
from typing import Any
from src.agent.tools import BaseTool
+from src.tools.path_utils import safe_user_path
from src.shadow_account import (
extract_shadow_profile,
load_profile,
@@ -38,6 +39,18 @@ def _ok(**payload: Any) -> str:
return json.dumps({"status": "ok", **payload}, ensure_ascii=False, default=str)
+def _validate_optional_journal_path(raw: Any) -> str | None:
+ """Validate a journal_path kwarg that may be missing/empty.
+
+ Returns the resolved path string, or None when the caller didn't pass
+ one. Raises ValueError (already the contract of `safe_user_path`) when
+ the path escapes the user envelope.
+ """
+ if not raw:
+ return None
+ return str(safe_user_path(raw))
+
+
# ---------------- Tool 1: extract ----------------
class ExtractShadowStrategyTool(BaseTool):
@@ -77,6 +90,10 @@ class ExtractShadowStrategyTool(BaseTool):
journal_path = kwargs.get("journal_path")
if not journal_path:
return _err("journal_path is required")
+ try:
+ journal_path = str(safe_user_path(journal_path))
+ except ValueError as exc:
+ return _err(str(exc))
try:
profile = extract_shadow_profile(
journal_path,
@@ -162,13 +179,17 @@ class RunShadowBacktestTool(BaseTool):
window_start = kwargs.get("window_start") or (today - timedelta(days=365)).isoformat()
markets = tuple(kwargs.get("markets") or ("china_a", "hk", "us", "crypto"))
+ try:
+ journal_path = _validate_optional_journal_path(kwargs.get("journal_path"))
+ except ValueError as exc:
+ return _err(str(exc))
try:
result = run_shadow_backtest(
profile,
window_start=window_start,
window_end=window_end,
markets=markets,
- journal_path=kwargs.get("journal_path"),
+ journal_path=journal_path,
)
except ValueError as exc:
return _err(str(exc))
@@ -223,6 +244,11 @@ class RenderShadowReportTool(BaseTool):
except FileNotFoundError as exc:
return _err(str(exc))
+ try:
+ journal_path = _validate_optional_journal_path(kwargs.get("journal_path"))
+ except ValueError as exc:
+ return _err(str(exc))
+
result = load_cached_result(profile.shadow_id)
if result is None:
today = date.today()
@@ -233,7 +259,7 @@ class RenderShadowReportTool(BaseTool):
profile,
window_start=window_start,
window_end=window_end,
- journal_path=kwargs.get("journal_path"),
+ journal_path=journal_path,
)
except Exception as exc: # pragma: no cover — defensive
logger.warning("backtest failed during report render: %s", exc)
diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.py
index dfb33a007..71ae0a07c 100644
--- a/agent/src/tools/trade_journal_tool.py
+++ b/agent/src/tools/trade_journal_tool.py
@@ -20,6 +20,7 @@ from typing import Any
import pandas as pd
from src.agent.tools import BaseTool
+from src.tools.path_utils import safe_user_path
from src.tools.trade_journal_parsers import (
TradeRecord,
parse_file,
@@ -406,7 +407,10 @@ def analyze_trade_journal(file_path: str, analysis_type: str = "full", filter_ex
JSON string. Keys: status, file, format_detected, total_records,
date_range, market, profile / behavior (when applicable).
"""
- path = Path(file_path)
+ try:
+ path = safe_user_path(file_path)
+ except ValueError as exc:
+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
if not path.exists():
return json.dumps({"status": "error", "error": f"File not found: {file_path}"}, ensure_ascii=False)
if path.suffix.lower() not in _ALLOWED_EXT:
diff --git a/agent/tests/test_path_safety.py b/agent/tests/test_path_safety.py
new file mode 100644
index 000000000..5ace4d9b8
--- /dev/null
+++ b/agent/tests/test_path_safety.py
@@ -0,0 +1,111 @@
+"""Tests for path safety helpers in src.tools.path_utils."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.tools.path_utils import safe_path, safe_user_path
+
+
+# ---------------------------------------------------------------------------
+# safe_path — tool-controlled sandbox under a fixed workdir
+# ---------------------------------------------------------------------------
+
+class TestSafePath:
+ def test_relative_path_resolves_under_workdir(self, tmp_path: Path):
+ result = safe_path("notes.md", tmp_path)
+ assert result == (tmp_path / "notes.md").resolve()
+
+ def test_nested_relative_path_ok(self, tmp_path: Path):
+ result = safe_path("sub/dir/file.txt", tmp_path)
+ assert result == (tmp_path / "sub" / "dir" / "file.txt").resolve()
+
+ def test_parent_traversal_rejected(self, tmp_path: Path):
+ with pytest.raises(ValueError, match="escapes workspace"):
+ safe_path("../../etc/passwd", tmp_path)
+
+ def test_absolute_path_outside_workdir_rejected(self, tmp_path: Path):
+ outside = tmp_path.parent / "elsewhere.txt"
+ with pytest.raises(ValueError, match="escapes workspace"):
+ safe_path(str(outside), tmp_path)
+
+ def test_unc_path_rejected(self, tmp_path: Path):
+ with pytest.raises(ValueError, match="UNC paths"):
+ safe_path("\\\\server\\share\\evil.csv", tmp_path)
+
+ def test_unix_double_slash_rejected(self, tmp_path: Path):
+ with pytest.raises(ValueError, match="UNC paths"):
+ safe_path("//server/share/evil.csv", tmp_path)
+
+ def test_normalizes_redundant_segments(self, tmp_path: Path):
+ (tmp_path / "a").mkdir()
+ result = safe_path("a/./file.txt", tmp_path)
+ assert result == (tmp_path / "a" / "file.txt").resolve()
+
+
+# ---------------------------------------------------------------------------
+# safe_user_path — user-supplied broker files, HOME ∪ CWD envelope
+# ---------------------------------------------------------------------------
+
+class TestSafeUserPath:
+ def test_home_file_accepted(self, tmp_path: Path, monkeypatch):
+ # Pretend HOME is tmp_path so we can control the envelope
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ target = tmp_path / "Desktop" / "broker.csv"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.touch()
+
+ result = safe_user_path(str(target))
+ assert result == target.resolve()
+
+ def test_tilde_expansion_works(self, tmp_path: Path, monkeypatch):
+ # Both Path.home() and Path.expanduser() read environment variables,
+ # so set HOME / USERPROFILE directly rather than patching Path.home.
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ target = tmp_path / "journal.csv"
+ target.touch()
+
+ result = safe_user_path("~/journal.csv")
+ assert result == target.resolve()
+
+ def test_cwd_file_accepted(self, tmp_path: Path, monkeypatch):
+ # HOME is far away; CWD is tmp_path
+ other = tmp_path.parent / "somewhere_else"
+ other.mkdir(exist_ok=True)
+ monkeypatch.setattr(Path, "home", lambda: other)
+ monkeypatch.chdir(tmp_path)
+
+ target = tmp_path / "local.csv"
+ target.touch()
+ result = safe_user_path("local.csv")
+ assert result == target.resolve()
+
+ def test_system_path_outside_envelope_rejected(self, tmp_path: Path, monkeypatch):
+ # HOME and CWD both inside tmp_path
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ # /etc is outside both
+ with pytest.raises(ValueError, match="outside the user home"):
+ safe_user_path("/etc/passwd")
+
+ def test_parent_traversal_from_cwd_rejected(self, tmp_path: Path, monkeypatch):
+ deep = tmp_path / "deep" / "cwd"
+ deep.mkdir(parents=True)
+ monkeypatch.setattr(Path, "home", lambda: deep)
+ monkeypatch.chdir(deep)
+
+ # Resolve back above both HOME and CWD
+ with pytest.raises(ValueError, match="outside the user home"):
+ safe_user_path("../../../../../etc/passwd")
+
+ def test_unc_path_rejected(self):
+ with pytest.raises(ValueError, match="UNC paths"):
+ safe_user_path("\\\\evil-server\\share\\passwd.csv")
+
+ def test_unix_double_slash_rejected(self):
+ with pytest.raises(ValueError, match="UNC paths"):
+ safe_user_path("//evil-server/share/passwd.csv")