feat(settings): check sandbox launchers and configure protected paths

This commit is contained in:
Xubin Ren committed 2026-11-08 14:29:46 +08:00
1 parent f158779c60
commit 5b84b78cac
33 files changed
+1179 -20

No files matched your search

+6 -1
View File
@@ -2324,6 +2324,7 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]
| `tools.restrictToWorkspace` | `false` | When `true`, enables nanobot's application-level workspace guards for workspace-aware tools. File tools resolve paths under the active workspace; selected internal roots can be added as read-only or explicitly write-enabled roots, and media uploads are read-only by default. Shell execution rejects workspace-external `working_dir` values and applies best-effort command path checks, but this is not an OS sandbox. |
| `tools.maxSessionMessagesPerMinute` | `6` | Maximum messages one source session may send during any rolling 60-second window. Additional sends are rejected to stop runaway agent loops. |
| `tools.exec.sandbox` | `""` | Sandbox backend for shell commands. `"bwrap"` (Linux) or `"seatbelt"` (macOS) restricts filesystem access to the workspace (read-write), media (read-only), required system paths and configured extra binds. The workspace's parent is denied except for allowed roots; keep secrets outside the workspace and binds. Automatically enables workspace restriction for file tools. `"bwrap"` requires bubblewrap (`apt install bubblewrap`; pre-installed in Docker). `"seatbelt"` uses macOS `sandbox-exec(1)`; it sets `HOME` and `TMPDIR` to the workspace rather than sharing host temporary directories. Use `mktemp "$TMPDIR/job.XXXXXX"` for macOS shell scratch files. Neither backend restricts network access. Windows logs a warning and runs commands without OS sandboxing. |
| `tools.exec.sandboxLauncher` | `""` | Optional absolute path to a sandbox launcher from a trusted publisher on the gateway. Empty keeps the existing system lookup. An override must resolve to an executable regular file owned by root, with root-owned parent directories and no group/other write permission or write access for the gateway's non-root account. It must be outside the workspace and extra writable binds. nanobot resolves symlinks and rechecks the path before each command; it does not install, elevate privileges, or trust the agent's `PATH`. |
| `tools.exec.enable` | `true` | When `false`, the shell `exec` tool is not registered at all. Use this to completely disable shell command execution. |
| `tools.exec.maxRuntime` | `3600` | Default hard runtime in seconds for shell commands, measured from process start even while output is arriving. Set `0` only in trusted configuration to allow unlimited runtime. |
| `tools.exec.maxRuntimeLimit` | `86400` | Positive upper bound in seconds for explicit model-requested hard runtimes. Independent of `maxRuntime`; it does not limit or change the trusted default. |
@@ -2377,7 +2378,11 @@ The tool result distinguishes a hard-runtime termination from inactivity. With `
Silence is not proof that a command is stuck: builds, downloads, and buffered programs can be quiet while working. Only bytes received through stdout or stderr count as activity; output redirected to files is not observed, and reading logs does not refresh the inactivity clock. Inactivity checks do not detect prompts or supply answers. Choose `"terminate"` only when stopping a quiet command is acceptable, and use a finite hard runtime when total execution time must remain bounded. Shell sessions are not durable jobs and should not be used as a replacement for a scheduler or service manager. A command that detaches a background service and exits is not a managed job; these timing checks do not manage that service afterward.
With a Unix sandbox enabled, the selected shell and any requested login profile run inside the sandbox, with its workspace-scoped `HOME`. Custom interpreters outside the exposed system paths require an explicit read-only bind. Tool PATH settings affect commands inside the sandbox, not selection of the host launcher. Install `bwrap` in the operating system's default executable search path (normally `/bin:/usr/bin`); a custom parent or tool `PATH` cannot override that launcher. Seatbelt uses `/usr/bin/sandbox-exec`. A missing or failed launcher never falls back to unsandboxed execution.
With a Unix sandbox enabled, the selected shell and any requested login profile run inside the sandbox, with its workspace-scoped `HOME`. Custom interpreters outside the exposed system paths require an explicit read-only bind. Tool PATH settings affect commands inside the sandbox, not selection of the host launcher. By default, install `bwrap` in the operating system's default executable search path (normally `/bin:/usr/bin`); a custom parent or tool `PATH` cannot override that launcher. Seatbelt defaults to `/usr/bin/sandbox-exec`. For a protected nonstandard installation, set `sandboxLauncher` instead of changing the host's global `/bin` or adding writable directories to the launcher search path. A missing, rejected, or failed launcher never falls back to unsandboxed execution.
In **Settings → Advanced → Command sandbox**, choose the host's isolation method and use **Check sandbox**. The gateway checks the saved configuration with a bounded, temporary test: launcher startup, workspace writes, and denial of an external test file. It does not run a user command, change the real workspace, or certify all security properties. The result describes the saved configuration, not a live command session; restart the gateway after saving to apply changes. Open **Advanced options** to set a trusted launcher path and the existing additional paths and command controls. An older host without this optional settings capability keeps the existing sandbox editor and does not receive check requests.
NAS and other custom packages can provide their own launcher, but a file in an app's writable data directory is not safe to launch before isolation. For fnOS or similar installations, ask the package maintainer to install bubblewrap and its parent directories in a root-protected location, then set that absolute path. Finding `bwrap` in an interactive shell or venv does not establish that the gateway can launch it safely or that the kernel permits namespaces. A failed check must be resolved in the launcher installation, host kernel policy, or container setup; it does not turn isolation off. Existing configurations without `sandboxLauncher` retain the same defaults. Clearing this field restores system lookup; no chat or configuration migration is required.
## Pairing
+115
View File
@@ -0,0 +1,115 @@
"""Bounded, explicit checks of saved shell sandbox settings, without a model."""
from __future__ import annotations
import asyncio
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
_PROBE_TIMEOUT_S = 5
class SandboxCheck(TypedDict):
state: str
reason: str
launcher: str | None
revision: str
supported_backend: str | None
def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
import sys
backend = "bwrap" if sys.platform.startswith("linux") else "seatbelt" if sys.platform == "darwin" else None
revision = hashlib.sha256(json.dumps(
{"config": config.model_dump(), "workspace": str(workspace)}, sort_keys=True,
).encode()).hexdigest()
result: SandboxCheck = {
"state": "unchecked", "reason": "", "launcher": None,
"revision": revision, "supported_backend": backend,
}
if not config.enable:
result["state"] = "disabled"
elif not config.sandbox:
result["state"] = "off"
elif sandbox_platform(config.sandbox) == "unsupported":
result.update(state="unsupported", reason="platform_unsupported")
else:
try:
result["launcher"] = resolve_sandbox_launcher(
config.sandbox, config.sandbox_launcher,
writable_roots=(workspace, *map(Path, config.sandbox_rw_binds)),
)
except SandboxLauncherError as exc:
result.update(state="unavailable", reason=exc.reason)
return result
async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
result = await asyncio.to_thread(sandbox_settings_status, config, workspace)
if result["state"] != "unchecked":
return result
# Use synthetic files only. Never run startup/login profiles or an arbitrary
# user-provided test command. This is a basic probe, not a full security audit.
with tempfile.TemporaryDirectory(prefix="nanobot-sandbox-check-") as directory:
root = Path(directory).resolve()
project = root / "workspace"
project.mkdir()
canary = root / "outside"
canary.write_text("unchanged")
script = (
"printf checked > inside && "
f"! test -r {shlex.quote(str(canary))} && "
f"! (printf changed > {shlex.quote(str(canary))})"
)
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)),
)
result["launcher"] = argv[0]
except SandboxLauncherError as exc:
result.update(state="unavailable", reason=exc.reason)
return result
process: asyncio.subprocess.Process | 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,
)
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"
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()
return result
+62
View File
@@ -0,0 +1,62 @@
"""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)
+13 -4
View File
@@ -29,6 +29,7 @@ from nanobot.agent.tools.exec_session import (
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,
@@ -178,6 +179,7 @@ class ExecTool(Tool):
restrict_to_workspace=ctx.config.restrict_to_workspace,
webui_allow_local_service_access=ctx.config.webui_allow_local_service_access,
sandbox=cfg.sandbox,
sandbox_launcher=cfg.sandbox_launcher,
path_prepend=cfg.path_prepend,
path_append=cfg.path_append,
sandbox_ro_binds=cfg.sandbox_ro_binds,
@@ -209,6 +211,7 @@ class ExecTool(Tool):
max_runtime_limit: int | None = None,
idle_timeout: int = 300,
idle_action: Literal["report", "terminate"] = "report",
sandbox_launcher: str = "",
):
if timeout is not None and max_runtime is not None:
raise ValueError("timeout and max_runtime are mutually exclusive")
@@ -220,6 +223,7 @@ class ExecTool(Tool):
self._exec_config = ExecToolConfig.model_validate(values)
self.working_dir = working_dir
self.sandbox = sandbox
self.sandbox_launcher = sandbox_launcher
self.deny_patterns = (deny_patterns or []) + [
r"\brm\s+-[rf]{1,2}\b",
r"\bdel\s+/[fq]\b",
@@ -472,10 +476,15 @@ class ExecTool(Tool):
sandbox_rw_binds=[str(p) for p in self.sandbox_rw_binds],
))
# Project/tool and inherited PATH can contain writable programs.
launcher = shutil.which(command[0], path=os.defpath)
if launcher is None:
return ToolResult.error(f"Error: sandbox launcher not found: {command[0]}")
command[0] = str(Path(launcher).absolute())
try:
command[0] = resolve_sandbox_launcher(
self.sandbox, self.sandbox_launcher,
writable_roots=(Path(workspace), *self.sandbox_rw_binds),
)
except SandboxLauncherError as exc:
if exc.reason == "launcher_missing":
return ToolResult.error(f"Error: sandbox launcher not found: {command[0]}")
return ToolResult.error(f"Error: sandbox launcher rejected: {exc.reason}")
cwd = str(Path(workspace).resolve())
return _PreparedCommand(
+1
View File
@@ -19,6 +19,7 @@ class ExecToolConfig(Base):
path_prepend: str = ""
path_append: str = ""
sandbox: str = ""
sandbox_launcher: str = ""
sandbox_ro_binds: list[str] = Field(default_factory=list)
sandbox_rw_binds: list[str] = Field(default_factory=list)
allowed_env_keys: list[str] = Field(default_factory=list)
+2
View File
@@ -28,6 +28,7 @@ UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
CONTEXT_GRAPH_REFERENCES_CAPABILITY = "webui.context-graph.references.v1"
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
SANDBOX_SETTINGS_CAPABILITY = "webui.sandbox-settings.v1"
class Compatibility(TypedDict):
@@ -48,6 +49,7 @@ def webui_contract() -> dict[str, object]:
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
PROMPT_NAVIGATION_CAPABILITY, CONTEXT_GRAPH_REFERENCES_CAPABILITY,
SANDBOX_SETTINGS_CAPABILITY,
],
}
+2
View File
@@ -131,6 +131,7 @@ _CAPABILITY_ROUTES = {
}
_SYSTEM_ROUTES = {
"/api/settings/sandbox/check": "sandbox-check",
"/api/settings/runtime-config/update": "runtime-config-update",
"/api/settings/cli-apps": "cli-list",
"/api/settings/cli-apps/install": "cli-install",
@@ -162,6 +163,7 @@ _SYSTEM_ROUTES = {
}
_SETTINGS_MUTATION_PATHS = frozenset({
"/api/settings/sandbox/check",
"/api/settings/nanobot-update/channel",
"/api/settings/nanobot-update/plan/create",
"/api/settings/nanobot-update/job/prepare",
+15 -1
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import ipaddress
import math
import re
from pathlib import PurePosixPath, PureWindowsPath
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Any, cast
from pydantic import BaseModel, TypeAdapter, ValidationError
@@ -33,6 +33,7 @@ RUNTIME_CONFIG_PATHS = (
"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",
@@ -152,6 +153,19 @@ def update_runtime_config(
raise WebUISettingsError("Set an API key in System before using a network bind address.")
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 (
SandboxLauncherError,
resolve_sandbox_launcher,
)
try:
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)),
)
except SandboxLauncherError as exc:
raise WebUISettingsError(f"sandbox_launcher_{exc.reason}") from None
if "tools.ssrf_whitelist" in values:
for cidr in validated.tools.ssrf_whitelist:
try:
+14
View File
@@ -17,6 +17,7 @@ import httpx
from pydantic import ValidationError
from pydantic.alias_generators import to_snake
from nanobot.agent.tools.sandbox_check import check_sandbox, sandbox_settings_status
from nanobot.build_info import COMMIT
from nanobot.channels._setup import channel_setup_spec
from nanobot.channels.connect import ChannelConnectError, ChannelConnector, ManagedChannelConnector
@@ -167,6 +168,7 @@ def system_settings_payload(
"exec_enabled": exec_config.enable,
"exec_max_runtime_limit": exec_config.max_runtime_limit,
"exec_sandbox": exec_config.sandbox or None,
"exec_sandbox_status": sandbox_settings_status(exec_config, config.workspace_path),
"exec_path_prepend_set": bool(exec_config.path_prepend),
"exec_path_append_set": bool(exec_config.path_append),
},
@@ -457,6 +459,7 @@ class SystemSettingsHandler:
self._closing_connectors = False
self._update_jobs = UpdateJobService()
self._remove_update_work: Callable[[], None] | None = None
self._sandbox_check_running = False
def _has_pending_connectors(self) -> bool:
return self._closing_connectors or any(
@@ -503,6 +506,17 @@ class SystemSettingsHandler:
channel_name: str | None = None,
connect_action: str | None = None,
) -> SettingsRouteResult:
if action == "sandbox-check":
if self._sandbox_check_running:
return SettingsRouteResult.failure(409, "sandbox_check_busy")
self._sandbox_check_running = True
try:
config = await asyncio.to_thread(self.settings.config.load)
return SettingsRouteResult.success({
"sandbox": await check_sandbox(config.tools.exec, config.workspace_path),
})
finally:
self._sandbox_check_running = False
if action == "runtime-config-update":
values = (request.payload or {}).get("values")
if not isinstance(values, dict):
+1
View File
@@ -217,6 +217,7 @@ _WEBUI_MUTATION_PATHS = {
"settings.image_generation.update": "/api/settings/image-generation/update",
"settings.transcription.update": "/api/settings/transcription/update",
"settings.runtime_config.update": "/api/settings/runtime-config/update",
"settings.sandbox.check": "/api/settings/sandbox/check",
"settings.network_safety.update": "/api/settings/network-safety/update",
"settings.cli_app.install": "/api/settings/cli-apps/install",
"settings.cli_app.update": "/api/settings/cli-apps/update",
+3 -2
View File
@@ -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"])
+138
View File
@@ -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",
+25
View File
@@ -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")
+16
View File
@@ -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)
@@ -43,6 +43,7 @@ import {
import { ChannelsSettings } from "@/components/settings/system/ChannelsSettings";
import { RUNTIME_CONFIG_FIELDS, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { RuntimeConfigSettings } from "@/components/settings/system/RuntimeConfigSettings";
import { useClient } from "@/providers/ClientProvider";
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
import type { SettingsController } from "@/components/settings/useSettingsController";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
@@ -92,6 +93,7 @@ export function SettingsPage({
isRestarting,
hostChromeInset,
}: SettingsPageProps) {
const { client, webuiCapabilities } = useClient();
const [dialogLayoutAnchor, setDialogLayoutAnchor] = useState<HTMLDivElement | null>(null);
const [mcpSetupName, setMcpSetupName] = useState<string | null>(null);
const presetDeletedCallback = useRef<(() => void) | null>(null);
@@ -193,7 +195,8 @@ export function SettingsPage({
: controllerPendingRestartSections;
const runtimeConfiguration = (page: RuntimeConfigPage) => settings && (
<RuntimeConfigSettings page={page} settings={settings} state={controller.runtimeConfigState}
<RuntimeConfigSettings page={page} settings={settings} state={controller.runtimeConfigState} client={client}
sandboxSupported={webuiCapabilities.includes("webui.sandbox-settings.v1")}
onRestart={showSidebar ? undefined : restartViaSettingsSurface} isRestarting={restartInProgress}
remoteBrowserAccess={remoteBrowserAccess}>
{page === "advanced" ? (
@@ -10,6 +10,7 @@ import { SharedProxyEditor } from "@/components/settings/shared/SharedProxyEdito
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
import { ShellRuntimeControl } from "@/components/settings/system/ShellRuntimeControl";
import { IdleCompactionControl } from "@/components/settings/system/IdleCompactionControl";
import { SandboxSettings } from "@/components/settings/system/SandboxSettings";
import { Input } from "@/components/ui/input";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigField, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { updateRuntimeConfigSettings } from "@/lib/api";
@@ -120,8 +121,10 @@ export function useRuntimeConfigSettings(
setSaved((prev) => ({ ...prev, [group]: true }));
} catch (error) {
const message = (error as Error).message;
setErrors((prev) => ({ ...prev, [group]: message }));
setInvalidField(changed.find((field) => message.startsWith(field.path))?.path ?? null);
const sandboxReason = message.match(/sandbox_launcher_([a-z_]+)/)?.[1];
setErrors((prev) => ({ ...prev, [group]: sandboxReason
? t(`settings.sandbox.reasons.${sandboxReason}`, { defaultValue: t("settings.sandbox.saveError") }) : message }));
setInvalidField(sandboxReason ? "tools.exec.sandbox_launcher" : changed.find((field) => message.startsWith(field.path))?.path ?? null);
} finally {
setSaving(null);
}
@@ -169,11 +172,13 @@ export function useRuntimeConfigSettings(
export type RuntimeConfigController = ReturnType<typeof useRuntimeConfigSettings>;
export function RuntimeConfigSettings({
page, settings, state, onRestart, isRestarting, remoteBrowserAccess, children,
page, settings, state, client, sandboxSupported = false, onRestart, isRestarting, remoteBrowserAccess, children,
}: {
page: RuntimeConfigPage;
settings: SettingsPayload;
state: RuntimeConfigController;
client?: NanobotClient;
sandboxSupported?: boolean;
onRestart?: () => void;
isRestarting: boolean;
remoteBrowserAccess: boolean;
@@ -193,18 +198,20 @@ export function RuntimeConfigSettings({
{restartPending && onRestart ? <RestartRequiredNotice message={t("settings.status.savedRestartApply")}
onRestart={onRestart} isRestarting={isRestarting} /> : null}
{groups.map((group) => {
if (group.enabledBy && state.value(group.enabledBy) === false) return null;
const sandbox = group.id === "shell" && sandboxSupported && settings.advanced.exec_sandbox_status && client;
if (group.enabledBy && state.value(group.enabledBy) === false && !sandbox) return null;
if (group.id === "chat") return <div key={group.id}>{children}</div>;
const fields = RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group.id);
const fields = RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group.id
&& field.path !== "tools.exec.sandbox_launcher" && (!sandbox || field.path !== "tools.exec.sandbox"));
const dirty = fields.filter(state.visible).some(state.dirty);
const title = tr(`groups.${group.id}.title`);
const errorId = `runtime-error-${group.id}`;
const inlineError = fields.some((field) => field.kind === "duration" && state.invalidField === field.path);
const section = (
<section key={group.id} aria-label={title}>
<SettingsSectionTitle>{group.id === "proxy"
{!sandbox ? <SettingsSectionTitle>{group.id === "proxy"
? <SettingsHint description={tr("fields.network_proxy.help")}>{title}</SettingsHint>
: title}</SettingsSectionTitle>
: title}</SettingsSectionTitle> : null}
<form noValidate onSubmit={(event) => { event.preventDefault(); void state.save(group.id); }}
onBlur={(event) => {
if (event.relatedTarget && event.currentTarget.contains(event.relatedTarget)) return;
@@ -298,11 +305,12 @@ export function RuntimeConfigSettings({
onRestart={onRestart} isRestarting={isRestarting} />
</SettingsGroup>
</fieldset>
{state.errors[group.id] && !inlineError ? <p id={errorId} role="alert" className="mt-2 break-words px-1 text-[12px] text-destructive">{state.errors[group.id]}</p> : null}
{state.errors[group.id] && !inlineError && !sandbox ? <p id={errorId} role="alert" className="mt-2 break-words px-1 text-[12px] text-destructive">{state.errors[group.id]}</p> : null}
</form>
</section>
);
return section;
return sandbox ? <SandboxSettings key={group.id} settings={settings} state={state}
client={client!} isRestarting={isRestarting}>{section}</SandboxSettings> : section;
})}
</div>
);
@@ -0,0 +1,123 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { CircleAlert, Loader2, ShieldCheck } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ProviderPicker } from "@/components/settings/shared/ModelControls";
import { SettingsGroup, SettingsRow, SettingsSectionTitle, StatusPill } from "@/components/settings/shared/SettingsControls";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ToggleButton } from "@/components/ui/toggle-button";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { checkSandboxSettings } from "@/lib/api";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { SandboxCheck, SettingsPayload } from "@/lib/types";
import type { RuntimeConfigController } from "./RuntimeConfigSettings";
import { RUNTIME_CONFIG_FIELDS } from "./runtime-config-fields";
export function SandboxSettings({ settings, state, client, isRestarting, children }: {
settings: SettingsPayload;
state: RuntimeConfigController;
client: NanobotClient;
isRestarting: boolean;
children: ReactNode;
}) {
const { t } = useTranslation();
const tx = (key: string) => t(`settings.sandbox.${key}`);
const saved = settings.advanced.exec_sandbox_status!;
const [result, setResult] = useState<SandboxCheck | null>(null);
const [checking, setChecking] = useState(false);
const [checkError, setCheckError] = useState(false);
const [confirmDisable, setConfirmDisable] = useState(false);
const generation = useRef(0);
useEffect(() => {
generation.current += 1;
setResult(null);
setChecking(false);
setCheckError(false);
return () => { generation.current += 1; };
}, [client, saved.revision, saved.state, saved.reason, saved.launcher]);
const field = (path: string) => RUNTIME_CONFIG_FIELDS.find((item) => item.path === path)!;
const enabledField = field("tools.exec.enable");
const sandboxField = field("tools.exec.sandbox");
const launcherField = field("tools.exec.sandbox_launcher");
const enabled = state.value(enabledField.path) !== false;
const backend = String(state.value(sandboxField.path));
const dirty = RUNTIME_CONFIG_FIELDS.some((item) => (item.group === "shell" || item.path === enabledField.path) && state.dirty(item));
const busy = state.saving !== null || isRestarting || checking;
const status = dirty ? "unchecked" : checking ? "checking" : result?.revision === saved.revision ? result.state : saved.state;
const error = state.errors.shell;
const reason = dirty ? "" : result?.revision === saved.revision ? result.reason : saved.reason;
const launcher = result?.revision === saved.revision ? result.launcher : saved.launcher;
const options = [{ name: "none", label: tx("off") }];
if (saved.supported_backend) options.unshift({ name: saved.supported_backend, label: saved.supported_backend === "seatbelt" ? "Seatbelt" : "bwrap" });
if (backend && !options.some((item) => item.name === backend)) options.unshift({ name: backend, label: backend });
const check = async () => {
const id = ++generation.current;
setChecking(true);
setCheckError(false);
try {
const response = await checkSandboxSettings(client);
if (id !== generation.current) return;
if (response.sandbox.revision !== saved.revision) { setCheckError(true); return; }
setResult(response.sandbox);
} catch {
if (id === generation.current) setCheckError(true);
} finally {
if (id === generation.current) setChecking(false);
}
};
return <section aria-label={tx("title")}>
<SettingsSectionTitle>{tx("title")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow title={t("settings.runtimeConfig.fields.tools_exec_enable.label")}>
<ToggleButton checked={enabled} disabled={busy} label={t("settings.runtimeConfig.fields.tools_exec_enable.label")}
onChange={(value) => state.commit(enabledField, value)} />
</SettingsRow>
<SettingsRow title={tx("method")}>
<ProviderPicker providers={options} value={backend || "none"} emptyLabel={tx("off")}
triggerProps={{ id: "runtime-tools.exec.sandbox", "aria-label": t("settings.runtimeConfig.fields.tools_exec_sandbox.label"), disabled: busy || !enabled }}
onChange={(value) => {
if (value === "none" && backend) setConfirmDisable(true);
else state.commit(sandboxField, value === "none" ? "" : value);
}} />
</SettingsRow>
<SettingsRow title={tx("status")}>
<StatusPill tone={status === "passed" ? "success" : status === "unavailable" || status === "unsupported" ? "warning" : "neutral"}>{tx(`states.${status}`)}</StatusPill>
</SettingsRow>
<div className="settings-list-inset pb-4 pt-1" aria-live="polite">
<div className="flex items-start gap-2 text-ui leading-6 text-muted-foreground">
{checking ? <Loader2 className="mt-1 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" aria-hidden />
: status === "passed" ? <ShieldCheck className="mt-1 h-4 w-4 shrink-0" aria-hidden /> : <CircleAlert className="mt-1 h-4 w-4 shrink-0" aria-hidden />}
<p>{reason ? t(`settings.sandbox.reasons.${reason}`, { defaultValue: tx("reasons.unknown") }) : tx(`help.${dirty ? "unsaved" : status}`)}</p>
</div>
{launcher ? <p className="mt-2 break-all font-mono text-caption text-muted-foreground">{launcher}</p> : null}
<p className="mt-2 text-caption leading-5 text-muted-foreground">{tx("scope")}</p>
{saved.supported_backend && enabled && backend ? <Button variant="outline" size="sm" className="mt-3 rounded-full" disabled={busy || dirty} onClick={() => void check()}>{tx(checking ? "checking" : "check")}</Button> : null}
{checkError ? <p role="alert" className="mt-2 text-caption text-destructive">{tx("checkError")}</p> : null}
{error ? <p id="sandbox-settings-error" role="alert" className="mt-2 text-caption text-destructive">{error}</p> : null}
</div>
<SettingsAdvancedOptions>
{saved.supported_backend ? <div className="settings-list-inset pb-4 pt-2">
<label htmlFor="runtime-tools.exec.sandbox_launcher" className="text-control-label">{tx("path")}</label>
<p id="sandbox-launcher-help" className="mb-3 mt-1 text-caption leading-5 text-muted-foreground">{tx("pathHelp")}</p>
<div className="flex flex-wrap items-center gap-2">
<Input id="runtime-tools.exec.sandbox_launcher" className="min-w-0 flex-1 basis-56 text-ui" value={String(state.value(launcherField.path))}
aria-invalid={state.invalidField === launcherField.path || undefined}
aria-describedby={state.invalidField === launcherField.path ? "sandbox-launcher-help sandbox-settings-error" : "sandbox-launcher-help"}
placeholder={tx("automatic")} disabled={busy} onChange={(event) => state.change(launcherField, event.target.value)} />
<Button variant="outline" size="sm" disabled={busy || !state.dirty(launcherField)} onClick={() => void state.save("shell")}>{t("settings.actions.save")}</Button>
</div>
</div> : null}
{children}
</SettingsAdvancedOptions>
</SettingsGroup>
<AlertDialog open={confirmDisable} onOpenChange={setConfirmDisable}>
<AlertDialogContent><AlertDialogHeader><AlertDialogTitle>{tx("disableTitle")}</AlertDialogTitle>
<AlertDialogDescription>{tx("disableHelp")}</AlertDialogDescription></AlertDialogHeader>
<AlertDialogFooter><AlertDialogCancel>{tx("keep")}</AlertDialogCancel><AlertDialogAction onClick={() => state.commit(sandboxField, "")}>{tx("disable")}</AlertDialogAction></AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</section>;
}
@@ -50,6 +50,7 @@ export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [
{ group: "shell", path: "tools.exec.path_prepend", kind: "text" },
{ group: "shell", path: "tools.exec.path_append", kind: "text" },
{ group: "shell", path: "tools.exec.sandbox", kind: "select", options: ["", "bwrap", "seatbelt"] },
{ group: "shell", path: "tools.exec.sandbox_launcher", kind: "text", manual: true },
{ group: "shell", path: "tools.exec.sandbox_ro_binds", kind: "list", when: { path: "tools.exec.sandbox", value: ["bwrap", "seatbelt"] } },
{ group: "shell", path: "tools.exec.sandbox_rw_binds", kind: "list", when: { path: "tools.exec.sandbox", value: ["bwrap", "seatbelt"] } },
{ group: "shell", path: "tools.exec.allowed_env_keys", kind: "list" },
+49
View File
@@ -477,6 +477,55 @@
"password": "Password",
"proxyReferenceAuth": "Set authentication in the referenced proxy URL."
},
"sandbox": {
"title": "Command sandbox",
"method": "Isolation method",
"off": "No isolation",
"status": "Saved configuration",
"check": "Check sandbox",
"checking": "Checking…",
"scope": "Checks the saved launcher with temporary test files only. This is not a full security audit. Restart the gateway to apply saved changes to command execution.",
"path": "Trusted launcher path",
"pathHelp": "Optional absolute path to a launcher from a trusted publisher. The file and its parent directories must be root-owned and not group- or world-writable, and outside writable agent paths. Leave blank for system lookup.",
"automatic": "System lookup",
"checkError": "Could not complete the check. Reopen settings and try again.",
"saveError": "Could not save. Keep your draft and try again.",
"disableTitle": "Turn off command isolation?",
"disableHelp": "Commands will run with the gateway account’s permissions after restart. This does not change file-tool permissions.",
"keep": "Keep isolation",
"disable": "Turn off isolation",
"states": {
"disabled": "Commands disabled",
"off": "Isolation off",
"unsupported": "Not supported",
"unchecked": "Not checked",
"unavailable": "Unavailable",
"passed": "Basic check passed",
"checking": "Checking…"
},
"help": {
"disabled": "Enable commands to use a sandbox.",
"off": "Commands are not isolated. Choose an isolation method to protect the host.",
"unsupported": "This isolation method is not supported on the gateway’s operating system.",
"unchecked": "Run a check to test the saved sandbox configuration.",
"unsaved": "Save changes, then check the sandbox.",
"unavailable": "The sandbox cannot start. Commands will not run in this sandbox.",
"passed": "The launcher started, workspace writes worked, and the external test file was blocked.",
"checking": "Starting a bounded sandbox test…"
},
"reasons": {
"launcher_missing": "Launcher not found. Install it on the gateway or set a trusted absolute path below.",
"path_not_absolute": "Enter an absolute path, not a command name.",
"not_executable": "The path must point to an executable file.",
"agent_writable": "The launcher is in an agent-writable path. Ask the package maintainer for a protected installation.",
"unprotected_installation": "The launcher or a parent directory is writable by a non-root user. Ask the administrator for a protected installation.",
"path_unavailable": "Cannot read this path. Check that it exists on the gateway and is accessible.",
"platform_unsupported": "Choose the isolation method supported by this gateway’s operating system.",
"probe_failed": "The isolation test failed. Check the launcher installation, kernel namespace support and additional mounts.",
"probe_timeout": "The check timed out. Check the launcher installation and host restrictions, then try again.",
"unknown": "The launcher is unavailable. Check its installation and access permissions."
}
},
"runtimeConfig": {
"apiSaved": "Saved. Restart the API service to apply changes.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "Contraseña",
"proxyReferenceAuth": "Configura la autenticación en la URL del proxy referenciada."
},
"sandbox": {
"title": "Sandbox de comandos",
"method": "Método de aislamiento",
"off": "Sin aislamiento",
"status": "Configuración guardada",
"check": "Comprobar sandbox",
"checking": "Comprobando…",
"scope": "Solo prueba el lanzador guardado con archivos temporales. No es una auditoría de seguridad completa. Reinicia la puerta de enlace para aplicar los cambios a los comandos.",
"path": "Ruta del lanzador de confianza",
"pathHelp": "Ruta absoluta opcional de un lanzador de confianza. El archivo y sus directorios padre deben ser de root, sin escritura para grupos u otros usuarios, y estar fuera de las rutas de escritura del agente. Déjala vacía para buscar en el sistema.",
"automatic": "Búsqueda del sistema",
"checkError": "No se pudo completar la prueba. Abre los ajustes de nuevo y reinténtalo.",
"saveError": "No se pudo guardar. El borrador se conserva; vuelve a intentarlo.",
"disableTitle": "¿Desactivar el aislamiento?",
"disableHelp": "Tras reiniciar, los comandos usarán los permisos de la cuenta de la puerta de enlace. No cambia los permisos de las herramientas de archivos.",
"keep": "Mantener aislamiento",
"disable": "Desactivar aislamiento",
"states": {
"disabled": "Comandos desactivados",
"off": "Sin aislamiento",
"unsupported": "No compatible",
"unchecked": "Sin comprobar",
"unavailable": "No disponible",
"passed": "Prueba básica superada",
"checking": "Comprobando…"
},
"help": {
"disabled": "Activa los comandos para usar un sandbox.",
"off": "Los comandos no están aislados. Elige un método para proteger el equipo.",
"unsupported": "El sistema de la puerta de enlace no admite este método.",
"unchecked": "Comprueba la configuración guardada del sandbox.",
"unsaved": "Guarda los cambios y comprueba el sandbox.",
"unavailable": "El sandbox no puede iniciarse. No se ejecutarán comandos en él.",
"passed": "El lanzador arrancó, se pudo escribir en el espacio de trabajo y se bloqueó el archivo externo de prueba.",
"checking": "Ejecutando una prueba con tiempo limitado…"
},
"reasons": {
"launcher_missing": "No se encontró el lanzador. Instálalo en la puerta de enlace o indica una ruta absoluta de confianza.",
"path_not_absolute": "Introduce una ruta absoluta, no un nombre de comando.",
"not_executable": "La ruta debe apuntar a un archivo ejecutable.",
"agent_writable": "El agente puede escribir en esta ruta. Pide una instalación protegida al responsable del paquete.",
"unprotected_installation": "Un usuario distinto de root puede modificar el lanzador o un directorio padre. Pide una instalación protegida al administrador.",
"path_unavailable": "No se puede leer la ruta. Comprueba su existencia y permisos en la puerta de enlace.",
"platform_unsupported": "Elige un método compatible con el sistema de la puerta de enlace.",
"probe_failed": "La prueba falló. Comprueba la instalación, los espacios de nombres del núcleo y los montajes adicionales.",
"probe_timeout": "La prueba agotó el tiempo. Comprueba la instalación y las restricciones del equipo y reinténtalo.",
"unknown": "Lanzador no disponible. Comprueba su instalación y permisos."
}
},
"runtimeConfig": {
"apiSaved": "Guardado. Reinicia el servicio API para aplicar los cambios.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "Mot de passe",
"proxyReferenceAuth": "Configurez l’authentification dans l’URL du proxy référencée."
},
"sandbox": {
"title": "Bac à sable des commandes",
"method": "Mode d’isolation",
"off": "Sans isolation",
"status": "Configuration enregistrée",
"check": "Vérifier le bac à sable",
"checking": "Vérification…",
"scope": "Teste uniquement le lanceur enregistré avec des fichiers temporaires. Ce n’est pas un audit de sécurité complet. Redémarrez la passerelle pour appliquer les changements aux commandes.",
"path": "Chemin du lanceur de confiance",
"pathHelp": "Chemin absolu facultatif d’un lanceur de confiance. Le fichier et ses dossiers parents doivent appartenir à root, sans écriture pour le groupe ou les autres utilisateurs, hors des chemins modifiables par l’agent. Laissez vide pour la recherche système.",
"automatic": "Recherche système",
"checkError": "La vérification a échoué. Rouvrez les paramètres et réessayez.",
"saveError": "Enregistrement impossible. Le brouillon est conservé ; réessayez.",
"disableTitle": "Désactiver l’isolation ?",
"disableHelp": "Après redémarrage, les commandes utiliseront les droits du compte de la passerelle. Les droits des outils de fichiers ne changent pas.",
"keep": "Garder l’isolation",
"disable": "Désactiver l’isolation",
"states": {
"disabled": "Commandes désactivées",
"off": "Sans isolation",
"unsupported": "Non pris en charge",
"unchecked": "Non vérifié",
"unavailable": "Indisponible",
"passed": "Test de base réussi",
"checking": "Vérification…"
},
"help": {
"disabled": "Activez les commandes pour utiliser un bac à sable.",
"off": "Les commandes ne sont pas isolées. Choisissez une méthode pour protéger l’hôte.",
"unsupported": "Le système de la passerelle ne prend pas en charge cette méthode.",
"unchecked": "Lancez la vérification de la configuration enregistrée.",
"unsaved": "Enregistrez les changements, puis lancez la vérification.",
"unavailable": "Le bac à sable ne peut pas démarrer. Aucune commande n’y sera exécutée.",
"passed": "Le lanceur a démarré, l’écriture dans l’espace de travail a réussi et le fichier externe a été bloqué.",
"checking": "Test avec durée limitée en cours…"
},
"reasons": {
"launcher_missing": "Lanceur introuvable. Installez-le sur la passerelle ou indiquez un chemin absolu de confiance.",
"path_not_absolute": "Indiquez un chemin absolu, pas un nom de commande.",
"not_executable": "Le chemin doit désigner un fichier exécutable.",
"agent_writable": "L’agent peut modifier ce chemin. Demandez une installation protégée au responsable du paquet.",
"unprotected_installation": "Un utilisateur autre que root peut modifier le lanceur ou un dossier parent. Demandez une installation protégée à l’administrateur.",
"path_unavailable": "Chemin illisible. Vérifiez sa présence et ses droits sur la passerelle.",
"platform_unsupported": "Choisissez une méthode compatible avec le système de la passerelle.",
"probe_failed": "Le test a échoué. Vérifiez l’installation, les espaces de noms du noyau et les montages supplémentaires.",
"probe_timeout": "Délai dépassé. Vérifiez l’installation et les restrictions de l’hôte, puis réessayez.",
"unknown": "Lanceur indisponible. Vérifiez son installation et ses droits."
}
},
"runtimeConfig": {
"apiSaved": "Enregistré. Redémarrez le service API pour appliquer les modifications.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "Kata sandi",
"proxyReferenceAuth": "Atur autentikasi di URL proxy yang dirujuk."
},
"sandbox": {
"title": "Sandbox perintah",
"method": "Metode isolasi",
"off": "Tanpa isolasi",
"status": "Konfigurasi tersimpan",
"check": "Periksa sandbox",
"checking": "Memeriksa…",
"scope": "Hanya menguji peluncur tersimpan dengan berkas sementara. Ini bukan audit keamanan lengkap. Mulai ulang gateway untuk menerapkan perubahan ke eksekusi perintah.",
"path": "Jalur peluncur tepercaya",
"pathHelp": "Jalur absolut opsional ke peluncur dari penerbit tepercaya. Berkas dan direktori induk harus dimiliki root, tidak dapat ditulis grup/pengguna lain, dan di luar jalur tulis agen. Kosongkan untuk pencarian sistem.",
"automatic": "Pencarian sistem",
"checkError": "Pemeriksaan gagal. Buka ulang pengaturan dan coba lagi.",
"saveError": "Gagal menyimpan. Draf tetap tersimpan; coba lagi.",
"disableTitle": "Nonaktifkan isolasi perintah?",
"disableHelp": "Setelah mulai ulang, perintah berjalan dengan izin akun gateway. Izin alat berkas tidak berubah.",
"keep": "Pertahankan isolasi",
"disable": "Nonaktifkan isolasi",
"states": {
"disabled": "Perintah nonaktif",
"off": "Isolasi nonaktif",
"unsupported": "Tidak didukung",
"unchecked": "Belum diperiksa",
"unavailable": "Tidak tersedia",
"passed": "Uji dasar berhasil",
"checking": "Memeriksa…"
},
"help": {
"disabled": "Aktifkan perintah untuk memakai sandbox.",
"off": "Perintah tidak diisolasi. Pilih metode untuk melindungi host.",
"unsupported": "Sistem operasi gateway tidak mendukung metode ini.",
"unchecked": "Jalankan pemeriksaan konfigurasi sandbox tersimpan.",
"unsaved": "Simpan perubahan, lalu periksa sandbox.",
"unavailable": "Sandbox tidak bisa dimulai. Perintah tidak akan dijalankan di sandbox ini.",
"passed": "Peluncur berjalan, ruang kerja dapat ditulis, dan berkas uji eksternal diblokir.",
"checking": "Menjalankan uji sandbox dengan batas waktu…"
},
"reasons": {
"launcher_missing": "Peluncur tidak ditemukan. Pasang di gateway atau isi jalur absolut tepercaya di bawah.",
"path_not_absolute": "Masukkan jalur absolut, bukan nama perintah.",
"not_executable": "Jalur harus menuju berkas yang dapat dieksekusi.",
"agent_writable": "Agen dapat menulis ke jalur ini. Minta pemasangan terlindungi kepada pengelola paket.",
"unprotected_installation": "Pengguna selain root dapat menulis ke peluncur atau induknya. Minta pemasangan terlindungi kepada administrator.",
"path_unavailable": "Jalur tidak dapat dibaca. Periksa keberadaan dan izinnya di gateway.",
"platform_unsupported": "Pilih metode yang didukung sistem operasi gateway.",
"probe_failed": "Uji isolasi gagal. Periksa pemasangan, namespace kernel, dan mount tambahan.",
"probe_timeout": "Waktu habis. Periksa pemasangan dan pembatasan host, lalu coba lagi.",
"unknown": "Peluncur tidak tersedia. Periksa pemasangan dan izin akses."
}
},
"runtimeConfig": {
"apiSaved": "Tersimpan. Mulai ulang layanan API untuk menerapkan perubahan.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "パスワード",
"proxyReferenceAuth": "参照先のプロキシ URL に認証情報を設定してください。"
},
"sandbox": {
"title": "コマンドサンドボックス",
"method": "隔離方式",
"off": "隔離なし",
"status": "保存済みの設定",
"check": "サンドボックスを確認",
"checking": "確認中…",
"scope": "一時ファイルのみで保存済みのランチャーを確認します。完全なセキュリティ監査ではありません。コマンドに設定を適用するにはゲートウェイを再起動してください。",
"path": "信頼するランチャーのパス",
"pathHelp": "信頼する提供元のランチャーの絶対パス(任意)。ファイルと親ディレクトリは root 所有で、グループや他のユーザーが書き込めず、Agent の書き込み範囲外である必要があります。空欄はシステム検索です。",
"automatic": "システム検索",
"checkError": "確認できませんでした。設定を開き直して再試行してください。",
"saveError": "保存できませんでした。下書きを保持しています。再試行してください。",
"disableTitle": "コマンドの隔離を無効にしますか?",
"disableHelp": "再起動後、コマンドはゲートウェイのアカウント権限で実行されます。ファイルツールの権限は変わりません。",
"keep": "隔離を維持",
"disable": "隔離を無効化",
"states": {
"disabled": "コマンド無効",
"off": "隔離なし",
"unsupported": "未対応",
"unchecked": "未確認",
"unavailable": "利用不可",
"passed": "基本確認に成功",
"checking": "確認中…"
},
"help": {
"disabled": "コマンドを有効にするとサンドボックスを使用できます。",
"off": "コマンドは隔離されていません。ホストを保護する隔離方式を選んでください。",
"unsupported": "ゲートウェイの OS はこの隔離方式に対応していません。",
"unchecked": "確認を実行して保存済みの設定を検証してください。",
"unsaved": "設定を保存してから確認してください。",
"unavailable": "サンドボックスを起動できません。このサンドボックス内ではコマンドを実行しません。",
"passed": "ランチャーの起動、作業領域への書き込み、外部テストファイルの遮断を確認しました。",
"checking": "時間制限付きのサンドボックステストを実行中…"
},
"reasons": {
"launcher_missing": "ランチャーが見つかりません。ゲートウェイにインストールするか、下に信頼する絶対パスを指定してください。",
"path_not_absolute": "コマンド名ではなく絶対パスを入力してください。",
"not_executable": "実行可能なファイルを指定してください。",
"agent_writable": "Agent が書き込める場所です。パッケージ管理者に保護された場所へのインストールを依頼してください。",
"unprotected_installation": "ランチャーまたは親ディレクトリに root 以外が書き込めます。管理者に保護された場所を依頼してください。",
"path_unavailable": "パスを読めません。ゲートウェイ上の存在とアクセス権を確認してください。",
"platform_unsupported": "ゲートウェイの OS に対応した隔離方式を選んでください。",
"probe_failed": "隔離テストに失敗しました。インストール、カーネルの名前空間対応、追加マウントを確認してください。",
"probe_timeout": "確認がタイムアウトしました。インストールとホストの制限を確認して再試行してください。",
"unknown": "ランチャーを利用できません。インストールとアクセス権を確認してください。"
}
},
"runtimeConfig": {
"apiSaved": "保存しました。API サービスを再起動すると反映されます。",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "비밀번호",
"proxyReferenceAuth": "참조된 프록시 URL에서 인증 정보를 설정하세요."
},
"sandbox": {
"title": "명령 샌드박스",
"method": "격리 방식",
"off": "격리 안 함",
"status": "저장된 설정",
"check": "샌드박스 확인",
"checking": "확인 중…",
"scope": "임시 파일만 사용해 저장된 실행기를 확인합니다. 전체 보안 감사가 아닙니다. 명령 실행에 저장된 설정을 적용하려면 게이트웨이를 다시 시작하세요.",
"path": "신뢰할 실행기 경로",
"pathHelp": "신뢰하는 배포자의 실행기 절대 경로(선택 사항). 파일과 상위 폴더는 root 소유여야 하며 그룹·다른 사용자가 쓸 수 없고 Agent 쓰기 범위 밖이어야 합니다. 비워 두면 시스템에서 찾습니다.",
"automatic": "시스템에서 찾기",
"checkError": "확인하지 못했습니다. 설정을 다시 열고 재시도하세요.",
"saveError": "저장하지 못했습니다. 초안을 유지했습니다. 다시 시도하세요.",
"disableTitle": "명령 격리를 끌까요?",
"disableHelp": "다시 시작하면 게이트웨이 계정 권한으로 명령을 실행합니다. 파일 도구 권한은 바뀌지 않습니다.",
"keep": "격리 유지",
"disable": "격리 끄기",
"states": {
"disabled": "명령 비활성화",
"off": "격리 꺼짐",
"unsupported": "지원되지 않음",
"unchecked": "확인 전",
"unavailable": "사용 불가",
"passed": "기본 확인 통과",
"checking": "확인 중…"
},
"help": {
"disabled": "명령을 활성화하면 샌드박스를 사용할 수 있습니다.",
"off": "명령이 격리되지 않습니다. 호스트를 보호할 격리 방식을 선택하세요.",
"unsupported": "게이트웨이 운영체제가 이 격리 방식을 지원하지 않습니다.",
"unchecked": "저장된 샌드박스 설정을 확인하세요.",
"unsaved": "설정을 저장한 뒤 확인하세요.",
"unavailable": "샌드박스를 시작할 수 없습니다. 이 샌드박스에서는 명령을 실행하지 않습니다.",
"passed": "실행기 시작, 작업 영역 쓰기 및 외부 테스트 파일 차단을 확인했습니다.",
"checking": "시간 제한이 있는 샌드박스 테스트 중…"
},
"reasons": {
"launcher_missing": "실행기를 찾지 못했습니다. 게이트웨이에 설치하거나 아래에 신뢰할 절대 경로를 입력하세요.",
"path_not_absolute": "명령 이름이 아닌 절대 경로를 입력하세요.",
"not_executable": "실행 파일을 가리키는 경로여야 합니다.",
"agent_writable": "Agent가 쓸 수 있는 경로입니다. 패키지 관리자에게 보호된 설치 위치를 요청하세요.",
"unprotected_installation": "실행기 또는 상위 폴더에 root 외 사용자가 쓸 수 있습니다. 관리자에게 보호된 설치를 요청하세요.",
"path_unavailable": "경로를 읽을 수 없습니다. 게이트웨이의 파일과 접근 권한을 확인하세요.",
"platform_unsupported": "게이트웨이 운영체제가 지원하는 격리 방식을 선택하세요.",
"probe_failed": "격리 테스트 실패. 설치, 커널 네임스페이스 지원 및 추가 마운트를 확인하세요.",
"probe_timeout": "확인 시간 초과. 설치와 호스트 제한을 확인하고 다시 시도하세요.",
"unknown": "실행기를 사용할 수 없습니다. 설치와 접근 권한을 확인하세요."
}
},
"runtimeConfig": {
"apiSaved": "저장했습니다. API 서비스를 다시 시작하면 적용됩니다.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "Senha",
"proxyReferenceAuth": "Configure a autenticação na URL do proxy referenciada."
},
"sandbox": {
"title": "Sandbox de comandos",
"method": "Método de isolamento",
"off": "Sem isolamento",
"status": "Configuração salva",
"check": "Verificar sandbox",
"checking": "Verificando…",
"scope": "Testa apenas o iniciador salvo com arquivos temporários. Não é uma auditoria completa de segurança. Reinicie o gateway para aplicar as alterações aos comandos.",
"path": "Caminho do iniciador confiável",
"pathHelp": "Caminho absoluto opcional de um iniciador confiável. O arquivo e as pastas superiores devem pertencer ao root, sem escrita por grupos ou outros usuários, fora dos caminhos graváveis pelo agente. Deixe vazio para busca no sistema.",
"automatic": "Busca no sistema",
"checkError": "Não foi possível verificar. Reabra as configurações e tente novamente.",
"saveError": "Não foi possível salvar. O rascunho foi mantido; tente novamente.",
"disableTitle": "Desativar o isolamento?",
"disableHelp": "Após reiniciar, os comandos usarão as permissões da conta do gateway. As permissões das ferramentas de arquivos não mudam.",
"keep": "Manter isolamento",
"disable": "Desativar isolamento",
"states": {
"disabled": "Comandos desativados",
"off": "Isolamento desativado",
"unsupported": "Não compatível",
"unchecked": "Não verificado",
"unavailable": "Indisponível",
"passed": "Teste básico aprovado",
"checking": "Verificando…"
},
"help": {
"disabled": "Ative os comandos para usar um sandbox.",
"off": "Os comandos não estão isolados. Escolha um método para proteger o host.",
"unsupported": "O sistema do gateway não aceita este método.",
"unchecked": "Verifique a configuração salva do sandbox.",
"unsaved": "Salve as alterações e verifique o sandbox.",
"unavailable": "O sandbox não inicia. Os comandos não serão executados nele.",
"passed": "O iniciador abriu, a gravação no espaço de trabalho funcionou e o arquivo externo foi bloqueado.",
"checking": "Executando um teste com limite de tempo…"
},
"reasons": {
"launcher_missing": "Iniciador não encontrado. Instale-o no gateway ou informe um caminho absoluto confiável.",
"path_not_absolute": "Informe um caminho absoluto, não um nome de comando.",
"not_executable": "O caminho deve apontar para um arquivo executável.",
"agent_writable": "O agente pode gravar nesse caminho. Peça uma instalação protegida ao mantenedor do pacote.",
"unprotected_installation": "Um usuário que não é root pode alterar o iniciador ou uma pasta superior. Peça uma instalação protegida ao administrador.",
"path_unavailable": "Não é possível ler o caminho. Verifique sua existência e permissões no gateway.",
"platform_unsupported": "Escolha um método aceito pelo sistema do gateway.",
"probe_failed": "O teste falhou. Verifique a instalação, os namespaces do kernel e as montagens adicionais.",
"probe_timeout": "Tempo esgotado. Verifique a instalação e as restrições do host e tente novamente.",
"unknown": "Iniciador indisponível. Verifique sua instalação e permissões."
}
},
"runtimeConfig": {
"apiSaved": "Salvo. Reinicie o serviço de API para aplicar as alterações.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "Mật khẩu",
"proxyReferenceAuth": "Thiết lập xác thực trong URL proxy được tham chiếu."
},
"sandbox": {
"title": "Sandbox lệnh",
"method": "Cách cô lập",
"off": "Không cô lập",
"status": "Cấu hình đã lưu",
"check": "Kiểm tra sandbox",
"checking": "Đang kiểm tra…",
"scope": "Chỉ kiểm tra trình khởi chạy đã lưu bằng tệp tạm. Đây không phải kiểm toán bảo mật đầy đủ. Khởi động lại gateway để áp dụng thay đổi cho lệnh.",
"path": "Đường dẫn trình khởi chạy tin cậy",
"pathHelp": "Đường dẫn tuyệt đối tùy chọn từ nhà phát hành tin cậy. Tệp và thư mục cha phải thuộc root, không cho nhóm/người khác ghi, và nằm ngoài vùng ghi của Agent. Để trống để tìm trong hệ thống.",
"automatic": "Tìm trong hệ thống",
"checkError": "Chưa kiểm tra được. Mở lại cài đặt và thử lại.",
"saveError": "Không lưu được. Bản nháp được giữ lại; hãy thử lại.",
"disableTitle": "Tắt cô lập lệnh?",
"disableHelp": "Sau khi khởi động lại, lệnh chạy với quyền tài khoản gateway. Quyền của công cụ tệp không thay đổi.",
"keep": "Giữ cô lập",
"disable": "Tắt cô lập",
"states": {
"disabled": "Đã tắt lệnh",
"off": "Không cô lập",
"unsupported": "Không hỗ trợ",
"unchecked": "Chưa kiểm tra",
"unavailable": "Không khả dụng",
"passed": "Đạt kiểm tra cơ bản",
"checking": "Đang kiểm tra…"
},
"help": {
"disabled": "Bật lệnh để dùng sandbox.",
"off": "Lệnh chưa được cô lập. Chọn cách cô lập để bảo vệ máy chủ.",
"unsupported": "Hệ điều hành gateway không hỗ trợ cách này.",
"unchecked": "Chạy kiểm tra cấu hình sandbox đã lưu.",
"unsaved": "Lưu thay đổi rồi kiểm tra sandbox.",
"unavailable": "Không thể khởi chạy sandbox. Lệnh sẽ không chạy trong sandbox này.",
"passed": "Trình khởi chạy hoạt động, vùng làm việc ghi được và tệp thử bên ngoài bị chặn.",
"checking": "Đang chạy kiểm tra sandbox có giới hạn thời gian…"
},
"reasons": {
"launcher_missing": "Không tìm thấy trình khởi chạy. Cài trên gateway hoặc nhập đường dẫn tuyệt đối tin cậy bên dưới.",
"path_not_absolute": "Nhập đường dẫn tuyệt đối, không phải tên lệnh.",
"not_executable": "Đường dẫn phải trỏ đến tệp thực thi.",
"agent_writable": "Agent có thể ghi vào đường dẫn này. Hãy nhờ người duy trì gói cung cấp vị trí cài đặt được bảo vệ.",
"unprotected_installation": "Người dùng không phải root có thể ghi vào trình khởi chạy hoặc thư mục cha. Nhờ quản trị viên cài ở vị trí được bảo vệ.",
"path_unavailable": "Không đọc được đường dẫn. Kiểm tra tệp và quyền truy cập trên gateway.",
"platform_unsupported": "Chọn cách cô lập được hệ điều hành gateway hỗ trợ.",
"probe_failed": "Kiểm tra thất bại. Kiểm tra cài đặt, hỗ trợ namespace của nhân và các mount bổ sung.",
"probe_timeout": "Hết thời gian. Kiểm tra cài đặt và giới hạn máy chủ rồi thử lại.",
"unknown": "Trình khởi chạy không khả dụng. Kiểm tra cài đặt và quyền truy cập."
}
},
"runtimeConfig": {
"apiSaved": "Đã lưu. Khởi động lại dịch vụ API để áp dụng thay đổi.",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "密码",
"proxyReferenceAuth": "请在引用的代理 URL 中设置认证信息。"
},
"sandbox": {
"title": "命令沙箱",
"method": "隔离方式",
"off": "不隔离",
"status": "已保存配置",
"check": "检测沙箱",
"checking": "检测中…",
"scope": "仅使用临时文件检测已保存的启动器,不代表完整安全审计。保存后需重启网关,命令执行才会使用新配置。",
"path": "可信启动器路径",
"pathHelp": "可选,填写可信来源启动器的绝对路径。文件及上级目录须归 root 所有、不可被组或其他用户写入,且不在 Agent 可写范围内。留空则使用系统查找。",
"automatic": "系统自动查找",
"checkError": "检测未完成,请重新打开设置后重试。",
"saveError": "保存失败,草稿已保留,请重试。",
"disableTitle": "关闭命令隔离?",
"disableHelp": "重启后,命令将以网关账号的权限直接运行。此操作不会改变文件工具的权限。",
"keep": "保留隔离",
"disable": "关闭隔离",
"states": {
"disabled": "命令已停用",
"off": "未隔离",
"unsupported": "系统不支持",
"unchecked": "尚未检测",
"unavailable": "不可用",
"passed": "基础检测通过",
"checking": "检测中…"
},
"help": {
"disabled": "启用命令执行后可使用沙箱。",
"off": "命令未隔离,可选择隔离方式保护宿主机。",
"unsupported": "网关所在系统不支持此隔离方式。",
"unchecked": "点击检测沙箱,验证已保存的配置。",
"unsaved": "请先保存配置,再检测沙箱。",
"unavailable": "沙箱无法启动,命令不会在此沙箱中执行。",
"passed": "启动器可运行,工作区可写,外部测试文件访问已被阻止。",
"checking": "正在进行有时间限制的沙箱测试…"
},
"reasons": {
"launcher_missing": "未找到启动器,请在网关安装,或在下方填写可信绝对路径。",
"path_not_absolute": "请填写绝对路径,而不是命令名称。",
"not_executable": "该路径必须指向可执行文件。",
"agent_writable": "启动器位于 Agent 可写范围,请联系安装包维护者提供受保护的安装位置。",
"unprotected_installation": "启动器或上级目录可被非 root 用户写入,请联系管理员调整安装位置。",
"path_unavailable": "无法读取路径,请确认文件在网关上存在且可访问。",
"platform_unsupported": "请选择网关所在系统支持的隔离方式。",
"probe_failed": "隔离测试失败,请检查启动器安装、内核命名空间支持和额外挂载。",
"probe_timeout": "检测超时,请检查启动器安装和宿主机限制后重试。",
"unknown": "启动器不可用,请检查安装和访问权限。"
}
},
"runtimeConfig": {
"apiSaved": "已保存,重启 API 服务后生效。",
"commandRuntime": {
+49
View File
@@ -477,6 +477,55 @@
"password": "密碼",
"proxyReferenceAuth": "請在參照的代理 URL 中設定認證資訊。"
},
"sandbox": {
"title": "命令沙箱",
"method": "隔離方式",
"off": "不隔離",
"status": "已儲存設定",
"check": "檢測沙箱",
"checking": "檢測中…",
"scope": "僅使用暫存檔檢測已儲存的啟動器,不代表完整安全稽核。儲存後須重新啟動閘道,命令執行才會使用新設定。",
"path": "可信啟動器路徑",
"pathHelp": "選填可信來源啟動器的絕對路徑。檔案及上層目錄須由 root 擁有、不可供群組或其他使用者寫入,且不在 Agent 可寫範圍內。留空則使用系統查找。",
"automatic": "系統自動查找",
"checkError": "檢測未完成,請重新開啟設定後再試。",
"saveError": "儲存失敗,草稿已保留,請再試。",
"disableTitle": "關閉命令隔離?",
"disableHelp": "重新啟動後,命令將以閘道帳號的權限直接執行。此操作不會變更檔案工具的權限。",
"keep": "保留隔離",
"disable": "關閉隔離",
"states": {
"disabled": "命令已停用",
"off": "未隔離",
"unsupported": "系統不支援",
"unchecked": "尚未檢測",
"unavailable": "無法使用",
"passed": "基本檢測通過",
"checking": "檢測中…"
},
"help": {
"disabled": "啟用命令執行後可使用沙箱。",
"off": "命令未隔離,可選擇隔離方式保護主機。",
"unsupported": "閘道所在系統不支援此隔離方式。",
"unchecked": "點選檢測沙箱,驗證已儲存的設定。",
"unsaved": "請先儲存設定,再檢測沙箱。",
"unavailable": "沙箱無法啟動,命令不會在此沙箱中執行。",
"passed": "啟動器可執行、工作區可寫入,外部測試檔案存取已被阻止。",
"checking": "正在進行有時間限制的沙箱測試…"
},
"reasons": {
"launcher_missing": "找不到啟動器,請在閘道安裝,或在下方填寫可信絕對路徑。",
"path_not_absolute": "請填寫絕對路徑,而非命令名稱。",
"not_executable": "此路徑必須指向可執行檔。",
"agent_writable": "啟動器位於 Agent 可寫範圍,請聯絡套件維護者提供受保護的安裝位置。",
"unprotected_installation": "啟動器或上層目錄可由非 root 使用者寫入,請聯絡管理員調整安裝位置。",
"path_unavailable": "無法讀取路徑,請確認檔案存在於閘道且可存取。",
"platform_unsupported": "請選擇閘道所在系統支援的隔離方式。",
"probe_failed": "隔離測試失敗,請檢查啟動器安裝、核心命名空間支援及額外掛載。",
"probe_timeout": "檢測逾時,請檢查啟動器安裝和主機限制後再試。",
"unknown": "啟動器無法使用,請檢查安裝及存取權限。"
}
},
"runtimeConfig": {
"apiSaved": "已儲存,重新啟動 API 服務後生效。",
"commandRuntime": {
+6
View File
@@ -1595,6 +1595,12 @@ export async function updateRuntimeConfigSettings(
return mutation<SettingsPayload>(transport, "settings.runtime_config.update", { values });
}
export async function checkSandboxSettings(
transport: WebUIMutationTransport,
): Promise<{ sandbox: import("@/lib/types").SandboxCheck }> {
return mutation(transport, "settings.sandbox.check", {});
}
export function starPromptAction(
transport: WebUIMutationTransport,
action: "claim" | "dismiss",
+9
View File
@@ -720,6 +720,14 @@ export type ProviderOAuthCompletionResult = SettingsPayload | ProviderOAuthPendi
export type RuntimeConfigValue = string | number | boolean | string[] | null;
export interface SandboxCheck {
state: "disabled" | "off" | "unsupported" | "unchecked" | "unavailable" | "passed";
reason: string;
launcher: string | null;
revision: string;
supported_backend: "bwrap" | "seatbelt" | null;
}
export interface SettingsPayload {
runtime_config?: Record<string, RuntimeConfigValue>;
surface?: RuntimeSurface;
@@ -1014,6 +1022,7 @@ export interface SettingsPayload {
exec_enabled: boolean;
exec_max_runtime_limit?: number;
exec_sandbox?: string | null;
exec_sandbox_status?: SandboxCheck;
exec_path_prepend_set: boolean;
exec_path_append_set: boolean;
};
+113
View File
@@ -0,0 +1,113 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { RuntimeConfigSettings, useRuntimeConfigSettings } from "@/components/settings/system/RuntimeConfigSettings";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { SettingsPayload } from "@/lib/types";
import { installSettingsViewTestHooks, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
function payload(): SettingsPayload {
const base = settingsPayload();
return { ...base, runtime_config: {
"tools.exec.enable": true, "tools.exec.sandbox": "bwrap", "tools.exec.sandbox_launcher": "",
"tools.exec.sandbox_ro_binds": [], "tools.exec.sandbox_rw_binds": [],
}, advanced: { ...base.advanced, exec_sandbox_status: {
state: "unavailable", reason: "launcher_missing", launcher: null, revision: "saved-one", supported_backend: "bwrap",
} } };
}
const capability = ["webui.sandbox-settings.v1"];
function open() {
renderSettingsView({ initialSection: "advanced", initialSettings: payload(), webuiCapabilities: capability });
return within(screen.getByRole("region", { name: "Command sandbox" }));
}
describe("Saved sandbox settings", () => {
installSettingsViewTestHooks();
it("checks saved configuration explicitly without changing the isolation policy", async () => {
const sandbox = open();
expect(sandbox.getByText(/Launcher not found/)).toBeVisible();
expect(requestMutationMock).not.toHaveBeenCalled();
requestMutationMock.mockResolvedValue({ sandbox: {
...payload().advanced.exec_sandbox_status, state: "passed", reason: "", launcher: "/usr/bin/bwrap",
} });
fireEvent.click(sandbox.getByRole("button", { name: "Check sandbox" }));
expect(await sandbox.findByText("Basic check passed")).toBeVisible();
expect(requestMutationMock).toHaveBeenCalledWith("settings.sandbox.check", {}, 20_000);
expect(sandbox.getByText(/Restart the gateway/)).toBeVisible();
});
it("retains rejected path drafts and localizes errors", async () => {
const sandbox = open();
fireEvent.click(sandbox.getByRole("button", { name: "Advanced options" }));
const input = sandbox.getByRole("textbox", { name: "Trusted launcher path" });
fireEvent.change(input, { target: { value: "/vol1/@apphome/nanobot/bin/bwrap" } });
expect(sandbox.getByRole("button", { name: "Check sandbox" })).toBeDisabled();
requestMutationMock.mockRejectedValueOnce(new Error("sandbox_launcher_unprotected_installation"));
fireEvent.click(sandbox.getByRole("button", { name: "Save" }));
await waitFor(() => expect(sandbox.getAllByRole("alert")[0]).toHaveTextContent(/protected installation/));
expect(input).toHaveValue("/vol1/@apphome/nanobot/bin/bwrap");
expect(sandbox.queryByText("sandbox_launcher_unprotected_installation")).not.toBeInTheDocument();
});
it("requires confirmation before disabling and cancellation makes no mutation", async () => {
const sandbox = open();
fireEvent.click(sandbox.getByRole("combobox", { name: "Command sandbox" }));
fireEvent.click(screen.getByRole("option", { name: "No isolation" }));
const dialog = await screen.findByRole("alertdialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Keep isolation" }));
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.click(sandbox.getByRole("combobox", { name: "Command sandbox" }));
fireEvent.click(screen.getByRole("option", { name: "No isolation" }));
const saved = payload();
saved.runtime_config!["tools.exec.sandbox"] = "";
saved.advanced.exec_sandbox_status = { ...saved.advanced.exec_sandbox_status!, state: "off", reason: "", revision: "saved-off" };
requestMutationMock.mockResolvedValue(saved);
fireEvent.click(within(await screen.findByRole("alertdialog")).getByRole("button", { name: "Turn off isolation" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.runtime_config.update", { values: { "tools.exec.sandbox": "" } }, 20_000));
});
it("clears a saved override explicitly to restore default lookup", async () => {
const settings = payload();
settings.runtime_config!["tools.exec.sandbox_launcher"] = "/opt/protected/bwrap";
renderSettingsView({ initialSection: "advanced", initialSettings: settings, webuiCapabilities: capability });
const sandbox = within(screen.getByRole("region", { name: "Command sandbox" }));
fireEvent.click(sandbox.getByRole("button", { name: "Advanced options" }));
fireEvent.change(sandbox.getByRole("textbox", { name: "Trusted launcher path" }), { target: { value: "" } });
requestMutationMock.mockResolvedValue(payload());
fireEvent.click(sandbox.getByRole("button", { name: "Save" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.runtime_config.update", { values: { "tools.exec.sandbox_launcher": "" } }, 20_000));
});
it("does not expose new controls without the optional host capability", () => {
renderSettingsView({ initialSection: "advanced", initialSettings: payload() });
expect(screen.queryByRole("button", { name: "Check sandbox" })).not.toBeInTheDocument();
expect(screen.queryByRole("textbox", { name: "Trusted launcher path" })).not.toBeInTheDocument();
expect(screen.getByRole("combobox", { name: "Command sandbox" })).toBeVisible();
});
it("does not offer a probe or custom launcher on an unsupported host", () => {
const settings = payload();
settings.advanced.exec_sandbox_status = { ...settings.advanced.exec_sandbox_status!, state: "unsupported", reason: "platform_unsupported", supported_backend: null };
renderSettingsView({ initialSection: "advanced", initialSettings: settings, webuiCapabilities: capability });
expect(screen.getByText("Not supported")).toBeVisible();
expect(screen.queryByRole("button", { name: "Check sandbox" })).not.toBeInTheDocument();
});
it("ignores a completed probe from the previously selected host", async () => {
let finish!: (response: unknown) => void;
const first = { requestMutation: vi.fn(() => new Promise((resolve) => { finish = resolve; })) } as unknown as NanobotClient;
const next = { requestMutation: vi.fn() } as unknown as NanobotClient;
const settings = payload();
function Harness({ client }: { client: NanobotClient }) {
const state = useRuntimeConfigSettings(settings, client, () => {});
return <RuntimeConfigSettings page="advanced" settings={settings} state={state} client={client} sandboxSupported isRestarting={false} remoteBrowserAccess={false} />;
}
const { rerender } = render(<Harness client={first} />);
fireEvent.click(screen.getByRole("button", { name: "Check sandbox" }));
rerender(<Harness client={next} />);
finish({ sandbox: { ...settings.advanced.exec_sandbox_status, state: "passed", reason: "" } });
await waitFor(() => expect(screen.getByRole("button", { name: "Check sandbox" })).not.toBeDisabled());
expect(screen.queryByText("Basic check passed")).not.toBeInTheDocument();
});
});
+2 -2
View File
@@ -140,7 +140,7 @@ type SettingsViewTestOptions = Partial<Pick<
| "onStartAutomationChat"
| "onNativeEngineRestart"
| "onRestart"
>> & { client?: NanobotClient };
>> & { client?: NanobotClient; webuiCapabilities?: string[] };
export function renderSettingsView(options: SettingsViewTestOptions = {}) {
render(
@@ -151,7 +151,7 @@ export function renderSettingsView(options: SettingsViewTestOptions = {}) {
handler("open");
return () => {};
},
} as never} token="tok">
} as never} token="tok" webuiCapabilities={options.webuiCapabilities}>
<SettingsView
themePreference={options.themePreference ?? "light"}
initialSection={options.initialSection ?? "apps"}