feat: sandbox exec calls with bwrap and run container as non-root

This commit is contained in:
kinchahoy
2026-03-16 23:55:19 -07:00
parent 49fc50b1e6
commit 7913e7150a
8 changed files with 1204 additions and 7 deletions
+49
View File
@@ -0,0 +1,49 @@
"""Sandbox backends for shell command execution.
To add a new backend, implement a function with the signature:
_wrap_<name>(command: str, workspace: str, cwd: str) -> str
and register it in _BACKENDS below.
"""
import shlex
from pathlib import Path
def _bwrap(command: str, workspace: str, cwd: str) -> str:
"""Wrap command in a bubblewrap sandbox (requires bwrap in container).
Only the workspace is bind-mounted read-write; its parent dir (which holds
config.json) is hidden behind a fresh tmpfs.
"""
ws = Path(workspace).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/resolv.conf", "/etc/ld.so.cache"]
args = ["bwrap"]
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), # mask config dir
"--dir", str(ws), # recreate workspace mount point
"--bind", str(ws), str(ws),
"--chdir", sandbox_cwd,
"--", "sh", "-c", command,
]
return shlex.join(args)
_BACKENDS = {"bwrap": _bwrap}
def wrap_command(sandbox: str, command: str, workspace: str, cwd: str) -> str:
"""Wrap *command* using the named sandbox backend."""
if backend := _BACKENDS.get(sandbox):
return backend(command, workspace, cwd)
raise ValueError(f"Unknown sandbox backend {sandbox!r}. Available: {list(_BACKENDS)}")
+8
View File
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Any
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.sandbox import wrap_command
class ExecTool(Tool):
@@ -19,10 +20,12 @@ class ExecTool(Tool):
deny_patterns: list[str] | None = None,
allow_patterns: list[str] | None = None,
restrict_to_workspace: bool = False,
sandbox: str = "",
path_append: str = "",
):
self.timeout = timeout
self.working_dir = working_dir
self.sandbox = sandbox
self.deny_patterns = deny_patterns or [
r"\brm\s+-[rf]{1,2}\b", # rm -r, rm -rf, rm -fr
r"\bdel\s+/[fq]\b", # del /f, del /q
@@ -84,6 +87,11 @@ class ExecTool(Tool):
if guard_error:
return guard_error
if self.sandbox:
workspace = self.working_dir or cwd
command = wrap_command(self.sandbox, command, workspace, cwd)
cwd = str(Path(workspace).resolve())
effective_timeout = min(timeout or self.timeout, self._MAX_TIMEOUT)
env = os.environ.copy()