Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(security): contain MCP swarm run IDs (#258)

Hinotobi078ce6fcd22d
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index ac9bbb591..c40348540 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -1141,7 +1141,10 @@ def get_swarm_status(run_id: str) -> str:
run_id: The run ID returned by run_swarm.
"""
store = _get_swarm_store()
- run = store.load_run(run_id)
+ try:
+ run = store.load_run(run_id)
+ except ValueError as exc:
+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
if run is None:
return json.dumps({"status": "error", "error": f"Run {run_id} not found"}, ensure_ascii=False)
reconciled = store.reconcile_run(run, write=True)
@@ -1165,7 +1168,10 @@ def get_run_result(run_id: str) -> str:
run_id: The run ID returned by run_swarm.
"""
store = _get_swarm_store()
- run = store.load_run(run_id)
+ try:
+ run = store.load_run(run_id)
+ except ValueError as exc:
+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
if run is None:
return json.dumps({"status": "error", "error": f"Run {run_id} not found"}, ensure_ascii=False)
reconciled = store.reconcile_run(run, write=True)
@@ -1249,7 +1255,10 @@ def retry_run(run_id: str) -> str:
from src.swarm.runtime import SwarmRuntime
store = _get_swarm_store()
- loaded = store.load_run(run_id)
+ try:
+ loaded = store.load_run(run_id)
+ except ValueError as exc:
+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
if loaded is None:
return json.dumps({"status": "error", "error": f"Run {run_id} not found"}, ensure_ascii=False)
diff --git a/agent/src/swarm/store.py b/agent/src/swarm/store.py
index 556e6f72e..68feb3a65 100644
--- a/agent/src/swarm/store.py
+++ b/agent/src/swarm/store.py
@@ -136,8 +136,21 @@ class SwarmStore:
Returns:
Path to the run directory.
+
+ Raises:
+ ValueError: If run_id is empty, absolute, or path-shaped.
"""
- return self.base_dir / run_id
+ candidate = Path(run_id)
+ if (
+ not run_id.strip()
+ or candidate.is_absolute()
+ or len(candidate.parts) != 1
+ or any(part in {"", ".", ".."} for part in candidate.parts)
+ or "/" in run_id
+ or "\\" in run_id
+ ):
+ raise ValueError(f"run_id {run_id!r} must be a bare run directory name")
+ return self.base_dir / candidate.name
def create_run(self, run: SwarmRun) -> Path:
"""Create the directory structure for a new run and write initial state.
@@ -439,7 +452,7 @@ class SwarmStore:
def _reap_stale(self, run: SwarmRun, *, now: datetime) -> SwarmRun:
"""Pure: mark non-terminal tasks failed; derive run status from tasks."""
- from src.swarm.models import RunStatus, TaskStatus
+ from src.swarm.models import TaskStatus
terminal_task = {TaskStatus.completed, TaskStatus.failed, TaskStatus.cancelled}
last_event_at = _last_event_timestamp(self.run_dir(run.id) / "events.jsonl")
diff --git a/agent/tests/test_swarm_retry.py b/agent/tests/test_swarm_retry.py
index a272b2a74..b982e4741 100644
--- a/agent/tests/test_swarm_retry.py
+++ b/agent/tests/test_swarm_retry.py
@@ -42,6 +42,16 @@ def test_retry_run_missing_returns_error(tmp_path, monkeypatch):
assert "not found" in payload["error"].lower()
+def test_retry_run_rejects_path_shaped_run_id(tmp_path, monkeypatch):
+ store = SwarmStore(base_dir=tmp_path)
+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)
+
+ payload = json.loads(mcp_server.retry_run("../outside/victim"))
+
+ assert payload["status"] == "error"
+ assert "run_id" in payload["error"]
+
+
def test_retry_run_refuses_running_run(tmp_path, monkeypatch):
store = SwarmStore(base_dir=tmp_path)
run = _make_run("r-running", RunStatus.running)
diff --git a/agent/tests/test_swarm_status_hydration.py b/agent/tests/test_swarm_status_hydration.py
index 409146bf0..7d1c97df0 100644
--- a/agent/tests/test_swarm_status_hydration.py
+++ b/agent/tests/test_swarm_status_hydration.py
@@ -20,9 +20,8 @@ from __future__ import annotations
import asyncio
import json
+import os
from datetime import datetime, timedelta, timezone
-from unittest.mock import patch
-
import mcp_server
import src.swarm.runtime as rt
import src.swarm.store as store_mod
@@ -498,6 +497,35 @@ def test_get_swarm_status_auto_recovers_zombie(tmp_path, monkeypatch):
assert store.load_run(run.id).status == RunStatus.failed
+def test_mcp_run_result_rejects_path_shaped_run_id_without_outside_write(tmp_path, monkeypatch):
+ """MCP result lookups must not treat run_id as a filesystem path.
+
+ HTTP swarm routes already reject traversal-shaped run ids; the MCP status
+ tools need the same invariant because reads can reconcile and write run
+ state back to disk.
+ """
+ base_dir = tmp_path / "runs"
+ outside_dir = tmp_path / "outside" / "victim"
+ base_dir.mkdir()
+ outside_dir.mkdir(parents=True)
+ traversal_id = os.path.relpath(outside_dir, base_dir)
+ store = SwarmStore(base_dir=base_dir)
+ run = _base_run(traversal_id)
+ run.status = RunStatus.running
+ run.tasks[0] = run.tasks[0].model_copy(
+ update={"status": TaskStatus.completed, "summary": "SAFE_MCP_SWARM_MARKER"}
+ )
+ (outside_dir / "run.json").write_text(run.model_dump_json(indent=2), encoding="utf-8")
+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)
+
+ payload = json.loads(mcp_server.get_run_result(traversal_id))
+
+ assert payload["status"] == "error"
+ assert "run_id" in payload["error"]
+ assert not (outside_dir / "tasks").exists()
+ assert not (outside_dir / "events.jsonl").exists()
+
+
def test_run_swarm_emits_keepalive_every_poll(tmp_path, monkeypatch):
"""Each polling iteration must emit a progress notification, even if the
task counts haven't changed. Earlier dedup-on-message version emitted