fix(exec): tighten Seatbelt filesystem and launcher boundaries

Keep temporary work inside the granted workspace instead of exposing host scratch trees, enforce read-only roots, and pin the system sandbox launcher before PATH lookup. Preserve documented network access and the narrow system paths needed by shell and Git.

Add native macOS containment and launcher regressions plus shared backend contract coverage. Document scratch and custom-tool requirements without changing existing bwrap or Windows behavior.
This commit is contained in:
Xubin Ren committed 2026-09-10 00:00:44 +08:00
1 parent 947ed17e8b
commit 8b9e35bf78
8 files changed
+241 -55

No files matched your search

+15 -12
View File
@@ -487,8 +487,9 @@ class TestPathAppendPlatform:
class TestSandboxPlatform:
@pytest.mark.asyncio
async def test_bwrap_skipped_on_windows(self):
"""bwrap must be silently skipped on Windows, not crash."""
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_skipped_on_windows(self, backend):
"""Configured Unix backends preserve the Windows native fallback."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"ok", b"")
mock_proc.returncode = 0
@@ -498,15 +499,16 @@ class TestSandboxPlatform:
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(sandbox="bwrap")
tool = ExecTool(sandbox=backend)
result = await tool.execute(command="dir")
assert "ok" in result
spawned_cmd = mock_spawn.call_args[0][0]
assert "bwrap" not in spawned_cmd
assert backend not in spawned_cmd
@pytest.mark.asyncio
async def test_bwrap_applied_on_unix(self):
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_applied_on_unix(self, backend):
"""On Unix, sandbox wrapping should still happen normally."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"sandboxed", b"")
@@ -514,20 +516,21 @@ class TestSandboxPlatform:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.wrap_command", return_value="bwrap -- sh -c ls") as mock_wrap,
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{backend} -- sh -c ls") as mock_wrap,
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(sandbox="bwrap", working_dir="/workspace")
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 "bwrap" in spawned_cmd
assert backend in spawned_cmd
@pytest.mark.asyncio
async def test_bwrap_receives_configured_bind_roots(self, tmp_path):
"""Configured bwrap bind roots should be forwarded to the sandbox wrapper."""
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_receives_configured_bind_roots(self, tmp_path, backend):
"""Configured bind roots should be forwarded to the sandbox wrapper."""
mock_proc = AsyncMock()
mock_proc.communicate.return_value = (b"sandboxed", b"")
mock_proc.returncode = 0
@@ -536,12 +539,12 @@ class TestSandboxPlatform:
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
patch("nanobot.agent.tools.shell.wrap_command", return_value="bwrap -- sh -c ls") as mock_wrap,
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{backend} -- sh -c ls") as mock_wrap,
patch.object(ExecTool, "_spawn", return_value=mock_proc),
patch.object(ExecTool, "_guard_command", return_value=None),
):
tool = ExecTool(
sandbox="bwrap",
sandbox=backend,
working_dir="/workspace",
sandbox_ro_binds=[str(tool_bin)],
sandbox_rw_binds=[str(tool_cache)],
+10 -7
View File
@@ -373,7 +373,8 @@ def test_exec_still_blocks_real_outside_path_via_redirect(tmp_path):
assert "path outside working dir" in blocked
def test_exec_allows_absolute_path_inside_bwrap_ro_bind(tmp_path, monkeypatch):
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
def test_exec_allows_absolute_path_inside_sandbox_ro_bind(tmp_path, monkeypatch, backend):
workspace = tmp_path / "workspace"
workspace.mkdir()
tool_bin = tmp_path / "home" / ".local" / "bin"
@@ -384,7 +385,7 @@ def test_exec_allows_absolute_path_inside_bwrap_ro_bind(tmp_path, monkeypatch):
tool = ExecTool(
working_dir=str(workspace),
restrict_to_workspace=True,
sandbox="bwrap",
sandbox=backend,
sandbox_ro_binds=[str(tool_bin)],
)
@@ -398,7 +399,8 @@ def test_exec_allows_absolute_path_inside_bwrap_ro_bind(tmp_path, monkeypatch):
assert blocked is None
def test_exec_allows_absolute_path_inside_bwrap_rw_bind(tmp_path, monkeypatch):
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
def test_exec_allows_absolute_path_inside_sandbox_rw_bind(tmp_path, monkeypatch, backend):
workspace = tmp_path / "workspace"
workspace.mkdir()
cache_dir = tmp_path / "cache"
@@ -407,7 +409,7 @@ def test_exec_allows_absolute_path_inside_bwrap_rw_bind(tmp_path, monkeypatch):
tool = ExecTool(
working_dir=str(workspace),
restrict_to_workspace=True,
sandbox="bwrap",
sandbox=backend,
sandbox_rw_binds=[str(cache_dir)],
)
@@ -421,7 +423,7 @@ def test_exec_allows_absolute_path_inside_bwrap_rw_bind(tmp_path, monkeypatch):
assert blocked is None
def test_exec_bind_roots_do_not_widen_guard_without_bwrap(tmp_path):
def test_exec_bind_roots_do_not_widen_guard_without_sandbox(tmp_path):
workspace = tmp_path / "workspace"
workspace.mkdir()
tool_bin = tmp_path / "home" / ".local" / "bin"
@@ -446,7 +448,8 @@ def test_exec_bind_roots_do_not_widen_guard_without_bwrap(tmp_path):
assert "path outside working dir" in blocked
def test_exec_bwrap_bind_parent_does_not_widen_workspace_guard(tmp_path, monkeypatch):
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
def test_exec_sandbox_bind_parent_does_not_widen_workspace_guard(tmp_path, monkeypatch, backend):
workspace = tmp_path / "workspace"
workspace.mkdir()
secret = tmp_path / "config.json"
@@ -455,7 +458,7 @@ def test_exec_bwrap_bind_parent_does_not_widen_workspace_guard(tmp_path, monkeyp
tool = ExecTool(
working_dir=str(workspace),
restrict_to_workspace=True,
sandbox="bwrap",
sandbox=backend,
sandbox_ro_binds=[str(tmp_path)],
)
+26 -10
View File
@@ -254,7 +254,7 @@ class TestSeatbeltBackend:
result = wrap_command("seatbelt", "echo hi", ws, ws)
tokens = _parse(result)
assert tokens[0] == "sandbox-exec"
assert tokens[0] == "/usr/bin/sandbox-exec"
assert tokens[1] == "-p"
assert tokens[-3] == "sh"
assert tokens[-2] == "-c"
@@ -323,15 +323,21 @@ class TestSeatbeltBackend:
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_scratch_space_covers_the_tmp_symlink_spelling(self, tmp_path):
"""`/tmp` and `/var` are symlinks; commands spell scratch paths both ways."""
def test_host_scratch_directories_are_not_shared(self, tmp_path):
profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path)))
write_rule = next(
line for line in profile.splitlines() if line.startswith("(allow file-write* ")
)
for expected in ('(subpath "/tmp")', '(subpath "/private/tmp")'):
assert expected in write_rule
for path in ("/tmp", "/private/tmp", "/var", "/private/var", "/var/folders",
"/private/var/folders", "/Library", "/etc", "/private/etc"):
assert f'(subpath "{path}")' not in profile
def test_home_and_tmpdir_use_workspace(self, tmp_path):
ws = tmp_path.resolve()
tokens = _parse(wrap_command("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)))
assert "(allow network*)" in profile
def test_media_dir_read_only(self, tmp_path, monkeypatch):
fake_media = (tmp_path / "media").resolve()
@@ -344,7 +350,7 @@ class TestSeatbeltBackend:
profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws)))
assert f"(allow file-read* (subpath {self._quote(fake_media)}))" in profile
assert f"file-write* (subpath {self._quote(fake_media)})" not in profile
assert f"(deny file-write* (subpath {self._quote(fake_media)}))" in profile
def test_cwd_inside_workspace(self, tmp_path):
ws = (tmp_path / "project").resolve()
@@ -372,7 +378,17 @@ class TestSeatbeltBackend:
)
assert f"(allow file-read* (subpath {self._quote(tool_bin)}))" in profile
assert f"file-write* (subpath {self._quote(tool_bin)})" not in profile
assert f"(deny file-write* (subpath {self._quote(tool_bin)}))" in profile
def test_read_only_bind_overrides_workspace_write(self, tmp_path):
ws = tmp_path.resolve()
ro = ws / "readonly"
profile = self._profile(wrap_command(
"seatbelt", "ls", str(ws), str(ws), sandbox_ro_binds=[str(ro)],
))
assert profile.index(f"(allow file-read* file-write* (subpath {self._quote(ws)}))") < (
profile.index(f"(deny file-write* (subpath {self._quote(ro)}))")
)
def test_custom_read_write_binds(self, tmp_path):
ws = (tmp_path / "project").resolve()
+142
View File
@@ -0,0 +1,142 @@
"""Exercise the kernel policy, not merely the presence of SBPL text.
Linux/Windows CI retain the portable generation tests in test_sandbox.py.
These native tests use only isolated fixtures and a loopback HTTP service.
"""
import shlex
import shutil
import sys
import tempfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Thread
import pytest
from nanobot.agent.tools.shell import ExecTool
pytestmark = pytest.mark.skipif(
sys.platform != "darwin" or shutil.which("sandbox-exec") is None,
reason="requires native macOS Seatbelt",
)
@pytest.fixture
def layout(tmp_path, monkeypatch):
root = tmp_path.resolve()
# A separate host /tmp root must not inherit the workspace-parent deny.
with tempfile.TemporaryDirectory(prefix="nanobot-seatbelt-peer-", dir="/tmp") as peer:
paths = {
"workspace": root / 'project with "quotes',
"config": root / "config.json",
"media": root / "media",
"peer": Path(peer).resolve(),
}
paths["workspace"].mkdir()
paths["media"].mkdir()
paths["config"].write_text("synthetic-config")
paths["ro"] = paths["workspace"] / "readonly"
paths["ro"].mkdir()
paths["rw"] = paths["peer"] / "cache"
paths["rw"].mkdir()
for name in ("workspace", "media", "peer", "ro", "rw"):
(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"])
yield paths
async def run_script(paths, script):
workspace = paths["workspace"]
(workspace / "probe.sh").write_text(script)
tool = ExecTool(
working_dir=str(workspace), sandbox="seatbelt",
sandbox_ro_binds=[str(paths["ro"])], sandbox_rw_binds=[str(paths["rw"])],
)
# Scripts are legitimate exec input; the kernel must enforce their effects.
return str(await tool.execute(command="sh probe.sh", timeout=5))
@pytest.mark.parametrize("target", ["workspace", "media", "ro", "rw"])
async def test_native_allowed_reads(layout, target):
result = await run_script(layout, f"cat {shlex.quote(str(layout[target] / 'sentinel'))}")
assert result == "synthetic-data\n\nExit code: 0"
@pytest.mark.parametrize("target", ["config", "peer", "link"])
async def test_native_outside_reads_denied(layout, target):
path = layout[target] if target == "config" else layout[target] / "sentinel"
result = await run_script(layout, f"cat {shlex.quote(str(path))}")
assert "Operation not permitted" in result
assert "synthetic-" not in result
@pytest.mark.parametrize("target", ["workspace", "rw"])
async def test_native_explicit_writes_allowed(layout, target):
path = layout[target] / "sentinel"
result = await run_script(layout, f"printf changed > {shlex.quote(str(path))}")
assert result == "\nExit code: 0"
assert path.read_text() == "changed"
@pytest.mark.parametrize("target", ["config", "peer", "link", "ro", "media"])
async def test_native_other_writes_denied(layout, target):
path = layout[target] if target == "config" else layout[target] / "sentinel"
before = path.read_text()
result = await run_script(layout, f"printf changed > {shlex.quote(str(path))}")
assert "Operation not permitted" in result
assert path.read_text() == before
async def test_native_scratch_and_home_stay_in_workspace(layout):
# Apple mktemp with no template prefers confstr's host temp directory even
# when TMPDIR is set. Use an explicit template; do not expose host scratch.
result = await run_script(
layout, 'printf "%s\\n" "$HOME"; mktemp "$TMPDIR/probe.XXXXXX" && printf ok > /dev/null',
)
assert "STDERR" not in result
assert result.endswith("Exit code: 0")
assert all(line.startswith(str(layout["workspace"])) for line in result.splitlines()[:2])
async def test_native_system_git_starts(layout):
result = await run_script(layout, "git --version")
assert "git version " in result
assert result.endswith("Exit code: 0")
async def test_native_launcher_cannot_be_shadowed_by_project_path(layout):
workspace = layout["workspace"]
impostor = workspace / "sandbox-exec"
impostor.write_text("#!/bin/sh\nprintf shadowed-launcher")
impostor.chmod(0o700)
tool = ExecTool(
working_dir=str(workspace), sandbox="seatbelt", path_prepend=str(workspace),
)
result = str(await tool.execute(command="printf real-sandbox", timeout=5))
assert result == "real-sandbox\n\nExit code: 0"
async def test_native_network_remains_available(layout):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"network-ok")
def log_message(self, *args):
pass
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
result = await run_script(
layout, f"curl --noproxy '*' --max-time 2 -sS http://127.0.0.1:{server.server_port}",
)
assert result == "network-ok\n\nExit code: 0"
finally:
server.shutdown()
thread.join(timeout=3)