Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(security): reject control characters in workspace virtual paths
trohitg6ecfa6f43e21
diff --git a/server/nodes/filesystem/_backend.py b/server/nodes/filesystem/_backend.pyindex e31ad548..49f9c942 100644--- a/server/nodes/filesystem/_backend.py+++ b/server/nodes/filesystem/_backend.py@@ -21,7 +21,7 @@ import tempfilefrom dataclasses import dataclassfrom datetime import datetimefrom pathlib import Path, PurePosixPath, PureWindowsPath-from typing import Any, Callable, Dict, Optional+from typing import Any, Callable, Dict, Final, Optionalfrom uuid import uuid4from weakref import WeakValueDictionary@@ -530,6 +530,27 @@ def atomic_write_bytes(_atomic_write(path, payload, root_dir)+# Everything except NUL, C0 controls and DEL, bounded to a conventional+# PATH_MAX. Deliberately permissive about the rest -- workspace files are+# named by users, by ``fileDownloader`` and by ``shell``, so spaces,+# parentheses and non-ASCII are all legitimate and must keep working.+#+# The characters it does refuse are worth refusing on their own merits: a NUL+# truncates the path in any C-level filesystem call, and CR/LF or terminal+# escapes embedded in a filename corrupt every log line and console that+# later prints it.+#+# It is also the shape CodeQL's ``py/path-injection`` recognises as a+# sanitizer -- a ``re.fullmatch`` guarding the value on its way to the path+# expression. The blocklist checks below (``..``, ``~``, drive prefixes) are+# the real containment work, but a static analyser cannot confirm a blocklist+# is exhaustive, so it keeps reporting the ``resolve()`` call underneath.+# Same reasoning, and same fix, as ``services/plugin/identifiers.py``.+# https://codeql.github.com/codeql-query-help/python/py-path-injection/+_SAFE_VIRTUAL_PATH_PATTERN: Final[str] = r"[^\x00-\x1f\x7f]{1,4096}"+_SAFE_VIRTUAL_PATH_RE: Final[re.Pattern[str]] = re.compile(_SAFE_VIRTUAL_PATH_PATTERN)++def _validate_virtual_path(path: str) -> str:normalized_input = str(path).replace("\\", "/")parts = PurePosixPath(normalized_input).parts@@ -542,6 +563,8 @@ def _validate_virtual_path(path: str) -> str:normalized = f"/{normalized}"if ".." in normalized.split("/"):raise ValueError(f"Path traversal detected after normalization: {path}")+ if not _SAFE_VIRTUAL_PATH_RE.fullmatch(normalized):+ raise ValueError(f"Path contains unsupported characters: {path!r}")return normalizeddiff --git a/server/tests/nodes/test_filesystem_backend.py b/server/tests/nodes/test_filesystem_backend.pyindex e852879c..b11af933 100644--- a/server/tests/nodes/test_filesystem_backend.py+++ b/server/tests/nodes/test_filesystem_backend.py@@ -46,6 +46,52 @@ def test_backend_rejects_traversal_and_symlink_escape():shutil.rmtree(test_root, ignore_errors=True)+ "hostile",+ [+ "docs/secret\x00.txt", # NUL truncates the path in any C-level call+ "docs/one\nline.txt", # CR/LF corrupts every log line that prints it+ "docs/esc\x1b[2Kape.txt", # terminal escape in a filename+ "docs/bell\x07.txt",+ ],+)+def test_backend_rejects_control_characters_in_paths(hostile):+ """Refused before the path is ever built, not after it is resolved."""+ test_root = _test_directory()+ try:+ root = test_root / "workspace"+ root.mkdir()+ backend = WorkspaceBackend(root)++ with pytest.raises(ValueError, match="unsupported characters"):+ backend._resolve_path(hostile)+ finally:+ shutil.rmtree(test_root, ignore_errors=True)+++def test_backend_still_accepts_ordinary_awkward_filenames():+ """The guard must not become a filename allowlist.++ ``fileDownloader`` and ``shell`` write whatever the remote or the user+ names a file, so spaces, parentheses and non-ASCII have to keep working.+ """+ test_root = _test_directory()+ try:+ root = test_root / "workspace"+ root.mkdir()+ backend = WorkspaceBackend(root)++ for ordinary in (+ "My Report (final).pdf",+ "ドキュメント.txt",+ "a-b_c.d.e.tar.gz",+ "emoji \U0001f600.wav",+ ):+ assert backend._resolve_path(ordinary).name == ordinary+ finally:+ shutil.rmtree(test_root, ignore_errors=True)++def test_backend_read_list_glob_and_literal_grep():test_root = _test_directory()try: