feat(settings): check sandbox launchers and configure protected paths
This commit is contained in:
1 parent
f158779c60
commit
5b84b78cac
33 files changed
+1179
-20
No files matched your search
@@ -527,11 +527,12 @@ class TestSandboxPlatform:
|
||||
async def test_sandbox_applied_on_unix(self, tmp_path, backend):
|
||||
mock_proc = _CompletedProcess(b"sandboxed")
|
||||
trusted_bin = tmp_path / "trusted-bin"
|
||||
launcher = "bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec"
|
||||
|
||||
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"{backend} -- sh -c ls") as mock_wrap,
|
||||
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{launcher} -- sh -c ls") as mock_wrap,
|
||||
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
|
||||
patch.object(ExecTool, "_guard_command", return_value=None),
|
||||
):
|
||||
@@ -541,7 +542,7 @@ class TestSandboxPlatform:
|
||||
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 / backend)
|
||||
assert spawned_cmd[0] == str(trusted_bin / launcher)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
"""Regression coverage for nonstandard sandbox launcher installations."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
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_config import ExecToolConfig
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="requires Unix launcher preparation")
|
||||
@@ -29,3 +37,133 @@ async def test_nonstandard_bwrap_is_not_silently_run_without_sandbox(tmp_path, m
|
||||
|
||||
assert "sandbox launcher not found: bwrap" in result
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix protected launcher permissions")
|
||||
@pytest.mark.parametrize("location", ["workspace", "apphome"])
|
||||
async def test_writable_custom_launcher_is_rejected_before_execution(tmp_path, location):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
installation = workspace if location == "workspace" else tmp_path / "apphome" / "nanobot" / "bin"
|
||||
installation.mkdir(parents=True, exist_ok=True)
|
||||
launcher = installation / "bwrap"
|
||||
marker = tmp_path / "launcher-ran"
|
||||
launcher.write_text(f"#!/bin/sh\ntouch {marker}\n")
|
||||
launcher.chmod(0o755)
|
||||
config = ExecToolConfig(sandbox="bwrap", sandbox_launcher=str(launcher))
|
||||
# Rejection is independent of the selected shell and PATH.
|
||||
tool = ExecTool(working_dir=str(workspace), sandbox="bwrap", sandbox_launcher=str(launcher))
|
||||
response = await tool.execute(command="echo command-ran", shell="/bin/sh", login=True)
|
||||
assert "sandbox launcher rejected" in response
|
||||
assert not marker.exists()
|
||||
if sys.platform.startswith("linux"):
|
||||
status = await check_sandbox(config, workspace)
|
||||
assert status["state"] == "unavailable"
|
||||
assert status["reason"] in {"agent_writable", "unprotected_installation"}
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix protected launcher permissions")
|
||||
def test_root_owned_override_and_expanded_writable_bind(monkeypatch):
|
||||
launcher = Path("/bin/sh").resolve()
|
||||
assert resolve_sandbox_launcher("bwrap", str(launcher)) == str(launcher)
|
||||
monkeypatch.setenv("SANDBOX_TEST_BIND", str(launcher.parent))
|
||||
with pytest.raises(SandboxLauncherError, match="agent_writable"):
|
||||
resolve_sandbox_launcher("bwrap", str(launcher), writable_roots=(Path("$SANDBOX_TEST_BIND"),))
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix absolute paths")
|
||||
@pytest.mark.parametrize("path,reason", [("bin/bwrap", "path_not_absolute"), ("/nonexistent-nanobot-launcher", "path_unavailable")])
|
||||
def test_custom_launcher_requires_existing_absolute_file(path, reason):
|
||||
with pytest.raises(SandboxLauncherError, match=reason):
|
||||
resolve_sandbox_launcher("bwrap", path)
|
||||
|
||||
|
||||
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"))
|
||||
with pytest.raises(SandboxLauncherError, match="platform_unsupported"):
|
||||
resolve_sandbox_launcher("bwrap", "C:\\tools\\bwrap.exe")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("settings,state", [({"enable": False}, "disabled"), ({}, "off")])
|
||||
async def test_disabled_settings_do_not_launch_a_probe(settings, state, tmp_path, monkeypatch):
|
||||
async def unexpected(*args, **kwargs):
|
||||
pytest.fail("disabled sandbox must not start a process")
|
||||
monkeypatch.setattr("asyncio.create_subprocess_exec", unexpected)
|
||||
assert (await check_sandbox(ExecToolConfig(**settings), tmp_path))["state"] == state
|
||||
|
||||
|
||||
async def test_unsupported_platform_reports_no_isolation_without_running(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
status = await check_sandbox(ExecToolConfig(sandbox="bwrap"), tmp_path)
|
||||
assert status["state"] == "unsupported"
|
||||
assert status["supported_backend"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix native sandbox")
|
||||
async def test_native_probe_checks_isolation_without_touching_workspace(tmp_path):
|
||||
backend = "seatbelt" if sys.platform == "darwin" else "bwrap"
|
||||
config = ExecToolConfig(sandbox=backend)
|
||||
if sandbox_settings_status(config, tmp_path)["state"] == "unavailable":
|
||||
pytest.skip("native sandbox launcher is not installed")
|
||||
original = tmp_path / "keep.txt"
|
||||
original.write_text("user data")
|
||||
result = await check_sandbox(config, tmp_path)
|
||||
assert result["state"] == "passed", result
|
||||
assert sorted(p.name for p in tmp_path.iterdir()) == ["keep.txt"]
|
||||
assert original.read_text() == "user data"
|
||||
# The same resolver and backend must work for actual command execution.
|
||||
tool = ExecTool(working_dir=str(tmp_path), sandbox=backend, sandbox_launcher=result["launcher"])
|
||||
assert "actual-command" in await tool.execute(command="printf actual-command")
|
||||
|
||||
|
||||
def test_probe_revision_changes_when_saved_policy_changes(tmp_path):
|
||||
config = ExecToolConfig(sandbox="bwrap")
|
||||
before = sandbox_settings_status(config, tmp_path)["revision"]
|
||||
config.sandbox_rw_binds = ["/opt/agent-cache"]
|
||||
assert sandbox_settings_status(config, tmp_path)["revision"] != before
|
||||
assert sandbox_settings_status(ExecToolConfig(sandbox="bwrap"), tmp_path / "other")["revision"] != before
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix process-group cleanup")
|
||||
@pytest.mark.parametrize("finish", ["timeout", "cancel"])
|
||||
async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_path, monkeypatch, finish):
|
||||
started, exited = asyncio.Event(), asyncio.Event()
|
||||
|
||||
class Process:
|
||||
pid = 12345
|
||||
returncode = None
|
||||
|
||||
async def wait(self):
|
||||
await exited.wait()
|
||||
return self.returncode
|
||||
|
||||
process = Process()
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
assert kwargs["start_new_session"]
|
||||
started.set()
|
||||
return process
|
||||
|
||||
def kill(pid, sig):
|
||||
assert (pid, sig) == (process.pid, signal.SIGKILL)
|
||||
process.returncode = -9
|
||||
exited.set()
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox_check.sandbox_settings_status", lambda *_: {
|
||||
"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(asyncio, "create_subprocess_exec", spawn)
|
||||
monkeypatch.setattr(os, "killpg", kill)
|
||||
task = asyncio.create_task(check_sandbox(ExecToolConfig(sandbox="bwrap"), tmp_path))
|
||||
await asyncio.wait_for(started.wait(), 1)
|
||||
if finish == "cancel":
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
else:
|
||||
assert (await task)["reason"] == "probe_timeout"
|
||||
assert exited.is_set()
|
||||
assert process.returncode == -9
|
||||
@@ -17,6 +17,7 @@
|
||||
"tools.exec.path_prepend",
|
||||
"tools.exec.path_append",
|
||||
"tools.exec.sandbox",
|
||||
"tools.exec.sandbox_launcher",
|
||||
"tools.exec.sandbox_ro_binds",
|
||||
"tools.exec.sandbox_rw_binds",
|
||||
"tools.exec.allowed_env_keys",
|
||||
|
||||
@@ -65,6 +65,31 @@ def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace:
|
||||
return request
|
||||
|
||||
|
||||
async def test_sandbox_check_is_authenticated_explicit_and_serialized(tmp_path, monkeypatch):
|
||||
path = "/api/settings/sandbox/check"
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
response = await router.dispatch(None, SimpleNamespace(path=path, headers=Headers()), path)
|
||||
assert response.status_code == 405
|
||||
unauthorized = _router(authorized=False, config_path=tmp_path / "config.json")
|
||||
assert (await unauthorized.dispatch(None, _mutation_request(path, {}), path)).status_code == 401
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def probe(config, workspace):
|
||||
started.set()
|
||||
await release.wait()
|
||||
return {"state": "passed", "reason": "", "launcher": "/usr/bin/bwrap", "revision": "test", "supported_backend": "bwrap"}
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.settings_system.check_sandbox", probe)
|
||||
first = asyncio.create_task(router.dispatch(None, _mutation_request(path, {}), path))
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
try:
|
||||
assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 409
|
||||
finally:
|
||||
release.set()
|
||||
assert (await first).status_code == 200
|
||||
assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nanobot_update_requires_auth_local_permission_and_websocket(tmp_path, monkeypatch):
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
|
||||
@@ -35,6 +35,22 @@ def test_shared_proxy_roundtrip_preserves_independent_feature_switches(tmp_path)
|
||||
assert load_config(path).tools.web.use_proxy is True
|
||||
|
||||
|
||||
def test_legacy_sandbox_config_roundtrip_and_rejected_override_are_atomic(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps({"tools": {"exec": {"sandbox": "bwrap", "sandboxRoBinds": ["/opt/tools"]}}}))
|
||||
config = load_config(path)
|
||||
assert config.tools.exec.sandbox_launcher == ""
|
||||
payload = update_runtime_config_settings({"tools.exec.timeout": 75}, config_path=path)
|
||||
assert payload["runtime_config"]["tools.exec.sandbox_launcher"] == ""
|
||||
assert load_config(path).tools.exec.sandbox_ro_binds == ["/opt/tools"]
|
||||
before = path.read_bytes()
|
||||
with pytest.raises(WebUISettingsError, match="sandbox_launcher_path_not_absolute"):
|
||||
update_runtime_config_settings({"tools.exec.sandbox_launcher": "bin/bwrap", "tools.exec.timeout": 99}, config_path=path)
|
||||
assert path.read_bytes() == before
|
||||
update_runtime_config_settings({"tools.exec.sandbox_launcher": ""}, config_path=path)
|
||||
assert load_config(path).tools.exec.sandbox == "bwrap"
|
||||
|
||||
|
||||
def test_enabling_web_proxy_without_an_address_preserves_config(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
save_config(Config(), path)
|
||||
|
||||
Reference in new issue
Block a user