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:
1 parent
0f5e56edd4
commit
90d69e7a11
14 files changed
+236
-275
No files matched your search
@@ -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
|
||||
@@ -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}",
|
||||
|
||||
@@ -56,6 +56,7 @@ async def spawn_process_tree(
|
||||
login: bool = False,
|
||||
*,
|
||||
stdin: int = asyncio.subprocess.DEVNULL,
|
||||
capture_output: bool = True,
|
||||
) -> ProcessTree:
|
||||
"""Start a prepared command in its own process group or Windows job."""
|
||||
if isinstance(command, list):
|
||||
@@ -87,18 +88,17 @@ async def spawn_process_tree(
|
||||
|
||||
job = _create_windows_job() if _IS_WINDOWS else None
|
||||
creationflags = job.creation_flags if job is not None else 0
|
||||
output = asyncio.subprocess.PIPE if capture_output else asyncio.subprocess.DEVNULL
|
||||
process = None
|
||||
try:
|
||||
if isinstance(launch, str):
|
||||
process = await asyncio.create_subprocess_shell(
|
||||
launch, stdin=stdin, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env,
|
||||
launch, stdin=stdin, stdout=output, stderr=output, cwd=cwd, env=env,
|
||||
creationflags=creationflags,
|
||||
)
|
||||
else:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*launch, stdin=stdin, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env,
|
||||
*launch, stdin=stdin, stdout=output, stderr=output, cwd=cwd, env=env,
|
||||
creationflags=creationflags,
|
||||
start_new_session=not _IS_WINDOWS,
|
||||
)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"""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.
|
||||
To add a backend, match the callable signature of _bwrap and _seatbelt and
|
||||
register it in _BACKENDS below.
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -11,16 +10,16 @@ from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.security.sandbox_launcher import resolve_sandbox_launcher
|
||||
|
||||
|
||||
def _normalize_bind_paths(
|
||||
paths: Iterable[str] | None,
|
||||
paths: Iterable[str],
|
||||
*,
|
||||
workspace: Path | None = None,
|
||||
workspace: Path,
|
||||
) -> list[str]:
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in paths or []:
|
||||
binds: dict[str, None] = {}
|
||||
for raw in paths:
|
||||
value = str(raw).strip()
|
||||
if not value:
|
||||
continue
|
||||
@@ -28,40 +27,23 @@ def _normalize_bind_paths(
|
||||
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:
|
||||
# A later bind of the workspace or an ancestor could cover the
|
||||
# tmpfs that hides the config directory.
|
||||
if workspace.is_relative_to(resolved_path):
|
||||
continue
|
||||
seen.add(resolved)
|
||||
out.append(resolved)
|
||||
return out
|
||||
binds[str(resolved_path)] = None
|
||||
return list(binds)
|
||||
|
||||
|
||||
def _bwrap(
|
||||
command: str,
|
||||
workspace: str,
|
||||
cwd: str,
|
||||
ws: Path,
|
||||
sandbox_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"]
|
||||
media: Path,
|
||||
ro_binds: list[str],
|
||||
rw_binds: list[str],
|
||||
) -> list[str]:
|
||||
optional = [
|
||||
"/bin",
|
||||
"/lib",
|
||||
@@ -75,9 +57,10 @@ def _bwrap(
|
||||
"/etc/ld.so.cache",
|
||||
]
|
||||
|
||||
args = ["bwrap", "--new-session", "--die-with-parent", "--setenv", "HOME", str(ws)]
|
||||
for p in required:
|
||||
args += ["--ro-bind", p, p]
|
||||
args = [
|
||||
"--new-session", "--die-with-parent", "--setenv", "HOME", str(ws),
|
||||
"--ro-bind", "/usr", "/usr",
|
||||
]
|
||||
for p in optional:
|
||||
args += ["--ro-bind-try", p, p]
|
||||
args += [
|
||||
@@ -87,12 +70,12 @@ def _bwrap(
|
||||
"--bind", str(ws), str(ws),
|
||||
"--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]
|
||||
for p in _normalize_bind_paths(sandbox_rw_binds, workspace=ws):
|
||||
for p in rw_binds:
|
||||
args += ["--bind-try", p, p]
|
||||
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
|
||||
@@ -138,16 +121,7 @@ def _seatbelt_ancestors(*paths: Path) -> list[str]:
|
||||
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
|
||||
return list(dict.fromkeys(str(ancestor) for path in paths for ancestor in path.parents))
|
||||
|
||||
|
||||
def _seatbelt_is_within(path: Path, root: Path) -> bool:
|
||||
@@ -177,12 +151,13 @@ def _sbpl_quote(path: str) -> str:
|
||||
|
||||
def _seatbelt(
|
||||
command: str,
|
||||
workspace: str,
|
||||
cwd: str,
|
||||
ws: Path,
|
||||
sandbox_cwd: str,
|
||||
*,
|
||||
sandbox_ro_binds: Iterable[str] | None = None,
|
||||
sandbox_rw_binds: Iterable[str] | None = None,
|
||||
) -> str:
|
||||
media: Path,
|
||||
ro_binds: list[str],
|
||||
rw_binds: list[str],
|
||||
) -> list[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
|
||||
@@ -199,20 +174,9 @@ def _seatbelt(
|
||||
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)",
|
||||
@@ -285,9 +249,7 @@ def _seatbelt(
|
||||
|
||||
# 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",
|
||||
return [
|
||||
"-p",
|
||||
"\n".join(rules),
|
||||
"/usr/bin/env",
|
||||
@@ -297,28 +259,37 @@ def _seatbelt(
|
||||
"-c",
|
||||
f"cd {shlex.quote(sandbox_cwd)} || exit\n{command}",
|
||||
]
|
||||
return shlex.join(args)
|
||||
|
||||
|
||||
_BACKENDS = {"bwrap": _bwrap, "seatbelt": _seatbelt}
|
||||
|
||||
|
||||
def wrap_command(
|
||||
def build_sandbox_argv(
|
||||
sandbox: str,
|
||||
command: str,
|
||||
workspace: str,
|
||||
cwd: str,
|
||||
*,
|
||||
launcher: 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)}")
|
||||
) -> list[str]:
|
||||
"""Build the sandbox argv with an independently resolved host launcher."""
|
||||
backend = _BACKENDS.get(sandbox)
|
||||
if backend is None:
|
||||
raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}")
|
||||
ws = Path(workspace).resolve()
|
||||
media = get_media_dir().resolve()
|
||||
requested_cwd = Path(cwd).resolve()
|
||||
sandbox_cwd = str(requested_cwd if requested_cwd.is_relative_to(ws) else ws)
|
||||
|
||||
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 shutil
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
|
||||
class SandboxLauncherError(ValueError):
|
||||
def __init__(self, reason: str):
|
||||
def __init__(self, reason: str, *, launcher: str = ""):
|
||||
self.reason = reason
|
||||
self.launcher = launcher
|
||||
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 supported_sandbox_backend() -> Literal["bwrap", "seatbelt"] | None:
|
||||
if sys.platform.startswith("linux"):
|
||||
return "bwrap"
|
||||
if sys.platform == "darwin":
|
||||
return "seatbelt"
|
||||
return None
|
||||
|
||||
|
||||
def resolve_sandbox_launcher(
|
||||
@@ -36,7 +38,7 @@ def resolve_sandbox_launcher(
|
||||
if not custom_path:
|
||||
launcher = shutil.which(name, path=os.defpath)
|
||||
if launcher is None:
|
||||
raise SandboxLauncherError("launcher_missing")
|
||||
raise SandboxLauncherError("launcher_missing", launcher=name)
|
||||
return str(Path(launcher).absolute())
|
||||
if os.name != "posix":
|
||||
raise SandboxLauncherError("platform_unsupported")
|
||||
@@ -146,7 +146,7 @@ def update_runtime_config(
|
||||
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")
|
||||
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,
|
||||
resolve_sandbox_launcher,
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user