Personal AI, On Personal Devices
Python
fix(tools): extend shell_exec env allowlist with Windows essentials (#807)
havolline1fb3eacf957e6
diff --git a/src/openjarvis/tools/shell_exec.py b/src/openjarvis/tools/shell_exec.pyindex e6f0d360..513fb169 100644--- a/src/openjarvis/tools/shell_exec.py+++ b/src/openjarvis/tools/shell_exec.py@@ -20,8 +20,32 @@ _MAX_TIMEOUT = 300# Default timeout (seconds)_DEFAULT_TIMEOUT = 30-# Environment variables always passed through-_BASE_ENV_KEYS = ("PATH", "HOME", "USER", "LANG", "TERM")+# Environment variables always passed through on every platform.+_PORTABLE_ENV_KEYS = (+ "PATH",+ "HOME",+ "USER",+ "LANG",+ "TERM",+)++# Windows needs these to bootstrap ordinary child processes: missing+# SystemRoot breaks Winsock/DNS initialization, while missing LOCALAPPDATA+# can make the Store Python launcher provision a fresh interpreter in cwd.+# Keep them conditional so a POSIX host that happens to define similarly+# named variables does not expand the tool's minimal environment.+_WINDOWS_ENV_KEYS = (+ "SystemRoot",+ "SystemDrive",+ "COMSPEC",+ "PATHEXT",+ "TEMP",+ "TMP",+ "USERPROFILE",+ "LOCALAPPDATA",+ "APPDATA",+)+_BASE_ENV_KEYS = _PORTABLE_ENV_KEYS + (_WINDOWS_ENV_KEYS if os.name == "nt" else ())@ToolRegistry.register("shell_exec")diff --git a/tests/tools/test_shell_exec.py b/tests/tools/test_shell_exec.pyindex defc95a1..2dddc83a 100644--- a/tests/tools/test_shell_exec.py+++ b/tests/tools/test_shell_exec.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport importlibimport osimport shlex+import subprocessimport sysfrom unittest.mock import MagicMock, patch@@ -277,3 +278,102 @@ class TestShellExecTool:result = tool.execute(command="/nonexistent_binary")assert result.success is Falseassert result.metadata["returncode"] == -1+++class TestSanitizedEnvWindowsKeys:+ """Regression for #789: the Python fallback's env allowlist was+ POSIX-focused ("PATH", "HOME", "USER", "LANG", "TERM") and omitted+ variables Windows needs for basic process bootstrapping -- missing+ SystemRoot breaks Winsock/DNS init for any network-touching command+ (git, curl, pip, npm all fail with "getaddrinfo() thread failed to+ start"), and missing LOCALAPPDATA makes the Windows Store Python+ launcher provision a ~170MB Python\\ folder in the cwd instead of+ finding the real interpreter.+ """++ def test_base_env_keys_include_windows_essentials(self):+ from openjarvis.tools.shell_exec import _WINDOWS_ENV_KEYS++ for key in (+ "SystemRoot",+ "SystemDrive",+ "COMSPEC",+ "PATHEXT",+ "TEMP",+ "TMP",+ "USERPROFILE",+ "LOCALAPPDATA",+ "APPDATA",+ ):+ assert key in _WINDOWS_ENV_KEYS, f"{key} missing from Windows keys"++ def test_windows_keys_are_only_enabled_on_windows(self):+ from openjarvis.tools.shell_exec import _BASE_ENV_KEYS, _WINDOWS_ENV_KEYS++ if os.name == "nt":+ assert set(_WINDOWS_ENV_KEYS) <= set(_BASE_ENV_KEYS)+ else:+ assert set(_WINDOWS_ENV_KEYS).isdisjoint(_BASE_ENV_KEYS)++ @pytest.mark.skipif(os.name != "nt", reason="requires a real Windows child")+ def test_windows_env_vars_reach_the_subprocess(self, monkeypatch):+ """End-to-end: with the Rust backend unavailable (forcing the+ Python sanitised-env fallback), a Windows-critical variable+ present in the host environment must actually reach the child+ process instead of being stripped."""+ monkeypatch.setenv("SystemRoot", r"C:\Windows")+ monkeypatch.setenv("LOCALAPPDATA", r"C:\Users\tester\AppData\Local")++ captured: dict = {}++ def _fake_run(*args, **kwargs):+ captured["env"] = kwargs.get("env")+ return subprocess.CompletedProcess(args, 0, stdout="ok\n", stderr="")++ tool = ShellExecTool()+ with (+ patch(+ "openjarvis._rust_bridge.get_rust_module",+ side_effect=ImportError("no rust module"),+ ),+ patch("subprocess.run", side_effect=_fake_run),+ ):+ result = tool.execute(command="echo ok")++ assert result.success is True+ env = captured["env"]+ assert env is not None+ assert env.get("SystemRoot") == r"C:\Windows"+ assert env.get("LOCALAPPDATA") == r"C:\Users\tester\AppData\Local"++ @pytest.mark.skipif(os.name != "nt", reason="requires a real Windows child")+ def test_real_windows_child_bootstraps_and_resolves_localhost(+ self, tmp_path, monkeypatch+ ):+ """Exercise the actual sanitized environment and Windows process path."""+ import json++ local_app_data = str(tmp_path / "LocalAppData")+ monkeypatch.setenv("LOCALAPPDATA", local_app_data)+ probe = (+ "import json, os, socket; "+ "addresses = socket.getaddrinfo('localhost', 80); "+ "print(json.dumps({"+ "'SystemRoot': os.environ.get('SystemRoot'), "+ "'LOCALAPPDATA': os.environ.get('LOCALAPPDATA'), "+ "'dns_ok': bool(addresses)}))"+ )+ command = subprocess.list2cmdline([sys.executable, "-c", probe])++ with patch(+ "openjarvis._rust_bridge.get_rust_module",+ side_effect=ImportError("force Python fallback"),+ ):+ result = ShellExecTool().execute(command=command)++ assert result.success is True, result.content+ stdout = result.content.split("=== STDOUT ===\n", 1)[1].splitlines()[0]+ payload = json.loads(stdout)+ assert payload["SystemRoot"] == os.environ["SystemRoot"]+ assert payload["LOCALAPPDATA"] == local_app_data+ assert payload["dns_ok"] is True