From 17b8921ee3148da2ebc575624268e610bbaaf9b9 Mon Sep 17 00:00:00 2001 From: Willem Jiang Date: Mon, 23 Nov 2026 11:37:35 +0800 Subject: [PATCH] fix(sandbox): separate local file tools from shell execution (#8494) * fix(sandbox): separate local file tools from shell execution Signed-off-by: Willem Jiang * test(sandbox): align the bash help assertion Signed-off-by: Willem Jiang * fix(sandbox): warn about retired local Bash and align guidance --------- Signed-off-by: Willem Jiang --- README.md | 2 +- backend/docs/CONFIGURATION.md | 19 +- .../harness/deerflow/config/sandbox_config.py | 25 ++- .../harness/deerflow/sandbox/AGENTS.md | 7 +- .../sandbox/local/local_sandbox_provider.py | 13 +- .../harness/deerflow/sandbox/security.py | 28 +-- .../harness/deerflow/sandbox/tools.py | 125 +---------- .../deerflow/tools/builtins/task_tool.py | 5 +- .../packages/harness/deerflow/tools/tools.py | 2 +- backend/tests/test_channel_user_id_env.py | 114 ---------- backend/tests/test_config_version.py | 28 +++ backend/tests/test_doctor.py | 8 +- .../test_goal_operation_progress_worker.py | 24 +- .../tests/test_lead_prompt_script_guidance.py | 15 +- backend/tests/test_local_bash_tool_loading.py | 4 +- .../tests/test_local_command_path_spaces.py | 128 ++--------- .../test_local_sandbox_command_timeout.py | 11 +- .../test_sandbox_command_cancellation.py | 23 +- backend/tests/test_sandbox_tools_security.py | 209 +----------------- backend/tests/test_setup_wizard.py | 6 +- .../test_skill_request_scoped_secrets.py | 153 ------------- backend/tests/test_subagent_routing_prompt.py | 2 + backend/tests/test_tool_result_meta.py | 34 +-- config.example.yaml | 14 +- deploy/helm/deer-flow/README.md | 2 +- deploy/helm/deer-flow/values.yaml | 2 +- docs/guide/sandbox.md | 29 +-- docs/guide/skills-and-tools.md | 22 +- .../content/en/application/configuration.mdx | 1 - .../operations-and-troubleshooting.mdx | 2 +- .../content/en/harness/design-principles.mdx | 2 +- frontend/src/content/en/harness/sandbox.mdx | 15 +- frontend/src/content/en/harness/skills.mdx | 7 +- .../content/en/harness/subagents/catalog.mdx | 2 +- .../en/harness/subagents/quick-start.mdx | 2 +- .../en/harness/subagents/reference.mdx | 1 - .../content/en/harness/subagents/sandbox.mdx | 4 +- .../en/harness/subagents/troubleshooting.mdx | 2 +- frontend/src/content/en/harness/tools.mdx | 2 +- .../content/zh/application/configuration.mdx | 1 - frontend/src/content/zh/harness/sandbox.mdx | 15 +- frontend/src/content/zh/harness/skills.mdx | 10 +- .../content/zh/harness/subagents/catalog.mdx | 2 +- .../zh/harness/subagents/quick-start.mdx | 2 +- .../zh/harness/subagents/reference.mdx | 1 - .../content/zh/harness/subagents/sandbox.mdx | 4 +- .../zh/harness/subagents/troubleshooting.mdx | 2 +- frontend/src/content/zh/harness/tools.mdx | 2 +- scripts/doctor.py | 17 +- scripts/setup_wizard.py | 6 +- scripts/wizard/steps/execution.py | 17 +- scripts/wizard/writer.py | 10 +- 52 files changed, 241 insertions(+), 942 deletions(-) diff --git a/README.md b/README.md index 7b045c9232..b780af68e9 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ Each guide is the full reference for its topic. Open the one you need. | Models, providers, `config.yaml`, environment variables | [Configuration](docs/guide/configuration.md) | | DeepSeek web search, thinking mode and citation excerpts | [DeepSeek Web Search](backend/docs/CONFIGURATION.md#deepseek-web-search) | | Docker, local development, upgrades, production deployment | [Running the Application](docs/guide/deployment.md) | -| Sandbox modes, Windows local execution, file system, uploads and outputs | [Sandbox](docs/guide/sandbox.md) | +| Workspace file tools, isolated shell providers, uploads and outputs | [Sandbox](docs/guide/sandbox.md) | | boxd machines, bounded output copies and cleanup retries | [boxd sandbox provider](backend/packages/harness/deerflow/community/boxd_sandbox/README.md) | | Skills, built-in tools, script workflows, Claude Code integration | [Skills & Tools](docs/guide/skills-and-tools.md) | | MCP servers | [MCP Server](docs/guide/mcp.md) | diff --git a/backend/docs/CONFIGURATION.md b/backend/docs/CONFIGURATION.md index 89422e7d10..9b4e05826b 100644 --- a/backend/docs/CONFIGURATION.md +++ b/backend/docs/CONFIGURATION.md @@ -1577,11 +1577,10 @@ externalized to `.tool-results`. To allow larger pages, raise DeerFlow supports multiple sandbox execution modes. Configure your preferred mode in `config.yaml`: -**Local Execution** (runs sandbox code directly on the host machine): +**Local Workspace** (provides workspace file tools): ```yaml sandbox: use: deerflow.sandbox.local:LocalSandboxProvider # Local execution - allow_host_bash: false # default; host bash is disabled unless explicitly re-enabled ``` **Docker Execution** (runs sandbox code in isolated Docker containers): @@ -1890,10 +1889,12 @@ Choose between local execution or Docker-based isolation: ```yaml sandbox: use: deerflow.sandbox.local:LocalSandboxProvider - allow_host_bash: false ``` -`allow_host_bash` is intentionally `false` by default. DeerFlow's local sandbox is a host-side convenience mode, not a secure shell isolation boundary. If you need `bash`, prefer `AioSandboxProvider`. Only set `allow_host_bash: true` for fully trusted single-user local workflows. +The local provider serves workspace file operations. To run shell commands, set +`sandbox.use` to an isolated provider such as `AioSandboxProvider`. Existing +configurations can still contain the deprecated `allow_host_bash` setting. The +local provider ignores it and logs migration guidance when it is set to `true`. When `LocalSandboxProvider` runs under `make up`, it runs inside the `deer-flow-gateway` container. In that mode, `sandbox.mounts[].host_path` is resolved from the gateway container's filesystem, not from your Docker host. If you need a local-sandbox custom mount in production Docker, bind the host directory into the gateway service first, then use the in-container path in `config.yaml`: @@ -2243,11 +2244,9 @@ This field is a discovery and activation allowlist; a listed skill's `allowed-to The same semantics apply to `subagents.agents..skills` and `subagents.custom_agents..skills`: omitted or `null` exposes all enabled skills, `[]` exposes none, and a list limits discovery and activation. A skill's `allowed-tools` declaration never removes baseline tools; it is compatibility metadata for other agent frameworks. -`LocalSandboxProvider` enforces this filesystem view through its managed virtual -path mappings only. Explicit per-Agent skill policies therefore fail closed when -`sandbox.allow_host_bash` is enabled, because host subprocesses can bypass those -mappings. Keep host bash disabled (the default), or use AIO/provisioner/E2B when -shell access and filesystem isolation are both required. +`LocalSandboxProvider` applies this view through the workspace file tools and +managed virtual path mappings. Use AIO, provisioner or E2B for workflows that +also require shell commands. ### Title Generation @@ -2404,7 +2403,7 @@ before exposing an instance to untrusted input. | Mode | `config.yaml` | Host Docker socket | Isolation | |------|---------------|--------------------|-----------| -| `local` (default) | `deerflow.sandbox.local:LocalSandboxProvider` | Not mounted | Commands run **inside the gateway container** on its filesystem. Not a strong boundary — `allow_host_bash` is `false` by default and should stay off for untrusted workloads. | +| `local` (default) | `deerflow.sandbox.local:LocalSandboxProvider` | Not mounted | Workspace file operations use the Gateway filesystem and configured mounts. | | `aio` (pure DooD) | `deerflow.community.aio_sandbox:AioSandboxProvider` (no `provisioner_url`) | **Mounted** (opt-in overlay) | Sandbox containers are started via the host Docker daemon. | | `provisioner` (Kubernetes) | `AioSandboxProvider` + `provisioner_url` | Not mounted | Sandbox pods are created through the provisioner's K8s API over HTTP. Strongest isolation. | diff --git a/backend/packages/harness/deerflow/config/sandbox_config.py b/backend/packages/harness/deerflow/config/sandbox_config.py index d68b55cebd..ab65a1400d 100644 --- a/backend/packages/harness/deerflow/config/sandbox_config.py +++ b/backend/packages/harness/deerflow/config/sandbox_config.py @@ -1,4 +1,5 @@ import ipaddress +import logging import math import re from typing import Literal @@ -8,6 +9,8 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validat from deerflow.config._boolean_guards import reject_boolean +logger = logging.getLogger(__name__) + SandboxOwnershipType = Literal["memory", "redis"] SandboxOverflowPolicy = Literal["wait", "reject", "burst"] SandboxNetworkMode = Literal["open", "isolated", "allowlist"] @@ -19,6 +22,11 @@ SandboxNetworkApproval = Literal["deny", "prompt"] _REDIS_MAX_SAFE_TTL_MILLISECONDS = (2**63 - 1) // 2 +def is_local_sandbox_use(use: str) -> bool: + """Identify the built-in local provider by its configured class path.""" + return use.endswith(":LocalSandboxProvider") and "deerflow.sandbox.local" in use + + def normalize_container_path(value: str) -> str: """Strip trailing slashes from a container mount/virtual path. @@ -237,8 +245,6 @@ class SandboxConfig(BaseModel): Common options: use: Class path of the sandbox provider (required) - allow_host_bash: Enable host-side bash execution for LocalSandboxProvider. - Dangerous and intended only for fully trusted local workflows. AioSandboxProvider, BoxliteProvider, E2BSandboxProvider, OpenSandboxProvider, and LocalSandboxProvider shared options: @@ -249,9 +255,7 @@ class SandboxConfig(BaseModel): idle_timeout: Idle timeout in seconds before released warm sandboxes/VMs are stopped (default: 600 = 10 minutes). Set to 0 to disable. environment: Environment variables to inject into the sandbox (values starting with $ are resolved from host env when config is loaded; providers use them verbatim). Injected - entries bypass the env-policy scrubber as operator-authorized values; - LocalSandboxProvider masks injected credentials from bash tool output and command - errors while preserving benign configuration values. + entries bypass the env-policy scrubber as operator-authorized values. BoxliteProvider specific options: health_check_skip_seconds: Optional reclaim-time skip window in seconds for recently released warm VMs. Default behavior is 0.0 = always validate before reuse. @@ -293,8 +297,17 @@ class SandboxConfig(BaseModel): ) allow_host_bash: bool = Field( default=False, - description="Allow the bash tool to execute directly on the host when using LocalSandboxProvider. Dangerous; intended only for fully trusted local environments.", + deprecated=True, + description="Legacy setting accepted for compatibility. Bash requires an isolated sandbox provider.", ) + + @field_validator("allow_host_bash") + @classmethod + def _warn_legacy_host_bash(cls, value: bool, info: ValidationInfo) -> bool: + if value and is_local_sandbox_use(info.data.get("use", "")): + logger.warning("LocalSandboxProvider ignores deprecated sandbox.allow_host_bash. To run Bash commands, select an isolated sandbox provider such as AioSandboxProvider via sandbox.use and remove sandbox.allow_host_bash.") + return value + prewarm: bool = Field( default=False, description=("Start an AioSandboxProvider acquire in parallel with the first model call when the user input contains a strong sandbox-use signal. Disabled by default; ignored by other sandbox providers."), diff --git a/backend/packages/harness/deerflow/sandbox/AGENTS.md b/backend/packages/harness/deerflow/sandbox/AGENTS.md index 587b6d62cf..04fc1a7415 100644 --- a/backend/packages/harness/deerflow/sandbox/AGENTS.md +++ b/backend/packages/harness/deerflow/sandbox/AGENTS.md @@ -70,11 +70,12 @@ Windows. The portable string assertions do not replace it. ## Tools +- Agent shell commands require a separate execution provider. The local provider + serves workspace file operations. - Tool execution depends on operational arguments only. The `description` argument is a progress label and may be empty. -- Pass the local `cmd.exe` workspace as the subprocess working directory. For - PowerShell, share the single-quote escaping rule with path mapping and stop - execution if `Set-Location` fails. +- Preserve subprocess working directory handling for direct `LocalSandbox` + calls that use the `cmd.exe` fallback. - Local writes publish a new file revision atomically and keep symlink targets and file metadata. Check write access without truncating the file. - Line endings are data. Full reads return the stored endings, and `str_replace` diff --git a/backend/packages/harness/deerflow/sandbox/local/local_sandbox_provider.py b/backend/packages/harness/deerflow/sandbox/local/local_sandbox_provider.py index 1365dc88bb..1e43d7428b 100644 --- a/backend/packages/harness/deerflow/sandbox/local/local_sandbox_provider.py +++ b/backend/packages/harness/deerflow/sandbox/local/local_sandbox_provider.py @@ -63,11 +63,9 @@ class LocalSandboxProvider(SandboxProvider): sandbox (losing only its ``_agent_written_paths`` reverse-resolve hint, which gracefully degrades read_file output). - The managed ``/mnt/skills`` projection is a logical boundary, not a host - filesystem security boundary. When host bash is enabled, a subprocess can - address canonical host paths without going through ``PathMapping``. The - provider therefore advertises Agent skill isolation only while host bash - remains disabled. + Agents access the managed ``/mnt/skills`` projection through the virtual + file tools. The provider advertises the managed view only for local + workspace configurations. """ uses_thread_data_mounts = True @@ -490,9 +488,8 @@ class LocalSandboxProvider(SandboxProvider): # # A thread view exists only to enforce an Agent skill allowlist, and # SandboxMiddleware keeps it fresh only while this provider can enforce - # one. With host bash allowed it skips the view (restricted runs are - # rejected), so mounting a leftover view would pin the last restricted - # Agent's allowlist; use the shared projection instead. + # one. Use the shared projection if support cannot be established to + # avoid pinning a stale restricted view. skill_projection = self._ensure_skills_projection( effective_user_id, thread_id=thread_id if self.supports_agent_skill_isolation else None, diff --git a/backend/packages/harness/deerflow/sandbox/security.py b/backend/packages/harness/deerflow/sandbox/security.py index 478016ad18..e41d35f999 100644 --- a/backend/packages/harness/deerflow/sandbox/security.py +++ b/backend/packages/harness/deerflow/sandbox/security.py @@ -1,23 +1,11 @@ """Security helpers for sandbox capability gating.""" from deerflow.config import get_app_config +from deerflow.config.sandbox_config import is_local_sandbox_use -_LOCAL_SANDBOX_PROVIDER_MARKERS = ( - "deerflow.sandbox.local:LocalSandboxProvider", - "deerflow.sandbox.local.local_sandbox_provider:LocalSandboxProvider", -) +LOCAL_HOST_BASH_DISABLED_MESSAGE = "Host bash execution is disabled for LocalSandboxProvider. Select an isolated sandbox provider to use bash." -LOCAL_HOST_BASH_DISABLED_MESSAGE = ( - "Host bash execution is disabled for LocalSandboxProvider because it is not a secure " - "sandbox boundary. Switch to AioSandboxProvider for isolated bash access, or set " - "sandbox.allow_host_bash: true only in a fully trusted local environment." -) - -LOCAL_BASH_SUBAGENT_DISABLED_MESSAGE = ( - "Bash subagent is disabled for LocalSandboxProvider because host bash execution is not " - "a secure sandbox boundary. Switch to AioSandboxProvider for isolated bash access, or " - "set sandbox.allow_host_bash: true only in a fully trusted local environment." -) +LOCAL_BASH_SUBAGENT_DISABLED_MESSAGE = "Bash subagent is disabled for LocalSandboxProvider. Select an isolated sandbox provider to use the bash subagent." def uses_local_sandbox_provider(config=None) -> bool: @@ -27,19 +15,15 @@ def uses_local_sandbox_provider(config=None) -> bool: sandbox_cfg = getattr(config, "sandbox", None) sandbox_use = getattr(sandbox_cfg, "use", "") - if sandbox_use in _LOCAL_SANDBOX_PROVIDER_MARKERS: - return True - return sandbox_use.endswith(":LocalSandboxProvider") and "deerflow.sandbox.local" in sandbox_use + return is_local_sandbox_use(sandbox_use) def is_host_bash_allowed(config=None) -> bool: - """Return whether host bash execution is explicitly allowed.""" + """Return whether the configured provider makes bash available to agents.""" if config is None: config = get_app_config() sandbox_cfg = getattr(config, "sandbox", None) if sandbox_cfg is None: return False - if not uses_local_sandbox_provider(config): - return True - return bool(getattr(sandbox_cfg, "allow_host_bash", False)) + return not uses_local_sandbox_provider(config) diff --git a/backend/packages/harness/deerflow/sandbox/tools.py b/backend/packages/harness/deerflow/sandbox/tools.py index 35017ec76c..fb376f1f56 100644 --- a/backend/packages/harness/deerflow/sandbox/tools.py +++ b/backend/packages/harness/deerflow/sandbox/tools.py @@ -29,7 +29,6 @@ from deerflow.constants import DEFAULT_SKILLS_CONTAINER_PATH, WRITE_ELISION_PLAC from deerflow.runtime.secret_context import read_active_secrets from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.sandbox.command_scope import command_owner -from deerflow.sandbox.env_policy import is_blocked_env_name from deerflow.sandbox.exceptions import ( SandboxAuthorizationError, SandboxError, @@ -45,7 +44,7 @@ from deerflow.sandbox.lease import ( sandbox_command_scope, sandbox_lease_owner, ) -from deerflow.sandbox.local.local_sandbox import LocalSandbox, escape_powershell_path, escape_powershell_single_quoted +from deerflow.sandbox.local.local_sandbox import LocalSandbox, escape_powershell_path from deerflow.sandbox.overwrite import unwrap_sandbox from deerflow.sandbox.path_patterns import PATH_START_BOUNDARY, build_output_mask_pattern, normalize_mask_tail, replace_output_path_matches from deerflow.sandbox.prewarm import claim_sandbox_prewarm @@ -62,7 +61,7 @@ from deerflow.sandbox.read_file_contract import ( from deerflow.sandbox.sandbox import CommandOutput, Sandbox from deerflow.sandbox.sandbox_provider import SandboxProvider, get_sandbox_provider from deerflow.sandbox.search import GrepMatch -from deerflow.sandbox.security import LOCAL_HOST_BASH_DISABLED_MESSAGE, is_host_bash_allowed +from deerflow.sandbox.security import LOCAL_HOST_BASH_DISABLED_MESSAGE from deerflow.tools.types import Runtime from deerflow.utils.file_io import await_drained from deerflow.utils.host_paths import windows_incompatible_segment @@ -1885,9 +1884,8 @@ def _is_expression_division_after_closer(command: str, start: int, spans: list[t def validate_local_bash_command_paths(command: str, thread_data: ThreadDataState | None) -> None: """Validate absolute paths in local-sandbox bash commands. - This validation is only a best-effort guard for the explicit - ``sandbox.allow_host_bash: true`` opt-in. It is not a secure sandbox - boundary and must not be treated as isolation from the host filesystem. + This compatibility helper checks literal paths in trusted local commands. + Agent shell commands are handled by a separate sandbox provider. In local mode, commands must use virtual paths under /mnt/user-data for user data access. Skills paths under /mnt/skills, ACP workspace paths @@ -2050,47 +2048,6 @@ def replace_virtual_paths_in_command(command: str, thread_data: ThreadDataState return result -def _apply_cwd_prefix(command: str, thread_data: ThreadDataState | None, *, shell: str | None = None) -> str: - """Anchor relative paths to the thread workspace with a shell-appropriate prefix. - - The syntax has to follow the shell that will actually run the command, not - the POSIX one this used to assume unconditionally. ``LocalSandbox._get_shell`` - falls back to ``powershell.exe`` and then ``cmd.exe`` on Windows, and a - ``cd '' && ...`` prefix is unparseable in both: Windows PowerShell - before 7 rejects ``&&`` ("not a valid statement separator in this version", - surfaced as ``InvalidEndOfLine``), and cmd.exe does not strip single quotes, - so it looks for a directory literally named ``''``. Either way every - ``bash`` call fails before the command runs. - - Each form keeps the fail-closed behaviour of ``&&``: the PowerShell variant - uses ``-ErrorAction Stop`` because ``Set-Location`` otherwise reports a - missing workspace as a non-terminating error and lets the command run from - the inherited working directory. - - Args: - command: The bash command to execute. - thread_data: The thread data containing the workspace path. - shell: The shell executable that will run the command. Defaults to the - one ``LocalSandbox`` resolves. - - Returns: - The command prefixed with a cwd change if workspace_path is available, - otherwise the original command unchanged. - """ - if not (thread_data and (workspace := thread_data.get("workspace_path"))): - return command - resolved_shell = shell or LocalSandbox._get_shell() - if LocalSandbox._is_powershell(resolved_shell): - # ``-ErrorAction Stop`` keeps the stop-on-failure semantics ``&&`` gives - # the POSIX form: ``Set-Location`` reports a missing directory as a - # non-terminating error, which would let the ``;``-separated command run - # from the gateway's inherited cwd. - return f"Set-Location -LiteralPath '{escape_powershell_single_quoted(workspace)}' -ErrorAction Stop; {command}" - if LocalSandbox._is_cmd_shell(resolved_shell): - return f'cd /d "{workspace}" && {command}' - return f"cd {shlex.quote(workspace)} && {command}" - - def get_thread_data(runtime: Runtime | None) -> ThreadDataState | None: """Extract thread_data from runtime state.""" if runtime is None: @@ -2805,10 +2762,6 @@ USER_ID_ENV = "DEERFLOW_USER_ID" _USER_ID_MAX_LEN = 256 -def _is_windows() -> bool: - return os.name == "nt" - - def _channel_identity_prefix(runtime: Runtime) -> str | None: """Build the command prefix that sets or clears the channel-user-id env var. @@ -2879,8 +2832,7 @@ def _user_identity_prefix(runtime: Runtime) -> str: is a convenience for skill scripts — exactly like ``DEERFLOW_CHANNEL_USER_ID`` — not a credential and not proof of who is acting. Any bash command can overwrite its own environment, and anything the - command sources or launches (a dependency, a sourced rc file on the - host-bash path) can silently re-export a different id before a skill's + command sources or launches (such as a dependency or shell startup file) can silently re-export a different id before a skill's scoping logic reads it; only the outer prefix on the *next* ``bash_tool`` call re-asserts the true value. Skills that need user-scoped *authorization* must resolve the identity server-side via ``resolve_runtime_user_id`` rather @@ -2921,18 +2873,12 @@ def _lark_cli_env_from_runtime(runtime: Runtime, command: str, *, sandbox_paths: @tool("bash", parse_docstring=True) def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | ToolMessage: - """Execute a bash command in the configured execution environment. + """Execute a bash command in the configured isolated sandbox. - Use `python` to run Python code. - Prefer a thread-local virtual environment in `/mnt/user-data/workspace/.venv`. - Use `python -m pip` (inside the virtual environment) to install Python packages. - - When running against the local host via host bash, inspect the current environment instead of - guessing. For OS detection, start with `uname -s`; on Darwin follow with `sw_vers`. On Linux, - start with `uname -a` and read host system files such as `/etc/os-release` only when the active - sandbox policy permits it. - - If local host bash rejects a path, do not repeat the rejected command. For environment questions, - retry with command-only probes; otherwise use allowed virtual paths or explain the restriction. - To start a long-lived process such as a web server, ALWAYS run it in the background with its output redirected, e.g. `your-command > /mnt/user-data/workspace/server.log 2>&1 &`, then check the log file or poll the port. A long-lived process run in the foreground blocks the turn until @@ -2945,69 +2891,16 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | To redaction_env = None try: sandbox = ensure_sandbox_initialized(runtime) + if isinstance(sandbox, LocalSandbox) or is_local_sandbox(runtime): + return f"Error: {LOCAL_HOST_BASH_DISABLED_MESSAGE}" # Only the active skill's explicitly resolved secrets belong here. injected_env = read_active_secrets(getattr(runtime, "context", None)) or None identity_prefix = _channel_identity_prefix(runtime) user_prefix = _user_identity_prefix(runtime) - lark_cli_env = _lark_cli_env_from_runtime(runtime, command, sandbox_paths=not is_local_sandbox(runtime), sandbox=sandbox) + lark_cli_env = _lark_cli_env_from_runtime(runtime, command, sandbox_paths=True, sandbox=sandbox) if lark_cli_env: injected_env = {**(injected_env or {}), **lark_cli_env} redaction_env = injected_env - if is_local_sandbox(runtime): - # Match the credential-name policy used for inherited host env. - # Keep benign operator settings readable and redact effective - # credentials before execution, including any exception output. - redaction_env = {name: value for name, value in (getattr(sandbox, "environment", None) or {}).items() if is_blocked_env_name(name)} - redaction_env.update(injected_env or {}) - if not is_host_bash_allowed(): - return f"Error: {LOCAL_HOST_BASH_DISABLED_MESSAGE}" - ensure_thread_directories_exist(runtime) - thread_data = get_thread_data(runtime) - validate_local_bash_command_paths(command, thread_data) - command = replace_virtual_paths_in_command(command, thread_data) - workspace = thread_data.get("workspace_path") if thread_data else None - cwd = None - if workspace and _is_windows() and isinstance(sandbox, LocalSandbox) and sandbox._is_cmd_shell(sandbox._get_shell()): - cwd = workspace - else: - command = _apply_cwd_prefix(command, thread_data) - # POSIX-only: the Windows local sandbox may execute via - # PowerShell/cmd.exe where `export` is not valid syntax, so the id - # is published through the subprocess environment instead — - # LocalSandbox layers `env` into the per-process environment, and - # unlike AioSandbox it has no persistent shell session that could - # carry a stale value forward. Deliberately kept out of - # `injected_env`, which doubles as the secret-redaction set: an - # identifier is not a secret and must stay readable in output. - local_env = injected_env - if not _is_windows(): - command = user_prefix + (identity_prefix or "") + command - else: - windows_user_id = _resolved_user_id(runtime) - if windows_user_id is not None: - local_env = {**(injected_env or {}), USER_ID_ENV: windows_user_id} - try: - from deerflow.config.app_config import get_app_config - - sandbox_cfg = get_app_config().sandbox - max_chars = sandbox_cfg.bash_output_max_chars if sandbox_cfg else 20000 - command_timeout = sandbox_cfg.bash_command_timeout if sandbox_cfg else None - except Exception: - max_chars = 20000 - command_timeout = None - output = _execute_bash_command( - sandbox, - command, - runtime=runtime, - env=local_env, - timeout=command_timeout, - cwd=cwd, - ) - content = _truncate_bash_output( - mask_secret_values(mask_local_paths_in_output(output, thread_data), redaction_env), - max_chars, - ) - return _bash_command_result(runtime, output, content) ensure_thread_directories_exist(runtime) command = f"cd {VIRTUAL_PATH_PREFIX}/workspace; {command}" command = user_prefix + (identity_prefix or "") + command diff --git a/backend/packages/harness/deerflow/tools/builtins/task_tool.py b/backend/packages/harness/deerflow/tools/builtins/task_tool.py index 92ef9aab7b..221b41564e 100644 --- a/backend/packages/harness/deerflow/tools/builtins/task_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/task_tool.py @@ -872,9 +872,8 @@ async def task_tool( when the assignment has clear specialist or context-isolation benefit, or is one of several independent, non-overlapping tasks that can actually run in parallel. - - **bash**: Command execution specialist for running bash commands. This is only - available when host bash is explicitly allowed or when using an isolated shell - sandbox such as `AioSandboxProvider`. Use it only for a bounded shell workflow + - **bash**: Command execution specialist that requires an isolated sandbox provider + such as `AioSandboxProvider`. Use it only for a bounded shell workflow with clear context-isolation or independent-parallel benefit. Routine git, build, test, or deploy operations are not sufficient reason to delegate. diff --git a/backend/packages/harness/deerflow/tools/tools.py b/backend/packages/harness/deerflow/tools/tools.py index 2878861360..b423bd58f6 100644 --- a/backend/packages/harness/deerflow/tools/tools.py +++ b/backend/packages/harness/deerflow/tools/tools.py @@ -136,7 +136,7 @@ def _select_tool_configs(config: AppConfig, groups: list[str] | None, include_co # whether the group is exposed at all. if not knowledge_enabled and tool.group == "knowledge": continue - # Do not expose host bash by default when LocalSandboxProvider is active. + # LocalSandboxProvider exposes workspace file tools only. if not host_bash_allowed and _is_host_bash_tool(tool): continue selected.append(tool) diff --git a/backend/tests/test_channel_user_id_env.py b/backend/tests/test_channel_user_id_env.py index 765556f8b3..456bc68b03 100644 --- a/backend/tests/test_channel_user_id_env.py +++ b/backend/tests/test_channel_user_id_env.py @@ -194,43 +194,6 @@ class TestBashToolChannelIdentityPrefix: assert b.calls[0]["command"] == f"{_USER_PREFIX}unset {CHANNEL_USER_ID_ENV}; cd /mnt/user-data/workspace; echo hi" assert b.calls[0]["env"] is None - def test_windows_local_sandbox_skips_prefix(self, monkeypatch): - """On Windows the local sandbox may execute via PowerShell/cmd.exe where - POSIX ``export`` is not valid syntax — skip injection rather than break - every IM-channel command.""" - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"channel_user_id": "ou_1", "thread_id": "t1", "user_id": _USER_ID}, - ) - sandbox = _CapturingSandbox() - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: True) - - bash_tool.func(runtime=runtime, description="test", command="echo hi") - - assert len(sandbox.calls) == 1 - assert "export" not in sandbox.calls[0]["command"] - - def test_posix_local_sandbox_gets_prefix(self, monkeypatch): - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"channel_user_id": "ou_1", "thread_id": "t1", "user_id": _USER_ID}, - ) - sandbox = _CapturingSandbox() - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: False) - - bash_tool.func(runtime=runtime, description="test", command="echo hi") - - assert len(sandbox.calls) == 1 - command = sandbox.calls[0]["command"] - assert command.startswith(f"{_USER_PREFIX}export {CHANNEL_USER_ID_ENV}=ou_1; ") - assert command.endswith("echo hi") - class TestBashToolUserIdentityPrefix: """#3919 — the authenticated user id is published to every bash command.""" @@ -298,80 +261,3 @@ class TestBashToolUserIdentityPrefix: assert call["env"] == {"ERP_TOKEN": "secret-value"} assert call["command"] == f"{_USER_PREFIX}export {CHANNEL_USER_ID_ENV}=ou_1; cd /mnt/user-data/workspace; echo hi" assert "secret-value" not in call["command"] - - def test_posix_local_sandbox_gets_user_prefix(self, monkeypatch): - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"thread_id": "t1", "user_id": _USER_ID}, - ) - sandbox = _CapturingSandbox() - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: False) - - bash_tool.func(runtime=runtime, description="test", command="echo hi") - - assert len(sandbox.calls) == 1 - assert sandbox.calls[0]["command"].startswith(_USER_PREFIX) - - def test_windows_local_sandbox_publishes_user_id_via_env(self, monkeypatch): - """POSIX ``export`` is invalid under the Windows local sandbox, so the id - moves to the ``env`` channel there rather than being dropped: the - contract is that every bash command can see the user id.""" - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"thread_id": "t1", "user_id": _USER_ID}, - ) - sandbox = _CapturingSandbox() - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: True) - - bash_tool.func(runtime=runtime, description="test", command="echo hi") - - assert len(sandbox.calls) == 1 - call = sandbox.calls[0] - assert USER_ID_ENV not in call["command"] - assert "export" not in call["command"] - assert call["env"] == {USER_ID_ENV: _USER_ID} - - def test_windows_env_channel_keeps_secrets_and_user_id_separate(self, monkeypatch): - """Secrets stay in ``env`` for redaction; the id rides alongside them - without entering the redaction set, so echoing it stays readable.""" - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={ - "thread_id": "t1", - "user_id": _USER_ID, - "__active_skill_secrets": {"ERP_TOKEN": "secret-value"}, - }, - ) - sandbox = _CapturingSandbox() - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: True) - - bash_tool.func(runtime=runtime, description="test", command="echo hi") - - assert sandbox.calls[0]["env"] == {"ERP_TOKEN": "secret-value", USER_ID_ENV: _USER_ID} - - def test_windows_local_sandbox_omits_unusable_user_id(self, monkeypatch): - """A corrupt id is dropped rather than published — there is no portable - way to clear a variable across PowerShell/cmd/MSYS, so the env channel - carries nothing instead of carrying garbage.""" - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"thread_id": "t1", "user_id": "x" * 5000}, - ) - sandbox = _CapturingSandbox() - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: True) - - bash_tool.func(runtime=runtime, description="test", command="echo hi") - - assert sandbox.calls[0]["env"] is None diff --git a/backend/tests/test_config_version.py b/backend/tests/test_config_version.py index dde03bcd23..1ba708b5b4 100644 --- a/backend/tests/test_config_version.py +++ b/backend/tests/test_config_version.py @@ -477,6 +477,34 @@ def _merge_missing(target: dict, source: dict) -> None: _merge_missing(target[key], value) +@pytest.mark.parametrize( + ("provider", "legacy_opt_in", "warns"), + [ + ("deerflow.sandbox.local:LocalSandboxProvider", True, True), + ("deerflow.sandbox.local.local_sandbox_provider:LocalSandboxProvider", "$ENABLE_LEGACY_BASH", True), + ("deerflow.sandbox.local:LocalSandboxProvider", False, False), + ("deerflow.community.aio_sandbox:AioSandboxProvider", True, False), + ], +) +def test_load_config_warns_only_for_legacy_local_bash(tmp_path, monkeypatch, caplog, provider, legacy_opt_in, warns): + monkeypatch.setenv("ENABLE_LEGACY_BASH", "true") + extensions_path = tmp_path / "extensions_config.json" + extensions_path.write_text("{}", encoding="utf-8") + monkeypatch.setenv("DEER_FLOW_EXTENSIONS_CONFIG_PATH", str(extensions_path)) + config_path = _make_config_files( + tmp_path, + {"config_version": 67, "sandbox": {"use": provider, "allow_host_bash": legacy_opt_in}}, + _load_repo_example(), + ) + + config = AppConfig.from_file(str(config_path)) + + assert config.sandbox.use == provider + assert ("allow_host_bash" in caplog.text) is warns + assert ("isolated sandbox provider" in caplog.text) is warns + assert "outdated" in caplog.text + + def test_security_fail_closed_bumped_config_version(): """The example must ship security_fail_closed under a version > 26 so v26 configs upgrade.""" example = _load_repo_example() diff --git a/backend/tests/test_doctor.py b/backend/tests/test_doctor.py index 71ceb90704..d33af88c78 100644 --- a/backend/tests/test_doctor.py +++ b/backend/tests/test_doctor.py @@ -1348,11 +1348,13 @@ class TestCheckSandbox: assert results[0].status == "ok" assert results[0].detail == "Local sandbox" - def test_local_sandbox_with_disabled_host_bash_warns(self, tmp_path): + @pytest.mark.parametrize("legacy_setting", ["false", "true"]) + def test_local_sandbox_with_bash_tool_points_to_isolated_provider(self, tmp_path, legacy_setting): cfg = tmp_path / "config.yaml" - cfg.write_text("config_version: 5\nsandbox:\n use: deerflow.sandbox.local:LocalSandboxProvider\n allow_host_bash: false\ntools:\n - name: bash\n use: deerflow.sandbox.tools:bash_tool\n") + cfg.write_text(f"config_version: 5\nsandbox:\n use: deerflow.sandbox.local:LocalSandboxProvider\n allow_host_bash: {legacy_setting}\ntools:\n - name: bash\n use: deerflow.sandbox.tools:bash_tool\n", encoding="utf-8") results = doctor.check_sandbox(cfg) - assert any(result.status == "warn" for result in results) + [warning] = [result for result in results if result.status == "warn"] + assert "isolated sandbox provider" in warning.fix def test_container_sandbox_without_runtime_warns(self, tmp_path, monkeypatch): cfg = tmp_path / "config.yaml" diff --git a/backend/tests/test_goal_operation_progress_worker.py b/backend/tests/test_goal_operation_progress_worker.py index c7de583618..5fc359e974 100644 --- a/backend/tests/test_goal_operation_progress_worker.py +++ b/backend/tests/test_goal_operation_progress_worker.py @@ -6,7 +6,6 @@ progress counting, and all existing worker guards execute production code. from __future__ import annotations -import os import socket from types import SimpleNamespace @@ -34,6 +33,7 @@ from deerflow.runtime.goal import ( ) from deerflow.runtime.runs import worker from deerflow.sandbox.local.local_sandbox import LocalSandbox, PathMapping +from deerflow.sandbox.sandbox import CommandOutput from deerflow.sandbox.tools import bash_tool, read_file_tool, write_file_tool @@ -296,16 +296,18 @@ def _native_tool_graph(tmp_path, monkeypatch, *, receipts): (tmp_path / "workspace").mkdir() (tmp_path / "workspace/input.txt").write_text("Stable input contents.\n", encoding="utf-8") sandbox = LocalSandbox("local", path_mappings=[PathMapping("/mnt/user-data/workspace", str(tmp_path / "workspace"))]) - monkeypatch.setattr("deerflow.sandbox.local.local_sandbox.build_sandbox_env", lambda _injected: {"PATH": os.defpath}) - # Bind only execution policy and the test-owned sandbox; tools, their real - # results, normalization, receipt stamping and worker decisions stay native. - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) + command_sandbox = SimpleNamespace(execute_command=lambda command, **kwargs: CommandOutput("Exit Code: 2", exit_code=2)) - async def initialized(_runtime): + def initialized(runtime): + if runtime.state["sandbox"]["sandbox_id"] == "fixture:command": + return command_sandbox return sandbox - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized_async", initialized) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) + async def initialized_async(runtime): + return initialized(runtime) + + monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", initialized) + monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized_async", initialized_async) errors = ToolErrorHandlingMiddleware() receipt = ToolReceiptMiddleware() if receipts else None @@ -324,7 +326,7 @@ def _native_tool_graph(tmp_path, monkeypatch, *, receipts): async def _native_tool_turn(graph, tmp_path, *, thread_id, turn, kind): args = ( - {"command": f"env -i /bin/sh -c 'exit 2' # attempt-{turn}", "description": "Controlled failing command"} + {"command": f"exit 2 # attempt-{turn}", "description": "Controlled failing command"} if kind == "failed-bash" else {"path": "/mnt/user-data/workspace/input.txt", "description": f"Read attempt {turn}"} if kind == "same-read" @@ -333,7 +335,7 @@ async def _native_tool_turn(graph, tmp_path, *, thread_id, turn, kind): tool_name = {"failed-bash": "bash", "same-read": "read_file", "same-write": "write_file"}[kind] state = await graph.ainvoke( { - "sandbox": {"sandbox_id": "local"}, + "sandbox": {"sandbox_id": "fixture:command" if kind == "failed-bash" else "local"}, "thread_data": {f"{name}_path": str(tmp_path / name) for name in ("workspace", "uploads", "outputs")}, "messages": [AIMessage(content="", tool_calls=[{"id": f"native-{turn}", "name": tool_name, "args": args}])], }, @@ -343,7 +345,6 @@ async def _native_tool_turn(graph, tmp_path, *, thread_id, turn, kind): return [*state["messages"], AIMessage(content="Work remains.", id=f"native-final-{turn}")], result -@pytest.mark.skipif(os.name == "nt", reason="Controlled native LocalSandbox commands use a POSIX shell") @pytest.mark.asyncio @pytest.mark.parametrize("mode", ["full", "delta"]) @pytest.mark.parametrize("receipts", [False, True], ids=["receipts-off", "receipts-on"]) @@ -374,7 +375,6 @@ async def test_native_tool_results_cannot_buy_goal_continuations(tmp_path, monke assert (tmp_path / "workspace/input.txt").read_text(encoding="utf-8") == "Stable input contents.\n" -@pytest.mark.skipif(os.name == "nt", reason="Controlled native LocalSandbox commands use a POSIX shell") @pytest.mark.asyncio @pytest.mark.parametrize("mode", ["full", "delta"]) @pytest.mark.parametrize("receipts", [False, True], ids=["receipts-off", "receipts-on"]) diff --git a/backend/tests/test_lead_prompt_script_guidance.py b/backend/tests/test_lead_prompt_script_guidance.py index 400b694519..13c68dbcd0 100644 --- a/backend/tests/test_lead_prompt_script_guidance.py +++ b/backend/tests/test_lead_prompt_script_guidance.py @@ -20,9 +20,9 @@ ROUTINE_SHELL_EXAMPLE = "- Run a routine test, build, or git command directly. U NO_BASH_ROUTINE_EXAMPLE = "- Do a routine file read, search, or edit directly. No `bash` tool is bound, and a subagent has none either." -def _app_config(*, allow_host_bash=False, acp_agents=None): +def _app_config(*, sandbox_use="deerflow.sandbox.local:LocalSandboxProvider", allow_host_bash=False, acp_agents=None): return SimpleNamespace( - sandbox=SimpleNamespace(use="deerflow.sandbox.local:LocalSandboxProvider", allow_host_bash=allow_host_bash, mounts=[]), + sandbox=SimpleNamespace(use=sandbox_use, allow_host_bash=allow_host_bash, mounts=[]), skills=SimpleNamespace(container_path="/mnt/skills", use="deerflow.skills.storage.local_skill_storage:LocalSkillStorage", get_skills_path=lambda: Path("/tmp/skills")), skill_evolution=SimpleNamespace(enabled=False), tool_search=SimpleNamespace(enabled=False), @@ -71,9 +71,9 @@ def test_prompt_defaults_to_the_script_guidance(render): @pytest.mark.parametrize("max_concurrent", [1, 3]) def test_subagent_section_agrees_with_the_lead_about_bash(render, max_concurrent): - # Host bash allowed, so the registry offers the bash subagent, but the lead's own tools lack bash + # The provider supports bash, but the lead's own tools can lack it # (for example a custom agent's tool_groups); the bash subagent inherits those groups. - config = _app_config(allow_host_bash=True) + config = _app_config(sandbox_use="deerflow.community.aio_sandbox:AioSandboxProvider") with_bash = render(config, subagent_enabled=True, max_concurrent_subagents=max_concurrent, bash_available=True) without_bash = render(config, subagent_enabled=True, max_concurrent_subagents=max_concurrent, bash_available=False) @@ -94,9 +94,8 @@ def test_subagent_section_agrees_with_the_lead_about_bash(render, max_concurrent @pytest.mark.parametrize("max_concurrent", [1, 3]) -def test_subagent_examples_drop_shell_work_when_host_bash_is_off(render, max_concurrent): - # The default local sandbox: the registry drops the bash subagent and the lead binds no bash. - prompt = render(_app_config(allow_host_bash=False), subagent_enabled=True, max_concurrent_subagents=max_concurrent, bash_available=False) +def test_subagent_examples_drop_shell_work_on_local_provider(render, max_concurrent): + prompt = render(_app_config(allow_host_bash=True), subagent_enabled=True, max_concurrent_subagents=max_concurrent, bash_available=False) assert "- **bash**:" not in prompt assert "Run a routine test, build, or git command" not in prompt @@ -107,7 +106,7 @@ def test_subagent_examples_drop_shell_work_when_host_bash_is_off(render, max_con @pytest.mark.parametrize("max_concurrent", [1, 3]) def test_subagent_examples_do_not_name_a_bash_subagent_that_is_not_offered(render, max_concurrent): # A custom agent may bind bash itself while its allowed_subagents leave the bash subagent out. - prompt = render(_app_config(allow_host_bash=True), subagent_enabled=True, max_concurrent_subagents=max_concurrent, allowed_subagents=["general-purpose"], bash_available=True) + prompt = render(_app_config(sandbox_use="deerflow.community.aio_sandbox:AioSandboxProvider"), subagent_enabled=True, max_concurrent_subagents=max_concurrent, allowed_subagents=["general-purpose"], bash_available=True) assert "- **bash**:" not in prompt assert "- Run a routine test, build, or git command directly.\n" in prompt diff --git a/backend/tests/test_local_bash_tool_loading.py b/backend/tests/test_local_bash_tool_loading.py index 60c79a9379..ca4abe58b5 100644 --- a/backend/tests/test_local_bash_tool_loading.py +++ b/backend/tests/test_local_bash_tool_loading.py @@ -34,7 +34,7 @@ def test_get_available_tools_hides_bash_for_default_local_sandbox(monkeypatch): assert "ls" in names -def test_get_available_tools_keeps_bash_when_explicitly_enabled(monkeypatch): +def test_get_available_tools_hides_bash_with_legacy_local_setting(monkeypatch): monkeypatch.setattr("deerflow.tools.tools.get_app_config", lambda: _make_config(allow_host_bash=True)) monkeypatch.setattr( "deerflow.tools.tools.resolve_variable", @@ -43,7 +43,7 @@ def test_get_available_tools_keeps_bash_when_explicitly_enabled(monkeypatch): names = [tool.name for tool in get_available_tools(include_mcp=False, subagent_enabled=False)] - assert "bash" in names + assert "bash" not in names assert "ls" in names diff --git a/backend/tests/test_local_command_path_spaces.py b/backend/tests/test_local_command_path_spaces.py index 3d20e4c2b5..61b5335ad6 100644 --- a/backend/tests/test_local_command_path_spaces.py +++ b/backend/tests/test_local_command_path_spaces.py @@ -2,14 +2,13 @@ import os import shutil -import subprocess from pathlib import Path from types import SimpleNamespace import pytest from deerflow.sandbox.local.local_sandbox import LocalSandbox, PathMapping -from deerflow.sandbox.tools import _apply_cwd_prefix, bash_tool, replace_virtual_paths_in_command +from deerflow.sandbox.tools import replace_virtual_paths_in_command @pytest.fixture @@ -191,67 +190,43 @@ def test_powershell_redirects_to_mapped_path_with_spaces(powershell, mounted): @pytest.mark.parametrize("quote", ["", '"', "'"]) @pytest.mark.parametrize("upload_directory", ["thread data", "O'Brien", "cost$USER", "a;b"]) -def test_public_bash_tool_preserves_thread_path_argument(powershell, tmp_path, monkeypatch, quote, upload_directory): - from deerflow.config.sandbox_config import SandboxConfig - +def test_local_sandbox_preserves_thread_path_argument(powershell, tmp_path, quote, upload_directory): dirs = {f"{name}_path": str(tmp_path / "thread data" / name) for name in ("workspace", "uploads", "outputs")} dirs["uploads_path"] = str(tmp_path / upload_directory / "uploads") for directory in dirs.values(): Path(directory).mkdir(parents=True) Path(dirs["uploads_path"], "marker.txt").write_text("needle", encoding="utf-8") sandbox = LocalSandbox("local", [PathMapping(f"/mnt/user-data/{name}", dirs[f"{name}_path"]) for name in ("workspace", "uploads", "outputs")]) - runtime = SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}, "thread_data": dirs}, context={"thread_id": "space-test"}) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda _: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - monkeypatch.setattr("deerflow.sandbox.tools.get_app_config", lambda: SimpleNamespace(sandbox=SandboxConfig())) - result = bash_tool.func(runtime=runtime, command=f"Get-Content {quote}/mnt/user-data/uploads/marker.txt{quote}") + result = sandbox.execute_command(f"Get-Content {quote}/mnt/user-data/uploads/marker.txt{quote}") assert "needle" in result assert "Exit Code:" not in result assert not result.startswith("Error:"), result -def _workspace_runtime(workspace, monkeypatch, *, filename="marker.txt"): - workspace.mkdir() - (workspace / filename).write_text("workspace-marker", encoding="utf-8") - sandbox = LocalSandbox("local", [PathMapping("/mnt/user-data/workspace", str(workspace))]) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda _: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - return SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": {"workspace_path": str(workspace)}, "thread_directories_created": True}, - context={"thread_id": "workspace-test"}, - ) - - -@pytest.mark.parametrize("apostrophe", ["\u2018", "\u2019"]) -def test_public_bash_tool_enters_powershell_workspace_with_curly_apostrophe(powershell, tmp_path, monkeypatch, apostrophe): - runtime = _workspace_runtime(tmp_path / f"O{apostrophe}Brien workspace", monkeypatch) - assert bash_tool.func(runtime=runtime, command="Get-Content marker.txt").strip() == "workspace-marker" - - @pytest.mark.skipif(os.name != "nt", reason="native Windows cmd.exe execution") -def test_public_bash_tool_enters_cmd_workspace_with_spaces(tmp_path, monkeypatch): +def test_local_cmd_honors_an_explicit_working_directory(tmp_path, monkeypatch): shell = shutil.which("cmd.exe") assert shell is not None monkeypatch.setattr(LocalSandbox, "_get_shell", staticmethod(lambda: shell)) workspace = tmp_path / "workspace with spaces" - runtime = _workspace_runtime(workspace, monkeypatch, filename="marker file.txt") + workspace.mkdir() + (workspace / "marker file.txt").write_text("workspace-marker", encoding="utf-8") + sandbox = LocalSandbox("local") + command = 'type "marker file.txt"' - assert bash_tool.func(runtime=runtime, command=command).strip() == "workspace-marker" + assert sandbox.execute_command(command, cwd=str(workspace)).strip() == "workspace-marker" monkeypatch.chdir(tmp_path) (tmp_path / "marker file.txt").write_text("inherited-directory-marker", encoding="utf-8") workspace.rename(tmp_path / "renamed workspace") - result = bash_tool.func(runtime=runtime, command=command) - assert result.startswith("Error:"), result - assert "inherited-directory-marker" not in result + with pytest.raises(OSError): + sandbox.execute_command(command, cwd=str(workspace)) -def test_public_bash_tool_passes_cmd_workspace_to_process_launch(tmp_path, monkeypatch): +def test_local_cmd_passes_explicit_working_directory_to_process_launch(tmp_path, monkeypatch): from deerflow.sandbox.local import local_sandbox workspace = tmp_path / "workspace with spaces" - runtime = _workspace_runtime(workspace, monkeypatch) - monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: True) monkeypatch.setattr(local_sandbox, "os", SimpleNamespace(**{**vars(os), "name": "nt"})) monkeypatch.setattr(LocalSandbox, "_get_shell", staticmethod(lambda: "cmd.exe")) calls = [] @@ -261,82 +236,5 @@ def test_public_bash_tool_passes_cmd_workspace_to_process_launch(tmp_path, monke return "workspace-marker", "", 0, False monkeypatch.setattr(LocalSandbox, "_run_windows_command", staticmethod(run)) - assert bash_tool.func(runtime=runtime, command='type "marker file.txt"') == "workspace-marker" + assert LocalSandbox("local").execute_command('type "marker file.txt"', cwd=str(workspace)) == "workspace-marker" assert calls == [('cmd.exe /d /s /c "type "marker file.txt""', str(workspace))] - - -@pytest.mark.parametrize( - ("shell", "expected_prefix"), - [ - ("/bin/bash", "cd '/tmp/thread data/workspace' && "), - ("/bin/sh", "cd '/tmp/thread data/workspace' && "), - # Git Bash/MSYS on Windows reports as sh.exe and speaks POSIX. - ("C:/Program Files/Git/bin/bash.exe", "cd '/tmp/thread data/workspace' && "), - # PowerShell 7 and Windows PowerShell 5.1: the 5.1 parser has no `&&`. - ("/usr/local/bin/pwsh", "Set-Location -LiteralPath '/tmp/thread data/workspace' -ErrorAction Stop; "), - ("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "Set-Location -LiteralPath '/tmp/thread data/workspace' -ErrorAction Stop; "), - # cmd.exe keeps single quotes as literal characters, so `cd ''` looks - # for a directory whose name includes them. - ("C:\\Windows\\System32\\cmd.exe", 'cd /d "/tmp/thread data/workspace" && '), - ], -) -def test_cwd_prefix_uses_syntax_the_selected_shell_can_parse(shell, expected_prefix): - workspace = "/tmp/thread data/workspace" - assert _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell=shell) == f"{expected_prefix}echo hi" - - -def test_cwd_prefix_quotes_a_workspace_with_an_apostrophe(): - workspace = "/tmp/O'Brien's thread/workspace" - assert _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell="/bin/bash") == "cd '/tmp/O'\"'\"'Brien'\"'\"'s thread/workspace' && echo hi" - # PowerShell escapes a literal quote by doubling it inside a single-quoted string. - assert _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell="pwsh") == "Set-Location -LiteralPath '/tmp/O''Brien''s thread/workspace' -ErrorAction Stop; echo hi" - - -@pytest.mark.parametrize("apostrophe", ["\u2018", "\u2019"]) -def test_cwd_prefix_quotes_a_workspace_with_a_curly_apostrophe(apostrophe): - workspace = f"/tmp/O{apostrophe}Brien workspace" - prefix = _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell="powershell.exe") - assert prefix == f"Set-Location -LiteralPath '/tmp/O{apostrophe * 2}Brien workspace' -ErrorAction Stop; echo hi" - - -@pytest.mark.parametrize("shell", ["/bin/bash", "pwsh", "C:\\Windows\\System32\\cmd.exe"]) -def test_cwd_prefix_leaves_the_command_alone_without_a_workspace(shell): - assert _apply_cwd_prefix("echo hi", None, shell=shell) == "echo hi" - assert _apply_cwd_prefix("echo hi", {}, shell=shell) == "echo hi" - - -def test_powershell_prefix_skips_the_command_when_the_workspace_is_gone(powershell, tmp_path): - """A vanished workspace must abort the command, not run it from the inherited cwd. - - ``Set-Location`` reports a missing directory as a non-terminating error, so - without ``-ErrorAction Stop`` the ``;``-separated command still runs — from - whatever directory the gateway was started in. - """ - missing = tmp_path / "workspace-that-was-removed" - command = _apply_cwd_prefix('Write-Output "SHOULD_NOT_RUN"', {"workspace_path": str(missing)}, shell=powershell) - completed = subprocess.run( - [powershell, "-NoProfile", "-Command", command], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=60, - ) - assert completed.returncode != 0, completed.stdout - assert "SHOULD_NOT_RUN" not in completed.stdout - - # Control: the same prefix does run the command once the workspace exists, - # so the assertion above cannot pass by the command never running at all. - workspace = tmp_path / "workspace" - workspace.mkdir() - ok_command = _apply_cwd_prefix('Write-Output "RAN"', {"workspace_path": str(workspace)}, shell=powershell) - ran = subprocess.run( - [powershell, "-NoProfile", "-Command", ok_command], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=60, - ) - assert ran.returncode == 0, ran.stderr - assert "RAN" in ran.stdout diff --git a/backend/tests/test_local_sandbox_command_timeout.py b/backend/tests/test_local_sandbox_command_timeout.py index 821cd3ebda..8522e14536 100644 --- a/backend/tests/test_local_sandbox_command_timeout.py +++ b/backend/tests/test_local_sandbox_command_timeout.py @@ -232,17 +232,10 @@ def test_bash_tool_description_guides_backgrounding_long_lived_processes(): assert "server" in description -def test_bash_tool_description_guides_safe_cross_platform_local_environment_probes(): - """The model-visible bash contract must recover from local path-guard failures (#4999).""" +def test_bash_tool_description_identifies_the_execution_environment(): from deerflow.sandbox.tools import bash_tool - description = " ".join(bash_tool.description.lower().split()) - assert "local host" in description - assert "uname -s" in description - assert "sw_vers" in description - assert "only when the active sandbox policy permits it" in description - assert "do not repeat the rejected command" in description - assert "command-only probes" in description + assert "configured isolated sandbox" in bash_tool.description @posix_only diff --git a/backend/tests/test_sandbox_command_cancellation.py b/backend/tests/test_sandbox_command_cancellation.py index b2ec80214c..4c85b768ae 100644 --- a/backend/tests/test_sandbox_command_cancellation.py +++ b/backend/tests/test_sandbox_command_cancellation.py @@ -7,13 +7,14 @@ import signal import subprocess import sys import threading +from functools import partial from pathlib import Path import pytest from deerflow.sandbox.command_scope import command_owner -from deerflow.sandbox.lease import run_sync_lifecycle_operation -from deerflow.sandbox.local.local_sandbox import LocalSandbox +from deerflow.sandbox.lease import run_sync_lifecycle_operation, sandbox_lease_owner +from deerflow.sandbox.local.local_sandbox import LocalSandbox, PathMapping def _alive(pid: int) -> bool: @@ -224,7 +225,7 @@ async def test_cancelled_aio_waiter_never_starts_or_interrupts_another_scope(mon @pytest.mark.skipif(os.name != "posix", reason="POSIX process groups") @pytest.mark.asyncio @pytest.mark.parametrize("outcome", ["interrupt", "failure", "loop_capped"]) -async def test_native_bash_to_worker_stops_owned_processes_before_release(monkeypatch, tmp_path, outcome): +async def test_worker_stops_owned_provider_processes_before_release(tmp_path, outcome): from types import SimpleNamespace as N from unittest.mock import AsyncMock, MagicMock @@ -232,15 +233,14 @@ async def test_native_bash_to_worker_stops_owned_processes_before_release(monkey from deerflow.runtime.runs.worker import RunContext, run_agent from deerflow.sandbox.lease import get_sandbox_lease_manager from deerflow.sandbox.sandbox_provider import reset_sandbox_provider, set_sandbox_provider - from deerflow.sandbox.tools import bash_tool + from deerflow.sandbox.tools import _execute_bash_command, ensure_sandbox_initialized_async - sandbox = LocalSandbox("local:worker-cancel") + sandbox = LocalSandbox("local:worker-cancel", [PathMapping("/mnt/user-data/workspace", str(tmp_path))]) provider = MagicMock() provider.get.return_value = sandbox provider.get_scoped.return_value = sandbox provider.acquire.return_value = sandbox.id provider.acquire_async = AsyncMock(return_value=sandbox.id) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) run_manager = RunManager() record = await run_manager.create("native-bash-cancellation") background = tmp_path / "background.pid" @@ -255,18 +255,25 @@ async def test_native_bash_to_worker_stops_owned_processes_before_release(monkey provider.release.side_effect = release + async def execute_owned(runtime, command): + active = await ensure_sandbox_initialized_async(runtime) + owner = sandbox_lease_owner(runtime.context) + assert owner is not None + execute = partial(_execute_bash_command, active, command, runtime=runtime, env=None) + return await run_sync_lifecycle_operation(execute, _on_cancel=partial(active.request_command_cancel, owner)) + class Agent: async def astream(self, graph_input, config, **kwargs): context = config["configurable"]["__pregel_runtime"].context state = {"sandbox": {"sandbox_id": sandbox.id}, "thread_data": {key: str(tmp_path) for key in ("workspace_path", "outputs_path", "uploads_path")}} runtime = N(context=context, state=state, config=config) command = "nohup " + _command(background, background=True).replace(shlex.quote(sys.executable), "python3").replace(str(tmp_path), "/mnt/user-data/workspace") - result = await bash_tool.coroutine(runtime=runtime, command=command) + result = await execute_owned(runtime, command) assert not result.startswith("Error:"), result await _pid(background) if outcome == "interrupt": command = _command(foreground, background=False).replace(shlex.quote(sys.executable), "python3").replace(str(tmp_path), "/mnt/user-data/workspace") - await bash_tool.coroutine(runtime=runtime, command=command) + await execute_owned(runtime, command) elif outcome == "failure": raise RuntimeError("scripted model failure after starting a process") else: diff --git a/backend/tests/test_sandbox_tools_security.py b/backend/tests/test_sandbox_tools_security.py index 17e124da38..35248d75dc 100644 --- a/backend/tests/test_sandbox_tools_security.py +++ b/backend/tests/test_sandbox_tools_security.py @@ -7,10 +7,9 @@ from unittest.mock import patch import pytest from deerflow.sandbox.exceptions import SandboxError -from deerflow.sandbox.local.local_sandbox import LocalSandbox, PathMapping +from deerflow.sandbox.local.local_sandbox import LocalSandbox from deerflow.sandbox.tools import ( VIRTUAL_PATH_PREFIX, - _apply_cwd_prefix, _compiled_mask_patterns, _extract_skill_name_from_skills_path, _get_custom_mount_for_path, @@ -235,36 +234,6 @@ def test_mask_local_paths_masks_every_entry_of_a_colon_joined_path_list() -> Non assert masked == "PATH=" + ":".join([*virtuals, "/usr/bin"]) -@pytest.mark.skipif(os.name == "nt", reason="POSIX shell and ':'-separated PATH") -def test_local_bash_tool_output_masks_every_entry_of_a_colon_joined_path_list(tmp_path: Path, monkeypatch) -> None: - """End to end through ``bash_tool``: output passes ``LocalSandbox``'s reverse - resolution and then ``mask_local_paths_in_output`` before reaching the model.""" - thread_root = tmp_path / "threads" / "t1" / "user-data" - thread_data = {f"{name}_path": str(thread_root / name) for name in ("workspace", "uploads", "outputs")} - for path in thread_data.values(): - Path(path).mkdir(parents=True) - workspace = str(Path(thread_data["workspace_path"]).resolve()) - sandbox = LocalSandbox( - id="local", - path_mappings=[PathMapping(container_path=f"{VIRTUAL_PATH_PREFIX}/workspace", local_path=workspace)], - ) - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": thread_data}, - context={"thread_id": "t1"}, - config={}, - ) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - - # The shell expands ``$PWD`` (the host workspace), so the host paths exist only - # in the output -- the ``export PATH="$PWD/.venv/bin:$PATH"`` shape. - command = "echo " + ":".join(f"$PWD/e{i}/bin" for i in range(_PATH_LIST_ENTRIES)) - result = bash_tool.func(runtime=runtime, description="print PATH", command=command) - - assert str(tmp_path) not in result - assert result.strip() == ":".join(f"{VIRTUAL_PATH_PREFIX}/workspace/e{i}/bin" for i in range(_PATH_LIST_ENTRIES)) - - @pytest.mark.parametrize("prefix", ["", "cwd: ", "see "]) def test_mask_local_paths_translates_a_bare_base_at_end_of_output(prefix: str) -> None: """``$`` is load-bearing: output ending exactly at a host base still masks. @@ -1387,88 +1356,21 @@ def test_validate_local_bash_command_paths_rejects_pwd_traversal_like_relative_t validate_local_bash_command_paths(command, _THREAD_DATA) -def test_bash_tool_rejects_variable_prefixed_host_path_before_execution(monkeypatch) -> None: +@pytest.mark.parametrize("sandbox_id", ["local", "fixture:cached"]) +def test_bash_tool_rejects_local_sandbox_with_legacy_setting(monkeypatch, sandbox_id) -> None: runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, + state={"sandbox": {"sandbox_id": sandbox_id}, "thread_data": _THREAD_DATA.copy()}, context={"thread_id": "thread-1"}, ) - monkeypatch.setattr( - "deerflow.sandbox.tools.ensure_sandbox_initialized", - lambda runtime: SimpleNamespace(execute_command=lambda command: pytest.fail("unsafe command should not execute")), - ) + + from deerflow.sandbox.local.local_sandbox import LocalSandbox + + sandbox = LocalSandbox("local") + monkeypatch.setattr(sandbox, "execute_command", lambda *args, **kwargs: pytest.fail("a local workspace must not execute the command")) + monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda _: sandbox) + config = SimpleNamespace(sandbox=SimpleNamespace(use="deerflow.sandbox.local:LocalSandboxProvider", allow_host_bash=True)) + monkeypatch.setattr("deerflow.sandbox.security.get_app_config", lambda: config) monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - - result = bash_tool.func(runtime=runtime, description="read key", command="cat $HOME/.ssh/id_rsa") - - assert "Unsafe absolute paths in command: $HOME/.ssh/id_rsa" in result - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX shell expands $HOME") -@pytest.mark.parametrize( - ("command", "rejected"), - [ - ('cat "$HOME/.ssh/id_rsa"', "Unsafe absolute paths in command: $HOME/.ssh/id_rsa"), - ('CDPATH="$HOME" cd .ssh && cat $PWD/id_rsa', "Unsafe working directory change via CDPATH"), - ('cat "$HOME/文档/id_rsa"', "Unsafe absolute paths in command: $HOME/文档/id_rsa"), - ('cat "${REVIEW_ROOT}/2"', "Unsafe absolute paths in command: /2"), - ('cat "$(printenv REVIEW_ROOT)/2"', "Unsafe absolute paths in command: /2"), - ("cat ${ROOT}[x]/secret", "Unsafe absolute paths in command: /secret"), - ('cat $(printf %s "$ROOT" # f(\n)/secret', "Unsafe absolute paths in command: /secret"), - ], -) -def test_local_bash_tool_does_not_read_variable_prefixed_host_file(tmp_path: Path, monkeypatch, command: str, rejected: str) -> None: - """End to end through a real ``LocalSandbox``: before the fix the shell - expanded ``$HOME`` and printed the host file.""" - home = tmp_path / "home" - (home / ".ssh").mkdir(parents=True) - (home / ".ssh" / "id_rsa").write_text("host-private-key") - (home / "文档").mkdir() - (home / "文档" / "id_rsa").write_text("host-private-key") - (home / "2").write_text("host-private-key", encoding="utf-8") - (home / "secret").write_text("host-private-key", encoding="utf-8") - glob_home = tmp_path / "homex" - glob_home.mkdir() - (glob_home / "secret").write_text("host-private-key", encoding="utf-8") - monkeypatch.setenv("HOME", str(home)) - monkeypatch.setenv("ROOT", str(home)) - monkeypatch.setenv("REVIEW_ROOT", str(home)) - thread_root = tmp_path / "threads" / "t1" / "user-data" - thread_data = {f"{name}_path": str(thread_root / name) for name in ("workspace", "uploads", "outputs")} - for path in thread_data.values(): - Path(path).mkdir(parents=True) - workspace = str(Path(thread_data["workspace_path"]).resolve()) - sandbox = LocalSandbox( - id="local", - path_mappings=[PathMapping(container_path=f"{VIRTUAL_PATH_PREFIX}/workspace", local_path=workspace)], - ) - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": thread_data}, - context={"thread_id": "t1"}, - config={}, - ) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda runtime: sandbox) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - - # The real shell can read the synthetic file; the public tool must stop it. - assert "host-private-key" in sandbox.execute_command(command) - result = bash_tool.func(runtime=runtime, description="read key", command=command) - - assert "host-private-key" not in result - assert rejected in result - - -def test_bash_tool_rejects_host_bash_when_local_sandbox_default(monkeypatch) -> None: - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"thread_id": "thread-1"}, - ) - - monkeypatch.setattr( - "deerflow.sandbox.tools.ensure_sandbox_initialized", - lambda runtime: SimpleNamespace(execute_command=lambda command: pytest.fail("host bash should not execute")), - ) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: False) result = bash_tool.func( runtime=runtime, @@ -1479,60 +1381,6 @@ def test_bash_tool_rejects_host_bash_when_local_sandbox_default(monkeypatch) -> assert "Host bash execution is disabled" in result -def test_bash_tool_description_scopes_environment_detection_to_local_host_bash() -> None: - description = bash_tool.description - - assert "local host via host bash" in description - assert "inspect the current environment instead of" in description - assert "`uname -s`" in description - assert "`sw_vers`" in description - assert "`uname -a`" in description - assert "`/etc/os-release` only when the active" in description - assert "sandbox policy permits it" in description - assert "do not repeat the rejected command" in description - assert "otherwise use allowed virtual paths or explain the restriction" in description - - -def test_bash_tool_guides_recovery_after_host_path_rejection(monkeypatch) -> None: - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"thread_id": "thread-1"}, - ) - monkeypatch.setattr( - "deerflow.sandbox.tools.ensure_sandbox_initialized", - lambda runtime: SimpleNamespace(execute_command=lambda command: pytest.fail("unsafe command should not execute")), - ) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - - result = bash_tool.func(runtime=runtime, description="detect the OS", command="cat /etc/os-release") - - assert "For environment questions, use command-only probes" in result - assert "Do not repeat the rejected path" in result - - -def test_bash_tool_blocks_relative_traversal_before_host_execution(monkeypatch) -> None: - runtime = SimpleNamespace( - state={"sandbox": {"sandbox_id": "local"}, "thread_data": _THREAD_DATA.copy()}, - context={"thread_id": "thread-1"}, - ) - - monkeypatch.setattr( - "deerflow.sandbox.tools.ensure_sandbox_initialized", - lambda runtime: SimpleNamespace(execute_command=lambda command: pytest.fail("unsafe command should not execute")), - ) - monkeypatch.setattr("deerflow.sandbox.tools.ensure_thread_directories_exist", lambda runtime: None) - monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True) - - result = bash_tool.func( - runtime=runtime, - description="run command", - command="cat ../uploads/secret.txt", - ) - - assert "path traversal" in result - - # ---------- Skills path tests ---------- @@ -1761,39 +1609,6 @@ def test_mask_local_paths_in_output_hides_acp_workspace_host_paths() -> None: assert "/mnt/acp-workspace/hello.py" in masked -# ---------- _apply_cwd_prefix ---------- - - -def test_apply_cwd_prefix_prepends_workspace() -> None: - """Command is prefixed with cd && when workspace_path is set.""" - # Pin the POSIX shell: the prefix follows the shell that will run it (see - # test_local_command_path_spaces.py for the PowerShell/cmd.exe forms), so the - # default would make this assertion host-dependent. - result = _apply_cwd_prefix("ls -la", _THREAD_DATA, shell="/bin/bash") - assert result.startswith("cd ") - assert "ls -la" in result - assert "/tmp/deer-flow/threads/t1/user-data/workspace" in result - - -def test_apply_cwd_prefix_no_thread_data() -> None: - """Command is returned unchanged when thread_data is None.""" - assert _apply_cwd_prefix("ls -la", None) == "ls -la" - - -def test_apply_cwd_prefix_missing_workspace_path() -> None: - """Command is returned unchanged when workspace_path is absent from thread_data.""" - assert _apply_cwd_prefix("ls -la", {}) == "ls -la" - - -def test_apply_cwd_prefix_quotes_path_with_spaces() -> None: - """Workspace path containing spaces is properly shell-quoted.""" - # The prefix follows the shell that will run it, so this POSIX assertion has - # to name the shell or it would depend on the host. - thread_data = {**_THREAD_DATA, "workspace_path": "/tmp/my workspace/t1"} - result = _apply_cwd_prefix("echo hello", thread_data, shell="/bin/bash") - assert result == "cd '/tmp/my workspace/t1' && echo hello" - - def test_validate_local_bash_command_paths_allows_mcp_filesystem_paths() -> None: """Bash commands referencing MCP filesystem server paths should be allowed.""" from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig diff --git a/backend/tests/test_setup_wizard.py b/backend/tests/test_setup_wizard.py index b1e3fd18d4..727a278425 100644 --- a/backend/tests/test_setup_wizard.py +++ b/backend/tests/test_setup_wizard.py @@ -315,15 +315,17 @@ class TestBuildMinimalConfig: assert "sandbox" in data assert "use" in data["sandbox"] assert data["sandbox"]["use"] == "deerflow.sandbox.local:LocalSandboxProvider" - assert data["sandbox"]["allow_host_bash"] is False + assert "allow_host_bash" not in data["sandbox"] - def test_bash_tool_disabled_by_default(self): + @pytest.mark.parametrize("include_bash_tool", [False, True]) + def test_local_config_omits_bash_tool(self, include_bash_tool): content = build_minimal_config( provider_use="langchain_openai:ChatOpenAI", model_name="gpt-4o", display_name="OpenAI", api_key_field="api_key", env_var="OPENAI_API_KEY", + include_bash_tool=include_bash_tool, ) data = yaml.safe_load(content) tool_names = [t["name"] for t in data.get("tools", [])] diff --git a/backend/tests/test_skill_request_scoped_secrets.py b/backend/tests/test_skill_request_scoped_secrets.py index 6d676cc05b..534925aabb 100644 --- a/backend/tests/test_skill_request_scoped_secrets.py +++ b/backend/tests/test_skill_request_scoped_secrets.py @@ -182,79 +182,6 @@ class TestLocalSandboxOperatorEnvironment: with pytest.raises(ValueError): LocalSandbox(id="local", environment={name: "v"}) - @pytest.mark.parametrize("override", [False, True]) - @pytest.mark.parametrize("result_kind", ["output", "sandbox_error", "permission_error", "unexpected_error"]) - def test_operator_environment_masked_from_bash_output(self, override, result_kind): - """[P1 regression] An operator-injected credential must not flow back - into model-visible tool output when a script echoes its environment — - the bash tool's redaction set includes the sandbox's operator - environment, with request-scoped values winning on name collision.""" - from deerflow.sandbox import tools as tools_mod - from deerflow.sandbox.exceptions import SandboxRuntimeError - - operator_secret = "operator-secret-value-123456" - request_secret = "request-secret-value-987654321" - database_secret = "database-credential-value-123456" - errors = { - "sandbox_error": SandboxRuntimeError, - "permission_error": PermissionError, - "unexpected_error": RuntimeError, - } - - class FakeSandbox: - environment = { - "MINIMAX_API_KEY": operator_secret, - "DATABASE_URL": database_secret, - "IMAGE_GENERATION_MODEL": "readable-model-name", - "IMAGE_GENERATION_BASE_URL": "https://images.example.test", - "REGION": "readable-region-name", - } - seen_env = None - - def execute_command(self, command, env=None, timeout=None): - self.seen_env = env - effective_env = {**self.environment, **(env or {})} - output = "\n".join(f"{key}={value}" for key, value in effective_env.items()) - if result_kind in errors: - raise errors[result_kind](output) - return output - - active_secrets = {"ERP_TOKEN": request_secret} if override else {} - if override: - active_secrets["MINIMAX_API_KEY"] = request_secret - sandbox = FakeSandbox() - runtime = SimpleNamespace( - context={"__active_skill_secrets": active_secrets, "user_id": "u-local"}, - state={"sandbox": {"sandbox_id": "local:1"}}, - ) - thread_data = {"workspace_path": "/tmp/ws", "cwd": "/mnt/user-data/workspace"} - fake_cfg = SimpleNamespace(sandbox=SimpleNamespace(bash_output_max_chars=20000, bash_command_timeout=42)) - with ( - patch.object(tools_mod, "ensure_sandbox_initialized", return_value=sandbox), - patch.object(tools_mod, "is_local_sandbox", return_value=True), - patch.object(tools_mod, "is_host_bash_allowed", return_value=True), - patch.object(tools_mod, "ensure_thread_directories_exist", return_value=None), - patch.object(tools_mod, "get_thread_data", return_value=thread_data), - patch.object(tools_mod, "validate_local_bash_command_paths", return_value=None), - patch.object(tools_mod, "replace_virtual_paths_in_command", side_effect=lambda command, td: command), - patch.object(tools_mod, "_apply_cwd_prefix", side_effect=lambda command, td: command), - patch.object(tools_mod, "_is_windows", return_value=False), - patch("deerflow.config.app_config.get_app_config", return_value=fake_cfg), - ): - out = tools_mod.bash_tool.func(runtime=runtime, command="env", description="dump env") - - assert sandbox.seen_env == (active_secrets or None) - assert operator_secret not in out - assert request_secret not in out - assert database_secret not in out - assert "MINIMAX_API_KEY=[redacted]" in out - assert "DATABASE_URL=[redacted]" in out - if override: - assert "ERP_TOKEN=[redacted]" in out - assert "IMAGE_GENERATION_MODEL=readable-model-name" in out - assert "IMAGE_GENERATION_BASE_URL=https://images.example.test" in out - assert "REGION=readable-region-name" in out - class TestAioSandboxEnvInjection: @pytest.fixture @@ -1534,86 +1461,6 @@ class TestBashToolInjectsActiveSecrets: out, captured = self._run_bash({}) assert captured["env"] in (None, {}) - def test_local_bash_forwards_env_and_timeout(self, monkeypatch): - from deerflow.sandbox import tools as tools_mod - from deerflow.sandbox.tools import USER_ID_ENV - - captured = {} - - class FakeSandbox: - def execute_command(self, command, env=None, timeout=None): - captured["command"] = command - captured["env"] = env - captured["timeout"] = timeout - return "done" - - runtime = SimpleNamespace( - context={"__active_skill_secrets": {"ERP_TOKEN": "tok-456"}, "user_id": "u-local"}, - state={"sandbox": {"sandbox_id": "local:1"}}, - ) - thread_data = {"workspace_path": "/tmp/ws", "cwd": "/mnt/user-data/workspace"} - fake_cfg = SimpleNamespace(sandbox=SimpleNamespace(bash_output_max_chars=321, bash_command_timeout=42)) - with ( - patch.object(tools_mod, "ensure_sandbox_initialized", return_value=FakeSandbox()), - patch.object(tools_mod, "is_local_sandbox", return_value=True), - patch.object(tools_mod, "is_host_bash_allowed", return_value=True), - patch.object(tools_mod, "ensure_thread_directories_exist", return_value=None), - patch.object(tools_mod, "get_thread_data", return_value=thread_data), - patch.object(tools_mod, "validate_local_bash_command_paths", return_value=None), - patch.object(tools_mod, "replace_virtual_paths_in_command", side_effect=lambda command, td: command), - patch.object(tools_mod, "_apply_cwd_prefix", side_effect=lambda command, td: command), - # Pinned so the assertion below does not depend on the host OS: - # the Windows local sandbox publishes the id through ``env`` rather - # than the command string (#3919). - patch.object(tools_mod, "_is_windows", return_value=False), - patch("deerflow.config.app_config.get_app_config", return_value=fake_cfg), - ): - out = tools_mod.bash_tool.func(runtime=runtime, command="echo hi", description="run local skill") - - assert out == "done" - assert captured["command"] == f"export {USER_ID_ENV}=u-local; echo hi" - assert captured["env"] == {"ERP_TOKEN": "tok-456"} - assert captured["timeout"] == 42 - - def test_local_bash_windows_publishes_user_id_via_env(self, monkeypatch): - """``export`` is invalid under the Windows local sandbox's - PowerShell/cmd.exe shells, so the id moves to the ``env`` channel there - instead of being dropped — the PR promises it on every bash command.""" - from deerflow.sandbox import tools as tools_mod - from deerflow.sandbox.tools import USER_ID_ENV - - captured = {} - - class FakeSandbox: - def execute_command(self, command, env=None, timeout=None): - captured["command"] = command - captured["env"] = env - return "done" - - runtime = SimpleNamespace( - context={"__active_skill_secrets": {"ERP_TOKEN": "tok-789"}, "user_id": "u-win"}, - state={"sandbox": {"sandbox_id": "local:1"}}, - ) - thread_data = {"workspace_path": "/tmp/ws", "cwd": "/mnt/user-data/workspace"} - fake_cfg = SimpleNamespace(sandbox=SimpleNamespace(bash_output_max_chars=321, bash_command_timeout=42)) - with ( - patch.object(tools_mod, "ensure_sandbox_initialized", return_value=FakeSandbox()), - patch.object(tools_mod, "is_local_sandbox", return_value=True), - patch.object(tools_mod, "is_host_bash_allowed", return_value=True), - patch.object(tools_mod, "ensure_thread_directories_exist", return_value=None), - patch.object(tools_mod, "get_thread_data", return_value=thread_data), - patch.object(tools_mod, "validate_local_bash_command_paths", return_value=None), - patch.object(tools_mod, "replace_virtual_paths_in_command", side_effect=lambda command, td: command), - patch.object(tools_mod, "_apply_cwd_prefix", side_effect=lambda command, td: command), - patch.object(tools_mod, "_is_windows", return_value=True), - patch("deerflow.config.app_config.get_app_config", return_value=fake_cfg), - ): - out = tools_mod.bash_tool.func(runtime=runtime, command="echo hi", description="run local skill") - - assert out == "done" - assert captured["command"] == "echo hi" - assert captured["env"] == {"ERP_TOKEN": "tok-789", USER_ID_ENV: "u-win"} - def test_remote_bash_forwards_shared_timeout(self): from deerflow.sandbox import tools as tools_mod diff --git a/backend/tests/test_subagent_routing_prompt.py b/backend/tests/test_subagent_routing_prompt.py index 4064ba72d2..058b584f1b 100644 --- a/backend/tests/test_subagent_routing_prompt.py +++ b/backend/tests/test_subagent_routing_prompt.py @@ -105,5 +105,7 @@ def test_bash_descriptions_require_benefit_beyond_routine_commands(monkeypatch) assert policy in section assert policy in task_tool.description + assert "requires an isolated sandbox provider" in " ".join(task_tool.description.split()) + assert "host bash" not in task_tool.description assert policy in BASH_AGENT_CONFIG.description assert "Execute commands one at a time when they depend on each other" in BASH_AGENT_CONFIG.system_prompt diff --git a/backend/tests/test_tool_result_meta.py b/backend/tests/test_tool_result_meta.py index b361bc8d10..f522cab3cb 100644 --- a/backend/tests/test_tool_result_meta.py +++ b/backend/tests/test_tool_result_meta.py @@ -4,7 +4,7 @@ from __future__ import annotations import json import os -import shlex +from unittest.mock import AsyncMock, Mock import pytest from langchain_core.messages import ToolMessage @@ -20,7 +20,6 @@ from deerflow.agents.middlewares.tool_result_meta import ( ) -@pytest.mark.skipif(os.name == "nt", reason="POSIX shell probes") @pytest.mark.parametrize("mode", ["sync", "async"]) @pytest.mark.parametrize("progress_enabled", [False, True]) @pytest.mark.parametrize( @@ -38,7 +37,7 @@ from deerflow.agents.middlewares.tool_result_meta import ( ], ) @pytest.mark.asyncio -async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, monkeypatch, mode, progress_enabled, stdout, exit_code): +async def test_bash_structured_exit_code_reaches_graph_and_receipt(tmp_path, monkeypatch, mode, progress_enabled, stdout, exit_code): from langchain.agents import create_agent from langchain_core.callbacks import BaseCallbackHandler from langchain_core.language_models.fake_chat_models import GenericFakeChatModel @@ -49,7 +48,8 @@ async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, m from deerflow.config import app_config, paths from deerflow.extensions.registry import EMPTY_EXTENSIONS from deerflow.sandbox import sandbox_provider - from deerflow.sandbox.local.local_sandbox_provider import LocalSandboxProvider + from deerflow.sandbox.lease import get_sandbox_lease_manager + from deerflow.sandbox.sandbox import CommandOutput, Sandbox from deerflow.sandbox.tools import bash_tool class Model(GenericFakeChatModel): @@ -73,11 +73,9 @@ async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, m { "models": [], "sandbox": { - "use": "deerflow.sandbox.local:LocalSandboxProvider", - "allow_host_bash": True, + "use": "deerflow.community.aio_sandbox:AioSandboxProvider", "bash_output_max_chars": 0 if exit_code == 124 else 80, "bash_command_timeout": 0.1 if exit_code == 124 else 5, - "environment": {"EXAMPLE_API_KEY": "example-api-secret"}, }, "memory": {"enabled": False}, "summarization": {"enabled": False}, @@ -87,15 +85,24 @@ async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, m ) monkeypatch.setattr(app_config, "_app_config", config) monkeypatch.setattr(app_config, "_app_config_is_custom", True) - provider = LocalSandboxProvider() + output = "Command timed out" if exit_code == 124 else stdout + if exit_code: + output = f"{output}\nExit Code: {exit_code}" + # This double models a provider with a structured exit code. AIO emits text. + execute_command = Mock(return_value=CommandOutput(output, exit_code)) + sandbox = Mock(spec=Sandbox, id="fixture:status", execute_command=execute_command, supports_command_cancellation=False) + provider = Mock(spec=sandbox_provider.SandboxProvider) + provider.uses_thread_data_mounts = False + provider.acquire.return_value = sandbox.id + provider.acquire_async = AsyncMock(return_value=sandbox.id) + provider.get.return_value = sandbox + provider.get_scoped.return_value = sandbox monkeypatch.setattr(sandbox_provider, "_default_sandbox_provider", provider) - command = f"printf '%s' {shlex.quote(stdout)}; exit {exit_code}" - if exit_code == 124: - command = "while :; do :; done" + monkeypatch.setattr("deerflow.sandbox.tools.read_active_secrets", lambda _: {"EXAMPLE_API_KEY": "example-api-secret"}) model = Model( messages=iter( [ - AIMessage(content="", tool_calls=[{"name": "bash", "args": {"command": command}, "id": "bash-probe"}]), + AIMessage(content="", tool_calls=[{"name": "bash", "args": {"command": "pwd"}, "id": "bash-probe"}]), AIMessage(content="Done."), ] ) @@ -107,6 +114,7 @@ async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, m captured = Requests() invoke_config = {"callbacks": [captured]} result = graph.invoke(state, context=context, config=invoke_config) if mode == "sync" else await graph.ainvoke(state, context=context, config=invoke_config) + execute_command.assert_called_once() message = next(m for m in result["messages"] if isinstance(m, ToolMessage) and m.name == "bash") if exit_code == 124: assert "timed out" in message.content.lower() @@ -128,7 +136,7 @@ async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, m projected = next(m for m in captured.messages[-1] if isinstance(m, ToolMessage) and m.name == "bash") assert json.loads(projected.content) == {TOOL_META_KEY: {"status": expected, "source": "tool_return"}, "content": message.content} finally: - provider.shutdown() + get_sandbox_lease_manager(provider).close() def _make_msg(content: str, *, status: str = "success", kwargs: dict[str, object] | None = None) -> ToolMessage: diff --git a/config.example.yaml b/config.example.yaml index ba6afe0f51..d61900b8f7 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -20,7 +20,7 @@ # ============================================================================ # Bump this number when the config schema changes. # Run `make config-upgrade` to merge new fields into your local config.yaml. -config_version: 67 +config_version: 68 # Optional operator-owned literal prompt extensions (see CONFIGURATION.md): # lead_prompt_overlay: @@ -1409,9 +1409,7 @@ tools: group: file:write use: deerflow.sandbox.tools:str_replace_tool - # Bash execution tool - # Active only when using an isolated shell sandbox or when - # sandbox.allow_host_bash: true explicitly opts into host bash. + # Bash execution tool. Select an isolated sandbox provider to use it. - name: bash group: bash use: deerflow.sandbox.tools:bash_tool @@ -1773,16 +1771,12 @@ uploads: # ============================================================================ # Sandbox Configuration # ============================================================================ -# Choose between local sandbox (direct execution), Docker-based AIO sandbox, +# Choose between local file tools, Docker-based AIO sandbox, # or BoxLite micro-VM sandbox # Option 1: Local Sandbox (Default) -# Executes commands directly on the host machine +# Serves workspace file operations sandbox: use: deerflow.sandbox.local:LocalSandboxProvider - # Host bash execution is disabled by default because LocalSandboxProvider is - # not a secure isolation boundary for shell access. Enable only for fully - # trusted, single-user local workflows. - allow_host_bash: false # For AioSandboxProvider only: overlap likely sandbox work with the first # model call. It is disabled by default and ignored by other providers. prewarm: false diff --git a/deploy/helm/deer-flow/README.md b/deploy/helm/deer-flow/README.md index e06f6d8093..8f0cb8fdb3 100644 --- a/deploy/helm/deer-flow/README.md +++ b/deploy/helm/deer-flow/README.md @@ -157,7 +157,7 @@ they resolve from the `secrets` map): ```yaml config: | - config_version: 67 + config_version: 68 models: - name: gpt-4 use: langchain_openai:ChatOpenAI diff --git a/deploy/helm/deer-flow/values.yaml b/deploy/helm/deer-flow/values.yaml index fa625e15ba..502f56f404 100644 --- a/deploy/helm/deer-flow/values.yaml +++ b/deploy/helm/deer-flow/values.yaml @@ -392,7 +392,7 @@ ingress: # -- DeerFlow config.yaml content. Secrets MUST stay as $VAR references — never # inline literal secret values here. The default enables provisioner sandbox. config: | - config_version: 67 + config_version: 68 log_level: info recursion_limit: 100 max_recursion_limit: 1000 diff --git a/docs/guide/sandbox.md b/docs/guide/sandbox.md index c0eddcc91f..55ae4c43fd 100644 --- a/docs/guide/sandbox.md +++ b/docs/guide/sandbox.md @@ -3,14 +3,15 @@ ## Sandbox Mode DeerFlow supports multiple sandbox execution modes: -- **Local Execution** (runs sandbox code directly on the host machine) +- **Local Workspace** (files through workspace tools and configured mounts) - **Docker Execution** (runs sandbox code in isolated Docker containers) - **Docker Execution with Kubernetes** (runs sandbox code in Kubernetes pods via provisioner service) -Local bash tool status follows the process exit code, including timeout failures. -Successful commands may print `Error:` or JSON containing an `error` field without -being marked as failed. Output is still subject to the configured redaction and -size limits; those transformations do not change the execution status. +When a provider returns a structured exit code, Bash tool status follows that +code, including timeout failures. Providers that return plain text, including +AIO, use output-based status detection. A command that exits successfully can be +reported as a failure if it prints `Error:` or JSON with an `error` field. +Configured redaction and output limits still apply. The optional [Tenki provider](../../backend/packages/harness/deerflow/community/tenki/README.md) retains failed termination handles for retry and rejects late acquisitions after @@ -38,7 +39,10 @@ checkpoint, the runtime resolves the reference against the authenticated user and thread before a tool can reuse it. A missing runtime thread ID raises an error even when the referenced sandbox is cached. -When host Bash is enabled for Local Execution, DeerFlow starts OS detection with `uname -s`, then uses `sw_vers` on Darwin. On Linux, it reads host system files such as `/etc/os-release` only when the active sandbox policy permits it. Host filesystem path checks still apply; after a blocked path, the agent is directed to use a permitted command-only probe or virtual path instead of repeating the rejected command. +Local workspaces use the dedicated file tools. Switch to an isolated sandbox +provider for workflows that need Bash. A config that opts into host Bash with +`allow_host_bash: true` still loads with the local provider and logs a migration +warning. For Docker development and production, service startup follows the configured sandbox mode, including when the `sandbox:` header or `use` field has a trailing @@ -177,12 +181,6 @@ deadline. Allow for the remaining command timeout (600 seconds by default), plus session/transport/recovery/cleanup time when setting operator-facing release budgets; the HTTP cleanup timeout does not bound the preceding lock wait. -With local host bash enabled, the path guard permits division in simple shell -arithmetic and recognized single-quoted Python, Node.js and Perl programs. -Variable-built paths remain checked even when the filename is numeric or a -glob precedes the slash. This is a best-effort guard; host filesystem isolation -requires an isolated sandbox provider. - Local `grep` reports file permission and I/O failures as errors rather than successful empty or partial searches. Binary files and files that disappear during scanning remain excluded. @@ -483,11 +481,8 @@ continue to accept URL-encoded paths. The `write_file` guidance reflects the active model's output token limit, including custom-agent and thinking-mode overrides. For longer documents, the agent is guided to write sections with `append=True`; models without a known limit receive no numeric budget hint. -With `AioSandboxProvider`, shell execution runs inside isolated containers. With `LocalSandboxProvider`, file tools still map to per-thread directories on the host, but host `bash` is disabled by default because it is not a secure isolation boundary. Re-enable host bash only for fully trusted local workflows. Host bash commands have a wall-clock timeout, and long-lived processes should be started in the background with output redirected to a workspace log. If local command startup fails after spawning a child, DeerFlow attempts to kill and reap that child before propagating the startup error. On Windows, Git Bash/MSYS argument-conversion exclusions are limited to safe non-root virtual path prefixes, so host-native CLI launchers retain their normal MSYS compatibility. When the local sandbox falls back to PowerShell, it captures output as UTF-8 so CJK text does not depend on the Gateway host locale. - -On Windows, relative paths in local commands start in the thread workspace. -PowerShell supports spaces and typographic apostrophes in the workspace path. -The `cmd.exe` fallback supports workspace paths on a local or mapped drive. +With `AioSandboxProvider`, shell execution runs inside the sandbox container. +With `LocalSandboxProvider`, the file tools map to per-thread directories. Docker AIO sandboxes default to their existing open egress behavior for compatibility. Operators can set `sandbox.network.mode` to `isolated` or diff --git a/docs/guide/skills-and-tools.md b/docs/guide/skills-and-tools.md index dc2b34d649..d7285bd458 100644 --- a/docs/guide/skills-and-tools.md +++ b/docs/guide/skills-and-tools.md @@ -298,23 +298,13 @@ The built-in `image-generation` skill supports Gemini, MiniMax, and OpenAI-compatible Images APIs. Select the latter with `IMAGE_GENERATION_PROVIDER=openai`, then configure `IMAGE_GENERATION_API_KEY`, `IMAGE_GENERATION_BASE_URL`, and -`IMAGE_GENERATION_MODEL`. For a containerized sandbox or an explicitly enabled -local host shell, expose these variables through `sandbox.environment`; sandbox -commands intentionally do not inherit API keys from the Gateway process. -The local provider uses the resolved configuration values unchanged, and -request-scoped secrets override operator values. Local bash output and command -errors redact credential values while leaving benign settings such as model -names and base URLs readable. +`IMAGE_GENERATION_MODEL`. Run the skill's script in an isolated sandbox such as +Docker/AIO, the Kubernetes provisioner, or E2B, and pass the variables through +`sandbox.environment`. Sandbox commands do not inherit API keys from the Gateway +process. -For `LocalSandboxProvider`, this is a managed tool-path boundary rather than host filesystem isolation. Explicit per-Agent skill policies are accepted only while host bash is disabled (the default), because a host subprocess can address canonical paths without using the provider's virtual-path mappings. Use Docker/AIO, the Kubernetes provisioner, or E2B when the filesystem boundary must remain enforceable alongside shell access. - -When the local sandbox uses PowerShell, mapped host-path spaces and shell metacharacters are escaped for the caller's quoting context; wildcard expansion is preserved. The public `bash` tool's existing workspace prefix uses `&&` and POSIX path quoting: it requires PowerShell 7 for that separator and does not support workspace paths containing apostrophes. These workspace-prefix limitations are separate from virtual-path mapping. - -On Windows, the local sandbox's `cmd.exe` fallback decodes builtin output using -the console output code page, including UTF-8 after `chcp 65001`, independently -of Python's UTF-8 mode. If no console page is available, it uses the system OEM -page, with ANSI as a last resort. Native programs can choose a different output -encoding; configure those programs to match the console page when needed. +The local provider applies the skill view through its workspace file tools. +Script-based skills require an isolated sandbox provider on Windows as well. Managed integrations install shared read-only skill packs without mixing them into custom skills. The Lark/Feishu CLI integration is available under diff --git a/frontend/src/content/en/application/configuration.mdx b/frontend/src/content/en/application/configuration.mdx index 10ab40f1bd..aec70da700 100644 --- a/frontend/src/content/en/application/configuration.mdx +++ b/frontend/src/content/en/application/configuration.mdx @@ -185,7 +185,6 @@ Choose the execution environment for agent file and command operations: ```yaml sandbox: use: deerflow.sandbox.local:LocalSandboxProvider - allow_host_bash: false # set true only for trusted single-user workflows ``` diff --git a/frontend/src/content/en/application/operations-and-troubleshooting.mdx b/frontend/src/content/en/application/operations-and-troubleshooting.mdx index b9e5a24b44..a179ec77b5 100644 --- a/frontend/src/content/en/application/operations-and-troubleshooting.mdx +++ b/frontend/src/content/en/application/operations-and-troubleshooting.mdx @@ -103,7 +103,7 @@ Or set it in your `.env` file at the repo root. If file tools (`read_file`, `ls`, `bash`) fail with permission or path errors: -1. For `LocalSandboxProvider`: check that `allow_host_bash` is set correctly and that the agent has read/write access to the thread data directory. +1. For `LocalSandboxProvider`, check that the file tools can access the thread data directory. Switch to an isolated provider if you need Bash. 2. For container sandboxes: verify Docker (or Apple Container) is running and the sandbox image is accessible. 3. For K8s Provisioner: check that the provisioner service is healthy (`curl http://localhost:8002/health`) and that the K8s cluster is reachable. diff --git a/frontend/src/content/en/harness/design-principles.mdx b/frontend/src/content/en/harness/design-principles.mdx index 9b41abfd69..5a5eb08b1f 100644 --- a/frontend/src/content/en/harness/design-principles.mdx +++ b/frontend/src/content/en/harness/design-principles.mdx @@ -80,7 +80,7 @@ Isolation is important because execution should be reproducible and controllable Two modes are available: -- **LocalSandbox**: commands run directly on the host. Suitable for trusted, single-user local workflows. +- **LocalSandbox**: workspace file operations through dedicated tools. - **Container-based sandbox**: commands run in an isolated container (Docker or Apple Container). Suitable for multi-user environments and production deployments. ## Context engineering keeps long tasks tractable diff --git a/frontend/src/content/en/harness/sandbox.mdx b/frontend/src/content/en/harness/sandbox.mdx index 8e1b2ac756..070b836e69 100644 --- a/frontend/src/content/en/harness/sandbox.mdx +++ b/frontend/src/content/en/harness/sandbox.mdx @@ -21,15 +21,11 @@ DeerFlow supports four sandbox modes. Choose the one that fits your deployment: ### LocalSandbox (default) -Commands run directly on the host machine's filesystem. There is no container isolation. - -- **Best for**: trusted, single-user local development workflows. -- **Risk**: the agent has access to the host filesystem. Use `allow_host_bash: false` (default) to prevent arbitrary command execution. +The local provider serves workspace file operations through dedicated tools. ```yaml sandbox: use: deerflow.sandbox.local:LocalSandboxProvider - allow_host_bash: false # default; set to true only for fully trusted workflows ``` ### Container-based AIO Sandbox @@ -213,14 +209,7 @@ Set to `0` to disable truncation. ### LocalSandbox -The `LocalSandbox` runs commands directly on the host. By default, the `bash` tool is **disabled** to prevent arbitrary host command execution. Enable it only for fully trusted, single-user workflows: - -```yaml -sandbox: - allow_host_bash: true # Dangerous: grants the agent shell access to your machine -``` - -Even without `bash`, the agent can still read and write files through the dedicated file tools. +Use the local provider for workspace file operations. Bash requires an isolated provider. ### Container sandbox diff --git a/frontend/src/content/en/harness/skills.mdx b/frontend/src/content/en/harness/skills.mdx index 6ffd8f4662..9d99ee3dc6 100644 --- a/frontend/src/content/en/harness/skills.mdx +++ b/frontend/src/content/en/harness/skills.mdx @@ -136,10 +136,9 @@ skills: For a lead custom Agent, an explicit list is enforced in both discovery and the sandbox filesystem. `/mnt/skills` contains only the intersection of globally enabled, user-visible, and Agent-allowed skills. AIO and E2B enforce that view -for shell commands and file tools. Local enforces it through managed virtual -paths only while host bash is disabled (the default); its host filesystem is -not a security boundary, and enabling host bash makes an explicit Agent policy -fail closed. A different sandbox provider must advertise the same contract or +for shell commands and file tools. The local provider enforces it through +managed virtual paths for its file tools. A different sandbox provider must +advertise the same contract or an explicit policy fails closed before the run acquires a sandbox. Agent configuration changes take effect on the thread's next run. diff --git a/frontend/src/content/en/harness/subagents/catalog.mdx b/frontend/src/content/en/harness/subagents/catalog.mdx index 2185562dbd..ef7a97edfd 100644 --- a/frontend/src/content/en/harness/subagents/catalog.mdx +++ b/frontend/src/content/en/harness/subagents/catalog.mdx @@ -22,7 +22,7 @@ Both use the model `inherit`, meaning the Lead Agent's current model. Both deny - Not available without a `sandbox` section. - Available with any container sandbox (any non-local provider). -- Under the local sandbox it depends on `sandbox.allow_host_bash`, which defaults to `false`. Delegating to `bash` then returns an explicit failure explaining that the option should only be enabled in a fully trusted local environment. +- Bash delegation requires an isolated provider. The local provider serves workspace file tools. The `general-purpose` system prompt carries a `tool_restrictions` block stating that `task` is unavailable and that it must never spawn further subagents; when parallelism is needed it should use bash background processes or work sequentially. diff --git a/frontend/src/content/en/harness/subagents/quick-start.mdx b/frontend/src/content/en/harness/subagents/quick-start.mdx index e3a0b0a841..752da73e89 100644 --- a/frontend/src/content/en/harness/subagents/quick-start.mdx +++ b/frontend/src/content/en/harness/subagents/quick-start.mdx @@ -12,7 +12,7 @@ This chapter is for people using DeerFlow through the web interface. By the end ## Prerequisites - DeerFlow is configured per [Quick Start](/docs/application/quick-start) and you can chat normally. The `subagents:` section in `config.yaml` can stay empty; the built-in defaults work. -- To use the `bash` subagent you need a container sandbox, or `sandbox.allow_host_bash: true` under the local sandbox, which is only appropriate in a fully trusted local environment. Otherwise `bash` is hidden from the catalog. +- Use an isolated sandbox provider to enable the `bash` subagent. diff --git a/frontend/src/content/en/harness/subagents/reference.mdx b/frontend/src/content/en/harness/subagents/reference.mdx index 90fd163d0c..7610eb838b 100644 --- a/frontend/src/content/en/harness/subagents/reference.mdx +++ b/frontend/src/content/en/harness/subagents/reference.mdx @@ -39,7 +39,6 @@ description: Quick reference for subagent configuration keys, request context ke | `tool_search.enabled` / `auto_promote_top_k` | | Deferred MCP tool loading | | `token_usage.enabled` | true | Whether cards show tokens | | `agent_storage.backend` | `file` | Where managed subagents are stored, `file` or `db` | -| `sandbox.allow_host_bash` | false | Whether the `bash` subagent is available under the local sandbox | | `sandbox.environment.MAX_SHELL_SESSIONS` | image default 10 | Must be at least `subagent_runtime.max_running + 1` | | Environment variable `DEER_FLOW_DATE_TIMEZONE` | server timezone | IANA zone used for the `current_date` reminder | diff --git a/frontend/src/content/en/harness/subagents/sandbox.mdx b/frontend/src/content/en/harness/subagents/sandbox.mdx index ef123902dd..6ee02868c2 100644 --- a/frontend/src/content/en/harness/subagents/sandbox.mdx +++ b/frontend/src/content/en/harness/subagents/sandbox.mdx @@ -43,9 +43,9 @@ The `bash` subagent enters the catalog only when `is_host_bash_allowed()` is tru | --------------------------- | --------------------------------------------------------- | | No `sandbox` section | Not available | | Container or remote provider | Available | -| `LocalSandboxProvider` | Depends on `sandbox.allow_host_bash`, default `false` | +| `LocalSandboxProvider` | File tools only | -Delegating to `bash` under the local sandbox returns an explicit failure explaining that the subagent is disabled and that `allow_host_bash` belongs only in a fully trusted local environment. +Use an isolated provider to delegate to `bash`. ## Identity propagation into commands diff --git a/frontend/src/content/en/harness/subagents/troubleshooting.mdx b/frontend/src/content/en/harness/subagents/troubleshooting.mdx index 26f97fb9bf..3886c72262 100644 --- a/frontend/src/content/en/harness/subagents/troubleshooting.mdx +++ b/frontend/src/content/en/harness/subagents/troubleshooting.mdx @@ -76,7 +76,7 @@ Check in order: ### `Bash subagent is disabled for LocalSandboxProvider` -The local sandbox does not allow host command execution by default. Set `sandbox.allow_host_bash: true` only in a fully trusted local environment, or switch to a container sandbox. +Switch to an isolated sandbox provider to enable command execution. ### A subagent reports `Error: task is not a valid tool` diff --git a/frontend/src/content/en/harness/tools.mdx b/frontend/src/content/en/harness/tools.mdx index fe0794bea1..1869fae098 100644 --- a/frontend/src/content/en/harness/tools.mdx +++ b/frontend/src/content/en/harness/tools.mdx @@ -92,7 +92,7 @@ The following tools interact with the sandbox filesystem. They require a sandbox | `grep` | Search file contents | | `write_file` | Write content to a file | | `str_replace` | Replace a string in a file | -| `bash` | Execute a shell command (requires `allow_host_bash: true` or a container sandbox) | +| `bash` | Execute a shell command in an isolated sandbox | These are configured in `config.yaml` under `tools:`: diff --git a/frontend/src/content/zh/application/configuration.mdx b/frontend/src/content/zh/application/configuration.mdx index 1c7849d54e..87b1e2b4db 100644 --- a/frontend/src/content/zh/application/configuration.mdx +++ b/frontend/src/content/zh/application/configuration.mdx @@ -174,7 +174,6 @@ models: # 本地开发(默认) sandbox: use: deerflow.sandbox.local:LocalSandboxProvider - allow_host_bash: false # 基于容器(推荐用于多用户) sandbox: diff --git a/frontend/src/content/zh/harness/sandbox.mdx b/frontend/src/content/zh/harness/sandbox.mdx index ab216a4343..0ea05fecbc 100644 --- a/frontend/src/content/zh/harness/sandbox.mdx +++ b/frontend/src/content/zh/harness/sandbox.mdx @@ -20,15 +20,11 @@ DeerFlow 支持四种沙箱模式,选择适合你部署的一种: ### LocalSandbox(默认) -命令直接在主机机器的文件系统上运行,没有容器隔离。 - -- **适合**:受信任的单用户本地开发工作流。 -- **风险**:Agent 可以访问主机文件系统。默认使用 `allow_host_bash: false` 防止任意命令执行。 +本地提供器通过专用文件工具处理工作区文件。 ```yaml sandbox: use: deerflow.sandbox.local:LocalSandboxProvider - allow_host_bash: false # 默认;仅对完全受信任的工作流设置为 true ``` ### 基于容器的 AIO 沙箱 @@ -201,14 +197,7 @@ sandbox: ### LocalSandbox -`LocalSandbox` 直接在主机上运行命令。默认情况下,`bash` 工具**被禁用**以防止任意主机命令执行。仅对完全受信任的单用户工作流启用它: - -```yaml -sandbox: - allow_host_bash: true # 危险:授予 Agent 对你机器的 Shell 访问权限 -``` - -即使没有 `bash`,Agent 也可以通过专用文件工具读写文件。 +本地提供器用于工作区文件操作。运行 Bash 命令需要使用隔离沙箱。 ### 容器沙箱 diff --git a/frontend/src/content/zh/harness/skills.mdx b/frontend/src/content/zh/harness/skills.mdx index 99fb90fc35..f57c20d6ed 100644 --- a/frontend/src/content/zh/harness/skills.mdx +++ b/frontend/src/content/zh/harness/skills.mdx @@ -128,11 +128,11 @@ skills: - **命名列表**:Agent 只加载那些特定技能。 对于作为主 Agent 运行的自定义 Agent,显式列表会同时约束技能发现和沙箱文件系统。 -`/mnt/skills` 只包含“全局已启用、当前用户可见、Agent 已允许”三者的交集。AIO 和 -E2B 会对 shell 命令及文件工具强制执行该视图。Local 仅在 host bash 保持默认禁用时, -通过受管理的虚拟路径执行该视图;主机文件系统并不是安全边界,启用 host bash 后, -显式 Agent 策略会失败关闭。其他 sandbox provider 若未声明支持,显式策略会在获取 -沙箱前失败关闭。Agent 配置变更会在该线程的下一次运行生效。 +`/mnt/skills` 只包含全局已启用、当前用户可见且 Agent 已获准使用的技能。AIO 和 +E2B 会对 Shell 命令和文件工具应用这一范围。LocalSandboxProvider 通过受管理的虚拟路径 +为工作区文件工具应用同一范围。需要运行技能脚本时,请使用 AIO 或 E2B 等隔离沙箱。 +如果沙箱提供器未声明支持这一约束,显式技能策略会在获取沙箱前拒绝运行。 +Agent 配置变更会在该线程的下一次运行生效。 ## 技能进化 diff --git a/frontend/src/content/zh/harness/subagents/catalog.mdx b/frontend/src/content/zh/harness/subagents/catalog.mdx index 19b750f07c..a265169386 100644 --- a/frontend/src/content/zh/harness/subagents/catalog.mdx +++ b/frontend/src/content/zh/harness/subagents/catalog.mdx @@ -22,7 +22,7 @@ import { Callout } from "nextra/components"; - 没有 `sandbox` 配置时不可用。 - 使用容器沙箱(任何非本地 provider)时可用。 -- 使用本地沙箱时取决于 `sandbox.allow_host_bash`,默认为 `false`。此时委派 `bash` 会得到一条明确的失败结果,提示只在完全可信的本地环境里开启该选项。 +- 委派 Bash 任务需要隔离沙箱。本地提供器用于工作区文件操作。 `general-purpose` 的系统提示里有一段 `tool_restrictions`,明确告诉它 `task` 不可用、不得再派生子 Agent;需要并行时用 bash 后台进程或顺序执行。 diff --git a/frontend/src/content/zh/harness/subagents/quick-start.mdx b/frontend/src/content/zh/harness/subagents/quick-start.mdx index 5e5644da7e..184c409b0e 100644 --- a/frontend/src/content/zh/harness/subagents/quick-start.mdx +++ b/frontend/src/content/zh/harness/subagents/quick-start.mdx @@ -12,7 +12,7 @@ import { Callout, Steps } from "nextra/components"; ## 前提 - 已按[快速上手](/docs/application/quick-start)完成配置并能正常对话。`config.yaml` 里的 `subagents:` 段可以完全留空,内置默认值即可使用。 -- 想用 `bash` 子 Agent,需要配置容器沙箱;或者在本地沙箱下显式设置 `sandbox.allow_host_bash: true`,这只适合完全可信的本地环境。否则目录会隐藏 `bash`。 +- 使用隔离沙箱可启用 `bash` 子 Agent。 diff --git a/frontend/src/content/zh/harness/subagents/reference.mdx b/frontend/src/content/zh/harness/subagents/reference.mdx index bead7ce244..63a20fff5b 100644 --- a/frontend/src/content/zh/harness/subagents/reference.mdx +++ b/frontend/src/content/zh/harness/subagents/reference.mdx @@ -39,7 +39,6 @@ description: 子 Agent 相关的配置键、请求上下文键、工具签名、 | `tool_search.enabled` / `auto_promote_top_k` | | 延迟加载 MCP 工具 | | `token_usage.enabled` | true | 卡片是否显示 token | | `agent_storage.backend` | `file` | 设置页管理的子 Agent 存储位置,`file` 或 `db` | -| `sandbox.allow_host_bash` | false | 本地沙箱下 `bash` 子 Agent 是否可用 | | `sandbox.environment.MAX_SHELL_SESSIONS` | 镜像默认 10 | 须不小于 `subagent_runtime.max_running + 1` | | 环境变量 `DEER_FLOW_DATE_TIMEZONE` | 服务器时区 | `current_date` 提醒使用的 IANA 时区 | diff --git a/frontend/src/content/zh/harness/subagents/sandbox.mdx b/frontend/src/content/zh/harness/subagents/sandbox.mdx index 4d6d6267d7..8d3c45abbb 100644 --- a/frontend/src/content/zh/harness/subagents/sandbox.mdx +++ b/frontend/src/content/zh/harness/subagents/sandbox.mdx @@ -43,9 +43,9 @@ AIO 镜像默认最多 10 个 shell 会话(`MAX_SHELL_SESSIONS`),超出时 | -------------------------- | --------------------------------------------- | | 没有 `sandbox` 段 | 不可用 | | 容器或远端 provider | 可用 | -| `LocalSandboxProvider` | 取决于 `sandbox.allow_host_bash`,默认 `false` | +| `LocalSandboxProvider` | 仅提供文件工具 | -在本地沙箱下委派 `bash` 会得到一条明确的失败结果,说明该子 Agent 被禁用、只应在完全可信的本地环境里开启 `allow_host_bash`。 +委派 `bash` 任务需要使用隔离沙箱。 ## 身份传播到命令 diff --git a/frontend/src/content/zh/harness/subagents/troubleshooting.mdx b/frontend/src/content/zh/harness/subagents/troubleshooting.mdx index a4e72fa7b0..e56b858b55 100644 --- a/frontend/src/content/zh/harness/subagents/troubleshooting.mdx +++ b/frontend/src/content/zh/harness/subagents/troubleshooting.mdx @@ -76,7 +76,7 @@ import { Callout } from "nextra/components"; ### `Bash subagent is disabled for LocalSandboxProvider` -本地沙箱默认不允许在宿主机执行命令。只在完全可信的本地环境里设置 `sandbox.allow_host_bash: true`,否则改用容器沙箱。 +切换到隔离沙箱即可启用命令执行。 ### 子 Agent 报 `Error: task is not a valid tool` diff --git a/frontend/src/content/zh/harness/tools.mdx b/frontend/src/content/zh/harness/tools.mdx index 6565ebc076..d990c6edd4 100644 --- a/frontend/src/content/zh/harness/tools.mdx +++ b/frontend/src/content/zh/harness/tools.mdx @@ -89,7 +89,7 @@ task(agent="general-purpose", task="...", context="...") | `grep` | 搜索文件内容 | | `write_file` | 向文件写入内容 | | `str_replace` | 替换文件中的字符串 | -| `bash` | 执行 Shell 命令(需要 `allow_host_bash: true` 或容器沙箱) | +| `bash` | 在隔离沙箱中执行 Shell 命令 | 在 `config.yaml` 的 `tools:` 下配置: diff --git a/scripts/doctor.py b/scripts/doctor.py index e3fcdc7047..c71f51ab01 100644 --- a/scripts/doctor.py +++ b/scripts/doctor.py @@ -963,24 +963,13 @@ def check_sandbox(config_path: Path) -> list[CheckResult]: if "LocalSandboxProvider" in sandbox_use: results.append(CheckResult("sandbox configured", "ok", "Local sandbox")) - has_bash_tool = "bash" in tool_names - allow_host_bash = bool(sandbox.get("allow_host_bash", False)) - if has_bash_tool and not allow_host_bash: + if "bash" in tool_names or sandbox.get("allow_host_bash"): results.append( CheckResult( "bash compatibility", "warn", - "bash tool configured but host bash is disabled", - fix="Enable host bash only in a fully trusted environment, or switch to container sandbox", - ) - ) - elif allow_host_bash: - results.append( - CheckResult( - "bash compatibility", - "warn", - "host bash enabled on LocalSandboxProvider", - fix="Use container sandbox for stronger isolation when bash is required", + "local sandbox supports workspace file tools", + fix="Select an isolated sandbox provider to use Bash", ) ) elif "AioSandboxProvider" in sandbox_use: diff --git a/scripts/setup_wizard.py b/scripts/setup_wizard.py index 6aec09363a..1997b9fa32 100644 --- a/scripts/setup_wizard.py +++ b/scripts/setup_wizard.py @@ -100,7 +100,6 @@ def main() -> int: web_fetch_tool_name=fetch_provider.tool_name if fetch_provider else "web_fetch", web_fetch_extra_config=fetch_provider.extra_config if fetch_provider else None, sandbox_use=execution.sandbox_use, - allow_host_bash=execution.allow_host_bash, include_bash_tool=execution.include_bash_tool, include_write_tools=execution.include_write_tools, channel_connection_providers=channels.enabled_providers, @@ -147,10 +146,7 @@ def main() -> int: sandbox_label = "Local sandbox" if execution.sandbox_use.endswith("LocalSandboxProvider") else "Container sandbox" print(f" {green('✓')} Execution: {sandbox_label}") if execution.include_bash_tool: - bash_label = "enabled" - if execution.allow_host_bash: - bash_label += " (host bash)" - print(f" {green('✓')} Bash: {bash_label}") + print(f" {green('✓')} Bash: enabled") else: print(f" {'—':>3} Bash: disabled") if execution.include_write_tools: diff --git a/scripts/wizard/steps/execution.py b/scripts/wizard/steps/execution.py index 79b140ade3..04ea1d1407 100644 --- a/scripts/wizard/steps/execution.py +++ b/scripts/wizard/steps/execution.py @@ -4,7 +4,7 @@ from __future__ import annotations from dataclasses import dataclass -from wizard.ui import ask_choice, ask_yes_no, print_header, print_info, print_warning +from wizard.ui import ask_choice, ask_yes_no, print_header, print_info LOCAL_SANDBOX = "deerflow.sandbox.local:LocalSandboxProvider" CONTAINER_SANDBOX = "deerflow.community.aio_sandbox:AioSandboxProvider" @@ -13,7 +13,6 @@ CONTAINER_SANDBOX = "deerflow.community.aio_sandbox:AioSandboxProvider" @dataclass class ExecutionStepResult: sandbox_use: str - allow_host_bash: bool include_bash_tool: bool include_write_tools: bool @@ -23,29 +22,25 @@ def run_execution_step(step_label: str = "Step 3/4") -> ExecutionStepResult: print_info("Choose how much execution power DeerFlow should have in this workspace.") options = [ - "Local sandbox — fastest, uses host filesystem paths", + "Local sandbox — workspace file tools", "Container sandbox — more isolated, requires Docker or Apple Container", ] sandbox_idx = ask_choice("Execution mode", options, default=0) sandbox_use = LOCAL_SANDBOX if sandbox_idx == 0 else CONTAINER_SANDBOX print() - if sandbox_use == LOCAL_SANDBOX: - print_warning( - "Local sandbox is convenient but not a secure shell isolation boundary." - ) - print_info("Keep host bash disabled unless this is a fully trusted local workflow.") + include_bash_tool = False + if sandbox_use == CONTAINER_SANDBOX: + include_bash_tool = ask_yes_no("Enable bash command execution?", default=False) else: - print_info("Container sandbox isolates shell execution better than host-local mode.") + print_info("Choose a container sandbox to use Bash.") - include_bash_tool = ask_yes_no("Enable bash command execution?", default=False) include_write_tools = ask_yes_no( "Enable file write tools (write_file, str_replace)?", default=True ) return ExecutionStepResult( sandbox_use=sandbox_use, - allow_host_bash=sandbox_use == LOCAL_SANDBOX and include_bash_tool, include_bash_tool=include_bash_tool, include_write_tools=include_write_tools, ) diff --git a/scripts/wizard/writer.py b/scripts/wizard/writer.py index 6be332a0b5..cf289967ec 100644 --- a/scripts/wizard/writer.py +++ b/scripts/wizard/writer.py @@ -189,7 +189,6 @@ def build_minimal_config( web_fetch_tool_name: str = "web_fetch", web_fetch_extra_config: dict | None = None, sandbox_use: str = "deerflow.sandbox.local:LocalSandboxProvider", - allow_host_bash: bool = False, include_bash_tool: bool = False, include_write_tools: bool = True, channel_connection_providers: list[str] | None = None, @@ -231,16 +230,13 @@ def build_minimal_config( web_fetch_use=web_fetch_use, web_fetch_tool_name=web_fetch_tool_name, web_fetch_extra_config=web_fetch_extra_config, - include_bash_tool=include_bash_tool, + include_bash_tool=include_bash_tool and not sandbox_use.endswith(":LocalSandboxProvider"), include_write_tools=include_write_tools, ) data["tools"] = tools sandbox_config = deepcopy(data.get("sandbox") if isinstance(data.get("sandbox"), dict) else {}) sandbox_config["use"] = sandbox_use - if sandbox_use == "deerflow.sandbox.local:LocalSandboxProvider": - sandbox_config["allow_host_bash"] = allow_host_bash - else: - sandbox_config.pop("allow_host_bash", None) + sandbox_config.pop("allow_host_bash", None) data["sandbox"] = sandbox_config if channel_connection_providers is not None: data["channel_connections"] = _build_channel_connections_config(channel_connection_providers) @@ -272,7 +268,6 @@ def write_config_yaml( web_fetch_tool_name: str = "web_fetch", web_fetch_extra_config: dict | None = None, sandbox_use: str = "deerflow.sandbox.local:LocalSandboxProvider", - allow_host_bash: bool = False, include_bash_tool: bool = False, include_write_tools: bool = True, channel_connection_providers: list[str] | None = None, @@ -307,7 +302,6 @@ def write_config_yaml( web_fetch_tool_name=web_fetch_tool_name, web_fetch_extra_config=web_fetch_extra_config, sandbox_use=sandbox_use, - allow_host_bash=allow_host_bash, include_bash_tool=include_bash_tool, include_write_tools=include_write_tools, channel_connection_providers=channel_connection_providers,