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
This commit is contained in:
Xubin Ren authored and GitHub committed 2026-11-13 15:29:01 +08:00
1 parent 0f5e56edd4
commit 90d69e7a11
14 files changed
+236 -275

No files matched your search

+26 -34
View File
@@ -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:
+54 -68
View File
@@ -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)
+32 -12
View File
@@ -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)
+8 -8
View File
@@ -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'"
+1 -1
View File
@@ -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