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

+1 -1
View File
@@ -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) | | 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) | | 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 | | 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/) | | 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. 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.
+2 -2
View File
@@ -24,6 +24,6 @@ HTTP/SSE MCP transports are part of this boundary: validate configured MCP URLs
## Shell Sandbox ## 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.
+28 -37
View File
@@ -7,20 +7,20 @@ import hashlib
import json import json
import os import os
import shlex import shlex
import signal
import tempfile import tempfile
from pathlib import Path from pathlib import Path
from typing import TypedDict 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.agent.tools.shell_config import ExecToolConfig
from nanobot.config.errors import ConfigLoadError from nanobot.config.errors import ConfigLoadError
from nanobot.config.loader import resolve_config_env_vars 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 _PROBE_TIMEOUT_S = 5
@@ -34,13 +34,11 @@ class SandboxCheck(TypedDict):
def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxCheck: 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]: def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecToolConfig, SandboxCheck]:
import sys backend = supported_sandbox_backend()
backend = "bwrap" if sys.platform.startswith("linux") else "seatbelt" if sys.platform == "darwin" else None
missing_env = False missing_env = False
try: try:
config = resolve_config_env_vars(config) config = resolve_config_env_vars(config)
@@ -58,7 +56,7 @@ def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecTool
result["state"] = "disabled" result["state"] = "disabled"
elif not config.sandbox: elif not config.sandbox:
result["state"] = "off" result["state"] = "off"
elif sandbox_platform(config.sandbox) == "unsupported": elif config.sandbox != backend:
result.update(state="unsupported", reason="platform_unsupported") result.update(state="unsupported", reason="platform_unsupported")
elif missing_env: elif missing_env:
result.update(state="unavailable", reason="path_unavailable") result.update(state="unavailable", reason="path_unavailable")
@@ -70,11 +68,11 @@ def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecTool
) )
except SandboxLauncherError as exc: except SandboxLauncherError as exc:
result.update(state="unavailable", reason=exc.reason) result.update(state="unavailable", reason=exc.reason)
return config, workspace, result return config, result
async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck: 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": if result["state"] != "unchecked":
return result return result
# Use synthetic files only. Never run startup/login profiles or an arbitrary # 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. # same path. What must stay unchanged is the host-side canary.
f"(printf changed > {shlex.quote(str(canary))} || true)" 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: try:
argv[0] = resolve_sandbox_launcher( argv = build_sandbox_argv(
config.sandbox, config.sandbox_launcher, config.sandbox, script, str(project), str(project),
writable_roots=(project, *map(Path, config.sandbox_rw_binds)), launcher=config.sandbox_launcher,
sandbox_ro_binds=config.sandbox_ro_binds,
sandbox_rw_binds=config.sandbox_rw_binds,
) )
result["launcher"] = argv[0] result["launcher"] = argv[0]
except SandboxLauncherError as exc: except SandboxLauncherError as exc:
result.update(state="unavailable", reason=exc.reason) result.update(state="unavailable", reason=exc.reason)
return result return result
process: asyncio.subprocess.Process | None = None tree: processes.ProcessTree | None = None
try: try:
process = await asyncio.create_subprocess_exec( tree = await processes.spawn_process_tree(
*argv, cwd=str(project), env={"PATH": os.defpath, "HOME": str(project)}, argv, str(project), {"PATH": os.defpath, "HOME": str(project)}, capture_output=False,
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL, start_new_session=True,
) )
await asyncio.wait_for(process.wait(), timeout=_PROBE_TIMEOUT_S) code = await asyncio.wait_for(tree.process.wait(), timeout=_PROBE_TIMEOUT_S)
success = process.returncode == 0 and (project / "inside").read_text() == "checked" and canary.read_text() == "unchanged" 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") result.update(state="passed" if success else "unavailable", reason="" if success else "probe_failed")
except TimeoutError: except TimeoutError:
result.update(state="unavailable", reason="probe_timeout") result.update(state="unavailable", reason="probe_timeout")
except OSError: except OSError:
result.update(state="unavailable", reason="probe_failed") result.update(state="unavailable", reason="probe_failed")
finally: finally:
if process is not None and process.returncode is None: if tree is not None:
try: if tree.process.returncode is None:
os.killpg(process.pid, signal.SIGKILL) await tree.terminate()
except ProcessLookupError: else:
pass tree.finish()
await process.wait()
return result return result
+8 -15
View File
@@ -26,8 +26,6 @@ from nanobot.agent.tools.exec_session import (
clamp_session_int, clamp_session_int,
format_session_poll, 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 ( from nanobot.agent.tools.schema import (
BooleanSchema, BooleanSchema,
IntegerSchema, IntegerSchema,
@@ -36,6 +34,8 @@ from nanobot.agent.tools.schema import (
) )
from nanobot.agent.tools.shell_config import ExecToolConfig from nanobot.agent.tools.shell_config import ExecToolConfig
from nanobot.config.paths import get_media_dir 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_access import current_scope_allows_loopback, current_tool_workspace
from nanobot.security.workspace_policy import is_path_within from nanobot.security.workspace_policy import is_path_within
@@ -436,24 +436,17 @@ class ExecTool(Tool):
args.append("-l") args.append("-l")
payload = shlex.join([*args, "-c", command]) payload = shlex.join([*args, "-c", command])
workspace = workspace_root or cwd 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: try:
command[0] = resolve_sandbox_launcher( command = build_sandbox_argv(
self.sandbox, self.sandbox_launcher, self.sandbox, payload, workspace, cwd,
writable_roots=(Path(workspace), *self.sandbox_rw_binds), 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: except SandboxLauncherError as exc:
if exc.reason == "launcher_missing": if exc.reason == "launcher_missing":
return ToolResult.error( 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( return ToolResult.error(
f"Error: sandbox launcher rejected: {exc.reason}", error_code=f"sandbox_{exc.reason}", f"Error: sandbox launcher rejected: {exc.reason}", error_code=f"sandbox_{exc.reason}",
+4 -4
View File
@@ -56,6 +56,7 @@ async def spawn_process_tree(
login: bool = False, login: bool = False,
*, *,
stdin: int = asyncio.subprocess.DEVNULL, stdin: int = asyncio.subprocess.DEVNULL,
capture_output: bool = True,
) -> ProcessTree: ) -> ProcessTree:
"""Start a prepared command in its own process group or Windows job.""" """Start a prepared command in its own process group or Windows job."""
if isinstance(command, list): if isinstance(command, list):
@@ -87,18 +88,17 @@ async def spawn_process_tree(
job = _create_windows_job() if _IS_WINDOWS else None job = _create_windows_job() if _IS_WINDOWS else None
creationflags = job.creation_flags if job is not None else 0 creationflags = job.creation_flags if job is not None else 0
output = asyncio.subprocess.PIPE if capture_output else asyncio.subprocess.DEVNULL
process = None process = None
try: try:
if isinstance(launch, str): if isinstance(launch, str):
process = await asyncio.create_subprocess_shell( process = await asyncio.create_subprocess_shell(
launch, stdin=stdin, stdout=asyncio.subprocess.PIPE, launch, stdin=stdin, stdout=output, stderr=output, cwd=cwd, env=env,
stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env,
creationflags=creationflags, creationflags=creationflags,
) )
else: else:
process = await asyncio.create_subprocess_exec( process = await asyncio.create_subprocess_exec(
*launch, stdin=stdin, stdout=asyncio.subprocess.PIPE, *launch, stdin=stdin, stdout=output, stderr=output, cwd=cwd, env=env,
stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env,
creationflags=creationflags, creationflags=creationflags,
start_new_session=not _IS_WINDOWS, start_new_session=not _IS_WINDOWS,
) )
@@ -1,8 +1,7 @@
"""Sandbox backends for shell command execution. """Sandbox backends for shell command execution.
To add a backend, match the callable signature of _bwrap and _seatbelt, To add a backend, match the callable signature of _bwrap and _seatbelt and
including keyword-only sandbox_ro_binds and sandbox_rw_binds, and register register it in _BACKENDS below.
it in _BACKENDS below.
""" """
import os import os
@@ -11,16 +10,16 @@ from pathlib import Path
from typing import Iterable from typing import Iterable
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.security.sandbox_launcher import resolve_sandbox_launcher
def _normalize_bind_paths( def _normalize_bind_paths(
paths: Iterable[str] | None, paths: Iterable[str],
*, *,
workspace: Path | None = None, workspace: Path,
) -> list[str]: ) -> list[str]:
out: list[str] = [] binds: dict[str, None] = {}
seen: set[str] = set() for raw in paths:
for raw in paths or []:
value = str(raw).strip() value = str(raw).strip()
if not value: if not value:
continue continue
@@ -28,40 +27,23 @@ def _normalize_bind_paths(
if not path.is_absolute(): if not path.is_absolute():
continue continue
resolved_path = path.resolve(strict=False) resolved_path = path.resolve(strict=False)
if workspace is not None: # A later bind of the workspace or an ancestor could cover the
try: # tmpfs that hides the config directory.
workspace.relative_to(resolved_path) if workspace.is_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:
continue continue
seen.add(resolved) binds[str(resolved_path)] = None
out.append(resolved) return list(binds)
return out
def _bwrap( def _bwrap(
command: str, command: str,
workspace: str, ws: Path,
cwd: str, sandbox_cwd: str,
*, *,
sandbox_ro_binds: Iterable[str] | None = None, media: Path,
sandbox_rw_binds: Iterable[str] | None = None, ro_binds: list[str],
) -> str: rw_binds: list[str],
ws = Path(workspace).resolve() ) -> list[str]:
media = get_media_dir().resolve()
try:
sandbox_cwd = str(ws / Path(cwd).resolve().relative_to(ws))
except ValueError:
sandbox_cwd = str(ws)
required = ["/usr"]
optional = [ optional = [
"/bin", "/bin",
"/lib", "/lib",
@@ -75,9 +57,10 @@ def _bwrap(
"/etc/ld.so.cache", "/etc/ld.so.cache",
] ]
args = ["bwrap", "--new-session", "--die-with-parent", "--setenv", "HOME", str(ws)] args = [
for p in required: "--new-session", "--die-with-parent", "--setenv", "HOME", str(ws),
args += ["--ro-bind", p, p] "--ro-bind", "/usr", "/usr",
]
for p in optional: for p in optional:
args += ["--ro-bind-try", p, p] args += ["--ro-bind-try", p, p]
args += [ args += [
@@ -87,12 +70,12 @@ def _bwrap(
"--bind", str(ws), str(ws), "--bind", str(ws), str(ws),
"--ro-bind-try", str(media), str(media), "--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] 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 += ["--bind-try", p, p]
args += ["--chdir", sandbox_cwd, "--", "sh", "-c", command] 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 # 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 command. Only ``file-read-metadata`` is granted for these: the directories
stay searchable, but listing or reading them is still denied. stay searchable, but listing or reading them is still denied.
""" """
out: list[str] = [] return list(dict.fromkeys(str(ancestor) for path in paths for ancestor in path.parents))
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
def _seatbelt_is_within(path: Path, root: Path) -> bool: def _seatbelt_is_within(path: Path, root: Path) -> bool:
@@ -177,12 +151,13 @@ def _sbpl_quote(path: str) -> str:
def _seatbelt( def _seatbelt(
command: str, command: str,
workspace: str, ws: Path,
cwd: str, sandbox_cwd: str,
*, *,
sandbox_ro_binds: Iterable[str] | None = None, media: Path,
sandbox_rw_binds: Iterable[str] | None = None, ro_binds: list[str],
) -> str: rw_binds: list[str],
) -> list[str]:
"""Wrap command in a macOS Seatbelt sandbox (requires sandbox-exec(1)). """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 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 Network access is left unrestricted, matching ``bwrap`` (which does not pass
``--unshare-net``). ``--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: def subpaths(paths: Iterable[str]) -> str:
return " ".join(f"(subpath {_sbpl_quote(p)})" for p in paths) 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 = [ rules = [
"(version 1)", "(version 1)",
"(deny default)", "(deny default)",
@@ -285,9 +249,7 @@ def _seatbelt(
# sandbox-exec(1) has no --chdir. Exit on failure before evaluating any of # 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. # the submitted shell list; `cd ... && a; b` would still execute b on failure.
args = [ return [
# Resolve the security boundary before consulting operator tool PATHs.
"/usr/bin/sandbox-exec",
"-p", "-p",
"\n".join(rules), "\n".join(rules),
"/usr/bin/env", "/usr/bin/env",
@@ -297,28 +259,37 @@ def _seatbelt(
"-c", "-c",
f"cd {shlex.quote(sandbox_cwd)} || exit\n{command}", f"cd {shlex.quote(sandbox_cwd)} || exit\n{command}",
] ]
return shlex.join(args)
_BACKENDS = {"bwrap": _bwrap, "seatbelt": _seatbelt} _BACKENDS = {"bwrap": _bwrap, "seatbelt": _seatbelt}
def wrap_command( def build_sandbox_argv(
sandbox: str, sandbox: str,
command: str, command: str,
workspace: str, workspace: str,
cwd: str, cwd: str,
*, *,
launcher: str = "",
sandbox_ro_binds: Iterable[str] | None = None, sandbox_ro_binds: Iterable[str] | None = None,
sandbox_rw_binds: Iterable[str] | None = None, sandbox_rw_binds: Iterable[str] | None = None,
) -> str: ) -> list[str]:
"""Wrap *command* using the named sandbox backend.""" """Build the sandbox argv with an independently resolved host launcher."""
if backend := _BACKENDS.get(sandbox): backend = _BACKENDS.get(sandbox)
return backend( if backend is None:
command, raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}")
workspace, ws = Path(workspace).resolve()
cwd, media = get_media_dir().resolve()
sandbox_ro_binds=sandbox_ro_binds, requested_cwd = Path(cwd).resolve()
sandbox_rw_binds=sandbox_rw_binds, sandbox_cwd = str(requested_cwd if requested_cwd.is_relative_to(ws) else ws)
)
raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}") 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]
@@ -5,22 +5,24 @@ from __future__ import annotations
import os import os
import shutil import shutil
import stat import stat
import sys
from pathlib import Path from pathlib import Path
from typing import Literal from typing import Literal
class SandboxLauncherError(ValueError): class SandboxLauncherError(ValueError):
def __init__(self, reason: str): def __init__(self, reason: str, *, launcher: str = ""):
self.reason = reason self.reason = reason
self.launcher = launcher
super().__init__(reason) super().__init__(reason)
def sandbox_platform(backend: str) -> Literal["supported", "unsupported"]: def supported_sandbox_backend() -> Literal["bwrap", "seatbelt"] | None:
import sys if sys.platform.startswith("linux"):
return "bwrap"
return "supported" if (backend == "bwrap" and sys.platform.startswith("linux")) or ( if sys.platform == "darwin":
backend == "seatbelt" and sys.platform == "darwin" return "seatbelt"
) else "unsupported" return None
def resolve_sandbox_launcher( def resolve_sandbox_launcher(
@@ -36,7 +38,7 @@ def resolve_sandbox_launcher(
if not custom_path: if not custom_path:
launcher = shutil.which(name, path=os.defpath) launcher = shutil.which(name, path=os.defpath)
if launcher is None: if launcher is None:
raise SandboxLauncherError("launcher_missing") raise SandboxLauncherError("launcher_missing", launcher=name)
return str(Path(launcher).absolute()) return str(Path(launcher).absolute())
if os.name != "posix": if os.name != "posix":
raise SandboxLauncherError("platform_unsupported") raise SandboxLauncherError("platform_unsupported")
+1 -1
View File
@@ -146,7 +146,7 @@ def update_runtime_config(
if "tools.exec.sandbox" in values and validated.tools.exec.sandbox not in {"", "bwrap", "seatbelt"}: 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") 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: 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, SandboxLauncherError,
resolve_sandbox_launcher, resolve_sandbox_launcher,
) )
+6
View File
@@ -92,6 +92,12 @@ IMPORT_RULES = (
("nanobot.execution.http",), ("nanobot.execution.http",),
(*_ADAPTERS, "nanobot.agent", "nanobot.config", "nanobot.providers", "nanobot.session"), (*_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( ImportRule(
"channel-routing-contracts", "channel-routing-contracts",
("nanobot.channels.notification_routes",), ("nanobot.channels.notification_routes",),
+26 -34
View File
@@ -525,55 +525,47 @@ class TestSandboxPlatform:
@pytest.mark.asyncio @pytest.mark.asyncio
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"]) @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") mock_proc = _CompletedProcess(b"sandboxed")
trusted_bin = tmp_path / "trusted-bin" trusted_bin = tmp_path / "trusted-bin"
launcher = "bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec" launcher = trusted_bin / ("bwrap" if backend == "bwrap" else "sandbox-exec")
workspace = tmp_path / "project"
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")
tool_bin = tmp_path / "tool-bin" tool_bin = tmp_path / "tool-bin"
tool_cache = tmp_path / "tool-cache" tool_cache = tmp_path / "tool-cache"
with ( with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", False), 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.execution.sandbox.resolve_sandbox_launcher", return_value=str(launcher)),
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)) as mock_spawn,
patch.object(processes, "spawn_process_tree", return_value=processes.ProcessTree(mock_proc)),
patch.object(ExecTool, "_guard_command", return_value=None), patch.object(ExecTool, "_guard_command", return_value=None),
): ):
tool = ExecTool( tool = ExecTool(
sandbox=backend, sandbox=backend,
working_dir="/workspace", working_dir=str(workspace),
sandbox_ro_binds=[str(tool_bin)], sandbox_ro_binds=[str(tool_bin)],
sandbox_rw_binds=[str(tool_cache)], sandbox_rw_binds=[str(tool_cache)],
) )
await tool.execute(command="ls") result = await tool.execute(command="ls")
kwargs = mock_wrap.call_args.kwargs assert "sandboxed" in result
assert kwargs["sandbox_ro_binds"] == [ command, cwd, *_ = mock_spawn.call_args.args
str(tool_bin.resolve(strict=False)) assert isinstance(command, list)
] assert command[0] == str(launcher)
assert kwargs["sandbox_rw_binds"] == [ assert cwd == str(workspace.resolve())
str(tool_cache.resolve(strict=False)) 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: class TestExecuteEndToEnd:
+54 -68
View File
@@ -3,19 +3,22 @@ from pathlib import Path
import pytest 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]: @pytest.fixture(autouse=True)
"""Split a wrapped command back into tokens for assertion.""" def portable_launcher(monkeypatch):
return shlex.split(cmd) # 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: class TestBwrapBackend:
def test_basic_structure(self, tmp_path): def test_basic_structure(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("bwrap", "echo hi", ws, ws) tokens = build_sandbox_argv("bwrap", "echo hi", ws, ws)
tokens = _parse(result)
assert tokens[0] == "bwrap" assert tokens[0] == "bwrap"
assert "--new-session" in tokens assert "--new-session" in tokens
@@ -30,16 +33,14 @@ class TestBwrapBackend:
def test_workspace_bind_mounted_rw(self, tmp_path): def test_workspace_bind_mounted_rw(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("bwrap", "ls", ws, ws) tokens = build_sandbox_argv("bwrap", "ls", ws, ws)
tokens = _parse(result)
bind_idx = [i for i, t in enumerate(tokens) if t == "--bind"] 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) 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): def test_home_env_points_to_workspace(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("bwrap", "echo $HOME", ws, ws) tokens = build_sandbox_argv("bwrap", "echo $HOME", ws, ws)
tokens = _parse(result)
setenv_idx = [i for i, t in enumerate(tokens) if t == "--setenv"] setenv_idx = [i for i, t in enumerate(tokens) if t == "--setenv"]
assert any( assert any(
@@ -49,8 +50,7 @@ class TestBwrapBackend:
def test_parent_dir_masked_with_tmpfs(self, tmp_path): def test_parent_dir_masked_with_tmpfs(self, tmp_path):
ws = tmp_path / "project" ws = tmp_path / "project"
result = wrap_command("bwrap", "ls", str(ws), str(ws)) tokens = build_sandbox_argv("bwrap", "ls", str(ws), str(ws))
tokens = _parse(result)
tmpfs_indices = [i for i, t in enumerate(tokens) if t == "--tmpfs"] tmpfs_indices = [i for i, t in enumerate(tokens) if t == "--tmpfs"]
tmpfs_targets = {tokens[i + 1] for i in tmpfs_indices} 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): def test_tmp_dir_mounted_as_tmpfs(self, tmp_path):
"""Regression coverage for #1948: commands need writable scratch space.""" """Regression coverage for #1948: commands need writable scratch space."""
ws = tmp_path / "project" ws = tmp_path / "project"
result = wrap_command("bwrap", "touch /tmp/probe", str(ws), str(ws)) tokens = build_sandbox_argv("bwrap", "touch /tmp/probe", str(ws), str(ws))
tokens = _parse(result)
tmpfs_indices = [i for i, t in enumerate(tokens) if t == "--tmpfs"] tmpfs_indices = [i for i, t in enumerate(tokens) if t == "--tmpfs"]
tmpfs_targets = {tokens[i + 1] for i in tmpfs_indices} 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): def test_parent_mask_precedes_workspace_recreation(self, tmp_path):
ws = tmp_path / "project" ws = tmp_path / "project"
result = wrap_command("bwrap", "ls", str(ws), str(ws)) tokens = build_sandbox_argv("bwrap", "ls", str(ws), str(ws))
tokens = _parse(result)
parent_mask = next( parent_mask = next(
i for i, t in enumerate(tokens) i for i, t in enumerate(tokens)
@@ -90,8 +88,7 @@ class TestBwrapBackend:
def test_cwd_inside_workspace(self, tmp_path): def test_cwd_inside_workspace(self, tmp_path):
ws = tmp_path / "project" ws = tmp_path / "project"
sub = ws / "src" / "lib" sub = ws / "src" / "lib"
result = wrap_command("bwrap", "pwd", str(ws), str(sub)) tokens = build_sandbox_argv("bwrap", "pwd", str(ws), str(sub))
tokens = _parse(result)
chdir_idx = tokens.index("--chdir") chdir_idx = tokens.index("--chdir")
assert tokens[chdir_idx + 1] == str(sub) assert tokens[chdir_idx + 1] == str(sub)
@@ -99,8 +96,7 @@ class TestBwrapBackend:
def test_cwd_outside_workspace_falls_back(self, tmp_path): def test_cwd_outside_workspace_falls_back(self, tmp_path):
ws = tmp_path / "project" ws = tmp_path / "project"
outside = tmp_path / "other" outside = tmp_path / "other"
result = wrap_command("bwrap", "pwd", str(ws), str(outside)) tokens = build_sandbox_argv("bwrap", "pwd", str(ws), str(outside))
tokens = _parse(result)
chdir_idx = tokens.index("--chdir") chdir_idx = tokens.index("--chdir")
assert tokens[chdir_idx + 1] == str(ws.resolve()) assert tokens[chdir_idx + 1] == str(ws.resolve())
@@ -108,16 +104,14 @@ class TestBwrapBackend:
def test_command_with_special_characters(self, tmp_path): def test_command_with_special_characters(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
cmd = "echo 'hello world' && cat \"file with spaces.txt\"" cmd = "echo 'hello world' && cat \"file with spaces.txt\""
result = wrap_command("bwrap", cmd, ws, ws) tokens = build_sandbox_argv("bwrap", cmd, ws, ws)
tokens = _parse(result)
sep = tokens.index("--") sep = tokens.index("--")
assert tokens[sep + 1:] == ["sh", "-c", cmd] assert tokens[sep + 1:] == ["sh", "-c", cmd]
def test_system_dirs_ro_bound(self, tmp_path): def test_system_dirs_ro_bound(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("bwrap", "ls", ws, ws) tokens = build_sandbox_argv("bwrap", "ls", ws, ws)
tokens = _parse(result)
ro_bind_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind"] 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} 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): def test_optional_dirs_use_ro_bind_try(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("bwrap", "ls", ws, ws) tokens = build_sandbox_argv("bwrap", "ls", ws, ws)
tokens = _parse(result)
try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"] try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"]
try_targets = {tokens[i + 1] for i in try_indices} try_targets = {tokens[i + 1] for i in try_indices}
@@ -137,12 +130,11 @@ class TestBwrapBackend:
fake_media = tmp_path / "media" fake_media = tmp_path / "media"
fake_media.mkdir() fake_media.mkdir()
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.sandbox.get_media_dir", "nanobot.execution.sandbox.get_media_dir",
lambda: fake_media, lambda: fake_media,
) )
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("bwrap", "ls", ws, ws) tokens = build_sandbox_argv("bwrap", "ls", ws, ws)
tokens = _parse(result)
try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"] 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} try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in try_indices}
@@ -152,14 +144,13 @@ class TestBwrapBackend:
ws = tmp_path / "project" ws = tmp_path / "project"
tool_bin = tmp_path / "home" / ".local" / "bin" tool_bin = tmp_path / "home" / ".local" / "bin"
result = wrap_command( tokens = build_sandbox_argv(
"bwrap", "bwrap",
"uv --version", "uv --version",
str(ws), str(ws),
str(ws), str(ws),
sandbox_ro_binds=[str(tool_bin)], sandbox_ro_binds=[str(tool_bin)],
) )
tokens = _parse(result)
try_indices = [i for i, t in enumerate(tokens) if t == "--ro-bind-try"] 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} try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in try_indices}
@@ -169,14 +160,13 @@ class TestBwrapBackend:
ws = tmp_path / "project" ws = tmp_path / "project"
cache_dir = tmp_path / "cache" cache_dir = tmp_path / "cache"
result = wrap_command( tokens = build_sandbox_argv(
"bwrap", "bwrap",
"touch cache/file", "touch cache/file",
str(ws), str(ws),
str(ws), str(ws),
sandbox_rw_binds=[str(cache_dir)], 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_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} 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): def test_custom_relative_bind_paths_are_ignored(self, tmp_path):
ws = tmp_path / "project" ws = tmp_path / "project"
result = wrap_command( tokens = build_sandbox_argv(
"bwrap", "bwrap",
"ls", "ls",
str(ws), str(ws),
@@ -194,7 +184,6 @@ class TestBwrapBackend:
sandbox_ro_binds=["relative/bin"], sandbox_ro_binds=["relative/bin"],
sandbox_rw_binds=["relative/cache"], sandbox_rw_binds=["relative/cache"],
) )
tokens = _parse(result)
assert "relative/bin" not in tokens assert "relative/bin" not in tokens
assert "relative/cache" not in tokens assert "relative/cache" not in tokens
@@ -203,7 +192,7 @@ class TestBwrapBackend:
ws = tmp_path / "private" / "project" ws = tmp_path / "private" / "project"
parent = ws.parent.resolve(strict=False) parent = ws.parent.resolve(strict=False)
result = wrap_command( tokens = build_sandbox_argv(
"bwrap", "bwrap",
"cat ../config.json", "cat ../config.json",
str(ws), str(ws),
@@ -211,7 +200,6 @@ class TestBwrapBackend:
sandbox_ro_binds=[str(parent)], sandbox_ro_binds=[str(parent)],
sandbox_rw_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_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} ro_try_pairs = {(tokens[i + 1], tokens[i + 2]) for i in ro_try_indices}
@@ -229,9 +217,8 @@ class TestSeatbeltBackend:
""" """
@staticmethod @staticmethod
def _profile(cmd: str) -> str: def _profile(tokens: list[str]) -> str:
"""Return the SBPL profile from a wrapped command.""" """Return the SBPL profile from a wrapped command."""
tokens = _parse(cmd)
return tokens[tokens.index("-p") + 1] return tokens[tokens.index("-p") + 1]
@staticmethod @staticmethod
@@ -249,8 +236,7 @@ class TestSeatbeltBackend:
def test_basic_structure(self, tmp_path): def test_basic_structure(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
result = wrap_command("seatbelt", "echo hi", ws, ws) tokens = build_sandbox_argv("seatbelt", "echo hi", ws, ws)
tokens = _parse(result)
assert tokens[0] == "/usr/bin/sandbox-exec" assert tokens[0] == "/usr/bin/sandbox-exec"
assert tokens[1] == "-p" assert tokens[1] == "-p"
@@ -259,7 +245,7 @@ class TestSeatbeltBackend:
assert tokens[-1].endswith("echo hi") assert tokens[-1].endswith("echo hi")
def test_denies_by_default(self, tmp_path): 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 "(version 1)" in profile
assert "(deny default)" in profile assert "(deny default)" in profile
@@ -271,13 +257,13 @@ class TestSeatbeltBackend:
profile listing only system subpaths kills every wrapped command profile listing only system subpaths kills every wrapped command
before it runs. 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 assert '(allow file-read* (literal "/"))' in profile
def test_workspace_allowed_read_write(self, tmp_path): def test_workspace_allowed_read_write(self, tmp_path):
ws = (tmp_path / "project").resolve() 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 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. re-exposes only the workspace subtree.
""" """
ws = (tmp_path / "project").resolve() 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)})") 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)})") workspace_allow = profile.index(f"(allow file-read* file-write* (subpath {self._quote(ws)})")
assert parent_deny < workspace_allow assert parent_deny < workspace_allow
def test_no_parent_deny_when_workspace_is_the_root(self): 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 assert "(deny file-read*" not in profile
@@ -307,20 +293,20 @@ class TestSeatbeltBackend:
runs anything. runs anything.
""" """
ws = (tmp_path / "project").resolve() 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"(literal {self._quote(ws.parent)})" in self._metadata_rule(profile)
def test_config_dir_is_searchable_but_not_listable(self, tmp_path): def test_config_dir_is_searchable_but_not_listable(self, tmp_path):
ws = (tmp_path / "project").resolve() 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"(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* (subpath {self._quote(ws.parent)}))" not in profile
assert f"(allow file-read* file-write* (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): 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", for path in ("/tmp", "/private/tmp", "/var", "/private/var", "/var/folders",
"/private/var/folders", "/Library", "/etc", "/private/etc"): "/private/var/folders", "/Library", "/etc", "/private/etc"):
@@ -328,22 +314,22 @@ class TestSeatbeltBackend:
def test_home_and_tmpdir_use_workspace(self, tmp_path): def test_home_and_tmpdir_use_workspace(self, tmp_path):
ws = tmp_path.resolve() 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}"] assert tokens[3:6] == ["/usr/bin/env", f"HOME={ws}", f"TMPDIR={ws}"]
def test_network_matches_bwrap_policy(self, tmp_path): 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 assert "(allow network*)" in profile
def test_media_dir_read_only(self, tmp_path, monkeypatch): def test_media_dir_read_only(self, tmp_path, monkeypatch):
fake_media = (tmp_path / "media").resolve() fake_media = (tmp_path / "media").resolve()
fake_media.mkdir() fake_media.mkdir()
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.sandbox.get_media_dir", "nanobot.execution.sandbox.get_media_dir",
lambda: fake_media, lambda: fake_media,
) )
ws = (tmp_path / "project").resolve() 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"(allow file-read* (subpath {self._quote(fake_media)}))" in profile
assert f"(deny file-write* (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): def test_cwd_inside_workspace(self, tmp_path):
ws = (tmp_path / "project").resolve() ws = (tmp_path / "project").resolve()
sub = ws / "src" / "lib" 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): def test_cwd_outside_workspace_falls_back(self, tmp_path):
ws = (tmp_path / "project").resolve() ws = (tmp_path / "project").resolve()
outside = tmp_path / "other" 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): def test_custom_read_only_binds(self, tmp_path):
ws = (tmp_path / "project").resolve() ws = (tmp_path / "project").resolve()
tool_bin = (tmp_path / "home" / ".local" / "bin").resolve(strict=False) tool_bin = (tmp_path / "home" / ".local" / "bin").resolve(strict=False)
profile = self._profile( profile = self._profile(
wrap_command( build_sandbox_argv(
"seatbelt", "uv --version", str(ws), str(ws), "seatbelt", "uv --version", str(ws), str(ws),
sandbox_ro_binds=[str(tool_bin)], sandbox_ro_binds=[str(tool_bin)],
) )
@@ -379,7 +365,7 @@ class TestSeatbeltBackend:
def test_read_only_bind_overrides_workspace_write(self, tmp_path): def test_read_only_bind_overrides_workspace_write(self, tmp_path):
ws = tmp_path.resolve() ws = tmp_path.resolve()
ro = ws / "readonly" 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)], "seatbelt", "ls", str(ws), str(ws), sandbox_ro_binds=[str(ro)],
)) ))
assert profile.index(f"(allow file-read* file-write* (subpath {self._quote(ws)}))") < ( assert profile.index(f"(allow file-read* file-write* (subpath {self._quote(ws)}))") < (
@@ -391,8 +377,8 @@ class TestSeatbeltBackend:
ws = (tmp_path / "workspace").resolve() ws = (tmp_path / "workspace").resolve()
ro = ws / 'tree with "quotes' / "branch" / "readonly" ro = ws / 'tree with "quotes' / "branch" / "readonly"
media = ro if source == "media" else tmp_path / "media" media = ro if source == "media" else tmp_path / "media"
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: media)
profile = self._profile(wrap_command( profile = self._profile(build_sandbox_argv(
"seatbelt", "ls", str(ws), str(ws), "seatbelt", "ls", str(ws), str(ws),
sandbox_ro_binds=[str(ro)] if source == "bind" else [], sandbox_ro_binds=[str(ro)] if source == "bind" else [],
)) ))
@@ -408,8 +394,8 @@ class TestSeatbeltBackend:
ws = (tmp_path / "workspace").resolve() ws = (tmp_path / "workspace").resolve()
ro = ws / "tree" / "readonly" ro = ws / "tree" / "readonly"
rw = {"root": ro, "parent": ro.parent, "child": ro / "cache"}[override] rw = {"root": ro, "parent": ro.parent, "child": ro / "cache"}[override]
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: ro) monkeypatch.setattr("nanobot.execution.sandbox.get_media_dir", lambda: ro)
profile = self._profile(wrap_command( profile = self._profile(build_sandbox_argv(
"seatbelt", "ls", str(ws), str(ws), "seatbelt", "ls", str(ws), str(ws),
sandbox_ro_binds=[str(ro)], sandbox_rw_binds=[str(rw)], sandbox_ro_binds=[str(ro)], sandbox_rw_binds=[str(rw)],
)) ))
@@ -442,7 +428,7 @@ class TestSeatbeltBackend:
cache_dir = (tmp_path / "cache").resolve(strict=False) cache_dir = (tmp_path / "cache").resolve(strict=False)
profile = self._profile( profile = self._profile(
wrap_command( build_sandbox_argv(
"seatbelt", "touch cache/file", str(ws), str(ws), "seatbelt", "touch cache/file", str(ws), str(ws),
sandbox_rw_binds=[str(cache_dir)], sandbox_rw_binds=[str(cache_dir)],
) )
@@ -455,7 +441,7 @@ class TestSeatbeltBackend:
parent = ws.parent.resolve(strict=False) parent = ws.parent.resolve(strict=False)
profile = self._profile( profile = self._profile(
wrap_command( build_sandbox_argv(
"seatbelt", "cat ../config.json", str(ws), str(ws), "seatbelt", "cat ../config.json", str(ws), str(ws),
sandbox_ro_binds=[str(parent)], sandbox_ro_binds=[str(parent)],
sandbox_rw_binds=[str(parent)], sandbox_rw_binds=[str(parent)],
@@ -469,7 +455,7 @@ class TestSeatbeltBackend:
"""An unescaped quote would terminate the literal early and silently """An unescaped quote would terminate the literal early and silently
widen every rule that follows it.""" widen every rule that follows it."""
ws = (tmp_path / 'pro"ject').resolve() 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('"', '\\"') escaped = str(ws).replace("\\", "\\\\").replace('"', '\\"')
assert f'(allow file-read* file-write* (subpath "{escaped}"))' in profile 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): def test_raises_value_error(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
with pytest.raises(ValueError, match="Unknown sandbox backend"): 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): def test_empty_string_raises(self, tmp_path):
ws = str(tmp_path / "project") ws = str(tmp_path / "project")
with pytest.raises(ValueError): 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.base import ToolResult
from nanobot.agent.tools.exec_session import ExecSessionManager 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_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 import ExecTool
from nanobot.agent.tools.shell_config import ExecToolConfig from nanobot.agent.tools.shell_config import ExecToolConfig
from nanobot.config.loader import resolve_config_env_vars 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") @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 = tmp_path / "system-bin"
default_bin.mkdir() default_bin.mkdir()
launcher = extra_bin / "bwrap" 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) launcher.chmod(0o700)
marker = workspace / "command-ran" marker = workspace / "command-ran"
monkeypatch.setattr(os, "defpath", str(default_bin)) monkeypatch.setattr(os, "defpath", str(default_bin))
monkeypatch.setattr(sys, "platform", "linux")
monkeypatch.setenv("PATH", str(extra_bin)) 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") tool = ExecTool(working_dir=str(workspace), sandbox="bwrap")
result = await tool.execute(command="printf ran > command-ran") result = await tool.execute(command="printf ran > command-ran")
assert "sandbox launcher not found: bwrap" in result assert "sandbox launcher not found: bwrap" in result
assert isinstance(result, ToolResult) and result.error_code == "sandbox_launcher_missing" 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() 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): 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"): with pytest.raises(SandboxLauncherError, match="platform_unsupported"):
resolve_sandbox_launcher("bwrap", "C:\\tools\\bwrap.exe") 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 assert (await check_sandbox(ExecToolConfig(**settings), tmp_path))["state"] == state
async def test_unsupported_platform_reports_no_isolation_without_running(tmp_path, monkeypatch): @pytest.mark.parametrize(("platform", "backend", "supported"), [
monkeypatch.setattr(sys, "platform", "win32") ("win32", "bwrap", None),
status = await check_sandbox(ExecToolConfig(sandbox="bwrap"), tmp_path) ("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["state"] == "unsupported"
assert status["supported_backend"] is None assert status["supported_backend"] == supported
@pytest.mark.skipif(os.name != "posix", reason="Unix native sandbox") @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. # The same resolver and backend must work for actual command execution.
tool = ExecTool(working_dir=str(tmp_path), sandbox=backend, sandbox_launcher=result["launcher"]) tool = ExecTool(working_dir=str(tmp_path), sandbox=backend, sandbox_launcher=result["launcher"])
assert "actual-command" in await tool.execute(command="printf actual-command") 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") failed_command = await tool.execute(command="printf 'sandbox launcher not found: bwrap'; exit 1")
assert "Exit code: 1" in failed_command assert "Exit code: 1" in failed_command
assert (failed_command.error_code if isinstance(failed_command, ToolResult) else None) is None 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"]) @pytest.mark.parametrize("finish", ["timeout", "cancel"])
async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_path, monkeypatch, finish): async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_path, monkeypatch, finish):
started, exited = asyncio.Event(), asyncio.Event() 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: class Process:
pid = 12345 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): async def spawn(*args, **kwargs):
assert kwargs["start_new_session"] 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() started.set()
return process return process
@@ -225,10 +249,6 @@ async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_pa
process.returncode = -9 process.returncode = -9
exited.set() 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("nanobot.agent.tools.sandbox_check._PROBE_TIMEOUT_S", 0.01)
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn) monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
monkeypatch.setattr(os, "killpg", kill) 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") outside.write_text("unchanged")
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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 = workspace / ("interpreter" if symlink else shell_name)
script.write_text( script.write_text(
"#!/bin/sh\n" "#!/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): async def test_sandboxed_shell_preserves_ordinary_bash_commands(tmp_path, monkeypatch):
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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) tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND)
result = await tool.execute(command="items=(hello world); printf '%s' \"${items[1]}\"", shell="bash") result = await tool.execute(command="items=(hello world); printf '%s' \"${items[1]}\"", shell="bash")
assert result.startswith("world\nExit code: 0\n"), result 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): async def test_configured_path_cannot_replace_sandbox_launcher(tmp_path, monkeypatch):
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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 = tmp_path / ("sandbox-exec" if BACKEND == "seatbelt" else "bwrap")
impostor.write_text("#!/bin/sh\nprintf shadowed-launcher") impostor.write_text("#!/bin/sh\nprintf shadowed-launcher")
impostor.chmod(0o700) impostor.chmod(0o700)
@@ -92,7 +92,7 @@ async def test_login_profile_runs_inside_sandbox(tmp_path, monkeypatch):
outside.write_text("unchanged") outside.write_text("unchanged")
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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( (workspace / ".bash_profile").write_text(
f"printf escaped > {shlex.quote(str(outside))}\n" f"printf escaped > {shlex.quote(str(outside))}\n"
"export SANDBOX_PROFILE_LOADED=yes\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") outside.write_text("unchanged")
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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 = workspace / ("sandbox-exec" if BACKEND == "seatbelt" else "bwrap")
impostor.write_text( impostor.write_text(
"#!/bin/sh\n" "#!/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): async def test_missing_launcher_does_not_run_command_unsandboxed(tmp_path, monkeypatch):
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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 original_which = shutil.which
launcher = "/usr/bin/sandbox-exec" if BACKEND == "seatbelt" else "bwrap" launcher = "/usr/bin/sandbox-exec" if BACKEND == "seatbelt" else "bwrap"
monkeypatch.setattr( monkeypatch.setattr(
@@ -150,7 +150,7 @@ async def test_trusted_shell_completion_preserves_sandbox(tmp_path, monkeypatch)
workspace.mkdir() workspace.mkdir()
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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) tool = ExecTool(working_dir=str(workspace), sandbox=BACKEND)
result = await tool.execute_to_completion("printf complete > result", str(workspace)) 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): async def test_sandbox_preserves_literal_argument_vector(tmp_path, monkeypatch):
media = tmp_path / "media" media = tmp_path / "media"
media.mkdir() 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) tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND)
literal = "hello | $HOME; 'world'" 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[name] / "sentinel").write_text("synthetic-data")
paths["link"] = paths["workspace"] / "outside-link" paths["link"] = paths["workspace"] / "outside-link"
paths["link"].symlink_to(paths["peer"], target_is_directory=True) 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 yield paths