From 90d69e7a112915b3fd36af153a34da3d8aee83c6 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:29:01 +0800 Subject: [PATCH] refactor(exec): share the sandbox launch path with settings checks (#6645) * refactor(exec): share the sandbox launch path with settings checks * refactor(sandbox): remove duplicate platform and path bookkeeping --- .agent/navigation.md | 2 +- .agent/security.md | 4 +- nanobot/agent/tools/sandbox_check.py | 65 ++++---- nanobot/agent/tools/shell.py | 23 +-- nanobot/execution/processes.py | 8 +- nanobot/{agent/tools => execution}/sandbox.py | 139 +++++++----------- .../tools => security}/sandbox_launcher.py | 18 ++- nanobot/webui/settings_runtime.py | 2 +- scripts/check_import_boundaries.py | 6 + tests/tools/test_exec_platform.py | 60 ++++---- tests/tools/test_sandbox.py | 122 +++++++-------- tests/tools/test_sandbox_launcher_compat.py | 44 ++++-- tests/tools/test_sandbox_shell_boundary.py | 16 +- tests/tools/test_seatbelt_native.py | 2 +- 14 files changed, 236 insertions(+), 275 deletions(-) rename nanobot/{agent/tools => execution}/sandbox.py (76%) rename nanobot/{agent/tools => security}/sandbox_launcher.py (84%) diff --git a/.agent/navigation.md b/.agent/navigation.md index 7a5c1bca4..a6cfaa08a 100644 --- a/.agent/navigation.md +++ b/.agent/navigation.md @@ -17,7 +17,7 @@ Choose the affected behavior below, then read its owner and existing tests. Foll | Prompt assembly, skills, or context limits | [`agent/context.py`](../nanobot/agent/context.py), [`agent/context_governance.py`](../nanobot/agent/context_governance.py); [prompt cautions](gotchas.md#prompt-templates) | [`test_context_builder.py`](../tests/agent/test_context_builder.py), [`test_skills_loader.py`](../tests/agent/test_skills_loader.py), [`test_context_governance.py`](../tests/agent/test_context_governance.py) | | Session persistence or recovery | [`session/state.py`](../nanobot/session/state.py), [`session/sqlite_store.py`](../nanobot/session/sqlite_store.py), [`session/recovery.py`](../nanobot/session/recovery.py) | [`tests/session/`](../tests/session/), [`test_loop_recovery.py`](../tests/agent/test_loop_recovery.py) | | WebUI/TUI wire events or displayed history | [`webui/outbound_delivery.py`](../nanobot/webui/outbound_delivery.py), [`webui/transcript.py`](../nanobot/webui/transcript.py); [client compatibility](review-guide.md) | [`tests/webui/`](../tests/webui/), [`WebSocket tests`](../nanobot/channels/websocket/tests/), and affected client tests | -| Workspace access or sandbox enforcement | [`security/workspace_access.py`](../nanobot/security/workspace_access.py), [`agent/tools/sandbox.py`](../nanobot/agent/tools/sandbox.py); [security rules](security.md) | [`tests/security/`](../tests/security/), [`test_workspace_scope.py`](../tests/agent/test_workspace_scope.py), [`test_sandbox.py`](../tests/tools/test_sandbox.py) | +| Workspace access or sandbox enforcement | [`security/workspace_access.py`](../nanobot/security/workspace_access.py), [`execution/sandbox.py`](../nanobot/execution/sandbox.py); [security rules](security.md) | [`tests/security/`](../tests/security/), [`test_workspace_scope.py`](../tests/agent/test_workspace_scope.py), [`test_sandbox.py`](../tests/tools/test_sandbox.py) | | Gateway startup, shutdown, or launchers | [`gateway/`](../nanobot/gateway/), [`cli/gateway_runtime.py`](../nanobot/cli/gateway_runtime.py) | [`tests/gateway/`](../tests/gateway/), the matching launcher tests in [`tests/cli/`](../tests/cli/) | For the end-to-end runtime flow, expand to [Architecture](../docs/architecture.md). For ownership changes, read [Design Constraints](design.md); directory proximity does not permit crossing those boundaries. diff --git a/.agent/security.md b/.agent/security.md index d1dda4073..eabbd9961 100644 --- a/.agent/security.md +++ b/.agent/security.md @@ -24,6 +24,6 @@ HTTP/SSE MCP transports are part of this boundary: validate configured MCP URLs ## Shell Sandbox -`tools/sandbox.py` provides optional command wrapping: `bwrap` (bubblewrap) on Linux and `seatbelt` (`sandbox-exec`) on macOS. Seatbelt must not expose shared host temporary directories; scratch stays in the workspace. On Windows a configured backend warns and leaves only the application guard. On Unix a configured backend that cannot start must fail, not silently execute without isolation. +`execution/sandbox.py` builds the sandbox argument vector for both shell execution and the settings probe. `security/sandbox_launcher.py` resolves the trusted host launcher. Backends are `bwrap` (bubblewrap) on Linux and `seatbelt` (`sandbox-exec`) on macOS. Seatbelt must not expose shared host temporary directories; scratch stays in the workspace. On Windows a configured backend warns and leaves only the application guard. On Unix a configured backend that cannot start must fail, not silently execute without isolation. -**Rule**: If adding a sandbox backend, match the backend callable contract in `nanobot/agent/tools/sandbox.py` and register it in `_BACKENDS`. Preserve read/write root handling and the configured backend's failure behavior. +**Rule**: If adding a sandbox backend, match the backend callable contract in `nanobot/execution/sandbox.py` and register it in `_BACKENDS`. Preserve read/write root handling and the configured backend's failure behavior. diff --git a/nanobot/agent/tools/sandbox_check.py b/nanobot/agent/tools/sandbox_check.py index cbc42ba7e..9496d2ba8 100644 --- a/nanobot/agent/tools/sandbox_check.py +++ b/nanobot/agent/tools/sandbox_check.py @@ -7,20 +7,20 @@ import hashlib import json import os import shlex -import signal import tempfile from pathlib import Path from typing import TypedDict -from nanobot.agent.tools.sandbox import wrap_command -from nanobot.agent.tools.sandbox_launcher import ( - SandboxLauncherError, - resolve_sandbox_launcher, - sandbox_platform, -) from nanobot.agent.tools.shell_config import ExecToolConfig from nanobot.config.errors import ConfigLoadError from nanobot.config.loader import resolve_config_env_vars +from nanobot.execution import processes +from nanobot.execution.sandbox import build_sandbox_argv +from nanobot.security.sandbox_launcher import ( + SandboxLauncherError, + resolve_sandbox_launcher, + supported_sandbox_backend, +) _PROBE_TIMEOUT_S = 5 @@ -34,13 +34,11 @@ class SandboxCheck(TypedDict): def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxCheck: - return _prepare_settings(config, workspace)[2] + return _prepare_settings(config, workspace)[1] -def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecToolConfig, Path, SandboxCheck]: - import sys - - backend = "bwrap" if sys.platform.startswith("linux") else "seatbelt" if sys.platform == "darwin" else None +def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecToolConfig, SandboxCheck]: + backend = supported_sandbox_backend() missing_env = False try: config = resolve_config_env_vars(config) @@ -58,7 +56,7 @@ def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecTool result["state"] = "disabled" elif not config.sandbox: result["state"] = "off" - elif sandbox_platform(config.sandbox) == "unsupported": + elif config.sandbox != backend: result.update(state="unsupported", reason="platform_unsupported") elif missing_env: result.update(state="unavailable", reason="path_unavailable") @@ -70,11 +68,11 @@ def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecTool ) except SandboxLauncherError as exc: result.update(state="unavailable", reason=exc.reason) - return config, workspace, result + return config, result async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck: - config, workspace, result = await asyncio.to_thread(_prepare_settings, config, workspace) + config, result = await asyncio.to_thread(_prepare_settings, config, workspace) if result["state"] != "unchecked": return result # Use synthetic files only. Never run startup/login profiles or an arbitrary @@ -92,40 +90,33 @@ async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck # same path. What must stay unchanged is the host-side canary. f"(printf changed > {shlex.quote(str(canary))} || true)" ) - argv = shlex.split(wrap_command( - config.sandbox, script, str(project), str(project), - sandbox_ro_binds=config.sandbox_ro_binds, - sandbox_rw_binds=config.sandbox_rw_binds, - )) - # Same resolver and wrapper as ExecTool. Recheck against the probe root. try: - argv[0] = resolve_sandbox_launcher( - config.sandbox, config.sandbox_launcher, - writable_roots=(project, *map(Path, config.sandbox_rw_binds)), + argv = build_sandbox_argv( + config.sandbox, script, str(project), str(project), + launcher=config.sandbox_launcher, + sandbox_ro_binds=config.sandbox_ro_binds, + sandbox_rw_binds=config.sandbox_rw_binds, ) result["launcher"] = argv[0] except SandboxLauncherError as exc: result.update(state="unavailable", reason=exc.reason) return result - process: asyncio.subprocess.Process | None = None + tree: processes.ProcessTree | None = None try: - process = await asyncio.create_subprocess_exec( - *argv, cwd=str(project), env={"PATH": os.defpath, "HOME": str(project)}, - stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL, - stderr=asyncio.subprocess.DEVNULL, start_new_session=True, + tree = await processes.spawn_process_tree( + argv, str(project), {"PATH": os.defpath, "HOME": str(project)}, capture_output=False, ) - await asyncio.wait_for(process.wait(), timeout=_PROBE_TIMEOUT_S) - success = process.returncode == 0 and (project / "inside").read_text() == "checked" and canary.read_text() == "unchanged" + code = await asyncio.wait_for(tree.process.wait(), timeout=_PROBE_TIMEOUT_S) + success = code == 0 and (project / "inside").read_text() == "checked" and canary.read_text() == "unchanged" result.update(state="passed" if success else "unavailable", reason="" if success else "probe_failed") except TimeoutError: result.update(state="unavailable", reason="probe_timeout") except OSError: result.update(state="unavailable", reason="probe_failed") finally: - if process is not None and process.returncode is None: - try: - os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: - pass - await process.wait() + if tree is not None: + if tree.process.returncode is None: + await tree.terminate() + else: + tree.finish() return result diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.py index 506d0e02a..20ab87b86 100644 --- a/nanobot/agent/tools/shell.py +++ b/nanobot/agent/tools/shell.py @@ -26,8 +26,6 @@ from nanobot.agent.tools.exec_session import ( clamp_session_int, format_session_poll, ) -from nanobot.agent.tools.sandbox import wrap_command -from nanobot.agent.tools.sandbox_launcher import SandboxLauncherError, resolve_sandbox_launcher from nanobot.agent.tools.schema import ( BooleanSchema, IntegerSchema, @@ -36,6 +34,8 @@ from nanobot.agent.tools.schema import ( ) from nanobot.agent.tools.shell_config import ExecToolConfig from nanobot.config.paths import get_media_dir +from nanobot.execution.sandbox import build_sandbox_argv +from nanobot.security.sandbox_launcher import SandboxLauncherError from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace from nanobot.security.workspace_policy import is_path_within @@ -436,24 +436,17 @@ class ExecTool(Tool): args.append("-l") payload = shlex.join([*args, "-c", command]) workspace = workspace_root or cwd - command = shlex.split(wrap_command( - self.sandbox, - payload, - workspace, - cwd, - sandbox_ro_binds=[str(p) for p in self.sandbox_ro_binds], - sandbox_rw_binds=[str(p) for p in self.sandbox_rw_binds], - )) - # Project/tool and inherited PATH can contain writable programs. try: - command[0] = resolve_sandbox_launcher( - self.sandbox, self.sandbox_launcher, - writable_roots=(Path(workspace), *self.sandbox_rw_binds), + command = build_sandbox_argv( + self.sandbox, payload, workspace, cwd, + launcher=self.sandbox_launcher, + sandbox_ro_binds=map(str, self.sandbox_ro_binds), + sandbox_rw_binds=map(str, self.sandbox_rw_binds), ) except SandboxLauncherError as exc: if exc.reason == "launcher_missing": return ToolResult.error( - f"Error: sandbox launcher not found: {command[0]}", error_code="sandbox_launcher_missing", + f"Error: sandbox launcher not found: {exc.launcher}", error_code="sandbox_launcher_missing", ) return ToolResult.error( f"Error: sandbox launcher rejected: {exc.reason}", error_code=f"sandbox_{exc.reason}", diff --git a/nanobot/execution/processes.py b/nanobot/execution/processes.py index ac1afe882..f64bd04ce 100644 --- a/nanobot/execution/processes.py +++ b/nanobot/execution/processes.py @@ -56,6 +56,7 @@ async def spawn_process_tree( login: bool = False, *, stdin: int = asyncio.subprocess.DEVNULL, + capture_output: bool = True, ) -> ProcessTree: """Start a prepared command in its own process group or Windows job.""" if isinstance(command, list): @@ -87,18 +88,17 @@ async def spawn_process_tree( job = _create_windows_job() if _IS_WINDOWS else None creationflags = job.creation_flags if job is not None else 0 + output = asyncio.subprocess.PIPE if capture_output else asyncio.subprocess.DEVNULL process = None try: if isinstance(launch, str): process = await asyncio.create_subprocess_shell( - launch, stdin=stdin, stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env, + launch, stdin=stdin, stdout=output, stderr=output, cwd=cwd, env=env, creationflags=creationflags, ) else: process = await asyncio.create_subprocess_exec( - *launch, stdin=stdin, stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env, + *launch, stdin=stdin, stdout=output, stderr=output, cwd=cwd, env=env, creationflags=creationflags, start_new_session=not _IS_WINDOWS, ) diff --git a/nanobot/agent/tools/sandbox.py b/nanobot/execution/sandbox.py similarity index 76% rename from nanobot/agent/tools/sandbox.py rename to nanobot/execution/sandbox.py index 87cf64aed..257435b2a 100644 --- a/nanobot/agent/tools/sandbox.py +++ b/nanobot/execution/sandbox.py @@ -1,8 +1,7 @@ """Sandbox backends for shell command execution. -To add a backend, match the callable signature of _bwrap and _seatbelt, -including keyword-only sandbox_ro_binds and sandbox_rw_binds, and register -it in _BACKENDS below. +To add a backend, match the callable signature of _bwrap and _seatbelt and +register it in _BACKENDS below. """ import os @@ -11,16 +10,16 @@ from pathlib import Path from typing import Iterable from nanobot.config.paths import get_media_dir +from nanobot.security.sandbox_launcher import resolve_sandbox_launcher def _normalize_bind_paths( - paths: Iterable[str] | None, + paths: Iterable[str], *, - workspace: Path | None = None, + workspace: Path, ) -> list[str]: - out: list[str] = [] - seen: set[str] = set() - for raw in paths or []: + binds: dict[str, None] = {} + for raw in paths: value = str(raw).strip() if not value: continue @@ -28,40 +27,23 @@ def _normalize_bind_paths( if not path.is_absolute(): continue resolved_path = path.resolve(strict=False) - if workspace is not None: - try: - workspace.relative_to(resolved_path) - except ValueError: - pass - else: - # A later bind of the workspace or one of its parents could - # cover the tmpfs that hides the config directory. - continue - resolved = str(resolved_path) - if resolved in seen: + # A later bind of the workspace or an ancestor could cover the + # tmpfs that hides the config directory. + if workspace.is_relative_to(resolved_path): continue - seen.add(resolved) - out.append(resolved) - return out + binds[str(resolved_path)] = None + return list(binds) def _bwrap( command: str, - workspace: str, - cwd: str, + ws: Path, + sandbox_cwd: str, *, - sandbox_ro_binds: Iterable[str] | None = None, - sandbox_rw_binds: Iterable[str] | None = None, -) -> str: - ws = Path(workspace).resolve() - media = get_media_dir().resolve() - - try: - sandbox_cwd = str(ws / Path(cwd).resolve().relative_to(ws)) - except ValueError: - sandbox_cwd = str(ws) - - required = ["/usr"] + media: Path, + ro_binds: list[str], + rw_binds: list[str], +) -> list[str]: optional = [ "/bin", "/lib", @@ -75,9 +57,10 @@ def _bwrap( "/etc/ld.so.cache", ] - args = ["bwrap", "--new-session", "--die-with-parent", "--setenv", "HOME", str(ws)] - for p in required: - args += ["--ro-bind", p, p] + args = [ + "--new-session", "--die-with-parent", "--setenv", "HOME", str(ws), + "--ro-bind", "/usr", "/usr", + ] for p in optional: args += ["--ro-bind-try", p, p] args += [ @@ -87,12 +70,12 @@ def _bwrap( "--bind", str(ws), str(ws), "--ro-bind-try", str(media), str(media), ] - for p in _normalize_bind_paths(sandbox_ro_binds, workspace=ws): + for p in ro_binds: args += ["--ro-bind-try", p, p] - for p in _normalize_bind_paths(sandbox_rw_binds, workspace=ws): + for p in rw_binds: args += ["--bind-try", p, p] args += ["--chdir", sandbox_cwd, "--", "sh", "-c", command] - return shlex.join(args) + return args # System code and certificates needed by command-line tools. Do not grant @@ -138,16 +121,7 @@ def _seatbelt_ancestors(*paths: Path) -> list[str]: command. Only ``file-read-metadata`` is granted for these: the directories stay searchable, but listing or reading them is still denied. """ - out: list[str] = [] - seen: set[str] = set() - for path in paths: - for ancestor in path.parents: - name = str(ancestor) - if name in seen: - continue - seen.add(name) - out.append(name) - return out + return list(dict.fromkeys(str(ancestor) for path in paths for ancestor in path.parents)) def _seatbelt_is_within(path: Path, root: Path) -> bool: @@ -177,12 +151,13 @@ def _sbpl_quote(path: str) -> str: def _seatbelt( command: str, - workspace: str, - cwd: str, + ws: Path, + sandbox_cwd: str, *, - sandbox_ro_binds: Iterable[str] | None = None, - sandbox_rw_binds: Iterable[str] | None = None, -) -> str: + media: Path, + ro_binds: list[str], + rw_binds: list[str], +) -> list[str]: """Wrap command in a macOS Seatbelt sandbox (requires sandbox-exec(1)). The workspace is read-write and media is read-only. The workspace's parent @@ -199,20 +174,9 @@ def _seatbelt( Network access is left unrestricted, matching ``bwrap`` (which does not pass ``--unshare-net``). """ - ws = Path(workspace).resolve() - media = get_media_dir().resolve() - - try: - sandbox_cwd = str(ws / Path(cwd).resolve().relative_to(ws)) - except ValueError: - sandbox_cwd = str(ws) - def subpaths(paths: Iterable[str]) -> str: return " ".join(f"(subpath {_sbpl_quote(p)})" for p in paths) - ro_binds = _normalize_bind_paths(sandbox_ro_binds, workspace=ws) - rw_binds = _normalize_bind_paths(sandbox_rw_binds, workspace=ws) - rules = [ "(version 1)", "(deny default)", @@ -285,9 +249,7 @@ def _seatbelt( # sandbox-exec(1) has no --chdir. Exit on failure before evaluating any of # the submitted shell list; `cd ... && a; b` would still execute b on failure. - args = [ - # Resolve the security boundary before consulting operator tool PATHs. - "/usr/bin/sandbox-exec", + return [ "-p", "\n".join(rules), "/usr/bin/env", @@ -297,28 +259,37 @@ def _seatbelt( "-c", f"cd {shlex.quote(sandbox_cwd)} || exit\n{command}", ] - return shlex.join(args) _BACKENDS = {"bwrap": _bwrap, "seatbelt": _seatbelt} -def wrap_command( +def build_sandbox_argv( sandbox: str, command: str, workspace: str, cwd: str, *, + launcher: str = "", sandbox_ro_binds: Iterable[str] | None = None, sandbox_rw_binds: Iterable[str] | None = None, -) -> str: - """Wrap *command* using the named sandbox backend.""" - if backend := _BACKENDS.get(sandbox): - return backend( - command, - workspace, - cwd, - sandbox_ro_binds=sandbox_ro_binds, - sandbox_rw_binds=sandbox_rw_binds, - ) - raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}") +) -> list[str]: + """Build the sandbox argv with an independently resolved host launcher.""" + backend = _BACKENDS.get(sandbox) + if backend is None: + raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}") + ws = Path(workspace).resolve() + media = get_media_dir().resolve() + requested_cwd = Path(cwd).resolve() + sandbox_cwd = str(requested_cwd if requested_cwd.is_relative_to(ws) else ws) + + rw_binds = tuple(sandbox_rw_binds or ()) + args = backend( + command, ws, sandbox_cwd, media=media, + ro_binds=_normalize_bind_paths(sandbox_ro_binds or (), workspace=ws), + rw_binds=_normalize_bind_paths(rw_binds, workspace=ws), + ) + executable = resolve_sandbox_launcher( + sandbox, launcher, writable_roots=(Path(workspace), *map(Path, rw_binds)), + ) + return [executable, *args] diff --git a/nanobot/agent/tools/sandbox_launcher.py b/nanobot/security/sandbox_launcher.py similarity index 84% rename from nanobot/agent/tools/sandbox_launcher.py rename to nanobot/security/sandbox_launcher.py index 3878eecdd..a32b0f504 100644 --- a/nanobot/agent/tools/sandbox_launcher.py +++ b/nanobot/security/sandbox_launcher.py @@ -5,22 +5,24 @@ from __future__ import annotations import os import shutil import stat +import sys from pathlib import Path from typing import Literal class SandboxLauncherError(ValueError): - def __init__(self, reason: str): + def __init__(self, reason: str, *, launcher: str = ""): self.reason = reason + self.launcher = launcher super().__init__(reason) -def sandbox_platform(backend: str) -> Literal["supported", "unsupported"]: - import sys - - return "supported" if (backend == "bwrap" and sys.platform.startswith("linux")) or ( - backend == "seatbelt" and sys.platform == "darwin" - ) else "unsupported" +def supported_sandbox_backend() -> Literal["bwrap", "seatbelt"] | None: + if sys.platform.startswith("linux"): + return "bwrap" + if sys.platform == "darwin": + return "seatbelt" + return None def resolve_sandbox_launcher( @@ -36,7 +38,7 @@ def resolve_sandbox_launcher( if not custom_path: launcher = shutil.which(name, path=os.defpath) if launcher is None: - raise SandboxLauncherError("launcher_missing") + raise SandboxLauncherError("launcher_missing", launcher=name) return str(Path(launcher).absolute()) if os.name != "posix": raise SandboxLauncherError("platform_unsupported") diff --git a/nanobot/webui/settings_runtime.py b/nanobot/webui/settings_runtime.py index e98ee58fd..6906d9355 100644 --- a/nanobot/webui/settings_runtime.py +++ b/nanobot/webui/settings_runtime.py @@ -146,7 +146,7 @@ def update_runtime_config( if "tools.exec.sandbox" in values and validated.tools.exec.sandbox not in {"", "bwrap", "seatbelt"}: raise WebUISettingsError("tools.exec.sandbox: choose no sandbox, bwrap, or seatbelt") if {"tools.exec.sandbox_launcher", "tools.exec.sandbox_rw_binds"} & values.keys() and validated.tools.exec.sandbox_launcher: - from nanobot.agent.tools.sandbox_launcher import ( + from nanobot.security.sandbox_launcher import ( SandboxLauncherError, resolve_sandbox_launcher, ) diff --git a/scripts/check_import_boundaries.py b/scripts/check_import_boundaries.py index a36850db2..33c0e1b43 100644 --- a/scripts/check_import_boundaries.py +++ b/scripts/check_import_boundaries.py @@ -92,6 +92,12 @@ IMPORT_RULES = ( ("nanobot.execution.http",), (*_ADAPTERS, "nanobot.agent", "nanobot.config", "nanobot.providers", "nanobot.session"), ), + ImportRule( + "sandbox-execution", + ("nanobot.execution.sandbox",), + (*_ADAPTERS, "nanobot.agent", "nanobot.config", "nanobot.session"), + allowed_targets=("nanobot.config.paths.get_media_dir",), + ), ImportRule( "channel-routing-contracts", ("nanobot.channels.notification_routes",), diff --git a/tests/tools/test_exec_platform.py b/tests/tools/test_exec_platform.py index 21a07b651..f2f886804 100644 --- a/tests/tools/test_exec_platform.py +++ b/tests/tools/test_exec_platform.py @@ -525,55 +525,47 @@ class TestSandboxPlatform: @pytest.mark.asyncio @pytest.mark.parametrize("backend", ["bwrap", "seatbelt"]) - async def test_sandbox_applied_on_unix(self, tmp_path, backend): + async def test_unix_sandbox_launch_uses_trusted_launcher_and_configured_binds(self, tmp_path, backend): mock_proc = _CompletedProcess(b"sandboxed") trusted_bin = tmp_path / "trusted-bin" - launcher = "bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec" - - with ( - patch("nanobot.agent.tools.shell._IS_WINDOWS", False), - patch("nanobot.agent.tools.shell.shutil.which", side_effect=lambda name, **_kwargs: str(trusted_bin / name)), - patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{launcher} -- sh -c ls") as mock_wrap, - patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)) as mock_spawn, - patch.object(ExecTool, "_guard_command", return_value=None), - ): - tool = ExecTool(sandbox=backend, working_dir="/workspace") - await tool.execute(command="ls") - - mock_wrap.assert_called_once() - spawned_cmd = mock_spawn.call_args[0][0] - assert isinstance(spawned_cmd, list) - assert spawned_cmd[0] == str(trusted_bin / launcher) - - @pytest.mark.asyncio - @pytest.mark.parametrize("backend", ["bwrap", "seatbelt"]) - async def test_sandbox_receives_configured_bind_roots(self, tmp_path, backend): - mock_proc = _CompletedProcess(b"sandboxed") + launcher = trusted_bin / ("bwrap" if backend == "bwrap" else "sandbox-exec") + workspace = tmp_path / "project" tool_bin = tmp_path / "tool-bin" tool_cache = tmp_path / "tool-cache" with ( patch("nanobot.agent.tools.shell._IS_WINDOWS", False), - patch("nanobot.agent.tools.shell.shutil.which", side_effect=lambda name, **_kwargs: f"/usr/bin/{name}"), - patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{backend} -- sh -c ls") as mock_wrap, - patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)), + patch("nanobot.execution.sandbox.resolve_sandbox_launcher", return_value=str(launcher)), + patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)) as mock_spawn, patch.object(ExecTool, "_guard_command", return_value=None), ): tool = ExecTool( sandbox=backend, - working_dir="/workspace", + working_dir=str(workspace), sandbox_ro_binds=[str(tool_bin)], sandbox_rw_binds=[str(tool_cache)], ) - await tool.execute(command="ls") + result = await tool.execute(command="ls") - kwargs = mock_wrap.call_args.kwargs - assert kwargs["sandbox_ro_binds"] == [ - str(tool_bin.resolve(strict=False)) - ] - assert kwargs["sandbox_rw_binds"] == [ - str(tool_cache.resolve(strict=False)) - ] + assert "sandboxed" in result + command, cwd, *_ = mock_spawn.call_args.args + assert isinstance(command, list) + assert command[0] == str(launcher) + assert cwd == str(workspace.resolve()) + if backend == "bwrap": + assert command[-9:-3] == [ + "--bind-try", str(tool_cache.resolve()), str(tool_cache.resolve()), + "--chdir", cwd, "--", + ] + assert command[-12:-9] == [ + "--ro-bind-try", str(tool_bin.resolve()), str(tool_bin.resolve()), + ] + else: + profile = command[2] + ro = str(tool_bin.resolve()).replace("\\", "\\\\") + rw = str(tool_cache.resolve()).replace("\\", "\\\\") + assert f'(deny file-write* (subpath "{ro}"))' in profile + assert f'(allow file-read* file-write* (subpath "{rw}"))' in profile class TestExecuteEndToEnd: diff --git a/tests/tools/test_sandbox.py b/tests/tools/test_sandbox.py index 7c653af98..7376e28c3 100644 --- a/tests/tools/test_sandbox.py +++ b/tests/tools/test_sandbox.py @@ -3,19 +3,22 @@ from pathlib import Path import pytest -from nanobot.agent.tools.sandbox import _sbpl_quote, _seatbelt_is_within, wrap_command +from nanobot.execution.sandbox import _sbpl_quote, _seatbelt_is_within, build_sandbox_argv -def _parse(cmd: str) -> list[str]: - """Split a wrapped command back into tokens for assertion.""" - return shlex.split(cmd) +@pytest.fixture(autouse=True) +def portable_launcher(monkeypatch): + # Test backend arguments on all platforms without installing either launcher. + def resolve(backend, *_args, **_kwargs): + return "bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec" + + monkeypatch.setattr("nanobot.execution.sandbox.resolve_sandbox_launcher", resolve) class TestBwrapBackend: def test_basic_structure(self, tmp_path): ws = str(tmp_path / "project") - result = wrap_command("bwrap", "echo hi", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "echo hi", ws, ws) assert tokens[0] == "bwrap" assert "--new-session" in tokens @@ -30,16 +33,14 @@ class TestBwrapBackend: def test_workspace_bind_mounted_rw(self, tmp_path): ws = str(tmp_path / "project") - result = wrap_command("bwrap", "ls", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "ls", ws, ws) bind_idx = [i for i, t in enumerate(tokens) if t == "--bind"] assert any(tokens[i + 1] == ws and tokens[i + 2] == ws for i in bind_idx) def test_home_env_points_to_workspace(self, tmp_path): ws = str(tmp_path / "project") - result = wrap_command("bwrap", "echo $HOME", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "echo $HOME", ws, ws) setenv_idx = [i for i, t in enumerate(tokens) if t == "--setenv"] assert any( @@ -49,8 +50,7 @@ class TestBwrapBackend: def test_parent_dir_masked_with_tmpfs(self, tmp_path): ws = tmp_path / "project" - result = wrap_command("bwrap", "ls", str(ws), str(ws)) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "ls", str(ws), str(ws)) tmpfs_indices = [i for i, t in enumerate(tokens) if t == "--tmpfs"] tmpfs_targets = {tokens[i + 1] for i in tmpfs_indices} @@ -59,8 +59,7 @@ class TestBwrapBackend: def test_tmp_dir_mounted_as_tmpfs(self, tmp_path): """Regression coverage for #1948: commands need writable scratch space.""" ws = tmp_path / "project" - result = wrap_command("bwrap", "touch /tmp/probe", str(ws), str(ws)) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "touch /tmp/probe", str(ws), str(ws)) tmpfs_indices = [i for i, t in enumerate(tokens) if t == "--tmpfs"] tmpfs_targets = {tokens[i + 1] for i in tmpfs_indices} @@ -68,8 +67,7 @@ class TestBwrapBackend: def test_parent_mask_precedes_workspace_recreation(self, tmp_path): ws = tmp_path / "project" - result = wrap_command("bwrap", "ls", str(ws), str(ws)) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "ls", str(ws), str(ws)) parent_mask = next( i for i, t in enumerate(tokens) @@ -90,8 +88,7 @@ class TestBwrapBackend: def test_cwd_inside_workspace(self, tmp_path): ws = tmp_path / "project" sub = ws / "src" / "lib" - result = wrap_command("bwrap", "pwd", str(ws), str(sub)) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "pwd", str(ws), str(sub)) chdir_idx = tokens.index("--chdir") assert tokens[chdir_idx + 1] == str(sub) @@ -99,8 +96,7 @@ class TestBwrapBackend: def test_cwd_outside_workspace_falls_back(self, tmp_path): ws = tmp_path / "project" outside = tmp_path / "other" - result = wrap_command("bwrap", "pwd", str(ws), str(outside)) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "pwd", str(ws), str(outside)) chdir_idx = tokens.index("--chdir") assert tokens[chdir_idx + 1] == str(ws.resolve()) @@ -108,16 +104,14 @@ class TestBwrapBackend: def test_command_with_special_characters(self, tmp_path): ws = str(tmp_path / "project") cmd = "echo 'hello world' && cat \"file with spaces.txt\"" - result = wrap_command("bwrap", cmd, ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", cmd, ws, ws) sep = tokens.index("--") assert tokens[sep + 1:] == ["sh", "-c", cmd] def test_system_dirs_ro_bound(self, tmp_path): ws = str(tmp_path / "project") - result = wrap_command("bwrap", "ls", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "ls", ws, ws) ro_bind_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind"] ro_targets = {tokens[i + 1] for i in ro_bind_indices} @@ -125,8 +119,7 @@ class TestBwrapBackend: def test_optional_dirs_use_ro_bind_try(self, tmp_path): ws = str(tmp_path / "project") - result = wrap_command("bwrap", "ls", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "ls", ws, ws) try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"] try_targets = {tokens[i + 1] for i in try_indices} @@ -137,12 +130,11 @@ class TestBwrapBackend: fake_media = tmp_path / "media" fake_media.mkdir() monkeypatch.setattr( - "nanobot.agent.tools.sandbox.get_media_dir", + "nanobot.execution.sandbox.get_media_dir", lambda: fake_media, ) ws = str(tmp_path / "project") - result = wrap_command("bwrap", "ls", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("bwrap", "ls", ws, ws) try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"] try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in try_indices} @@ -152,14 +144,13 @@ class TestBwrapBackend: ws = tmp_path / "project" tool_bin = tmp_path / "home" / ".local" / "bin" - result = wrap_command( + tokens = build_sandbox_argv( "bwrap", "uv --version", str(ws), str(ws), sandbox_ro_binds=[str(tool_bin)], ) - tokens = _parse(result) try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"] try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in try_indices} @@ -169,14 +160,13 @@ class TestBwrapBackend: ws = tmp_path / "project" cache_dir = tmp_path / "cache" - result = wrap_command( + tokens = build_sandbox_argv( "bwrap", "touch cache/file", str(ws), str(ws), sandbox_rw_binds=[str(cache_dir)], ) - tokens = _parse(result) bind_try_indices = [i for i, t in enumerate(tokens) if t == "--bind-try"] bind_try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in bind_try_indices} @@ -186,7 +176,7 @@ class TestBwrapBackend: def test_custom_relative_bind_paths_are_ignored(self, tmp_path): ws = tmp_path / "project" - result = wrap_command( + tokens = build_sandbox_argv( "bwrap", "ls", str(ws), @@ -194,7 +184,6 @@ class TestBwrapBackend: sandbox_ro_binds=["relative/bin"], sandbox_rw_binds=["relative/cache"], ) - tokens = _parse(result) assert "relative/bin" not in tokens assert "relative/cache" not in tokens @@ -203,7 +192,7 @@ class TestBwrapBackend: ws = tmp_path / "private" / "project" parent = ws.parent.resolve(strict=False) - result = wrap_command( + tokens = build_sandbox_argv( "bwrap", "cat ../config.json", str(ws), @@ -211,7 +200,6 @@ class TestBwrapBackend: sandbox_ro_binds=[str(parent)], sandbox_rw_binds=[str(parent)], ) - tokens = _parse(result) ro_try_indices = [i for i, token in enumerate(tokens) if token == "--ro-bind-try"] ro_try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in ro_try_indices} @@ -229,9 +217,8 @@ class TestSeatbeltBackend: """ @staticmethod - def _profile(cmd: str) -> str: + def _profile(tokens: list[str]) -> str: """Return the SBPL profile from a wrapped command.""" - tokens = _parse(cmd) return tokens[tokens.index("-p") + 1] @staticmethod @@ -249,8 +236,7 @@ class TestSeatbeltBackend: def test_basic_structure(self, tmp_path): ws = str(tmp_path / "project") - result = wrap_command("seatbelt", "echo hi", ws, ws) - tokens = _parse(result) + tokens = build_sandbox_argv("seatbelt", "echo hi", ws, ws) assert tokens[0] == "/usr/bin/sandbox-exec" assert tokens[1] == "-p" @@ -259,7 +245,7 @@ class TestSeatbeltBackend: assert tokens[-1].endswith("echo hi") def test_denies_by_default(self, tmp_path): - profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(tmp_path), str(tmp_path))) assert "(version 1)" in profile assert "(deny default)" in profile @@ -271,13 +257,13 @@ class TestSeatbeltBackend: profile listing only system subpaths kills every wrapped command before it runs. """ - profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(tmp_path), str(tmp_path))) assert '(allow file-read* (literal "/"))' in profile def test_workspace_allowed_read_write(self, tmp_path): ws = (tmp_path / "project").resolve() - profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(ws), str(ws))) assert f"(allow file-read* file-write* (subpath {self._quote(ws)}))" in profile @@ -288,14 +274,14 @@ class TestSeatbeltBackend: re-exposes only the workspace subtree. """ ws = (tmp_path / "project").resolve() - profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(ws), str(ws))) parent_deny = profile.index(f"(deny file-read* file-write* (subpath {self._quote(ws.parent)})") workspace_allow = profile.index(f"(allow file-read* file-write* (subpath {self._quote(ws)})") assert parent_deny < workspace_allow def test_no_parent_deny_when_workspace_is_the_root(self): - profile = self._profile(wrap_command("seatbelt", "ls", "/", "/")) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", "/", "/")) assert "(deny file-read*" not in profile @@ -307,20 +293,20 @@ class TestSeatbeltBackend: runs anything. """ ws = (tmp_path / "project").resolve() - profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(ws), str(ws))) assert f"(literal {self._quote(ws.parent)})" in self._metadata_rule(profile) def test_config_dir_is_searchable_but_not_listable(self, tmp_path): ws = (tmp_path / "project").resolve() - profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(ws), str(ws))) assert f"(literal {self._quote(ws.parent)})" in self._metadata_rule(profile) assert f"(allow file-read* (subpath {self._quote(ws.parent)}))" not in profile assert f"(allow file-read* file-write* (subpath {self._quote(ws.parent)}))" not in profile def test_host_scratch_directories_are_not_shared(self, tmp_path): - profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(tmp_path), str(tmp_path))) for path in ("/tmp", "/private/tmp", "/var", "/private/var", "/var/folders", "/private/var/folders", "/Library", "/etc", "/private/etc"): @@ -328,22 +314,22 @@ class TestSeatbeltBackend: def test_home_and_tmpdir_use_workspace(self, tmp_path): ws = tmp_path.resolve() - tokens = _parse(wrap_command("seatbelt", "mktemp", str(ws), str(ws))) + tokens = build_sandbox_argv("seatbelt", "mktemp", str(ws), str(ws)) assert tokens[3:6] == ["/usr/bin/env", f"HOME={ws}", f"TMPDIR={ws}"] def test_network_matches_bwrap_policy(self, tmp_path): - profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(tmp_path), str(tmp_path))) assert "(allow network*)" in profile def test_media_dir_read_only(self, tmp_path, monkeypatch): fake_media = (tmp_path / "media").resolve() fake_media.mkdir() monkeypatch.setattr( - "nanobot.agent.tools.sandbox.get_media_dir", + "nanobot.execution.sandbox.get_media_dir", lambda: fake_media, ) ws = (tmp_path / "project").resolve() - profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(ws), str(ws))) assert f"(allow file-read* (subpath {self._quote(fake_media)}))" in profile assert f"(deny file-write* (subpath {self._quote(fake_media)}))" in profile @@ -351,23 +337,23 @@ class TestSeatbeltBackend: def test_cwd_inside_workspace(self, tmp_path): ws = (tmp_path / "project").resolve() sub = ws / "src" / "lib" - result = wrap_command("seatbelt", "pwd", str(ws), str(sub)) + result = build_sandbox_argv("seatbelt", "pwd", str(ws), str(sub)) - assert _parse(result)[-1] == f"cd {shlex.quote(str(sub))} || exit\npwd" + assert result[-1] == f"cd {shlex.quote(str(sub))} || exit\npwd" def test_cwd_outside_workspace_falls_back(self, tmp_path): ws = (tmp_path / "project").resolve() outside = tmp_path / "other" - result = wrap_command("seatbelt", "pwd", str(ws), str(outside)) + result = build_sandbox_argv("seatbelt", "pwd", str(ws), str(outside)) - assert _parse(result)[-1] == f"cd {shlex.quote(str(ws))} || exit\npwd" + assert result[-1] == f"cd {shlex.quote(str(ws))} || exit\npwd" def test_custom_read_only_binds(self, tmp_path): ws = (tmp_path / "project").resolve() tool_bin = (tmp_path / "home" / ".local" / "bin").resolve(strict=False) profile = self._profile( - wrap_command( + build_sandbox_argv( "seatbelt", "uv --version", str(ws), str(ws), sandbox_ro_binds=[str(tool_bin)], ) @@ -379,7 +365,7 @@ class TestSeatbeltBackend: def test_read_only_bind_overrides_workspace_write(self, tmp_path): ws = tmp_path.resolve() ro = ws / "readonly" - profile = self._profile(wrap_command( + profile = self._profile(build_sandbox_argv( "seatbelt", "ls", str(ws), str(ws), sandbox_ro_binds=[str(ro)], )) assert profile.index(f"(allow file-read* file-write* (subpath {self._quote(ws)}))") < ( @@ -391,8 +377,8 @@ class TestSeatbeltBackend: ws = (tmp_path / "workspace").resolve() ro = ws / 'tree with "quotes' / "branch" / "readonly" media = ro if source == "media" else tmp_path / "media" - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) - profile = self._profile(wrap_command( + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) + profile = self._profile(build_sandbox_argv( "seatbelt", "ls", str(ws), str(ws), sandbox_ro_binds=[str(ro)] if source == "bind" else [], )) @@ -408,8 +394,8 @@ class TestSeatbeltBackend: ws = (tmp_path / "workspace").resolve() ro = ws / "tree" / "readonly" rw = {"root": ro, "parent": ro.parent, "child": ro / "cache"}[override] - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: ro) - profile = self._profile(wrap_command( + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: ro) + profile = self._profile(build_sandbox_argv( "seatbelt", "ls", str(ws), str(ws), sandbox_ro_binds=[str(ro)], sandbox_rw_binds=[str(rw)], )) @@ -442,7 +428,7 @@ class TestSeatbeltBackend: cache_dir = (tmp_path / "cache").resolve(strict=False) profile = self._profile( - wrap_command( + build_sandbox_argv( "seatbelt", "touch cache/file", str(ws), str(ws), sandbox_rw_binds=[str(cache_dir)], ) @@ -455,7 +441,7 @@ class TestSeatbeltBackend: parent = ws.parent.resolve(strict=False) profile = self._profile( - wrap_command( + build_sandbox_argv( "seatbelt", "cat ../config.json", str(ws), str(ws), sandbox_ro_binds=[str(parent)], sandbox_rw_binds=[str(parent)], @@ -469,7 +455,7 @@ class TestSeatbeltBackend: """An unescaped quote would terminate the literal early and silently widen every rule that follows it.""" ws = (tmp_path / 'pro"ject').resolve() - profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + profile = self._profile(build_sandbox_argv("seatbelt", "ls", str(ws), str(ws))) escaped = str(ws).replace("\\", "\\\\").replace('"', '\\"') assert f'(allow file-read* file-write* (subpath "{escaped}"))' in profile @@ -482,9 +468,9 @@ class TestUnknownBackend: def test_raises_value_error(self, tmp_path): ws = str(tmp_path / "project") with pytest.raises(ValueError, match="Unknown sandbox backend"): - wrap_command("nonexistent", "ls", ws, ws) + build_sandbox_argv("nonexistent", "ls", ws, ws) def test_empty_string_raises(self, tmp_path): ws = str(tmp_path / "project") with pytest.raises(ValueError): - wrap_command("", "ls", ws, ws) + build_sandbox_argv("", "ls", ws, ws) diff --git a/tests/tools/test_sandbox_launcher_compat.py b/tests/tools/test_sandbox_launcher_compat.py index 0a1ce5f3e..59083a4f4 100644 --- a/tests/tools/test_sandbox_launcher_compat.py +++ b/tests/tools/test_sandbox_launcher_compat.py @@ -13,10 +13,10 @@ import pytest from nanobot.agent.tools.base import ToolResult from nanobot.agent.tools.exec_session import ExecSessionManager from nanobot.agent.tools.sandbox_check import check_sandbox, sandbox_settings_status -from nanobot.agent.tools.sandbox_launcher import SandboxLauncherError, resolve_sandbox_launcher from nanobot.agent.tools.shell import ExecTool from nanobot.agent.tools.shell_config import ExecToolConfig from nanobot.config.loader import resolve_config_env_vars +from nanobot.security.sandbox_launcher import SandboxLauncherError, resolve_sandbox_launcher @pytest.mark.skipif(os.name != "posix", reason="requires Unix launcher preparation") @@ -28,19 +28,24 @@ async def test_nonstandard_bwrap_is_not_silently_run_without_sandbox(tmp_path, m default_bin = tmp_path / "system-bin" default_bin.mkdir() launcher = extra_bin / "bwrap" - launcher.write_text("#!/bin/sh\nprintf launched > \"$1\"\n") + launcher.write_text("#!/bin/sh\nprintf launched > launcher-ran\n") launcher.chmod(0o700) marker = workspace / "command-ran" monkeypatch.setattr(os, "defpath", str(default_bin)) + monkeypatch.setattr(sys, "platform", "linux") monkeypatch.setenv("PATH", str(extra_bin)) - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: workspace) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: workspace) tool = ExecTool(working_dir=str(workspace), sandbox="bwrap") result = await tool.execute(command="printf ran > command-ran") assert "sandbox launcher not found: bwrap" in result assert isinstance(result, ToolResult) and result.error_code == "sandbox_launcher_missing" + status = await check_sandbox(ExecToolConfig(sandbox="bwrap"), workspace) + assert status["state"] == "unavailable" + assert status["reason"] == "launcher_missing" + assert not (workspace / "launcher-ran").exists() assert not marker.exists() @@ -88,7 +93,7 @@ def test_custom_launcher_requires_existing_absolute_file(path, reason): def test_copied_custom_launcher_config_does_not_assume_unix_permissions_on_windows(monkeypatch): - monkeypatch.setattr("nanobot.agent.tools.sandbox_launcher.os", SimpleNamespace(name="nt")) + monkeypatch.setattr("nanobot.security.sandbox_launcher.os", SimpleNamespace(name="nt")) with pytest.raises(SandboxLauncherError, match="platform_unsupported"): resolve_sandbox_launcher("bwrap", "C:\\tools\\bwrap.exe") @@ -101,11 +106,20 @@ async def test_disabled_settings_do_not_launch_a_probe(settings, state, tmp_path assert (await check_sandbox(ExecToolConfig(**settings), tmp_path))["state"] == state -async def test_unsupported_platform_reports_no_isolation_without_running(tmp_path, monkeypatch): - monkeypatch.setattr(sys, "platform", "win32") - status = await check_sandbox(ExecToolConfig(sandbox="bwrap"), tmp_path) +@pytest.mark.parametrize(("platform", "backend", "supported"), [ + ("win32", "bwrap", None), + ("linux", "seatbelt", "bwrap"), + ("darwin", "bwrap", "seatbelt"), +]) +async def test_unsupported_backend_does_not_run(tmp_path, monkeypatch, platform, backend, supported): + async def unexpected(*args, **kwargs): + pytest.fail("unsupported sandbox must not start a process") + + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr(asyncio, "create_subprocess_exec", unexpected) + status = await check_sandbox(ExecToolConfig(sandbox=backend), tmp_path) assert status["state"] == "unsupported" - assert status["supported_backend"] is None + assert status["supported_backend"] == supported @pytest.mark.skipif(os.name != "posix", reason="Unix native sandbox") @@ -155,6 +169,9 @@ async def test_native_probe_checks_isolation_without_touching_workspace(tmp_path # The same resolver and backend must work for actual command execution. tool = ExecTool(working_dir=str(tmp_path), sandbox=backend, sandbox_launcher=result["launcher"]) assert "actual-command" in await tool.execute(command="printf actual-command") + clock = await tool.execute(command="date +%s") + assert clock.splitlines()[0].isdigit() + assert "Exit code: 0" in clock failed_command = await tool.execute(command="printf 'sandbox launcher not found: bwrap'; exit 1") assert "Exit code: 1" in failed_command assert (failed_command.error_code if isinstance(failed_command, ToolResult) else None) is None @@ -204,6 +221,10 @@ def test_probe_revision_changes_when_saved_policy_changes(tmp_path): @pytest.mark.parametrize("finish", ["timeout", "cancel"]) async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_path, monkeypatch, finish): started, exited = asyncio.Event(), asyncio.Event() + trusted_launcher = tmp_path / "bwrap" + trusted_launcher.touch(mode=0o700) + monkeypatch.setattr(os, "defpath", str(tmp_path)) + monkeypatch.setattr(sys, "platform", "linux") class Process: pid = 12345 @@ -217,6 +238,9 @@ async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_pa async def spawn(*args, **kwargs): assert kwargs["start_new_session"] + assert args[0] == str(trusted_launcher) + assert kwargs["stdin"] == kwargs["stdout"] == kwargs["stderr"] == asyncio.subprocess.DEVNULL + assert kwargs["env"] == {"PATH": str(tmp_path), "HOME": kwargs["cwd"]} started.set() return process @@ -225,10 +249,6 @@ async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_pa process.returncode = -9 exited.set() - monkeypatch.setattr("nanobot.agent.tools.sandbox_check._prepare_settings", lambda config, workspace: (config, workspace, { - "state": "unchecked", "reason": "", "launcher": "/test/launcher", "revision": "test", "supported_backend": "bwrap", - })) - monkeypatch.setattr("nanobot.agent.tools.sandbox_check.resolve_sandbox_launcher", lambda *_args, **_kwargs: "/test/launcher") monkeypatch.setattr("nanobot.agent.tools.sandbox_check._PROBE_TIMEOUT_S", 0.01) monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn) monkeypatch.setattr(os, "killpg", kill) diff --git a/tests/tools/test_sandbox_shell_boundary.py b/tests/tools/test_sandbox_shell_boundary.py index d52b937a4..8861ed436 100644 --- a/tests/tools/test_sandbox_shell_boundary.py +++ b/tests/tools/test_sandbox_shell_boundary.py @@ -29,7 +29,7 @@ async def test_selected_shell_runs_inside_sandbox(tmp_path, monkeypatch, session outside.write_text("unchanged") media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) script = workspace / ("interpreter" if symlink else shell_name) script.write_text( "#!/bin/sh\n" @@ -67,7 +67,7 @@ async def test_selected_shell_runs_inside_sandbox(tmp_path, monkeypatch, session async def test_sandboxed_shell_preserves_ordinary_bash_commands(tmp_path, monkeypatch): media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND) result = await tool.execute(command="items=(hello world); printf '%s' \"${items[1]}\"", shell="bash") assert result.startswith("world\nExit code: 0\n"), result @@ -76,7 +76,7 @@ async def test_sandboxed_shell_preserves_ordinary_bash_commands(tmp_path, monkey async def test_configured_path_cannot_replace_sandbox_launcher(tmp_path, monkeypatch): media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) impostor = tmp_path / ("sandbox-exec" if BACKEND == "seatbelt" else "bwrap") impostor.write_text("#!/bin/sh\nprintf shadowed-launcher") impostor.chmod(0o700) @@ -92,7 +92,7 @@ async def test_login_profile_runs_inside_sandbox(tmp_path, monkeypatch): outside.write_text("unchanged") media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) (workspace / ".bash_profile").write_text( f"printf escaped > {shlex.quote(str(outside))}\n" "export SANDBOX_PROFILE_LOADED=yes\n" @@ -110,7 +110,7 @@ async def test_parent_path_cannot_replace_sandbox_launcher(tmp_path, monkeypatch outside.write_text("unchanged") media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) impostor = workspace / ("sandbox-exec" if BACKEND == "seatbelt" else "bwrap") impostor.write_text( "#!/bin/sh\n" @@ -130,7 +130,7 @@ async def test_parent_path_cannot_replace_sandbox_launcher(tmp_path, monkeypatch async def test_missing_launcher_does_not_run_command_unsandboxed(tmp_path, monkeypatch): media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) original_which = shutil.which launcher = "/usr/bin/sandbox-exec" if BACKEND == "seatbelt" else "bwrap" monkeypatch.setattr( @@ -150,7 +150,7 @@ async def test_trusted_shell_completion_preserves_sandbox(tmp_path, monkeypatch) workspace.mkdir() media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) tool = ExecTool(working_dir=str(workspace), sandbox=BACKEND) result = await tool.execute_to_completion("printf complete > result", str(workspace)) @@ -162,7 +162,7 @@ async def test_trusted_shell_completion_preserves_sandbox(tmp_path, monkeypatch) async def test_sandbox_preserves_literal_argument_vector(tmp_path, monkeypatch): media = tmp_path / "media" media.mkdir() - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media) tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND) literal = "hello | $HOME; 'world'" diff --git a/tests/tools/test_seatbelt_native.py b/tests/tools/test_seatbelt_native.py index 50b42870f..467dedf7a 100644 --- a/tests/tools/test_seatbelt_native.py +++ b/tests/tools/test_seatbelt_native.py @@ -44,7 +44,7 @@ def layout(tmp_path, monkeypatch): (paths[name] / "sentinel").write_text("synthetic-data") paths["link"] = paths["workspace"] / "outside-link" paths["link"].symlink_to(paths["peer"], target_is_directory=True) - monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: paths["media"]) + monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: paths["media"]) yield paths