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

-324
View File
@@ -1,324 +0,0 @@
"""Sandbox backends for shell command execution.
To add a backend, match the callable signature of _bwrap and _seatbelt,
including keyword-only sandbox_ro_binds and sandbox_rw_binds, and register
it in _BACKENDS below.
"""
import os
import shlex
from pathlib import Path
from typing import Iterable
from nanobot.config.paths import get_media_dir
def _normalize_bind_paths(
paths: Iterable[str] | None,
*,
workspace: Path | None = None,
) -> list[str]:
out: list[str] = []
seen: set[str] = set()
for raw in paths or []:
value = str(raw).strip()
if not value:
continue
path = Path(os.path.expandvars(value)).expanduser()
if not path.is_absolute():
continue
resolved_path = path.resolve(strict=False)
if workspace is not None:
try:
workspace.relative_to(resolved_path)
except ValueError:
pass
else:
# A later bind of the workspace or one of its parents could
# cover the tmpfs that hides the config directory.
continue
resolved = str(resolved_path)
if resolved in seen:
continue
seen.add(resolved)
out.append(resolved)
return out
def _bwrap(
command: str,
workspace: str,
cwd: str,
*,
sandbox_ro_binds: Iterable[str] | None = None,
sandbox_rw_binds: Iterable[str] | None = None,
) -> str:
ws = Path(workspace).resolve()
media = get_media_dir().resolve()
try:
sandbox_cwd = str(ws / Path(cwd).resolve().relative_to(ws))
except ValueError:
sandbox_cwd = str(ws)
required = ["/usr"]
optional = [
"/bin",
"/lib",
"/lib64",
"/etc/alternatives",
"/etc/ssl/certs",
"/etc/pki/tls/certs",
"/etc/pki/ca-trust",
"/etc/crypto-policies",
"/etc/resolv.conf",
"/etc/ld.so.cache",
]
args = ["bwrap", "--new-session", "--die-with-parent", "--setenv", "HOME", str(ws)]
for p in required:
args += ["--ro-bind", p, p]
for p in optional:
args += ["--ro-bind-try", p, p]
args += [
"--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp",
"--tmpfs", str(ws.parent),
"--dir", str(ws),
"--bind", str(ws), str(ws),
"--ro-bind-try", str(media), str(media),
]
for p in _normalize_bind_paths(sandbox_ro_binds, workspace=ws):
args += ["--ro-bind-try", p, p]
for p in _normalize_bind_paths(sandbox_rw_binds, workspace=ws):
args += ["--bind-try", p, p]
args += ["--chdir", sandbox_cwd, "--", "sh", "-c", command]
return shlex.join(args)
# 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",
"/dev",
"/System",
"/Library/Developer/CommandLineTools",
"/private/etc/ssl",
"/private/var/db/dyld",
"/private/var/db/timezone",
)
_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
# (subpath "/private/var") does not cover its own parent.
_SEATBELT_TRAVERSABLE_LITERALS = ("/private",)
def _seatbelt_ancestors(*paths: Path) -> list[str]:
"""Collect every ancestor directory of *paths*, closest first.
Seatbelt checks each path component while resolving, so a sandbox that
allows a deep directory but not its ancestors fails with ENOTDIR on every
command. Only ``file-read-metadata`` is granted for these: the directories
stay searchable, but listing or reading them is still denied.
"""
out: list[str] = []
seen: set[str] = set()
for path in paths:
for ancestor in path.parents:
name = str(ancestor)
if name in seen:
continue
seen.add(name)
out.append(name)
return out
def _seatbelt_is_within(path: Path, root: Path) -> bool:
"""Match existing path aliases without lowercasing case-sensitive volumes."""
if path.is_relative_to(root):
return True
for ancestor in (path, *path.parents):
try:
if ancestor.samefile(root):
return True
except OSError:
# Missing/inaccessible paths retain conservative lexical matching.
continue
return False
def _sbpl_quote(path: str) -> str:
"""Render *path* as an SBPL string literal.
SBPL uses C-style string escaping, so a backslash or a double quote in a
path would otherwise terminate the literal early and change the meaning of
every rule that follows it.
"""
escaped = path.replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
def _seatbelt(
command: str,
workspace: str,
cwd: str,
*,
sandbox_ro_binds: Iterable[str] | None = None,
sandbox_rw_binds: Iterable[str] | None = None,
) -> str:
"""Wrap command in a macOS Seatbelt sandbox (requires sandbox-exec(1)).
The workspace is read-write and media is read-only. The workspace's parent
(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
wins, which re-exposes the workspace subtree while the rest of the parent
stays denied. Unlike ``bwrap``, a denied parent still appears in directory
listings; only its contents are inaccessible.
Network access is left unrestricted, matching ``bwrap`` (which does not pass
``--unshare-net``).
"""
ws = Path(workspace).resolve()
media = get_media_dir().resolve()
try:
sandbox_cwd = str(ws / Path(cwd).resolve().relative_to(ws))
except ValueError:
sandbox_cwd = str(ws)
def subpaths(paths: Iterable[str]) -> str:
return " ".join(f"(subpath {_sbpl_quote(p)})" for p in paths)
ro_binds = _normalize_bind_paths(sandbox_ro_binds, workspace=ws)
rw_binds = _normalize_bind_paths(sandbox_rw_binds, workspace=ws)
rules = [
"(version 1)",
"(deny default)",
"(allow process*)",
"(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)})",
"(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
# workspace subtree, because the last matching rule wins.
parent = ws.parent
if parent != ws and str(parent) != "/":
rules.append(f"(deny file-read* file-write* (subpath {_sbpl_quote(str(parent))}))")
# 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),
*(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),
*traversable,
]
rules.append(
"(allow file-read-metadata "
+ " ".join(f"(literal {_sbpl_quote(p)})" for p in literals)
+ ")"
)
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)}))")
# Path-based read-only rules do not follow a renamed ancestor. Keep those
# directory entries fixed without denying writes to their other children.
# A RW bind covering the entire RO root intentionally overrides protection;
# a writable descendant must not unlock the rest of the read-only tree.
writable_roots = [Path(p) for p in rw_binds]
protected_roots = [
root for root in (media, *(Path(p) for p in ro_binds))
if not any(_seatbelt_is_within(root, writable) for writable in writable_roots)
]
ancestors = _seatbelt_ancestors(*protected_roots)
if ancestors:
rules.append(
"(deny file-write-unlink "
+ " ".join(f"(literal {_sbpl_quote(p)})" for p in ancestors)
+ ")"
)
# sandbox-exec(1) has no --chdir. Exit on failure before evaluating any of
# the submitted shell list; `cd ... && a; b` would still execute b on failure.
args = [
# Resolve the security boundary before consulting operator tool PATHs.
"/usr/bin/sandbox-exec",
"-p",
"\n".join(rules),
"/usr/bin/env",
f"HOME={ws}",
f"TMPDIR={ws}",
"sh",
"-c",
f"cd {shlex.quote(sandbox_cwd)} || exit\n{command}",
]
return shlex.join(args)
_BACKENDS = {"bwrap": _bwrap, "seatbelt": _seatbelt}
def wrap_command(
sandbox: str,
command: str,
workspace: str,
cwd: str,
*,
sandbox_ro_binds: Iterable[str] | None = None,
sandbox_rw_binds: Iterable[str] | None = None,
) -> str:
"""Wrap *command* using the named sandbox backend."""
if backend := _BACKENDS.get(sandbox):
return backend(
command,
workspace,
cwd,
sandbox_ro_binds=sandbox_ro_binds,
sandbox_rw_binds=sandbox_rw_binds,
)
raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}")
+28 -37
View File
@@ -7,20 +7,20 @@ import hashlib
import json
import os
import shlex
import signal
import tempfile
from pathlib import Path
from typing import TypedDict
from nanobot.agent.tools.sandbox import wrap_command
from nanobot.agent.tools.sandbox_launcher import (
SandboxLauncherError,
resolve_sandbox_launcher,
sandbox_platform,
)
from nanobot.agent.tools.shell_config import ExecToolConfig
from nanobot.config.errors import ConfigLoadError
from nanobot.config.loader import resolve_config_env_vars
from nanobot.execution import processes
from nanobot.execution.sandbox import build_sandbox_argv
from nanobot.security.sandbox_launcher import (
SandboxLauncherError,
resolve_sandbox_launcher,
supported_sandbox_backend,
)
_PROBE_TIMEOUT_S = 5
@@ -34,13 +34,11 @@ class SandboxCheck(TypedDict):
def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
return _prepare_settings(config, workspace)[2]
return _prepare_settings(config, workspace)[1]
def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecToolConfig, Path, SandboxCheck]:
import sys
backend = "bwrap" if sys.platform.startswith("linux") else "seatbelt" if sys.platform == "darwin" else None
def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecToolConfig, SandboxCheck]:
backend = supported_sandbox_backend()
missing_env = False
try:
config = resolve_config_env_vars(config)
@@ -58,7 +56,7 @@ def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecTool
result["state"] = "disabled"
elif not config.sandbox:
result["state"] = "off"
elif sandbox_platform(config.sandbox) == "unsupported":
elif config.sandbox != backend:
result.update(state="unsupported", reason="platform_unsupported")
elif missing_env:
result.update(state="unavailable", reason="path_unavailable")
@@ -70,11 +68,11 @@ def _prepare_settings(config: ExecToolConfig, workspace: Path) -> tuple[ExecTool
)
except SandboxLauncherError as exc:
result.update(state="unavailable", reason=exc.reason)
return config, workspace, result
return config, result
async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
config, workspace, result = await asyncio.to_thread(_prepare_settings, config, workspace)
config, result = await asyncio.to_thread(_prepare_settings, config, workspace)
if result["state"] != "unchecked":
return result
# Use synthetic files only. Never run startup/login profiles or an arbitrary
@@ -92,40 +90,33 @@ async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck
# same path. What must stay unchanged is the host-side canary.
f"(printf changed > {shlex.quote(str(canary))} || true)"
)
argv = shlex.split(wrap_command(
config.sandbox, script, str(project), str(project),
sandbox_ro_binds=config.sandbox_ro_binds,
sandbox_rw_binds=config.sandbox_rw_binds,
))
# Same resolver and wrapper as ExecTool. Recheck against the probe root.
try:
argv[0] = resolve_sandbox_launcher(
config.sandbox, config.sandbox_launcher,
writable_roots=(project, *map(Path, config.sandbox_rw_binds)),
argv = build_sandbox_argv(
config.sandbox, script, str(project), str(project),
launcher=config.sandbox_launcher,
sandbox_ro_binds=config.sandbox_ro_binds,
sandbox_rw_binds=config.sandbox_rw_binds,
)
result["launcher"] = argv[0]
except SandboxLauncherError as exc:
result.update(state="unavailable", reason=exc.reason)
return result
process: asyncio.subprocess.Process | None = None
tree: processes.ProcessTree | None = None
try:
process = await asyncio.create_subprocess_exec(
*argv, cwd=str(project), env={"PATH": os.defpath, "HOME": str(project)},
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL, start_new_session=True,
tree = await processes.spawn_process_tree(
argv, str(project), {"PATH": os.defpath, "HOME": str(project)}, capture_output=False,
)
await asyncio.wait_for(process.wait(), timeout=_PROBE_TIMEOUT_S)
success = process.returncode == 0 and (project / "inside").read_text() == "checked" and canary.read_text() == "unchanged"
code = await asyncio.wait_for(tree.process.wait(), timeout=_PROBE_TIMEOUT_S)
success = code == 0 and (project / "inside").read_text() == "checked" and canary.read_text() == "unchanged"
result.update(state="passed" if success else "unavailable", reason="" if success else "probe_failed")
except TimeoutError:
result.update(state="unavailable", reason="probe_timeout")
except OSError:
result.update(state="unavailable", reason="probe_failed")
finally:
if process is not None and process.returncode is None:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
await process.wait()
if tree is not None:
if tree.process.returncode is None:
await tree.terminate()
else:
tree.finish()
return result
-62
View File
@@ -1,62 +0,0 @@
"""Resolve sandbox launchers without trusting the agent's command search path."""
from __future__ import annotations
import os
import shutil
import stat
from pathlib import Path
from typing import Literal
class SandboxLauncherError(ValueError):
def __init__(self, reason: str):
self.reason = reason
super().__init__(reason)
def sandbox_platform(backend: str) -> Literal["supported", "unsupported"]:
import sys
return "supported" if (backend == "bwrap" and sys.platform.startswith("linux")) or (
backend == "seatbelt" and sys.platform == "darwin"
) else "unsupported"
def resolve_sandbox_launcher(
backend: str, custom_path: str = "", *, writable_roots: tuple[Path, ...] = (),
) -> str:
"""Keep default lookup unchanged; explicit overrides require a protected install.
A configured filename is not proof of provenance. The administrator must
trust its publisher. Root ownership and non-writable ancestors prevent
ordinary agent processes from replacing an override before confinement.
"""
name = "bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec"
if not custom_path:
launcher = shutil.which(name, path=os.defpath)
if launcher is None:
raise SandboxLauncherError("launcher_missing")
return str(Path(launcher).absolute())
if os.name != "posix":
raise SandboxLauncherError("platform_unsupported")
candidate = Path(custom_path)
if not candidate.is_absolute():
raise SandboxLauncherError("path_not_absolute")
try:
resolved = candidate.resolve(strict=True)
metadata = resolved.stat()
if not stat.S_ISREG(metadata.st_mode) or not os.access(resolved, os.X_OK):
raise SandboxLauncherError("not_executable")
for root in writable_roots:
root = Path(os.path.expandvars(str(root))).expanduser()
if root.is_absolute() and resolved.is_relative_to(root.resolve()):
raise SandboxLauncherError("agent_writable")
for item in (resolved, *resolved.parents):
info = item.stat()
if (info.st_uid != 0 or info.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
or (os.geteuid() != 0 and os.access(item, os.W_OK))):
raise SandboxLauncherError("unprotected_installation")
except (OSError, RuntimeError):
raise SandboxLauncherError("path_unavailable") from None
return str(resolved)
+8 -15
View File
@@ -26,8 +26,6 @@ from nanobot.agent.tools.exec_session import (
clamp_session_int,
format_session_poll,
)
from nanobot.agent.tools.sandbox import wrap_command
from nanobot.agent.tools.sandbox_launcher import SandboxLauncherError, resolve_sandbox_launcher
from nanobot.agent.tools.schema import (
BooleanSchema,
IntegerSchema,
@@ -36,6 +34,8 @@ from nanobot.agent.tools.schema import (
)
from nanobot.agent.tools.shell_config import ExecToolConfig
from nanobot.config.paths import get_media_dir
from nanobot.execution.sandbox import build_sandbox_argv
from nanobot.security.sandbox_launcher import SandboxLauncherError
from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace
from nanobot.security.workspace_policy import is_path_within
@@ -436,24 +436,17 @@ class ExecTool(Tool):
args.append("-l")
payload = shlex.join([*args, "-c", command])
workspace = workspace_root or cwd
command = shlex.split(wrap_command(
self.sandbox,
payload,
workspace,
cwd,
sandbox_ro_binds=[str(p) for p in self.sandbox_ro_binds],
sandbox_rw_binds=[str(p) for p in self.sandbox_rw_binds],
))
# Project/tool and inherited PATH can contain writable programs.
try:
command[0] = resolve_sandbox_launcher(
self.sandbox, self.sandbox_launcher,
writable_roots=(Path(workspace), *self.sandbox_rw_binds),
command = build_sandbox_argv(
self.sandbox, payload, workspace, cwd,
launcher=self.sandbox_launcher,
sandbox_ro_binds=map(str, self.sandbox_ro_binds),
sandbox_rw_binds=map(str, self.sandbox_rw_binds),
)
except SandboxLauncherError as exc:
if exc.reason == "launcher_missing":
return ToolResult.error(
f"Error: sandbox launcher not found: {command[0]}", error_code="sandbox_launcher_missing",
f"Error: sandbox launcher not found: {exc.launcher}", error_code="sandbox_launcher_missing",
)
return ToolResult.error(
f"Error: sandbox launcher rejected: {exc.reason}", error_code=f"sandbox_{exc.reason}",