From 8b9e35bf780aa6f6f49d000c951b427d5066be18 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Mon, 7 Sep 2026 17:56:13 +0800 Subject: [PATCH] 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. --- .agent/security.md | 2 +- SECURITY.md | 10 +- docs/configuration.md | 2 +- nanobot/agent/tools/sandbox.py | 60 ++++++++---- tests/tools/test_exec_platform.py | 27 +++--- tests/tools/test_exec_security.py | 17 ++-- tests/tools/test_sandbox.py | 36 +++++-- tests/tools/test_seatbelt_native.py | 142 ++++++++++++++++++++++++++++ 8 files changed, 241 insertions(+), 55 deletions(-) create mode 100644 tests/tools/test_seatbelt_native.py diff --git a/.agent/security.md b/.agent/security.md index 91f2f41b1..faedd9e54 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. The only backend currently shipped is `bwrap` (bubblewrap), intended for containerized deployments. On Windows and bare-metal Linux without `bwrap`, commands run in the native shell with workspace restriction as an application-level guard only. +`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. **Rule**: If adding a new sandbox backend, implement `_wrap_(command, workspace, cwd) -> str` and register it in `_BACKENDS`. diff --git a/SECURITY.md b/SECURITY.md index 9032f44d4..513bc668f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -79,13 +79,13 @@ The `exec` tool can execute shell commands. While dangerous command patterns are **Exec sandbox (bwrap on Linux, seatbelt on macOS):** -Set `"tools.exec.sandbox"` to wrap every shell command in an OS sandbox. Both backends enforce the same policy: +Set `"tools.exec.sandbox"` to wrap every shell command in an OS sandbox. Both backends restrict filesystem access: - Workspace directory → **read-write** (agent works normally) - Media directory → **read-only** (can read uploaded attachments) - System directories (`/usr`, `/bin`, `/lib`) → **read-only** (commands still work) -- Config files and API keys (`~/.nanobot/config.json`) → **hidden** -- Everything else, including `~/.ssh` → **denied** +- The workspace's parent, which holds `~/.nanobot/config.json` in the default layout → **denied**, except for explicitly exposed roots +- Unlisted paths, including `~/.ssh` in the default layout → **denied** | Backend | Value | Platform | Requires | |---------|-------|----------|----------| @@ -94,7 +94,9 @@ Set `"tools.exec.sandbox"` to wrap every shell command in an OS sandbox. Both ba **Windows has no backend**: nanobot logs a warning and runs the command unsandboxed. -The backends hide the config directory differently. `bwrap` masks the workspace's parent with a tmpfs, so it disappears from directory listings. Seatbelt has no mount namespace, so it denies the parent instead — the directory still appears in listings, but its contents are unreadable. +The backends protect the workspace's parent differently. `bwrap` masks it with a tmpfs and re-exposes the workspace and allowed binds. Seatbelt has no mount namespace: it denies the parent, re-allows traversal metadata, and exposes the workspace and allowed roots. Keep configuration and credentials outside the workspace and extra binds; choosing an overly broad workspace or explicitly exposing secret-bearing paths defeats that separation. + +Seatbelt does **not** expose the host's shared `/tmp`, `/var/folders`, `/Library`, or `/etc` trees. It allows system code, device reads and selected system configuration/certificate paths. `HOME` and `TMPDIR` point to the workspace. Tools must use that scratch location; on macOS use an explicit template such as `mktemp "$TMPDIR/job.XXXXXX"`, since bare `mktemp` may prefer the host's system temp directory. Tools that require other installations or caches need narrow `sandboxRoBinds` / `sandboxRwBinds`. Read-only binds revoke workspace writes beneath them; explicit read-write binds are applied last, matching bwrap's operator-controlled precedence. This is filesystem containment, not a VM or separate user identity. Neither backend restricts network access. diff --git a/docs/configuration.md b/docs/configuration.md index 4ca5d0b02..41ed6f25b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2110,7 +2110,7 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets] |--------|---------|-------------| | `tools.restrictToWorkspace` | `false` | When `true`, enables nanobot's application-level workspace guards for workspace-aware tools. File tools resolve paths under the active workspace; selected internal roots can be added as read-only or explicitly write-enabled roots, and media uploads are read-only by default. Shell execution rejects workspace-external `working_dir` values and applies best-effort command path checks, but this is not an OS sandbox. | | `tools.maxSessionMessagesPerMinute` | `6` | Maximum messages one source session may send during any rolling 60-second window. Additional sends are rejected to stop runaway agent loops. | -| `tools.exec.sandbox` | `""` | Sandbox backend for shell commands. Set to `"bwrap"` (Linux) or `"seatbelt"` (macOS) to wrap exec calls in an OS sandbox — the process can only see the workspace (read-write) and media directory (read-only); config files and API keys are hidden. Automatically enables workspace restriction for file tools. `"bwrap"` requires `bwrap` installed (`apt install bubblewrap`; pre-installed in the Docker image) and depends on Linux kernel namespaces. `"seatbelt"` uses the `sandbox-exec(1)` binary shipped with macOS. Neither backend is available on Windows, where nanobot logs a warning and runs commands unsandboxed. | +| `tools.exec.sandbox` | `""` | Sandbox backend for shell commands. `"bwrap"` (Linux) or `"seatbelt"` (macOS) restricts filesystem access to the workspace (read-write), media (read-only), required system paths and configured extra binds. The workspace's parent is denied except for allowed roots; keep secrets outside the workspace and binds. Automatically enables workspace restriction for file tools. `"bwrap"` requires bubblewrap (`apt install bubblewrap`; pre-installed in Docker). `"seatbelt"` uses macOS `sandbox-exec(1)`; it sets `HOME` and `TMPDIR` to the workspace rather than sharing host temporary directories. Use `mktemp "$TMPDIR/job.XXXXXX"` for macOS shell scratch files. Neither backend restricts network access. Windows logs a warning and runs commands without OS sandboxing. | | `tools.exec.enable` | `true` | When `false`, the shell `exec` tool is not registered at all. Use this to completely disable shell command execution. | | `tools.exec.timeout` | `60` | Default hard timeout in seconds for shell commands. Config values may exceed the per-call tool cap; set `0` to disable the hard timeout for trusted long-running commands. | | `tools.exec.pathPrepend` | `""` | Extra directories to prepend to `PATH` when running shell commands. Use this when configured tools should win executable lookup precedence, such as a Python virtual environment's `bin` or `Scripts` directory. | diff --git a/nanobot/agent/tools/sandbox.py b/nanobot/agent/tools/sandbox.py index 8aa7bfccd..6cba5dd1b 100644 --- a/nanobot/agent/tools/sandbox.py +++ b/nanobot/agent/tools/sandbox.py @@ -101,28 +101,34 @@ def _bwrap( return shlex.join(args) -# Directories every command needs to read for the dynamic linker, system -# binaries, certificates and device nodes. Seatbelt evaluates resolved paths, -# so the /private-prefixed form is what actually matches on macOS; the bare -# symlink form is listed too because commands spell paths both ways. +# System code and certificates needed by command-line tools. Do not grant +# /var, /tmp, /Library or /etc wholesale: those contain host application data, +# not an isolated scratch filesystem as in bwrap. Seatbelt matches real paths. _SEATBELT_SYSTEM_READ_SUBPATHS = ( "/usr", "/bin", "/sbin", - "/etc", "/dev", "/System", - "/Library", - "/private/etc", - "/var", - "/private/var", - "/tmp", - "/private/tmp", + "/Library/Developer/CommandLineTools", + "/private/etc/ssl", + "/private/var/db/dyld", + "/private/var/db/timezone", ) -# Writable scratch space. /private/var/folders holds $TMPDIR, which build tools -# and test runners rely on; /tmp is its symlink spelling. -_SEATBELT_SCRATCH_SUBPATHS = ("/tmp", "/private/tmp", "/var/folders", "/private/var/folders") +_SEATBELT_SYSTEM_READ_LITERALS = ( + "/private/etc/hosts", + "/private/etc/services", + "/private/etc/protocols", + "/private/etc/gitconfig", + "/etc/gitconfig", + "/private/var/run/resolv.conf", + "/private/var/select/sh", + "/private/var/select/developer_dir", + "/private/var/db/xcode_select_link", + "/var/select/developer_dir", + "/var/db/xcode_select_link", +) # Ancestors that must stay searchable but are not covered by any allowed # subpath. Resolving "/private/var/..." stats "/private", and @@ -171,9 +177,10 @@ def _seatbelt( ) -> str: """Wrap command in a macOS Seatbelt sandbox (requires sandbox-exec(1)). - Mirrors the ``bwrap`` policy: the workspace is read-write, the media - directory is read-only, and the workspace's parent (which holds - ``config.json``) is unreadable so API keys stay hidden. + The workspace is read-write and media is read-only. The workspace's parent + (the config directory in the default layout) is denied. Host temporary and + application-data directories are not shared; TMPDIR and HOME use the + workspace instead. Additional tool installations need explicit read binds. Seatbelt has no mount namespace, so masking the parent is expressed as a deny rule placed *before* the workspace allow — the last matching rule @@ -205,12 +212,16 @@ def _seatbelt( "(allow sysctl-read)", "(allow mach*)", "(allow ipc*)", + "(allow network*)", # sh(1) reads the root directory while resolving a path, and # (subpath "/usr") does not cover "/" itself. Without this rule the # shell aborts during startup. '(allow file-read* (literal "/"))', f"(allow file-read* {subpaths(_SEATBELT_SYSTEM_READ_SUBPATHS)})", - f"(allow file-write* {subpaths(_SEATBELT_SCRATCH_SUBPATHS)})", + "(allow file-read* " + + " ".join(f"(literal {_sbpl_quote(p)})" for p in _SEATBELT_SYSTEM_READ_LITERALS) + + ")", + '(allow file-write* (literal "/dev/null") (literal "/dev/zero"))', ] # Mask the config directory. The workspace allow below re-exposes the @@ -222,7 +233,9 @@ def _seatbelt( # Keep every ancestor of an allowed path searchable, including the masked # parent: metadata only, so it cannot be listed or read. traversable = _seatbelt_ancestors( - ws, media, *(Path(p) for p in ro_binds), *(Path(p) for p in rw_binds) + ws, media, *(Path(p) for p in ro_binds), *(Path(p) for p in rw_binds), + *(Path(p) for p in _SEATBELT_SYSTEM_READ_SUBPATHS), + *(Path(p) for p in _SEATBELT_SYSTEM_READ_LITERALS), ) literals = [ *(p for p in _SEATBELT_TRAVERSABLE_LITERALS if p not in traversable), @@ -236,18 +249,25 @@ def _seatbelt( rules.append(f"(allow file-read* file-write* (subpath {_sbpl_quote(str(ws))}))") rules.append(f"(allow file-read* (subpath {_sbpl_quote(str(media))}))") + rules.append(f"(deny file-write* (subpath {_sbpl_quote(str(media))}))") for p in ro_binds: rules.append(f"(allow file-read* (subpath {_sbpl_quote(p)}))") + # A read allow does not revoke a broader write grant (e.g. workspace). + rules.append(f"(deny file-write* (subpath {_sbpl_quote(p)}))") for p in rw_binds: rules.append(f"(allow file-read* file-write* (subpath {_sbpl_quote(p)}))") # sandbox-exec(1) has no --chdir, so the working directory is entered by # the wrapped shell. `&&` keeps the command from running if cd is denied. args = [ - "sandbox-exec", + # Resolve the security boundary before consulting operator tool PATHs. + "/usr/bin/sandbox-exec", "-p", "\n".join(rules), + "/usr/bin/env", + f"HOME={ws}", + f"TMPDIR={ws}", "sh", "-c", f"cd {shlex.quote(sandbox_cwd)} && {command}", diff --git a/tests/tools/test_exec_platform.py b/tests/tools/test_exec_platform.py index 24ac42928..44a3f8b59 100644 --- a/tests/tools/test_exec_platform.py +++ b/tests/tools/test_exec_platform.py @@ -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)], diff --git a/tests/tools/test_exec_security.py b/tests/tools/test_exec_security.py index c6e6af8de..25e3c6c2e 100644 --- a/tests/tools/test_exec_security.py +++ b/tests/tools/test_exec_security.py @@ -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)], ) diff --git a/tests/tools/test_sandbox.py b/tests/tools/test_sandbox.py index c8a199a46..b6682ddaa 100644 --- a/tests/tools/test_sandbox.py +++ b/tests/tools/test_sandbox.py @@ -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() diff --git a/tests/tools/test_seatbelt_native.py b/tests/tools/test_seatbelt_native.py new file mode 100644 index 000000000..39760fa32 --- /dev/null +++ b/tests/tools/test_seatbelt_native.py @@ -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)