fix(sandbox): resolve saved environment paths during validation
This commit is contained in:
1 parent
fb159257cb
commit
16250540d3
5 files changed
+97
-12
No files matched your search
@@ -19,6 +19,8 @@ from nanobot.agent.tools.sandbox_launcher import (
|
||||
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
|
||||
|
||||
_PROBE_TIMEOUT_S = 5
|
||||
|
||||
@@ -32,9 +34,19 @@ class SandboxCheck(TypedDict):
|
||||
|
||||
|
||||
def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
|
||||
return _prepare_settings(config, workspace)[2]
|
||||
|
||||
|
||||
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
|
||||
missing_env = False
|
||||
try:
|
||||
config = resolve_config_env_vars(config)
|
||||
workspace = Path(resolve_config_env_vars(str(workspace))).expanduser()
|
||||
except ConfigLoadError:
|
||||
missing_env = True
|
||||
revision = hashlib.sha256(json.dumps(
|
||||
{"config": config.model_dump(), "workspace": str(workspace)}, sort_keys=True,
|
||||
).encode()).hexdigest()
|
||||
@@ -48,6 +60,8 @@ def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxC
|
||||
result["state"] = "off"
|
||||
elif sandbox_platform(config.sandbox) == "unsupported":
|
||||
result.update(state="unsupported", reason="platform_unsupported")
|
||||
elif missing_env:
|
||||
result.update(state="unavailable", reason="path_unavailable")
|
||||
else:
|
||||
try:
|
||||
result["launcher"] = resolve_sandbox_launcher(
|
||||
@@ -56,11 +70,11 @@ def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxC
|
||||
)
|
||||
except SandboxLauncherError as exc:
|
||||
result.update(state="unavailable", reason=exc.reason)
|
||||
return result
|
||||
return config, workspace, result
|
||||
|
||||
|
||||
async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
|
||||
result = await asyncio.to_thread(sandbox_settings_status, config, workspace)
|
||||
config, workspace, 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
|
||||
|
||||
@@ -2,7 +2,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, cast, overload
|
||||
from typing import Any, TypeVar, cast, overload
|
||||
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from pydantic_settings import SettingsError
|
||||
@@ -180,14 +180,15 @@ def merge_missing_defaults(existing: object, defaults: object) -> object:
|
||||
|
||||
|
||||
_ENV_REF_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
||||
_ConfigValue = TypeVar("_ConfigValue")
|
||||
|
||||
|
||||
def resolve_config_env_vars(
|
||||
config: Config,
|
||||
config: _ConfigValue,
|
||||
*,
|
||||
config_path: Path | None = None,
|
||||
) -> Config:
|
||||
"""Return *config* with ``${VAR}`` env-var references resolved.
|
||||
) -> _ConfigValue:
|
||||
"""Return a config or config subtree with ``${VAR}`` references resolved.
|
||||
|
||||
Walks in place so fields declared with ``exclude=True`` survive;
|
||||
returns the same instance when no references are present.
|
||||
|
||||
@@ -8,6 +8,8 @@ from typing import Any, cast
|
||||
|
||||
from pydantic import BaseModel, TypeAdapter, ValidationError
|
||||
|
||||
from nanobot.config.errors import ConfigLoadError
|
||||
from nanobot.config.loader import resolve_config_env_vars
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.security.network import is_loopback_host
|
||||
from nanobot.webui.settings_contracts import WebUISettingsError
|
||||
@@ -160,10 +162,14 @@ def update_runtime_config(
|
||||
)
|
||||
|
||||
try:
|
||||
exec_config = resolve_config_env_vars(validated.tools.exec)
|
||||
workspace = Path(resolve_config_env_vars(str(validated.workspace_path))).expanduser()
|
||||
resolve_sandbox_launcher(
|
||||
validated.tools.exec.sandbox, validated.tools.exec.sandbox_launcher,
|
||||
writable_roots=(validated.workspace_path, *map(Path, validated.tools.exec.sandbox_rw_binds)),
|
||||
exec_config.sandbox, exec_config.sandbox_launcher,
|
||||
writable_roots=(workspace, *map(Path, exec_config.sandbox_rw_binds)),
|
||||
)
|
||||
except ConfigLoadError:
|
||||
raise WebUISettingsError("sandbox_launcher_path_unavailable") from None
|
||||
except SandboxLauncherError as exc:
|
||||
raise WebUISettingsError(f"sandbox_launcher_{exc.reason}") from None
|
||||
if "tools.ssrf_whitelist" in values:
|
||||
|
||||
@@ -14,6 +14,7 @@ from nanobot.agent.tools.sandbox_check import check_sandbox, sandbox_settings_st
|
||||
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
|
||||
from nanobot.config.loader import resolve_config_env_vars
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="requires Unix launcher preparation")
|
||||
@@ -102,15 +103,24 @@ async def test_unsupported_platform_reports_no_isolation_without_running(tmp_pat
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix native sandbox")
|
||||
async def test_native_probe_checks_isolation_without_touching_workspace(tmp_path):
|
||||
@pytest.mark.parametrize("env_refs", [False, True])
|
||||
async def test_native_probe_checks_isolation_without_touching_workspace(tmp_path, monkeypatch, env_refs):
|
||||
backend = "seatbelt" if sys.platform == "darwin" else "bwrap"
|
||||
config = ExecToolConfig(sandbox=backend)
|
||||
status = sandbox_settings_status(config, tmp_path)
|
||||
if status["state"] == "unavailable":
|
||||
pytest.skip("native sandbox launcher is not installed")
|
||||
workspace = tmp_path
|
||||
if env_refs:
|
||||
monkeypatch.setenv("SANDBOX_TEST_LAUNCHER", status["launcher"])
|
||||
monkeypatch.setenv("SANDBOX_TEST_WORKSPACE", str(tmp_path))
|
||||
config.sandbox_launcher = "${SANDBOX_TEST_LAUNCHER}"
|
||||
workspace = Path("${SANDBOX_TEST_WORKSPACE}")
|
||||
status = sandbox_settings_status(config, workspace)
|
||||
assert status == sandbox_settings_status(resolve_config_env_vars(config), tmp_path)
|
||||
original = tmp_path / "keep.txt"
|
||||
original.write_text("user data")
|
||||
result = await check_sandbox(config, tmp_path)
|
||||
result = await check_sandbox(config, workspace)
|
||||
if backend == "bwrap":
|
||||
# An installed launcher is not proof that the host permits namespaces.
|
||||
# Establish this independently of nanobot's wrapper and probe. In that
|
||||
@@ -132,11 +142,30 @@ async def test_native_probe_checks_isolation_without_touching_workspace(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"
|
||||
if env_refs:
|
||||
assert config.sandbox_launcher == "${SANDBOX_TEST_LAUNCHER}"
|
||||
monkeypatch.setenv("SANDBOX_TEST_WORKSPACE", str(tmp_path / "other"))
|
||||
assert sandbox_settings_status(config, workspace)["revision"] != result["revision"]
|
||||
# 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")
|
||||
|
||||
|
||||
async def test_missing_environment_launcher_does_not_fall_back_or_launch(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "linux")
|
||||
monkeypatch.delenv("SANDBOX_TEST_MISSING_LAUNCHER", raising=False)
|
||||
|
||||
async def unexpected(*args, **kwargs):
|
||||
pytest.fail("unresolved launcher must not start a process")
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", unexpected)
|
||||
config = ExecToolConfig(sandbox="bwrap", sandbox_launcher="${SANDBOX_TEST_MISSING_LAUNCHER}")
|
||||
status = await check_sandbox(config, tmp_path)
|
||||
assert status["state"] == "unavailable"
|
||||
assert status["reason"] == "path_unavailable"
|
||||
assert status["launcher"] is None
|
||||
|
||||
|
||||
def test_probe_revision_changes_when_saved_policy_changes(tmp_path):
|
||||
config = ExecToolConfig(sandbox="bwrap")
|
||||
before = sandbox_settings_status(config, tmp_path)["revision"]
|
||||
@@ -170,9 +199,9 @@ async def test_probe_reaps_its_process_on_timeout_or_request_cancellation(tmp_pa
|
||||
process.returncode = -9
|
||||
exited.set()
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox_check.sandbox_settings_status", lambda *_: {
|
||||
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(asyncio, "create_subprocess_exec", spawn)
|
||||
|
||||
@@ -53,6 +53,41 @@ def test_legacy_sandbox_config_roundtrip_and_rejected_override_are_atomic(tmp_pa
|
||||
assert load_config(path).tools.exec.sandbox == "bwrap"
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Unix protected launcher permissions")
|
||||
def test_sandbox_environment_paths_are_validated_without_rewriting_references(tmp_path, monkeypatch):
|
||||
path = tmp_path / "config.json"
|
||||
monkeypatch.setenv("SANDBOX_TEST_WORKSPACE", str(tmp_path / "workspace"))
|
||||
monkeypatch.setenv("SANDBOX_TEST_LAUNCHER", "/bin/sh")
|
||||
monkeypatch.delenv("SANDBOX_TEST_MISSING_PROVIDER", raising=False)
|
||||
config = Config.model_validate({
|
||||
"agents": {"defaults": {"workspace": "${SANDBOX_TEST_WORKSPACE}"}},
|
||||
"providers": {"openai": {"apiKey": "${SANDBOX_TEST_MISSING_PROVIDER}"}},
|
||||
"tools": {"exec": {"sandbox": "bwrap"}},
|
||||
})
|
||||
save_config(config, path)
|
||||
payload = update_runtime_config_settings({
|
||||
"tools.exec.sandbox_launcher": "${SANDBOX_TEST_LAUNCHER}",
|
||||
}, config_path=path)
|
||||
saved = load_config(path)
|
||||
assert payload["runtime_config"]["tools.exec.sandbox_launcher"] == "${SANDBOX_TEST_LAUNCHER}"
|
||||
assert saved.tools.exec.sandbox_launcher == "${SANDBOX_TEST_LAUNCHER}"
|
||||
assert saved.agents.defaults.workspace == "${SANDBOX_TEST_WORKSPACE}"
|
||||
assert saved.providers.openai.api_key == "${SANDBOX_TEST_MISSING_PROVIDER}"
|
||||
before = path.read_bytes()
|
||||
monkeypatch.setenv("SANDBOX_TEST_RW_BIND", str(Path("/bin/sh").resolve().parent))
|
||||
with pytest.raises(WebUISettingsError, match="sandbox_launcher_agent_writable"):
|
||||
update_runtime_config_settings({
|
||||
"tools.exec.sandbox_rw_binds": ["${SANDBOX_TEST_RW_BIND}"],
|
||||
}, config_path=path)
|
||||
assert path.read_bytes() == before
|
||||
monkeypatch.delenv("SANDBOX_TEST_LAUNCHER")
|
||||
with pytest.raises(WebUISettingsError, match="sandbox_launcher_path_unavailable"):
|
||||
update_runtime_config_settings({
|
||||
"tools.exec.sandbox_launcher": "${SANDBOX_TEST_LAUNCHER}",
|
||||
}, config_path=path)
|
||||
assert path.read_bytes() == before
|
||||
|
||||
|
||||
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