Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Refine agent terminal sandbox off-switch and expand WSL env blocklist (#59520)

MartinYe1234037f32aef010
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 5705b3e23cd..0bf2f0e49fb 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -3542,6 +3542,34 @@ impl AcpThread {
};
(task_command, task_args, sandbox_config, None)
} else {
+ // No sandbox wrap means we're running unsandboxed, and
+ // on Windows that deliberately changes the shell: the
+ // sandboxed path runs under WSL's Linux bash, but this
+ // fallback uses the host's `shell` (resolved above via
+ // `get_default_system_shell_preferring_bash`) against
+ // the native cwd. That resolution prefers Git Bash (or
+ // scoop's bash), only dropping to the native Windows
+ // shell (PowerShell/cmd) when no bash is installed — so
+ // the interpreter usually stays bash-compatible, but its
+ // path conventions differ from WSL's (e.g. `/c/...` or
+ // native `C:\...` rather than `/mnt/c/...`). This is
+ // unlike Linux/macOS, where the unsandboxed path (the
+ // `#[cfg(not(target_os = "windows"))]` block below)
+ // reuses the exact same shell and merely omits the bwrap
+ // wrapper, so shell semantics are preserved untouched.
+ //
+ // The shell switch is intentional on Windows. The only
+ // ways to reach this branch are: the model asking for
+ // `unsandboxed: true` (often to run a Windows program),
+ // the user choosing "run unsandboxed" after a sandbox-
+ // creation failure, the `allow_unsandboxed` setting, or a
+ // per-thread fallback grant. For the fallback cases the
+ // command isn't one the model chose to run unsandboxed,
+ // so the terminal tool's `sandbox_not_applied` note
+ // warns it that the command ran without a sandbox *and*,
+ // on Windows, that the shell and its path conventions
+ // changed too (see `sandbox_note` in the terminal tool),
+ // so it can adapt a command written for WSL.
let (task_command, task_args) =
ShellBuilder::new(&Shell::Program(shell), is_windows)
.redirect_stdin_to_dev_null()
@@ -3549,6 +3577,12 @@ impl AcpThread {
(task_command, task_args, None, cwd.clone())
};
+ // On Linux/macOS the same shell (`/bin/sh`) is used whether or
+ // not we sandbox: `ShellBuilder` builds the command, and
+ // `apply_sandbox_wrap` either wraps it in bwrap (`Some`) or
+ // returns it untouched (`None`). Either way the interpreter is
+ // identical, so the unsandboxed fallback keeps shell semantics
+ // intact — unlike Windows, which falls back to the host shell.
#[cfg(not(target_os = "windows"))]
let (task_command, task_args, sandbox_config, spawn_cwd) = {
let (task_command, task_args) =
diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs
index 1d491dbc627..d3e6a7bbfe4 100644
--- a/crates/acp_thread/src/terminal.rs
+++ b/crates/acp_thread/src/terminal.rs
@@ -178,9 +178,6 @@ impl SandboxWrap {
/// grow their own failure cases later without a migration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SandboxNotAppliedReason {
- /// Unsandboxed execution is permanently allowed via the `allow_unsandboxed`
- /// setting.
- DisabledForever,
/// The user allowed unsandboxed execution for the rest of this thread after
/// an earlier sandbox failure. There is always a preceding tool call whose
/// reason is [`SandboxNotAppliedReason::ErrorLinuxWsl`].
diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs
index be32c552655..2ea5dcf3e70 100644
--- a/crates/agent/src/sandboxing.rs
+++ b/crates/agent/src/sandboxing.rs
@@ -7,9 +7,15 @@
//!
//! The current policy is: enabled iff the user has the `sandboxing` feature
//! flag turned on, the project is local, the platform has an integration, and
-//! the user has not turned sandboxing off entirely (the `disabled` sandbox
-//! setting; the `allow_unsandboxed` grant only auto-approves commands that
-//! explicitly request to run unsandboxed and doesn't turn the sandbox off).
+//! the user has not persistently allowed unsandboxed execution (the
+//! `allow_unsandboxed` sandbox setting). Setting `allow_unsandboxed`
+//! persistently turns sandboxing off for the model-facing surface entirely:
+//! the plain (non-sandboxed) `terminal` tool is exposed and the system prompt
+//! omits the sandbox section, since every command would run without a wrap
+//! anyway. The model-requested `unsandboxed: true` escape approved "once" or
+//! "for this thread" does NOT change the prompt/tool set — the sandboxed tool
+//! stays exposed and only the individual command runs without a wrap. See
+//! `sandboxing_enabled_for_project` and `ThreadSandboxGrants`.
//!
//! macOS (Seatbelt), Linux (Bubblewrap), and Windows (Bubblewrap via WSL)
//! have real sandbox integrations; on platforms without one the per-command
@@ -34,10 +40,21 @@ pub(crate) fn sandboxing_enabled(cx: &App) -> bool {
}
/// Whether the sandboxed terminal can be exposed for this project.
+///
+/// The persistent `allow_unsandboxed` setting turns sandboxing off for the
+/// model-facing surface: when it's set we expose the plain `terminal` tool and
+/// omit the sandbox section from the system prompt, because every command would
+/// run without a wrap regardless. This is deliberately keyed off the
+/// *persistent* setting only. A model-requested `unsandboxed: true` escape that
+/// the user approves "once" or "for this thread" keeps the sandboxed tool and
+/// prompt in place, since the model is still operating in the sandbox model and
+/// only escaping individual commands (tracked in `ThreadSandboxGrants`).
pub(crate) fn sandboxing_enabled_for_project(project: &Project, cx: &App) -> bool {
sandboxing_enabled(cx)
&& project.is_local()
- && !AgentSettings::get_global(cx).sandbox_permissions.disabled
+ && !AgentSettings::get_global(cx)
+ .sandbox_permissions
+ .allow_unsandboxed
&& cfg!(any(
target_os = "macos",
target_os = "linux",
@@ -152,7 +169,14 @@ impl ThreadSandboxGrants {
persistent: &SandboxPermissions,
) -> bool {
if request.unsandboxed {
- return self.unsandboxed || persistent.allow_unsandboxed;
+ // The persistent `allow_unsandboxed` setting is intentionally not
+ // consulted here: when it's set, sandboxing is removed from the
+ // model-facing surface (the plain `terminal` tool is exposed
+ // instead of the sandboxed one), so the model can't issue an
+ // `unsandboxed: true` request at all. Only a "for this thread"
+ // grant suppresses the re-prompt while the sandboxed tool is
+ // active — see `sandboxing_enabled_for_project`.
+ return self.unsandboxed;
}
if !self.network_covered(&request.network, persistent) {
return false;
@@ -572,21 +596,34 @@ mod tests {
}
#[test]
- fn persistent_unsandboxed_covers_unsandboxed_requests_only() {
+ fn thread_grant_covers_unsandboxed_requests() {
+ // A "for this thread" grant suppresses the re-prompt for later
+ // `unsandboxed: true` requests within the same thread.
+ let mut grants = ThreadSandboxGrants::default();
+ assert!(!covers(&grants, &unsandboxed_request()));
+ grants.record(&unsandboxed_request());
+ assert!(covers(&grants, &unsandboxed_request()));
+
+ // A thread-wide unsandboxed grant only covers unsandboxed requests; it
+ // does not widen network or filesystem scope.
+ assert!(!covers(
+ &grants,
+ &request(NetworkRequest::AnyHost, false, &[])
+ ));
+ assert!(!covers(&grants, &request(NetworkRequest::None, true, &[])));
+ }
+
+ #[test]
+ fn persistent_allow_unsandboxed_does_not_cover_here() {
+ // The persistent setting is handled by removing the sandboxed tool (see
+ // `sandboxing_enabled_for_project`), not by covering requests, so on
+ // its own it never makes an `unsandboxed: true` request "covered".
let grants = ThreadSandboxGrants::default();
let persistent = SandboxPermissions {
allow_unsandboxed: true,
..Default::default()
};
-
- assert!(grants.covers_with_persistent(&unsandboxed_request(), &persistent));
- assert!(
- !grants
- .covers_with_persistent(&request(NetworkRequest::AnyHost, false, &[]), &persistent)
- );
- assert!(
- !grants.covers_with_persistent(&request(NetworkRequest::None, true, &[]), &persistent)
- );
+ assert!(!grants.covers_with_persistent(&unsandboxed_request(), &persistent));
}
#[test]
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index 0de7df5251a..93706a10d83 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -289,7 +289,7 @@ fn always_allow_tools(cx: &mut TestAppContext) {
fn disable_sandboxing(cx: &mut TestAppContext) {
cx.update(|cx| {
let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
- settings.sandbox_permissions.disabled = true;
+ settings.sandbox_permissions.allow_unsandboxed = true;
agent_settings::AgentSettings::override_global(settings, cx);
});
}
diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs
index cbd2b9a2e1c..f0045aa479c 100644
--- a/crates/agent/src/thread.rs
+++ b/crates/agent/src/thread.rs
@@ -5729,8 +5729,10 @@ impl ToolCallEventStream {
})
}
- /// Persist the `allow_unsandboxed` setting so future commands skip the
- /// sandbox when it can't be created, without prompting again.
+ /// Persist the `allow_unsandboxed` setting. Going forward this turns
+ /// sandboxing off for the model-facing surface: later turns expose the
+ /// plain `terminal` tool (with no sandbox prompt section) and commands run
+ /// without an OS sandbox. On Windows, WSL sandbox setup is skipped.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn persist_sandbox_unsandboxed_permission(fs: Option<Arc<dyn Fs>>, cx: &AsyncApp) {
let Some(fs) = fs else {
diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs
index 61c0ee47cc5..5590a524824 100644
--- a/crates/agent/src/tools/terminal_tool.rs
+++ b/crates/agent/src/tools/terminal_tool.rs
@@ -115,11 +115,11 @@ pub struct SandboxedTerminalToolInput {
`https://` URLs rather than `git@`/`ssh://`."
)]
#[cfg_attr(
- target_os = "linux",
- doc = "\nNOTE: on Linux the sandbox cannot restrict network access to specific \
- hosts. Any value here grants the command unrestricted outbound network access \
- (exactly like `allow_all_hosts`), and the user is asked to approve access to \
- all hosts rather than the ones you list. Prefer setting `allow_all_hosts` \
+ any(target_os = "linux", target_os = "windows"),
+ doc = "\nNOTE: on Linux and Windows the sandbox cannot restrict network access to \
+ specific hosts. Any value here grants the command unrestricted outbound network \
+ access (exactly like `allow_all_hosts`), and the user is asked to approve access \
+ to all hosts rather than the ones you list. Prefer setting `allow_all_hosts` \
directly when per-host restriction isn't available."
)]
#[serde(default)]
@@ -168,6 +168,15 @@ pub struct SandboxedTerminalToolInput {
/// `allow_fs_write_all`); use this only when the command needs behavior
/// the sandbox can't grant on a per-permission basis. Requesting it
/// triggers a user approval prompt.
+ #[cfg_attr(
+ target_os = "windows",
+ doc = "\nOn Windows, running unsandboxed also switches the shell. Sandboxed \
+ commands run under WSL's Linux bash; an unsandboxed command instead runs in the \
+ host's default shell — Git Bash (or scoop's bash) when one is installed, otherwise \
+ PowerShell/cmd. Path conventions change accordingly (e.g. `C:\\...` or `/c/...` \
+ rather than WSL's `/mnt/c/...`), so a command written for the sandboxed shell may \
+ behave differently here."
+ )]
#[serde(default)]
pub unsandboxed: Option<bool>,
/// A short justification for why this command needs the sandbox
@@ -474,6 +483,13 @@ async fn run_terminal_tool(
// create the sandbox it aborts. As the consumer we may still run the command
// without a sandbox (when the user has opted into that), but we record
// *why* in `sandbox_not_applied` so we can warn the user and tell the agent.
+ // Only the Linux/Windows sandbox-creation fallbacks (and the matching
+ // "for this thread" grant) ever reassign this, so on other platforms the
+ // binding stays `None` and wouldn't need `mut`.
+ #[cfg_attr(
+ not(any(target_os = "linux", target_os = "windows")),
+ allow(unused_mut)
+ )]
let mut sandbox_not_applied: Option<acp_thread::SandboxNotAppliedReason> = None;
let sandbox_wrap = if sandboxing && !want_unsandboxed {
let sandbox_permissions = cx.update(|cx| {
@@ -482,13 +498,7 @@ async fn run_terminal_tool(
.clone()
});
- if sandbox_permissions.allow_unsandboxed {
- // Unsandboxed execution is permanently allowed in settings: skip
- // the sandbox machinery entirely and run the command the same way
- // the unsandboxed terminal tool does.
- sandbox_not_applied = Some(acp_thread::SandboxNotAppliedReason::DisabledForever);
- None
- } else if event_stream.sandbox_fallback_granted_for_thread() {
+ if event_stream.sandbox_fallback_granted_for_thread() {
// The user allowed unsandboxed execution for the rest of this
// thread after an earlier sandbox failure (Linux and Windows, which
// share the `authorize_sandbox_fallback` flow).
@@ -698,22 +708,41 @@ async fn run_terminal_tool(
// chose to run through), tell the agent so it can account for the weaker
// isolation. Computed here — after the Windows fallback above may have set
// the reason — so every affected command communicates the state.
- let sandbox_note = sandbox_not_applied.as_ref().map(|reason| match reason {
- acp_thread::SandboxNotAppliedReason::DisabledForever => {
- "Note: this command ran WITHOUT an OS sandbox because unsandboxed execution is \
- enabled in settings."
- .to_string()
- }
- acp_thread::SandboxNotAppliedReason::DisabledForThisThread => {
- "Note: this command ran WITHOUT an OS sandbox because you allowed unsandboxed \
- execution for the rest of this thread."
- .to_string()
+ let sandbox_note = sandbox_not_applied.as_ref().map(|reason| {
+ // Only the Windows-specific block below mutates this; on other
+ // platforms the note is returned exactly as built.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_mut))]
+ let mut note = match reason {
+ acp_thread::SandboxNotAppliedReason::DisabledForThisThread => {
+ "Note: this command ran WITHOUT an OS sandbox because the user allowed unsandboxed \
+ execution for the rest of this thread."
+ .to_string()
+ }
+ acp_thread::SandboxNotAppliedReason::ErrorLinuxWsl(error) => format!(
+ "Note: this command ran WITHOUT an OS sandbox because one could not be \
+ created ({}).",
+ error.user_facing_message()
+ ),
+ };
+ // On Windows, running without a sandbox also changes the interpreter:
+ // the sandboxed path runs the command under WSL's Linux shell, but
+ // every unsandboxed path that reaches here falls back to the host
+ // shell (Git Bash, or PowerShell/cmd when no bash is installed) against
+ // native Windows paths. The model writes commands for the WSL/Linux
+ // sandbox, so the loss of isolation isn't the whole story — warn it
+ // that the shell and path conventions differ too, or a command that
+ // worked sandboxed may silently misbehave or fail here.
+ #[cfg(target_os = "windows")]
+ {
+ note.push(' ');
+ note.push_str(
+ "It also ran under the host shell (Git Bash, or PowerShell/cmd when no bash is \
+ installed) instead of WSL's Linux shell, so the interpreter and path \
+ conventions differ from the sandbox: Linux-only commands and `/mnt/...` paths \
+ may fail. Rewrite the command for the host shell if it doesn't work.",
+ );
}
- acp_thread::SandboxNotAppliedReason::ErrorLinuxWsl(error) => format!(
- "Note: I tried to run this command inside an OS sandbox, but it could not be \
- created ({}). It ran WITHOUT a sandbox.",
- error.user_facing_message()
- ),
+ note
});
let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?;
diff --git a/crates/agent_settings/src/agent_settings.rs b/crates/agent_settings/src/agent_settings.rs
index 4288006d7a1..90bec446400 100644
--- a/crates/agent_settings/src/agent_settings.rs
+++ b/crates/agent_settings/src/agent_settings.rs
@@ -422,12 +422,14 @@ pub struct SandboxPermissions {
/// consumed (`agent::sandboxing`).
pub network_hosts: Vec<String>,
pub allow_fs_write_all: bool,
- /// Auto-approve commands that request `unsandboxed: true`. Unlike
- /// `disabled`, the sandbox stays on for commands that don't ask.
+ /// Persistently run agent terminal commands outside the OS sandbox. This is
+ /// the model-facing "off switch": when set, the sandboxed terminal tool is
+ /// not exposed and the system prompt omits the sandbox section, so the
+ /// model uses the plain `terminal` tool (on Windows, WSL sandbox setup is
+ /// skipped). Distinct from the model-requested `unsandboxed: true` escape
+ /// approved "once" or "for this thread", which keeps the sandboxed
+ /// tool/prompt in place — see `agent::sandboxing`.
pub allow_unsandboxed: bool,
- /// Turn terminal sandboxing off entirely: the sandboxed terminal tool is
- /// not exposed and every command runs outside the sandbox.
- pub disabled: bool,
pub write_paths: Vec<PathBuf>,
}
@@ -814,7 +816,6 @@ fn compile_sandbox_permissions(
network_hosts,
allow_fs_write_all: content.allow_fs_write_all.unwrap_or(false),
allow_unsandboxed: content.allow_unsandboxed.unwrap_or(false),
- disabled: content.disabled.unwrap_or(false),
write_paths,
}
}
@@ -1118,9 +1119,6 @@ mod tests {
);
assert!(!permissions.allow_fs_write_all);
assert!(permissions.allow_unsandboxed);
- // `allow_unsandboxed` is a per-request grant; it must not imply that
- // sandboxing is disabled.
- assert!(!permissions.disabled);
assert_eq!(
permissions.write_paths,
vec![PathBuf::from("/tmp/build"), PathBuf::from("/var/log")]
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 118ceeb325f..0c77d89a816 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -7211,7 +7211,7 @@ impl ThreadView {
.child(command_element),
)
.when_some(tool_call.sandbox_not_applied.as_ref(), |this, reason| {
- this.child(self.render_sandbox_not_applied_warning(reason, terminal, cx))
+ this.child(self.render_sandbox_not_applied_warning(reason, cx))
})
.when(is_expanded && terminal_view.is_some(), |this| {
this.child(
@@ -7265,45 +7265,36 @@ impl ThreadView {
fn render_sandbox_not_applied_warning(
&self,
reason: &SandboxNotAppliedReason,
- terminal: &Entity<acp_thread::Terminal>,
cx: &Context<Self>,
) -> AnyElement {
- // (title, optional detail line, whether to offer the settings shortcut)
- let (title, detail, show_settings_button): (SharedString, Option<SharedString>, bool) =
- match reason {
- SandboxNotAppliedReason::DisabledForever => (
- "Ran without sandbox".into(),
- Some("Unsandboxed execution is enabled in settings.".into()),
- true,
- ),
- SandboxNotAppliedReason::ErrorLinuxWsl(error) => (
- "Couldn't create a sandbox".into(),
- Some(error.user_facing_message().into()),
- false,
- ),
- SandboxNotAppliedReason::DisabledForThisThread => {
- // The grant only exists because an earlier command failed to
- // create a sandbox; surface that same explanation here.
- let detail = self
- .find_thread_sandbox_error(cx)
- .map(|error| {
- SharedString::from(format!(
- "Allowed for this thread after the sandbox failed: {}",
- error.user_facing_message()
- ))
- })
- .unwrap_or_else(|| {
- "Unsandboxed execution is allowed for the rest of this thread.".into()
- });
- ("Ran without sandbox".into(), Some(detail), false)
- }
- };
+ // (title, optional detail line)
+ let (title, detail): (SharedString, Option<SharedString>) = match reason {
+ SandboxNotAppliedReason::ErrorLinuxWsl(error) => (
+ "Couldn't create a sandbox".into(),
+ Some(error.user_facing_message().into()),
+ ),
+ SandboxNotAppliedReason::DisabledForThisThread => {
+ // The grant only exists because an earlier command failed to
+ // create a sandbox; surface that same explanation here.
+ let detail = self
+ .find_thread_sandbox_error(cx)
+ .map(|error| {
+ SharedString::from(format!(
+ "Allowed for this thread after the sandbox failed: {}",
+ error.user_facing_message()
+ ))
+ })
+ .unwrap_or_else(|| {
+ "Unsandboxed execution is allowed for the rest of this thread.".into()
+ });
+ ("Ran without sandbox".into(), Some(detail))
+ }
+ };
h_flex()
.px_2()
.py_1()
.gap_1()
- .justify_between()
.border_t_1()
.border_color(cx.theme().status().warning_border)
.bg(cx.theme().status().warning_background.opacity(0.5))
@@ -7332,29 +7323,6 @@ impl ThreadView {
}),
),
)
- .when(show_settings_button, |this| {
- this.child(
- IconButton::new(
- SharedString::from(format!(
- "open-sandbox-setting-{}",
- terminal.entity_id()
- )),
- IconName::Settings,
- )
- .icon_size(IconSize::XSmall)
- .icon_color(Color::Muted)
- .tooltip(Tooltip::text("Open the sandbox permission settings"))
- .on_click(|_event, window, cx| {
- window.dispatch_action(
- Box::new(zed_actions::OpenSettingsAt {
- path: zed_actions::AGENT_SANDBOX_SETTINGS_PATH.to_string(),
- target: None,
- }),
- cx,
- );
- }),
- )
- })
.into_any_element()
}
diff --git a/crates/sandbox/src/windows_wsl.rs b/crates/sandbox/src/windows_wsl.rs
index eefee912b71..50beab807a6 100644
--- a/crates/sandbox/src/windows_wsl.rs
+++ b/crates/sandbox/src/windows_wsl.rs
@@ -777,18 +777,76 @@ fn build_bwrap_args<S: std::hash::BuildHasher>(
/// ...) Windows keeps in the environment block — so they must be skipped or
/// bwrap aborts with "setenv failed".
///
-/// Beyond that, a few variables hold Windows-specific values that would be
-/// meaningless or actively break the command inside WSL: `PATH` would shadow
-/// WSL's own `PATH` and stop the shell from finding Linux executables, the
-/// temp-dir variables point at Windows paths that don't exist in WSL (bwrap
-/// provides a fresh tmpfs `/tmp` instead), and WSL interop variables would
-/// undermine the explicit interop block above. Matched case-insensitively
-/// because Windows environment variable names are.
+/// Beyond that, many variables hold Windows-specific values that would be
+/// meaningless or actively break the command inside WSL, so they are dropped
+/// rather than forwarded: `PATH`/`PATHEXT` would shadow WSL's own `PATH` and
+/// stop the shell from finding Linux executables, the temp-dir variables point
+/// at Windows paths that don't exist in WSL (bwrap provides a fresh tmpfs
+/// `/tmp` instead), the WSL interop variables would undermine the explicit
+/// interop block above, a Windows-set `HOME` would clobber the distro's own
+/// `$HOME` and break the shell, and the rest are Windows system locations,
+/// shell settings, host/session identity, and CPU descriptors that are either
+/// wrong or misleading inside Linux. This is a blocklist rather than an allowlist so
+/// genuinely portable variables (e.g. `LANG`, `CARGO_TERM_COLOR`, `PAGER`)
+/// still reach the command; it only needs to cover the variables Windows
+/// populates by default. Matched case-insensitively because Windows
+/// environment variable names are.
fn is_forwardable_env_var(name: &str) -> bool {
if name.is_empty() || name.contains('=') {
return false;
}
- const BLOCKED: [&str; 6] = ["PATH", "TMPDIR", "TMP", "TEMP", "WSL_INTEROP", "WSLENV"];
+ const BLOCKED: &[&str] = &[
+ // Shadow or break the Linux process environment.
+ "PATH",
+ "PATHEXT",
+ "TMPDIR",
+ "TMP",
+ "TEMP",
+ // Would undermine the explicit WSL interop block above.
+ "WSL_INTEROP",
+ "WSLENV",
+ // Windows system locations and shell, meaningless inside Linux.
+ "OS",
+ "COMSPEC",
+ "WINDIR",
+ "SYSTEMROOT",
+ "SYSTEMDRIVE",
+ // When Windows has `HOME` set (e.g. for git), it's a Windows path that
+ // would clobber the distro's correct Linux `$HOME` and break the shell.
+ "HOME",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ "HOMESHARE",
+ "USERPROFILE",
+ "PUBLIC",
+ "ALLUSERSPROFILE",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "PROGRAMDATA",
+ "PROGRAMFILES",
+ "PROGRAMFILES(X86)",
+ "PROGRAMW6432",
+ "COMMONPROGRAMFILES",
+ "COMMONPROGRAMFILES(X86)",
+ "COMMONPROGRAMW6432",
+ "PSMODULEPATH",
+ "DRIVERDATA",
+ "ONEDRIVE",
+ // Windows host/session identity, misleading inside Linux.
+ "COMPUTERNAME",
+ "USERNAME",
+ "USERDOMAIN",
+ "USERDOMAIN_ROAMINGPROFILE",
+ "LOGONSERVER",
+ "SESSIONNAME",
+ // Windows CPU descriptors.
+ "NUMBER_OF_PROCESSORS",
+ "PROCESSOR_ARCHITECTURE",
+ "PROCESSOR_ARCHITEW6432",
+ "PROCESSOR_IDENTIFIER",
+ "PROCESSOR_LEVEL",
+ "PROCESSOR_REVISION",
+ ];
!BLOCKED
.iter()
.any(|blocked| name.eq_ignore_ascii_case(blocked))
@@ -1224,9 +1282,12 @@ mod tests {
fn bwrap_does_not_forward_windows_specific_env() {
// These hold Windows paths/values that would break or be meaningless
// inside WSL, so they must never cross the boundary. Names are matched
- // case-insensitively, as Windows env var names are.
+ // case-insensitively, as Windows env var names are. `(x86)` variants
+ // contain parentheses but no `=`, so they'd pass the `setenv` filter
+ // and must be blocked by name.
let env = HashMap::from([
("Path".to_string(), r"C:\Windows\System32".to_string()),
+ ("PATHEXT".to_string(), ".COM;.EXE;.BAT".to_string()),
(
"TEMP".to_string(),
r"C:\Users\me\AppData\Local\Temp".to_string(),
@@ -1236,11 +1297,61 @@ mod tests {
r"C:\Users\me\AppData\Local\Temp".to_string(),
),
("TMPDIR".to_string(), r"C:\tmp".to_string()),
+ ("OS".to_string(), "Windows_NT".to_string()),
+ (
+ "ComSpec".to_string(),
+ r"C:\Windows\system32\cmd.exe".to_string(),
+ ),
+ ("windir".to_string(), r"C:\Windows".to_string()),
+ ("SystemRoot".to_string(), r"C:\Windows".to_string()),
+ ("HOME".to_string(), r"C:\Users\me".to_string()),
+ ("USERPROFILE".to_string(), r"C:\Users\me".to_string()),
+ (
+ "APPDATA".to_string(),
+ r"C:\Users\me\AppData\Roaming".to_string(),
+ ),
+ (
+ "LOCALAPPDATA".to_string(),
+ r"C:\Users\me\AppData\Local".to_string(),
+ ),
+ (
+ "ProgramFiles(x86)".to_string(),
+ r"C:\Program Files (x86)".to_string(),
+ ),
+ ("USERNAME".to_string(), "me".to_string()),
+ ("COMPUTERNAME".to_string(), "DESKTOP-ABC".to_string()),
+ ("PROCESSOR_ARCHITECTURE".to_string(), "AMD64".to_string()),
+ ("NUMBER_OF_PROCESSORS".to_string(), "16".to_string()),
]);
let args = build_bwrap_args(&[], SandboxPermissions::default(), None, false, &env);
assert!(!args.iter().any(|arg| arg == "--setenv"));
}
+ #[test]
+ fn bwrap_forwards_portable_env_alongside_windows_specific_env() {
+ // A blocklist (not an allowlist) means genuinely portable variables
+ // still reach the command even when Windows-only ones are present.
+ let env = HashMap::from([
+ ("USERPROFILE".to_string(), r"C:\Users\me".to_string()),
+ ("LANG".to_string(), "en_US.UTF-8".to_string()),
+ ("CARGO_TERM_COLOR".to_string(), "always".to_string()),
+ ]);
+ let args = build_bwrap_args(&[], SandboxPermissions::default(), None, false, &env);
+ assert!(
+ args.windows(3)
+ .any(|window| window == ["--setenv", "LANG", "en_US.UTF-8"])
+ );
+ assert!(
+ args.windows(3)
+ .any(|window| window == ["--setenv", "CARGO_TERM_COLOR", "always"])
+ );
+ assert!(!args.windows(3).any(|window| {
+ matches!(window, [flag, name, _]
+ if flag.as_str() == "--setenv"
+ && name.eq_ignore_ascii_case("USERPROFILE"))
+ }));
+ }
+
#[test]
fn bwrap_skips_env_names_setenv_would_reject() {
// bwrap's `--setenv` calls `setenv(3)`, which rejects empty names and
diff --git a/crates/settings_content/src/agent.rs b/crates/settings_content/src/agent.rs
index 44ca78eddb4..1ad5d7a7660 100644
--- a/crates/settings_content/src/agent.rs
+++ b/crates/settings_content/src/agent.rs
@@ -487,10 +487,6 @@ impl AgentSettingsContent {
.allow_unsandboxed = Some(true);
}
- pub fn disable_sandbox(&mut self) {
- self.sandbox_permissions.get_or_insert_default().disabled = Some(true);
- }
-
pub fn add_sandbox_write_path(&mut self, path: PathBuf) {
let write_paths = &mut self
.sandbox_permissions
@@ -748,16 +744,15 @@ pub struct SandboxPermissionsContent {
/// Default: false
pub allow_fs_write_all: Option<bool>,
- /// Whether terminal commands may always run outside the sandbox without
- /// prompting when they request `unsandboxed: true`.
+ /// Whether to persistently run agent terminal commands outside the OS
+ /// sandbox. This is the model-facing "off switch": when true, the sandboxed
+ /// terminal tool is not exposed and the system prompt omits the sandbox
+ /// section, so the model uses the plain `terminal` tool. On Windows, WSL
+ /// sandbox setup is skipped. Distinct from the model-requested
+ /// `unsandboxed: true` escape approved "once" or "for this thread".
/// Default: false
pub allow_unsandboxed: Option<bool>,
- /// Whether terminal sandboxing is turned off entirely, so agent terminal
- /// commands always run outside the sandbox.
- /// Default: false
- pub disabled: Option<bool>,
-
/// Directory subtrees that sandboxed terminal commands may always write
/// to without prompting. Paths written by Zed are absolute.
/// Default: []
@@ -1045,7 +1040,6 @@ mod tests {
);
settings.allow_sandbox_fs_write_all();
settings.allow_sandbox_unsandboxed();
- settings.disable_sandbox();
settings.add_sandbox_write_path(PathBuf::from("/tmp/build"));
let sandbox_permissions = settings.sandbox_permissions.as_ref().unwrap();
@@ -1061,7 +1055,6 @@ mod tests {
);
assert_eq!(sandbox_permissions.allow_fs_write_all, Some(true));
assert_eq!(sandbox_permissions.allow_unsandboxed, Some(true));
- assert_eq!(sandbox_permissions.disabled, Some(true));
assert_eq!(
sandbox_permissions
.write_paths
diff --git a/crates/settings_ui/src/pages/sandbox_settings.rs b/crates/settings_ui/src/pages/sandbox_settings.rs
index 02ef0183a62..eb86182ef36 100644
--- a/crates/settings_ui/src/pages/sandbox_settings.rs
+++ b/crates/settings_ui/src/pages/sandbox_settings.rs
@@ -50,7 +50,7 @@ pub(crate) fn render_sandbox_settings_page(
let add_path_input = render_add_path_input(cx);
let empty_border = cx.theme().colors().border_variant;
- let sandbox_enabled = !permissions.disabled;
+ let sandbox_enabled = !permissions.allow_unsandboxed;
v_flex()
.id("sandbox-settings-page")
@@ -155,27 +155,7 @@ pub(crate) fn render_sandbox_settings_page(
empty_border,
)),
)
- .child(Divider::horizontal())
- .child(
- v_flex()
- .gap_3()
- .child(SettingsSectionHeader::new("Sandbox").no_padding(true))
- .child(
- SwitchField::new(
- "sandbox-allow-unsandboxed",
- Some("Allow Unsandboxed Terminal Commands"),
- Some(
- "Run terminal commands without the OS sandbox."
- .into(),
- ),
- permissions.allow_unsandboxed,
- move |state, _window, cx| {
- set_allow_unsandboxed(*state == ToggleState::Selected, cx);
- },
- )
- .tab_index(0),
- ),
- ))
+ )
.into_any_element()
}
@@ -430,9 +410,9 @@ fn update_sandbox_permissions(
fn set_sandbox_enabled(value: bool, cx: &mut App) {
// The UI presents an "enabled" switch, but the stored setting is the
- // inverse (`disabled`).
+ // inverse (`allow_unsandboxed`).
update_sandbox_permissions(cx, move |permissions| {
- permissions.disabled = Some(!value);
+ permissions.allow_unsandboxed = Some(!value);
});
}
@@ -448,12 +428,6 @@ fn set_allow_fs_write_all(value: bool, cx: &mut App) {
});
}
-fn set_allow_unsandboxed(value: bool, cx: &mut App) {
- update_sandbox_permissions(cx, move |permissions| {
- permissions.allow_unsandboxed = Some(value);
- });
-}
-
fn add_network_host(host: String, cx: &mut App) {
update_sandbox_permissions(cx, move |permissions| {
let hosts = &mut permissions.network_hosts.get_or_insert_default().0;
diff --git a/sandbox-bubblewrap-next-steps.md b/sandbox-bubblewrap-next-steps.md
deleted file mode 100644
index b48203f21ee..00000000000
--- a/sandbox-bubblewrap-next-steps.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Bubblewrap sandbox — remaining work
-
-Status of the Landlock → bwrap migration and what's left. Concise by
-intent; see `sandbox-bubblewrap-migration.md` for the original rationale.
-
-## Done
-
-- Landlock removed (code, dep, `Cargo.lock`).
-- `linux_bubblewrap`: locate + setuid rejection, `build_bwrap_args` (incl.
- `--tmpfs /tmp`), launcher (`run_launcher_if_invoked`, encode/decode), unit
- tests.
-- `apply_sandbox_wrap` wired to bwrap; `main.rs` hook.
-- Linux: no special `$TMPDIR` (relies on tmpfs `/tmp`); prompt updated.
-- **Network deny via `bwrap --unshare-net`.** The current policy is a coarse
- on/off, which `bwrap`'s own network namespace expresses directly — no
- seccomp, `NO_NEW_PRIVS`, or `seccompiler` dependency. Tradeoff: a
- network-denied command can't reach *abstract* `AF_UNIX` endpoints (D-Bus
- etc.); pathname unix sockets still work. Seccomp returns only when we need a
- finer policy (allow-list/egress proxy).
-- **Thick launcher + status reporting (was §1).** All sandbox work
- (locate/probe) lives in the launcher — check and run are one process, no
- parent/launcher TOCTOU. The launcher reports a `LauncherStatus` as a one-shot
- datagram (`SOCK_DGRAM`) over an abstract `AF_UNIX` socket (`StatusChannel`)
- whose address is passed in argv. Statuses:
- `Success | BwrapNotFound | SetuidRejected | SandboxProbeFailed`. The probe
- runs `bwrap <real args> -- true`, so it validates the *exact* policy we're
- about to use.
- - The launcher never runs a command unsandboxed: on any non-`Success`
- outcome it reports the reason and **aborts**. Choosing what to do about a
- failure is the *consumer's* job:
- - The agent (`run_terminal_tool`) **fails open** for now — it checks
- `SandboxWrap::can_create_sandbox` up front and, if the sandbox can't be
- created, runs the command without one and prepends a note for the model
- ("failed to create the sandbox … ran without a sandbox"). No UI yet; see
- "UI tiers" below.
- - The NixOS tests **fail closed** — they assert the reported status and that
- the command did *not* run.
-- **`apply_sandbox_wrap` rework (was §2).** Parent passes raw policy (socket,
- permissions, cwd, writable dirs, program, args) to the launcher and listens
- on the channel in a background thread (diagnostic only now). Parent-side
- `locate_bwrap`/`is_available` + their `OnceLock` caches deleted; the up-front
- viability check is `linux_bubblewrap::check_can_create_sandbox`.
-- **NixOS tests (was §5).** Landlock kernel matrix replaced by three scenarios
- (`sandbox-userns-enabled`, `sandbox-userns-disabled`, `sandbox-no-bwrap`) under
- `nix/tests/sandboxing`. New `bwrap_test_helper` bin (sandbox crate,
- `nixos-test` feature) drives the real launcher and reads the status; an
- enforcement probe **skips** (not fails) when the VM can't enforce. Checks
- wired into the flake (`packages.nix`); xtask prefix is now `sandbox-`.
-- **Windows WSL behavior tests.** Parity with the NixOS bwrap tests for the
- Windows WSL sandbox (`windows_wsl`). New `wsl_sandbox_test_helper` bin (sandbox
- crate, `wsl-test` feature) drives the real `wrap_invocation`, spawns the
- produced `wsl.exe` command, and asserts the same grants/restrictions hold
- end-to-end (writable binds land on host, reads allowed, `/tmp` ephemeral,
- network on/off, fs-write escape hatch) plus the Windows-specific ones: a
- native `C:\` writable path is translated and bound, and **WSL interop is
- blocked** so a sandboxed process can't exec a Windows binary to escape bwrap.
- Core FS checks run against the WSL rootfs (robust regardless of how drvfs
- `/mnt` submounts behave under the recursive root bind). Like the Linux helper
- it **skips** when the environment can't enforce; set
- `ZED_TEST_SANDBOX_REQUIRE_ENFORCED=1` to turn that into a failure. Run with
- `cargo xtask wsl-sandbox-tests` or `script/test-wsl-sandbox.ps1` (the latter
- provisions `bubblewrap` + unprivileged user namespaces in the default distro
- first). Not wired into CI — matching the NixOS tests, which aren't either.
- Degraded scenarios (no bwrap / userns disabled) have no boot-level toggle in
- WSL, so that coverage stays at the unit level (probe parsing + the
- bad-request-vs-unavailable error classification, also re-checked end-to-end).
-
-## Remaining
-
-### 1. UI tiers
-
-- `Success` → sandboxed, no warning.
-- Any failure → surface the reason and offer **Run unsandboxed / Deny**
- (unidirectional: on "run unsandboxed" the parent re-spawns a normal terminal;
- the launcher never blocks for a decision).
-- Orange "unsandboxed" indicator on terminals that ran without the sandbox.
-
-### 2. Bundled bwrap
-
-`bundled_bwrap_path()` is a `None` stub, so today sandboxing needs a system
-`bwrap`. Build a static musl, non-setuid `bwrap` (Nix `pkgsStatic`,
-`-Dselinux=disabled`) per arch, bundle it, ship LGPL source/notice. Open: bundle
-vs download.