Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(paths): sanitize node-id path components; colon ids broke agent tool cwd
trohitg21fb1a9a6bc3
diff --git a/server/core/paths.py b/server/core/paths.pyindex 3b42f84a..b9a60805 100644--- a/server/core/paths.py+++ b/server/core/paths.py@@ -96,12 +96,29 @@ contents manually:from __future__ import annotations+import refrom pathlib import Pathfrom core.logging import get_loggerlogger = get_logger(__name__)+_UNSAFE_COMPONENT = re.compile(r"[^A-Za-z0-9._-]")+++def safe_path_component(value: str, fallback: str = "item") -> str:+ """Sanitize a wire identifier (node id, process name) into one safe+ path component.++ Canvas node ids can be colon-namespaced (``2:processManager:4``) and+ ``ntpath.join`` / ``PureWindowsPath.__truediv__`` parse a leading+ ``2:`` as a DRIVE, silently discarding the base path — so raw ids+ must never be joined into a path. Dot-only results (``..``) collapse+ to ``fallback`` so traversal cannot survive sanitization.+ """+ cleaned = _UNSAFE_COMPONENT.sub("_", str(value or ""))+ return cleaned if cleaned.strip(".") else fallback+# Repo root: server/core/paths.py -> parents[2] is the project root._REPO_ROOT = Path(__file__).resolve().parents[2]@@ -297,6 +314,7 @@ def example_workflows_dir() -> Path:__all__ = [+ "safe_path_component","project_root","opencompany_root","machina_root",diff --git a/server/nodes/utility/http_request/__init__.py b/server/nodes/utility/http_request/__init__.pyindex a7a7ef62..b17a9e62 100644--- a/server/nodes/utility/http_request/__init__.py+++ b/server/nodes/utility/http_request/__init__.py@@ -6,7 +6,7 @@ from typing import Any, Dict, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field-from services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueueclass HttpRequestParams(BaseModel):@@ -125,7 +125,12 @@ class HttpRequestNode(ActionNode):else:kwargs["json"] = body- response = await client.request(**kwargs)+ try:+ response = await client.request(**kwargs)+ except httpx.ConnectError as e:+ raise NodeUserError(f"Could not connect to {params.url} ({e}) — is the server running and the URL reachable?") from e+ except httpx.TimeoutException as e:+ raise NodeUserError(f"Request to {params.url} timed out after {params.timeout}s ({e}).") from etry:response_data = response.json()except Exception:diff --git a/server/nodes/utility/process_manager/__init__.py b/server/nodes/utility/process_manager/__init__.pyindex 55749334..5e042580 100644--- a/server/nodes/utility/process_manager/__init__.py+++ b/server/nodes/utility/process_manager/__init__.py@@ -2,10 +2,12 @@from __future__ import annotations+import osfrom typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from core.paths import safe_path_componentfrom services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue@@ -69,14 +71,16 @@ class ProcessManagerNode(ActionNode):@Operation("dispatch")async def dispatch(self, ctx: NodeContext, params: ProcessManagerParams) -> Any:"""Inlined from handlers/process.py (Wave 11.D.1)."""- import osfrom services.process_service import get_process_servicesvc = get_process_service()workflow_id = ctx.workflow_id or "default"workspace_dir = ctx.workspace_dir or ""- # Each agent node gets its own subfolder in the workspace.- agent_dir = os.path.join(workspace_dir, ctx.node_id) if workspace_dir else ""+ # Each agent node gets its own subfolder in the workspace. Sanitized:+ # canvas ids can be colon-namespaced ("2:processManager:4") and+ # ntpath.join parses "2:" as a drive, discarding the workspace prefix,+ # so the raw id failed the ProcessService containment guardrail.+ agent_dir = os.path.join(workspace_dir, safe_path_component(ctx.node_id, "node")) if workspace_dir else ""op = params.operationname = _clean(params.name)diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.pyindex d5ab7095..88788522 100644--- a/server/services/cli_agent/session.py+++ b/server/services/cli_agent/session.py@@ -46,6 +46,7 @@ from typing import Any, Awaitable, Callable, Dict, List, Optionalimport anyiofrom core.logging import get_logger+from core.paths import safe_path_componentfrom services._supervisor.process import BaseProcessSupervisorfrom services.cli_agent.jsonl_watcher import JsonlWatcher, snapshot_jsonl_sizesfrom services.cli_agent.lockfile import remove_ide_lockfile, write_ide_lockfile@@ -109,7 +110,10 @@ class AICliSession(BaseProcessSupervisor):# (per-workflow isolation; ``cwd`` for memory-bound runs is# ``repo_root`` which would otherwise be shared across workflows).self._workspace_dir = Path(workspace_dir).resolve()- self._worktree_dir = self._workspace_dir / node_id / f"wt_{self._task_id}"+ # safe_path_component: colon-namespaced node ids ("2:codexAgent:1")+ # parse as a DRIVE under WindowsPath division and discard the+ # workspace prefix entirely.+ self._worktree_dir = self._workspace_dir / safe_path_component(node_id, "node") / f"wt_{self._task_id}"self._branch = task.branch or f"opencompany/{self._task_id}"self._broadcaster = broadcasterself._defaults = defaultsdiff --git a/server/services/process_service.py b/server/services/process_service.pyindex 84373868..1bc0d35d 100644--- a/server/services/process_service.py+++ b/server/services/process_service.py@@ -171,7 +171,8 @@ class ProcessService:"success": False,"error": (f"Working directory must be inside workspace ({workspace_base}) "- f"or daemons ({daemon_base})."+ f"or daemons ({daemon_base}); got '{cwd_resolved}'. "+ "Omit cwd to run in this node's workspace folder."),}diff --git a/server/tests/conftest.py b/server/tests/conftest.pyindex 8ff998df..977f0a81 100644--- a/server/tests/conftest.py+++ b/server/tests/conftest.py@@ -152,10 +152,17 @@ setattr(_core_pkg, "encryption", _encryption_mod)# locally; the stub just keeps import-time ``OPENCOMPANY_CLAUDE_DIR =# data_path("claude")`` calls from blowing up._TEST_OPENCOMPANY_ROOT = Path(__file__).parent / "_test_opencompany_root"+# safe_path_component is pure stdlib and consumed at plugin import time+# (process_manager's agent_dir), so expose the REAL implementation on the+# stub — file-load under a private name, same rationale as core.ansi above.+_paths_spec = _importlib_util.spec_from_file_location("_real_core_paths", SERVER_DIR / "core" / "paths.py")+_paths_mod = _importlib_util.module_from_spec(_paths_spec)+_paths_spec.loader.exec_module(_paths_mod)_make_submodule("core","paths",{+ "safe_path_component": _paths_mod.safe_path_component,"project_root": lambda: _TEST_OPENCOMPANY_ROOT.parent,"opencompany_root": lambda: _TEST_OPENCOMPANY_ROOT,"machina_root": lambda: _TEST_OPENCOMPANY_ROOT,diff --git a/server/tests/nodes/test_http_request_errors.py b/server/tests/nodes/test_http_request_errors.pynew file mode 100644index 00000000..24998498--- /dev/null+++ b/server/tests/nodes/test_http_request_errors.py@@ -0,0 +1,36 @@+"""Connection failures on httpRequest are user/LLM-correctable, not bugs.++A dead target (dev server not yet started) used to raise raw+``httpx.ConnectError`` and log a full double traceback; the NodeUserError+contract is one WARN line plus a structured envelope the agent can act on.+"""++from __future__ import annotations++import httpx+import pytest++from nodes.utility.http_request import HttpRequestNode, HttpRequestParams+from services.plugin import NodeContext, NodeUserError+++async def test_connect_error_surfaces_as_node_user_error(monkeypatch) -> None:+ async def refuse(self, *args, **kwargs):+ raise httpx.ConnectError("All connection attempts failed")++ monkeypatch.setattr(httpx.AsyncClient, "request", refuse)+ ctx = NodeContext(node_id="h1", node_type="httpRequest")+ with pytest.raises(NodeUserError) as excinfo:+ await HttpRequestNode().request(ctx, HttpRequestParams(method="GET", url="http://localhost:5173"))+ assert "localhost:5173" in str(excinfo.value)+++async def test_timeout_surfaces_as_node_user_error(monkeypatch) -> None:+ async def stall(self, *args, **kwargs):+ raise httpx.ConnectTimeout("timed out")++ monkeypatch.setattr(httpx.AsyncClient, "request", stall)+ ctx = NodeContext(node_id="h1", node_type="httpRequest")+ with pytest.raises(NodeUserError) as excinfo:+ await HttpRequestNode().request(ctx, HttpRequestParams(method="GET", url="http://localhost:5173", timeout=2))+ assert "timed out" in str(excinfo.value)diff --git a/server/tests/nodes/test_process_manager_cwd.py b/server/tests/nodes/test_process_manager_cwd.pynew file mode 100644index 00000000..72456791--- /dev/null+++ b/server/tests/nodes/test_process_manager_cwd.py@@ -0,0 +1,101 @@+"""Colon-namespaced node ids must never reach a path join raw.++Regression: on Windows, ``ntpath.join(workspace, "2:processManager:4")``+parses ``2:`` as a drive and discards the workspace prefix, so the+processManager ``agent_dir`` default resolved outside every containment+root and the ProcessService guardrail rejected every cwd-less start —+the multi-agent "Working directory must be inside workspace" loop.+"""++from __future__ import annotations++import ntpath+from pathlib import Path+from types import SimpleNamespace++from core.paths import safe_path_component+from nodes.utility.process_manager import ProcessManagerNode, ProcessManagerParams+from services.plugin import NodeContext+from services.process_service import ProcessService++WORKSPACE_BASE = r"D:\ws\AI_Employee_1"+COLON_NODE_ID = "2:processManager:4"+++def test_safe_path_component_neutralizes_colon_namespaced_ids() -> None:+ assert safe_path_component(COLON_NODE_ID) == "2_processManager_4"+ assert ":" not in safe_path_component("321151185156422f965c63a299945da7:processManager:4")+++def test_safe_path_component_collapses_dot_only_values() -> None:+ assert safe_path_component("..", "node") == "node"+ assert safe_path_component("", "node") == "node"+ assert safe_path_component(".", "node") == "node"+++def test_ntpath_drive_hazard_is_neutralized_by_sanitize_first() -> None:+ # The hazard this fix exists for: the raw id replaces the base outright.+ assert ntpath.join(WORKSPACE_BASE, COLON_NODE_ID) == COLON_NODE_ID+ assert ntpath.join(WORKSPACE_BASE, safe_path_component(COLON_NODE_ID)).startswith(WORKSPACE_BASE)+++class _CaptureService:+ def __init__(self) -> None:+ self.calls: list[dict] = []++ async def start(self, name, command, workflow_id, working_directory="", *, ports=None, extra_env=None):+ self.calls.append({"name": name, "working_directory": working_directory})+ return {"success": True, "pid": 1, "status": "running"}+++async def test_cwd_less_start_defaults_to_sanitized_agent_dir(monkeypatch, tmp_path) -> None:+ svc = _CaptureService()+ monkeypatch.setattr("services.process_service.get_process_service", lambda: svc)++ ctx = NodeContext(+ node_id=COLON_NODE_ID,+ node_type="processManager",+ workflow_id="2",+ workspace_dir=str(tmp_path),+ )+ result = await ProcessManagerNode().dispatch(+ ctx, ProcessManagerParams(operation="start", name="web", command="python -V")+ )++ assert result["success"] is True+ wd = Path(svc.calls[0]["working_directory"])+ assert wd == tmp_path / "2_processManager_4"+ assert wd.is_relative_to(tmp_path)+++async def test_explicit_cwd_passes_through_unchanged(monkeypatch, tmp_path) -> None:+ svc = _CaptureService()+ monkeypatch.setattr("services.process_service.get_process_service", lambda: svc)++ explicit = str(tmp_path / "app")+ ctx = NodeContext(+ node_id=COLON_NODE_ID,+ node_type="processManager",+ workflow_id="2",+ workspace_dir=str(tmp_path),+ )+ await ProcessManagerNode().dispatch(+ ctx, ProcessManagerParams(operation="start", name="web", command="python -V", cwd=explicit)+ )++ assert svc.calls[0]["working_directory"] == explicit+++async def test_guardrail_rejection_names_the_rejected_path(monkeypatch, tmp_path) -> None:+ workspace = tmp_path / "workspaces"+ workspace.mkdir()+ monkeypatch.setattr("core.config.Settings", lambda: SimpleNamespace(workspace_base_resolved=str(workspace)))+ monkeypatch.setattr("core.paths.daemons_dir", lambda: tmp_path / "daemons")++ outside = tmp_path / "elsewhere"+ outside.mkdir()+ result = await ProcessService().start("web", "python -V", working_directory=str(outside))++ assert result["success"] is False+ assert "elsewhere" in result["error"]+ assert "Omit cwd" in result["error"]