Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(mcp): refuse directory symlinks and junctions during plan-time snapshot (#1211) (#1492)

Nurkhan Esenbek65ea670b9b05
diff --git a/changelog.d/0.75.1/1492.fixed.md b/changelog.d/0.75.1/1492.fixed.md
new file mode 100644
index 00000000..1c4ea734
--- /dev/null
+++ b/changelog.d/0.75.1/1492.fixed.md
@@ -0,0 +1,2 @@
+- **Refuse `.soup` and `.soup/mcp-runs` directory symlinks and junctions at plan time (#1211 by @kok-o in #1492).**
+ Following #1158 and #1171, `snapshot_config` now inspects the directory hierarchy with `refuse_linked_dirs` before creating directories or writing `config.yaml`, preventing config snapshot redirection outside the working directory when `.soup` or `.soup/mcp-runs` is a symbolic link or Windows junction.
diff --git a/docs/commands.md b/docs/commands.md
index 83f97100..a23f0e35 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -500,7 +500,7 @@ mutating tools (`train_start`, `export`) are gated behind `--allow-mutating`
**Execution Security & Boundaries:**
- **Flag Safety:** `--allow-execute` is default-off and dangerous. `--allow-mutating` alone can NEVER trigger subprocess execution.
- **One-Time Confirmation Tokens:** Authorization requires a server-issued random token. Client confirmation is UX-only; security relies entirely on the server-side token state.
-- **Subprocess Isolation:** Execution runs the Soup CLI as an isolated subprocess (`shell=False`, `stdin=DEVNULL`, `cwd` pinned to server startup directory). Child stdout/stderr is redirected to `.soup/mcp-runs/<run_id>.log` to avoid corrupting the MCP JSON-RPC stdio stream. Execution is refused if `.soup` or `.soup/mcp-runs` is a symbolic link or junction, or if a hard link exists at the run log path.
+- **Subprocess Isolation:** Execution runs the Soup CLI as an isolated subprocess (`shell=False`, `stdin=DEVNULL`, `cwd` pinned to server startup directory). Child stdout/stderr is redirected to `.soup/mcp-runs/<run_id>.log` to avoid corrupting the MCP JSON-RPC stdio stream. Planning (`train_start` config snapshot) and execution are refused if `.soup` or `.soup/mcp-runs` is a symbolic link or junction, or if a hard link exists at the run log path.
- **Concurrency & Disconnects:** Enforces 1 active execution at a time, gated on a persisted run whose process is still alive — so a **restarted** server does not launch a second training while a child from a previous server is still running, and a stale record whose process is gone never blocks execution. A `launching` record (committed before the child process exists, pid not yet written) blocks restart capacity too: it is indistinguishable from "about to spawn", so treating it as live is the safe direction after a crash in that window. If a server crash leaves that row behind, `soup mcp runs reconcile --expunge-launching` removes rows older than five minutes and prints every removed `run_id`; use `--older-than-seconds N` to choose another positive threshold. The command refuses the whole operation if any candidate records a PID that is still alive. Launches run in background (fire-and-forget). Disconnecting the MCP client does not terminate an already-running subprocess.
- **Config Snapshotting & Input Revalidation:** At plan time (`train_start`), the validated config is snapshotted to `.soup/mcp-runs/<run_id>/config.yaml`, and execution uses this snapshot rather than the original mutable config path. External protected inputs (such as datasets and model/checkpoint directories or files) are not frozen in the snapshot; instead, their content digests (computed via SHA-256 for regular files, or deterministic recursive content hashing over sorted relative file paths for directory trees, bounded by file-count and total-byte safety limits) are recorded at plan time and revalidated immediately before spawn. Modifying an external protected input between plan and execute invalidates the token. Modifying the original config path after planning has no effect because execution strictly uses the snapshotted config. Snapshotting freezes only the configuration itself, not external filesystem assets.
- **Every Local Input Is Pinned:** A train plan pins every local file or directory the run reads (model, datasets, reward/teacher/PRM models, reward `.py` files, unlearning sets); an input outside the working directory is refused at plan time, and an input that did not exist at plan time must still not exist at execution.
diff --git a/src/soup_cli/mcp_server/execution.py b/src/soup_cli/mcp_server/execution.py
index 7074d87e..ddd6c1fa 100644
--- a/src/soup_cli/mcp_server/execution.py
+++ b/src/soup_cli/mcp_server/execution.py
@@ -202,6 +202,13 @@ class ExecutionManager:
def snapshot_config(self, run_id: str, content: str) -> str:
"""Write the exact validated config content to .soup/mcp-runs/<run_id>/config.yaml."""
run_dir = Path(self.cwd) / ".soup" / "mcp-runs" / run_id
+ try:
+ refuse_linked_dirs(run_dir.parent, stop_at=self.cwd)
+ except OSError as exc:
+ raise ExecutionError(
+ "cannot plan: config snapshot directory or file is a "
+ "symbolic link or junction"
+ ) from exc
run_dir.mkdir(parents=True, exist_ok=True)
snapshot_file = str(run_dir / "config.yaml")
atomic_write_text(content, snapshot_file, field="config snapshot")
diff --git a/tests/test_issue1211_mcp_plan_symlink.py b/tests/test_issue1211_mcp_plan_symlink.py
new file mode 100644
index 00000000..6692714a
--- /dev/null
+++ b/tests/test_issue1211_mcp_plan_symlink.py
@@ -0,0 +1,182 @@
+"""#1211 — MCP plan time: snapshot_config writes through a symlinked or junctioned .soup directory.
+
+Follow-up to #1158 / #1171:
+PR #1171 hardened the MCP run log at execution time against a symlinked or
+junctioned directory above it. This suite covers the plan-time half:
+when snapshot_config copies the validated config into .soup/mcp-runs/<id>/config.yaml,
+any directory symlink or junction at .soup or .soup/mcp-runs must be refused
+before directory creation and write.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from soup_cli.mcp_server.execution import ExecutionError, ExecutionManager
+from soup_cli.mcp_server.registry import McpToolError, build_registry
+
+
+def _get_train_start_spec(manager: ExecutionManager):
+ specs = build_registry(allow_mutating=True, allow_execute=True, execution=manager)
+ for tool in specs:
+ if tool.name == "train_start":
+ return tool
+ raise KeyError("train_start")
+
+
+def _setup_valid_config(tmp_path: Path) -> Path:
+ data_file = tmp_path / "data.jsonl"
+ data_file.write_text('{"text": "example"}\n', encoding="utf-8")
+ cfg_file = tmp_path / "soup.yaml"
+ cfg_file.write_text(
+ "base: Qwen/Qwen2.5-0.5B\ntask: sft\ndata:\n train: data.jsonl\n",
+ encoding="utf-8",
+ )
+ return cfg_file
+
+
+class TestPlanTimeDirectorySymlinkAndJunction:
+ @pytest.mark.requires_symlink
+ def test_plan_refuses_a_directory_symlink_one_level_up(self, tmp_path, monkeypatch):
+ """A directory symlink at .soup/mcp-runs -> evildir is refused at plan time."""
+ monkeypatch.chdir(tmp_path)
+ _setup_valid_config(tmp_path)
+ manager = ExecutionManager()
+
+ evildir = tmp_path / "evildir"
+ evildir.mkdir()
+ soup_dir = tmp_path / ".soup"
+ soup_dir.mkdir()
+ os.symlink(str(evildir), str(soup_dir / "mcp-runs"), target_is_directory=True)
+
+ # 1. Direct snapshot_config refusal
+ with pytest.raises(ExecutionError, match="symbolic link or junction"):
+ manager.snapshot_config("planrun1", "dummy: content")
+ assert not any(evildir.iterdir())
+
+ # 2. End-to-end plan tool refusal
+ spec = _get_train_start_spec(manager)
+ with pytest.raises(McpToolError, match="symbolic link or junction"):
+ spec.handler({"config": "soup.yaml"})
+ assert not any(evildir.iterdir())
+
+ @pytest.mark.requires_symlink
+ def test_plan_refuses_symlink_at_soup_directory_itself(self, tmp_path, monkeypatch):
+ """A symlink at .soup itself is refused without creating mcp-runs in target."""
+ monkeypatch.chdir(tmp_path)
+ _setup_valid_config(tmp_path)
+ manager = ExecutionManager()
+
+ evildir = tmp_path / "evildir"
+ evildir.mkdir()
+ os.symlink(str(evildir), str(tmp_path / ".soup"), target_is_directory=True)
+
+ # 1. Direct snapshot_config refusal
+ with pytest.raises(ExecutionError, match="symbolic link or junction"):
+ manager.snapshot_config("planrun2", "dummy: content")
+ assert not (evildir / "mcp-runs").exists()
+ assert not any(evildir.iterdir())
+
+ # 2. End-to-end plan tool refusal
+ spec = _get_train_start_spec(manager)
+ with pytest.raises(McpToolError, match="symbolic link or junction"):
+ spec.handler({"config": "soup.yaml"})
+ assert not (evildir / "mcp-runs").exists()
+ assert not any(evildir.iterdir())
+
+ @pytest.mark.skipif(os.name != "nt", reason="Windows junctions only exist on Windows")
+ def test_plan_refuses_a_directory_junction_one_level_up(self, tmp_path, monkeypatch):
+ """A directory junction at .soup/mcp-runs -> evildir is refused at plan time."""
+ import _winapi
+
+ monkeypatch.chdir(tmp_path)
+ _setup_valid_config(tmp_path)
+ manager = ExecutionManager()
+
+ evildir = tmp_path / "evildir"
+ evildir.mkdir()
+ soup_dir = tmp_path / ".soup"
+ soup_dir.mkdir()
+ _winapi.CreateJunction(str(evildir), str(soup_dir / "mcp-runs"))
+
+ with pytest.raises(ExecutionError, match="symbolic link or junction"):
+ manager.snapshot_config("junctionrun1", "dummy: content")
+ assert not any(evildir.iterdir())
+
+ spec = _get_train_start_spec(manager)
+ with pytest.raises(McpToolError, match="symbolic link or junction"):
+ spec.handler({"config": "soup.yaml"})
+ assert not any(evildir.iterdir())
+
+ @pytest.mark.skipif(os.name != "nt", reason="Windows junctions only exist on Windows")
+ def test_plan_refuses_junction_at_soup_directory_itself(self, tmp_path, monkeypatch):
+ """A junction at .soup itself is refused without creating mcp-runs in target."""
+ import _winapi
+
+ monkeypatch.chdir(tmp_path)
+ _setup_valid_config(tmp_path)
+ manager = ExecutionManager()
+
+ evildir = tmp_path / "evildir"
+ evildir.mkdir()
+ _winapi.CreateJunction(str(evildir), str(tmp_path / ".soup"))
+
+ with pytest.raises(ExecutionError, match="symbolic link or junction"):
+ manager.snapshot_config("junctionrun2", "dummy: content")
+ assert not (evildir / "mcp-runs").exists()
+ assert not any(evildir.iterdir())
+
+ spec = _get_train_start_spec(manager)
+ with pytest.raises(McpToolError, match="symbolic link or junction"):
+ spec.handler({"config": "soup.yaml"})
+ assert not (evildir / "mcp-runs").exists()
+ assert not any(evildir.iterdir())
+
+ def test_plan_ordinary_path_creates_regular_snapshot(self, tmp_path, monkeypatch):
+ """Ordinary path creates a regular directory and file under working directory."""
+ monkeypatch.chdir(tmp_path)
+ _setup_valid_config(tmp_path)
+ manager = ExecutionManager()
+
+ spec = _get_train_start_spec(manager)
+ result = spec.handler({"config": "soup.yaml"})
+
+ assert "confirmation_token" in result
+ token = result["confirmation_token"]
+ assert isinstance(token, str)
+
+ snapshot_dir = tmp_path / ".soup" / "mcp-runs"
+ assert snapshot_dir.exists()
+ assert not os.path.islink(snapshot_dir)
+
+ run_dirs = list(snapshot_dir.iterdir())
+ assert len(run_dirs) == 1
+ cfg_snapshot = run_dirs[0] / "config.yaml"
+ assert cfg_snapshot.exists()
+ assert not os.path.islink(cfg_snapshot)
+ assert "base: Qwen/Qwen2.5-0.5B" in cfg_snapshot.read_text(encoding="utf-8")
+
+ @pytest.mark.requires_symlink
+ def test_repaired_layout_allows_subsequent_plan(self, tmp_path, monkeypatch):
+ """After removing the directory link, a subsequent plan succeeds cleanly."""
+ monkeypatch.chdir(tmp_path)
+ _setup_valid_config(tmp_path)
+ manager = ExecutionManager()
+
+ evildir = tmp_path / "evildir"
+ evildir.mkdir()
+ link = tmp_path / ".soup"
+ os.symlink(str(evildir), str(link), target_is_directory=True)
+
+ with pytest.raises(ExecutionError, match="symbolic link or junction"):
+ manager.snapshot_config("blocked", "content")
+
+ (os.rmdir if os.name == "nt" else os.unlink)(link)
+
+ # Fresh plan succeeds
+ spec = _get_train_start_spec(manager)
+ res = spec.handler({"config": "soup.yaml"})
+ assert "confirmation_token" in res