Skip to content

"Vibe-Trading: Your Personal Trading Agent"

[security] fix(live): contain mandate proposal identifiers (#256)

Hinotobi43d33a036ff0
diff --git a/agent/src/live/mandate/commit.py b/agent/src/live/mandate/commit.py
index a31c6dec8..49c397837 100644
--- a/agent/src/live/mandate/commit.py
+++ b/agent/src/live/mandate/commit.py
@@ -30,6 +30,7 @@ import hashlib
import json
import logging
import os
+import re
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -46,6 +47,7 @@ DEFAULT_MANDATE_LIFETIME_DAYS = 30
_MANDATE_FILENAME = "mandate.json"
_PROPOSALS_DIRNAME = "proposals"
_CONSENT_DIRNAME = "consent"
+_PROPOSAL_ID_RE = re.compile(r"^mp_[0-9a-f]{32}$")
#: Maps every accepted alias of a clamped limit to its CANONICAL name. The
#: proposal profile, the ceiling snapshot, and the clamp in
@@ -150,6 +152,19 @@ def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
os.replace(tmp, path)
+def _proposal_path(broker: str, proposal_id: str) -> Path:
+ """Return the contained proposal path for a valid opaque proposal id."""
+ if not _PROPOSAL_ID_RE.fullmatch(proposal_id):
+ raise ValueError("proposal_id must be a bare mp_<32 hex> identifier")
+ base = _proposals_dir(broker).resolve()
+ path = (base / f"{proposal_id}.json").resolve()
+ try:
+ path.relative_to(base)
+ except ValueError as exc: # pragma: no cover - regex is the primary guard
+ raise ValueError("proposal_id escapes the proposals directory") from exc
+ return path
+
+
# ---------------------------------------------------------------------------
# PROPOSE state — proposal persistence (read-only; grants no authority)
# ---------------------------------------------------------------------------
@@ -179,13 +194,17 @@ def save_proposal(proposal: Mapping[str, Any]) -> None:
broker = str((proposal.get("account") or {}).get("broker") or "").strip()
if not broker:
raise ValueError("proposal must carry account.broker")
- path = _proposals_dir(broker) / f"{proposal_id}.json"
+ path = _proposal_path(broker, proposal_id)
_atomic_write_json(path, dict(proposal))
def _load_proposal(broker: str, proposal_id: str) -> dict[str, Any] | None:
"""Load a persisted proposal, or ``None`` when absent/unreadable."""
- path = _proposals_dir(broker) / f"{proposal_id}.json"
+ try:
+ path = _proposal_path(broker, proposal_id)
+ except ValueError as exc:
+ logger.warning("proposal %s for %s is invalid: %s", proposal_id, broker, exc)
+ return None
if not path.is_file():
return None
try:
@@ -199,8 +218,8 @@ def _load_proposal(broker: str, proposal_id: str) -> dict[str, Any] | None:
def _invalidate_proposal(broker: str, proposal_id: str) -> None:
"""Delete a proposal so it can never be committed twice (idempotency)."""
try:
- (_proposals_dir(broker) / f"{proposal_id}.json").unlink()
- except FileNotFoundError:
+ _proposal_path(broker, proposal_id).unlink()
+ except (FileNotFoundError, ValueError):
pass
diff --git a/agent/tests/test_consent_commit.py b/agent/tests/test_consent_commit.py
index de81f157c..4fde5c27f 100644
--- a/agent/tests/test_consent_commit.py
+++ b/agent/tests/test_consent_commit.py
@@ -252,7 +252,7 @@ def _save_handcrafted_proposal(
Lets a test exercise commit-time validation against a profile the clamping
proposer would never emit (e.g. one that breaches an alias-keyed ceiling).
"""
- proposal_id = "mp_handcrafted_h9"
+ proposal_id = "mp_" + "9" * 32
save_proposal(
{
"type": "mandate.proposal",
diff --git a/agent/tests/test_mandate_commit_security.py b/agent/tests/test_mandate_commit_security.py
new file mode 100644
index 000000000..6968e4951
--- /dev/null
+++ b/agent/tests/test_mandate_commit_security.py
@@ -0,0 +1,113 @@
+"""Security regressions for live mandate proposal commit boundaries."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+import src.live.paths as paths
+from src.live.mandate.commit import CommitError, commit_mandate, save_proposal
+
+
+def _proposal(proposal_id: str) -> dict[str, object]:
+ """Return a minimal valid proposal payload for commit_mandate."""
+ return {
+ "proposal_id": proposal_id,
+ "account": {"broker": "robinhood"},
+ "ceilings": {
+ "max_order_notional_usd": 100.0,
+ "max_total_exposure_usd": 500.0,
+ "max_trades_per_day": 2,
+ "leverage": "none",
+ },
+ "profiles": [
+ {
+ "ordinal": 1,
+ "account_funding_usd": 500.0,
+ "max_order_usd": 100.0,
+ "max_total_exposure_usd": 500.0,
+ "daily_trade_cap": 2,
+ "leverage": "none",
+ "instruments": ["equity"],
+ "asset_classes": ["us_equity"],
+ "exclude_symbols": ["GME"],
+ }
+ ],
+ }
+
+
+def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point live-channel state at a temp runtime root."""
+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)
+ return tmp_path
+
+
+def test_commit_mandate_accepts_saved_bare_proposal_id(live_runtime: Path) -> None:
+ """The normal propose -> commit flow still works for opaque proposal ids."""
+ proposal_id = "mp_" + "a" * 32
+ save_proposal(_proposal(proposal_id))
+
+ result = commit_mandate(
+ proposal_id=proposal_id,
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ account_ref="acct-ok",
+ )
+
+ assert result["broker"] == "robinhood"
+ mandate_path = live_runtime / "live" / "robinhood" / "mandate.json"
+ assert mandate_path.is_file()
+ mandate = json.loads(mandate_path.read_text(encoding="utf-8"))
+ assert mandate["consent"]["account_ref"] == "acct-ok"
+
+
+def test_save_proposal_rejects_path_shaped_proposal_id(live_runtime: Path) -> None:
+ """Only generated mp_<hex> ids may be persisted as proposal records."""
+ with pytest.raises(ValueError, match="proposal_id"):
+ save_proposal(_proposal("../outside"))
+
+ assert not (live_runtime / "outside.json").exists()
+
+
+def test_commit_mandate_rejects_proposal_id_traversal_to_external_json(live_runtime: Path) -> None:
+ """A commit must not resolve proposal_id outside the broker proposals dir.
+
+ Before the fix, _load_proposal() joined ``proposal_id`` directly into
+ ``<live>/<broker>/proposals/{proposal_id}.json``. A path-shaped id could
+ escape that directory and load an attacker-controlled JSON file, then write
+ a live mandate from it.
+ """
+ from src.live.paths import broker_dir
+
+ proposals_dir = broker_dir("robinhood") / "proposals"
+ proposals_dir.mkdir(parents=True)
+
+ external = live_runtime / "uploads" / "crafted_proposal.json"
+ external.parent.mkdir(parents=True)
+ marker = "VIBE_TRAVERSAL_PROPOSAL_SHOULD_NOT_COMMIT"
+ payload = _proposal("mp_" + "b" * 32)
+ payload["profiles"][0]["exclude_symbols"] = [marker] # type: ignore[index]
+ external.write_text(json.dumps(payload), encoding="utf-8")
+
+ # commit_mandate appends ".json", so omit the suffix from the relative path.
+ traversal_id = os.path.relpath(external.with_suffix(""), proposals_dir)
+ assert ".." in Path(traversal_id).parts
+
+ with pytest.raises(CommitError, match="not live"):
+ commit_mandate(
+ proposal_id=traversal_id,
+ ordinal=1,
+ adjustments=None,
+ consent_ack=True,
+ broker="robinhood",
+ account_ref="acct-traversal",
+ )
+
+ mandate_path = broker_dir("robinhood") / "mandate.json"
+ assert not mandate_path.exists()