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.

agent: Sanboxing on linux (#58355)

Cameron Mcloughlin6661273a412e
diff --git a/Cargo.lock b/Cargo.lock
index cb3f111be90..085dd33797b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15895,6 +15895,7 @@ name = "sandbox"
version = "0.1.0"
dependencies = [
"anyhow",
+ "libc",
"tempfile",
]
@@ -22984,6 +22985,7 @@ dependencies = [
"repl",
"reqwest_client",
"rope",
+ "sandbox",
"search",
"semver",
"serde",
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 8d5e71c292e..8a94e0a366e 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -181,6 +181,10 @@ pub struct SandboxAuthorizationDetails {
pub unsandboxed: bool,
#[serde(default)]
pub write_paths: Vec<PathBuf>,
+ /// The agent-provided justification for requesting these permissions,
+ /// shown to the user (attributed to the agent) in the approval prompt.
+ #[serde(default)]
+ pub reason: String,
}
pub fn meta_with_sandbox_authorization(details: SandboxAuthorizationDetails) -> acp::Meta {
@@ -3410,8 +3414,13 @@ impl AcpThread {
// child's proxy env vars.
let (proxy_handle, network_policy) =
setup_network_proxy(sandbox_wrap.as_ref(), &mut env, cx)?;
- let (task_command, task_args, sandbox_config) =
- apply_sandbox_wrap(task_command, task_args, sandbox_wrap, network_policy)?;
+ let (task_command, task_args, sandbox_config) = apply_sandbox_wrap(
+ task_command,
+ task_args,
+ cwd.as_deref(),
+ sandbox_wrap,
+ network_policy,
+ )?;
let terminal = project
.update(cx, |project, cx| {
project.create_terminal_task(
diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs
index 95421953a9d..186a9db4228 100644
--- a/crates/acp_thread/src/terminal.rs
+++ b/crates/acp_thread/src/terminal.rs
@@ -1,4 +1,6 @@
use agent_client_protocol::schema as acp;
+#[cfg(target_os = "linux")]
+use anyhow::Context as _;
use anyhow::Result;
use collections::HashMap;
use futures::{FutureExt as _, future::Shared};
@@ -22,10 +24,9 @@ use util::get_default_system_shell_preferring_bash;
/// Request to run a terminal command inside an OS-level sandbox.
///
/// Passed to [`super::AcpThread::create_terminal`]. The actual sandboxing
-/// mechanism is platform-specific (today: macOS Seatbelt; nothing on other
-/// platforms — the wrap is silently a no-op there), so callers describe the
-/// *intent* with plain data here rather than constructing platform-specific
-/// types directly.
+/// mechanism is platform-specific (macOS Seatbelt; Linux Bubblewrap; a no-op
+/// on other platforms), so callers describe the *intent* with plain data here
+/// rather than constructing platform-specific types directly.
///
/// Default is the fully-sandboxed run (no network, project-only writes).
/// Setting `network` / `allow_fs_write` requests a relaxation; the caller is
@@ -75,6 +76,41 @@ impl SandboxNetworkAccess {
}
}
+impl SandboxWrap {
+ /// Whether the OS sandbox for this request can actually be created right now,
+ /// returning a short human-readable reason when it can't.
+ ///
+ /// The sandbox implementation never runs a command unsandboxed on its own —
+ /// it aborts if it can't create the sandbox. This lets a caller decide, up
+ /// front, whether to run sandboxed, fall back to an unsandboxed run
+ /// (fail-open), or refuse (fail-closed). It runs a brief probe subprocess on
+ /// Linux, so call it off the main thread. On platforms whose sandbox can't
+ /// fail to set up this way it always returns `Ok`.
+ pub fn can_create_sandbox(&self, cwd: Option<&std::path::Path>) -> Result<(), String> {
+ #[cfg(target_os = "linux")]
+ {
+ let writable: Vec<&std::path::Path> = self
+ .writable_paths
+ .iter()
+ .chain(self.extra_write_paths.iter())
+ .map(|path| path.as_path())
+ .collect();
+ let allow_network = !matches!(self.network, SandboxNetworkAccess::None);
+ let permissions = sandbox::SandboxPermissions {
+ allow_network,
+ allow_fs_write: self.allow_fs_write,
+ };
+ sandbox::linux_bubblewrap::check_can_create_sandbox(&writable, permissions, cwd)
+ .map_err(|status| status.describe().to_string())
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ let _ = cwd;
+ Ok(())
+ }
+ }
+}
+
/// Opaque RAII handle the sandbox implementation hands back to keep its
/// per-command resources (e.g. an on-disk Seatbelt config file) alive for
/// the duration of the spawned command. `Terminal` holds it in a field
@@ -93,21 +129,31 @@ pub(crate) enum NetworkPolicy {
}
/// Apply a [`SandboxWrap`] to a `(program, args)` pair, substituting the
-/// platform's sandbox-launcher invocation in place of the original. The
-/// returned `SandboxConfigHandle` (when `Some`) must be kept alive for the
-/// duration of the spawned command — dropping it deletes any on-disk
-/// config the launcher reads at startup.
+/// platform's sandboxed invocation in place of the original. The returned
+/// `SandboxConfigHandle` (when `Some`) must be kept alive for the duration
+/// of the spawned command — dropping it deletes any on-disk config the
+/// launcher reads at startup.
///
/// `network_policy` is the decision resolved by [`setup_network_proxy`].
/// Unrestricted network access must be requested explicitly via
/// [`SandboxNetworkAccess::All`].
///
-/// On non-macOS hosts this is a no-op: the inputs pass through unchanged
-/// and the returned handle is `None`. (We don't yet have a sandbox
-/// integration for other platforms.)
+/// There is a dedicated code path per platform:
+/// * macOS wraps the command with `sandbox-exec` and a Seatbelt config file
+/// (returned as the handle).
+/// * Linux re-execs this binary as a launcher that locates `bwrap` and `exec`s
+/// it for filesystem and network isolation (see
+/// [`sandbox::linux_bubblewrap`]); no handle is needed. The launcher reports
+/// back over a status channel whether it could enforce the sandbox, and when
+/// it can't (no usable `bwrap`, user namespaces disabled, …) it runs the
+/// command unsandboxed and the parent logs a warning rather than failing.
+/// * Windows and all other platforms pass the command through unchanged —
+/// we have no sandbox integration there, so the command runs with the
+/// agent's ambient permissions.
pub(crate) fn apply_sandbox_wrap(
program: String,
args: Vec<String>,
+ cwd: Option<&std::path::Path>,
sandbox_wrap: Option<SandboxWrap>,
network_policy: NetworkPolicy,
) -> anyhow::Result<(String, Vec<String>, Option<SandboxConfigHandle>)> {
@@ -119,6 +165,7 @@ pub(crate) fn apply_sandbox_wrap(
{
use sandbox::macos_seatbelt::NetworkAccess;
+ let _ = cwd;
let writable: Vec<&std::path::Path> = sandbox_wrap
.writable_paths
.iter()
@@ -142,16 +189,105 @@ pub(crate) fn apply_sandbox_wrap(
Some(Box::new(config_file) as SandboxConfigHandle),
))
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "linux")]
+ {
+ use sandbox::linux_bubblewrap::{self, LauncherStatus, StatusChannel};
+ use std::time::Duration;
+
+ let writable: Vec<_> = sandbox_wrap
+ .writable_paths
+ .iter()
+ .chain(sandbox_wrap.extra_write_paths.iter())
+ .map(|p| p.as_path())
+ .collect();
+ let allow_network = match network_policy {
+ NetworkPolicy::Denied => false,
+ NetworkPolicy::Unrestricted => true,
+ NetworkPolicy::Proxied(port) => {
+ // Bubblewrap can only toggle network access wholesale, so it
+ // can't confine egress to the proxy's loopback port.
+ // `setup_network_proxy` never resolves to `Proxied` on Linux;
+ // deny network rather than silently widening access.
+ log::debug!(
+ "[sandbox/network] ignoring proxy port {port}; bubblewrap can't confine to a loopback port"
+ );
+ false
+ }
+ };
+ let permissions = sandbox::SandboxPermissions {
+ allow_network,
+ allow_fs_write: sandbox_wrap.allow_fs_write,
+ };
+
+ let launcher = std::env::current_exe()
+ .context("failed to resolve current executable for sandbox launcher")?;
+ let launcher = launcher.to_str().with_context(|| {
+ format!(
+ "current executable path contains invalid UTF-8: {}",
+ launcher.display()
+ )
+ })?;
+
+ // Bind a status channel the launcher reports back on, so we can warn
+ // when it couldn't actually enforce the sandbox. All the sandbox logic
+ // (locating bwrap, probing it) lives in the launcher; the parent only
+ // assembles the invocation and listens.
+ let channel = StatusChannel::bind().context("failed to set up sandbox status channel")?;
+ let (new_program, new_args) = linux_bubblewrap::wrap_invocation(
+ launcher,
+ Some(channel.name()),
+ permissions,
+ &writable,
+ cwd,
+ &program,
+ &args,
+ );
+
+ // Read the launcher's report in the background, purely for diagnostics.
+ // Callers are expected to check `SandboxWrap::can_create_sandbox` before
+ // reaching here, so the launcher should almost always succeed; a failure
+ // status means the launcher aborted (it never runs a command
+ // unsandboxed), so the command did not run.
+ const STATUS_TIMEOUT: Duration = Duration::from_secs(30);
+ let status_thread = std::thread::Builder::new()
+ .name("zed-sandbox-status".into())
+ .spawn(move || match channel.recv(STATUS_TIMEOUT) {
+ Some(LauncherStatus::Success) => {}
+ Some(status) => log::warn!(
+ "sandbox could not be created ({}); the command was aborted",
+ status.describe()
+ ),
+ None => log::warn!("could not determine terminal command sandbox status"),
+ })
+ .context("failed to spawn sandbox status thread")?;
+ // The thread is self-contained and bounded by STATUS_TIMEOUT; let it run
+ // to completion on its own rather than joining here.
+ drop(status_thread);
+
+ // The sandbox applies in-process via the re-exec'd launcher, so
+ // there's no on-disk resource to keep alive.
+ Ok((new_program, new_args, None))
+ }
+ #[cfg(target_os = "windows")]
+ {
+ // No sandbox integration on Windows; run with ambient permissions.
+ if let NetworkPolicy::Proxied(port) = network_policy {
+ log::debug!(
+ "[sandbox/network] ignoring proxy port {port} because this platform has no sandbox integration"
+ );
+ }
+ let _ = (sandbox_wrap, cwd);
+ Ok((program, args, None))
+ }
+ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
{
- // No sandbox integration available; ignore the wrap request and
- // let the command run with the agent's ambient permissions.
+ // No sandbox integration available; run with ambient permissions.
if let NetworkPolicy::Proxied(port) = network_policy {
log::debug!(
"[sandbox/network] ignoring proxy port {port} because this platform has no sandbox integration"
);
}
- let _sandbox_wrap = sandbox_wrap;
+ let _ = (sandbox_wrap, cwd);
Ok((program, args, None))
}
}
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index 8634f11646c..eaea0103b2e 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -3092,49 +3092,63 @@ impl ThreadEnvironment for NativeThreadEnvironment {
sandbox_wrap: Option<acp_thread::SandboxWrap>,
cx: &mut AsyncApp,
) -> Task<Result<Rc<dyn TerminalHandle>>> {
- // Use a per-thread temp directory for all terminal commands, even when
- // sandboxing is disabled, so the model can't infer sandbox state from
- // `$TMPDIR` changing between conversations.
+ // On Seatbelt-style sandboxes (macOS) there's no tmpfs overlay, so to
+ // give the command a writable temp area we point `$TMPDIR`/`$TMP`/
+ // `$TEMP` at a per-thread directory inside the sandbox's writable
+ // scope. Doing this even when sandboxing is disabled keeps `$TMPDIR`
+ // stable so the model can't infer sandbox state from it.
//
// Only do this for local projects. For remote projects the temp
// directory would be created on the client, but the terminal runs on
// the remote host, so pointing `$TMPDIR` (and the sandbox writable
// scope) at a client-side path would leak client environment into the
// remote terminal and reference a directory that doesn't exist there.
+ //
+ // Linux is excluded: the bwrap sandbox already mounts a fresh,
+ // writable `tmpfs` over `/tmp`, so the environment looks like a normal
+ // filesystem with no special `$TMPDIR` (which would only make the
+ // sandbox more obviously Zed-specific).
+ #[cfg_attr(target_os = "linux", allow(unused_mut))]
let mut extra_env = extra_env;
+ #[cfg_attr(target_os = "linux", allow(unused_mut))]
let mut sandbox_wrap = sandbox_wrap;
- let temp_dir = self.thread.update(cx, |thread, cx| {
- thread
- .project()
- .read(cx)
- .is_local()
- .then(|| thread.sandboxed_terminal_temp_dir(cx))
- });
- match temp_dir {
- Ok(Some(Ok(temp_dir))) => {
- // Canonicalize so the path matches what the sandbox resolves
- // symlinks to (e.g. `/var` -> `/private/var` on macOS).
- // `$TMPDIR` and the writable-scope entry below must agree, and
- // they must agree with the path the kernel actually checks.
- let temp_dir = temp_dir.canonicalize().unwrap_or(temp_dir);
- let temp_dir_string = temp_dir.to_string_lossy().into_owned();
- extra_env.extend([
- acp::EnvVariable::new("TMPDIR", &temp_dir_string),
- acp::EnvVariable::new("TMP", &temp_dir_string),
- acp::EnvVariable::new("TEMP", &temp_dir_string),
- ]);
- // The command's `$TMPDIR` must live inside the sandbox's
- // writable scope. The per-thread temp directory is owned here
- // (not in the terminal tool that assembles the rest of the
- // writable set), so add it whenever the command is sandboxed.
- if let Some(sandbox_wrap) = &mut sandbox_wrap {
- sandbox_wrap.writable_paths.push(temp_dir);
+ #[cfg(not(target_os = "linux"))]
+ {
+ let temp_dir = self.thread.update(cx, |thread, cx| {
+ thread
+ .project()
+ .read(cx)
+ .is_local()
+ .then(|| thread.sandboxed_terminal_temp_dir(cx))
+ });
+ match temp_dir {
+ Ok(Some(Ok(temp_dir))) => {
+ // Canonicalize so the path matches what the sandbox
+ // resolves symlinks to (e.g. `/var` -> `/private/var` on
+ // macOS). `$TMPDIR` and the writable-scope entry below must
+ // agree, and they must agree with the path the kernel
+ // actually checks.
+ let temp_dir = temp_dir.canonicalize().unwrap_or(temp_dir);
+ let temp_dir_string = temp_dir.to_string_lossy().into_owned();
+ extra_env.extend([
+ acp::EnvVariable::new("TMPDIR", &temp_dir_string),
+ acp::EnvVariable::new("TMP", &temp_dir_string),
+ acp::EnvVariable::new("TEMP", &temp_dir_string),
+ ]);
+ // The command's `$TMPDIR` must live inside the sandbox's
+ // writable scope. The per-thread temp directory is owned
+ // here (not in the terminal tool that assembles the rest
+ // of the writable set), so add it whenever the command is
+ // sandboxed.
+ if let Some(sandbox_wrap) = &mut sandbox_wrap {
+ sandbox_wrap.writable_paths.push(temp_dir);
+ }
}
- }
- Ok(None) => {}
- Ok(Some(Err(error))) => return Task::ready(Err(error)),
- Err(error) => return Task::ready(Err(error)),
- };
+ Ok(None) => {}
+ Ok(Some(Err(error))) => return Task::ready(Err(error)),
+ Err(error) => return Task::ready(Err(error)),
+ };
+ }
let task = self.acp_thread.update(cx, |thread, cx| {
thread.create_terminal(
command,
diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs
index 066235a51d9..c9cc400e19c 100644
--- a/crates/agent/src/sandboxing.rs
+++ b/crates/agent/src/sandboxing.rs
@@ -5,12 +5,13 @@
//! caller see the same answer (and so the `target_os` gate lives in one
//! place instead of scattered across the agent crate).
//!
-//! The current policy is: enabled iff we're on macOS *and* the user has the
-//! `sandboxing` feature flag turned on. There's deliberately no settings or
-//! env-var override yet — the flag is the only switch.
+//! The current policy is: enabled iff the user has the `sandboxing` feature
+//! flag turned on. There's deliberately no settings or env-var override yet —
+//! the flag is the only switch.
//!
-//! On non-macOS hosts we don't have a sandbox integration today, so this
-//! returns `false` regardless of the flag.
+//! macOS (Seatbelt) and Linux (Bubblewrap) have real sandbox integrations; on
+//! platforms without one the per-command wrap is a no-op, so commands run with
+//! the agent's ambient permissions even when the flag is on.
//!
//! Naming note: this module is about agent terminal sandboxing specifically.
//! Other agent operations (e.g. file edits) are gated separately.
@@ -24,7 +25,7 @@ use std::path::PathBuf;
/// Whether agent-run terminal commands should be wrapped in an OS-level
/// sandbox for this process. See module docs for the policy.
pub(crate) fn sandboxing_enabled(cx: &App) -> bool {
- cfg!(target_os = "macos") && cx.has_flag::<SandboxingFeatureFlag>()
+ cx.has_flag::<SandboxingFeatureFlag>()
}
/// Network escalation requested for (or granted to) a sandboxed command.
diff --git a/crates/agent/src/templates.rs b/crates/agent/src/templates.rs
index 39a79cd339e..c08aeb91025 100644
--- a/crates/agent/src/templates.rs
+++ b/crates/agent/src/templates.rs
@@ -49,6 +49,12 @@ pub struct SystemPromptTemplate<'a> {
/// per-command flags the model can request to relax them. When
/// `false`, the prompt omits the sandbox section entirely.
pub sandboxing: bool,
+ /// Whether the host is Linux. The writable-temp story differs by
+ /// platform (Linux exposes an ephemeral `tmpfs` over `/tmp`; other
+ /// platforms provide a persistent per-thread `$TMPDIR`), so the sandbox
+ /// section describes the right one rather than advertising a `$TMPDIR`
+ /// that doesn't behave as stated.
+ pub is_linux: bool,
}
impl Template for SystemPromptTemplate<'_> {
@@ -94,6 +100,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@@ -125,6 +132,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: Some("always be concise".into()),
sandboxing: false,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@@ -152,6 +160,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@@ -183,6 +192,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: true,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@@ -198,6 +208,35 @@ mod tests {
assert!(rendered.contains("for the rest of the thread"));
}
+ #[test]
+ fn test_system_prompt_linux_sandbox_section_omits_tmpdir() {
+ use prompt_store::{ProjectContext, WorktreeContext};
+
+ let worktrees = vec![WorktreeContext {
+ root_name: "alpha".to_string(),
+ abs_path: std::path::Path::new("/tmp/alpha").into(),
+ rules_file: None,
+ }];
+ let project = ProjectContext::new(worktrees);
+ let template = SystemPromptTemplate {
+ project: &project,
+ available_tools: vec!["echo".into()],
+ model_name: Some("test-model".to_string()),
+ date: "2026-01-01".to_string(),
+ user_agents_md: None,
+ sandboxing: true,
+ is_linux: true,
+ };
+ let templates = Templates::new();
+ let rendered = template.render(&templates).unwrap();
+
+ assert!(rendered.contains("## Terminal sandbox"));
+ // On Linux we must not advertise the special persistent `$TMPDIR`.
+ assert!(!rendered.contains("$TMPDIR"));
+ assert!(rendered.contains("`/tmp` is writable"));
+ assert!(rendered.contains("`/tmp/alpha`"));
+ }
+
#[test]
fn test_system_prompt_sandbox_section_handles_zero_worktrees() {
let project = prompt_store::ProjectContext::default();
@@ -208,6 +247,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: true,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@@ -226,6 +266,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
@@ -242,6 +283,7 @@ mod tests {
date: "2026-01-01".to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: false,
};
let templates = Templates::new();
let rendered = template.render(&templates).unwrap();
diff --git a/crates/agent/src/templates/system_prompt.hbs b/crates/agent/src/templates/system_prompt.hbs
index cb68e09b32e..5bcd1876032 100644
--- a/crates/agent/src/templates/system_prompt.hbs
+++ b/crates/agent/src/templates/system_prompt.hbs
@@ -159,19 +159,36 @@ The current project contains the following root directories:
The `terminal` tool runs commands inside a sandbox with these permissions:
- Reads: any path on the filesystem is readable.
+{{#if is_linux}}
+- Writes: `/tmp` is writable but is cleared between `terminal` calls{{#if worktrees}}. These project directories are also writable and persist across calls:
+{{#each worktrees}}
+ - `{{abs_path}}`
+{{/each}}
+ Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
+{{else}}
- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this thread{{#if worktrees}}, along with these project directories:
{{#each worktrees}}
- `{{abs_path}}`
{{/each}}
Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
+{{/if}}
- Network: outbound network access is blocked.
+{{#if is_linux}}
+The sandbox can only allow or block outbound network access as a whole — it cannot restrict access to specific hosts. There is no HTTP/HTTPS proxy, so once network access is granted SSH, FTP, and raw sockets work too.
+
+You can request elevated permissions on individual `terminal` calls:
+
+- `allow_all_hosts: true` — allow unrestricted outbound network access. On this platform this is the only way to grant network access.
+- `allow_hosts: ["github.com", ...]` — accepted, but on this platform listing hosts grants unrestricted outbound network access (identical to `allow_all_hosts`), because per-host restriction can't be enforced. Prefer `allow_all_hosts` so the request is explicit.
+{{else}}
Network access works through an HTTP/HTTPS proxy (standard proxy environment variables are set for the command). Tools that don't honor proxy environment variables (SSH, FTP, raw sockets, etc.) can't reach the network even when access is granted, so use `https://` URLs instead of `git@`/`ssh://` when cloning or pushing.
You can request elevated permissions on individual `terminal` calls:
- `allow_hosts: ["github.com", "*.npmjs.org"]` — allow outbound HTTP/HTTPS to specific hosts (exact hostnames or leading-`*.` subdomain wildcards; no IP literals). Prefer this whenever you know which hosts the command needs.
- `allow_all_hosts: true` — allow outbound HTTP/HTTPS to any host. Use only when the specific hosts can't be enumerated up front.
+{{/if}}
- `fs_write_paths: ["/abs/or/worktree-relative/path", ...]` — allow writes to specific paths (each directory grants its whole subtree). Prefer this whenever you know which paths the command needs to write.
- `allow_fs_write_all: true` — allow unrestricted filesystem writes. Only use this when the specific paths can't be enumerated up front.
- `unsandboxed: true` — run the command with no sandbox at all. Use only when none of the above suffice.
diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs
index 2930c7f4542..a5e6772b298 100644
--- a/crates/agent/src/thread.rs
+++ b/crates/agent/src/thread.rs
@@ -1367,6 +1367,9 @@ impl Thread {
&self.id
}
+ // Only used by Seatbelt-style sandboxes; Linux relies on bwrap's tmpfs
+ // `/tmp` and never needs a per-thread temp directory.
+ #[cfg(not(target_os = "linux"))]
pub(crate) fn sandboxed_terminal_temp_dir(
&mut self,
cx: &mut Context<Self>,
@@ -3905,6 +3908,7 @@ impl Thread {
date: Local::now().format("%Y-%m-%d").to_string(),
user_agents_md,
sandboxing: crate::sandboxing::sandboxing_enabled(cx),
+ is_linux: cfg!(target_os = "linux"),
}
.render(&self.templates)
.context("failed to build system prompt")
@@ -5244,6 +5248,7 @@ impl ToolCallEventStream {
title: impl Into<String>,
command: Option<String>,
request: SandboxRequest,
+ reason: String,
cx: &mut App,
) -> Task<Result<()>> {
if Self::sandbox_request_covered_by_grants(&request, &self.sandbox_grants, cx) {
@@ -5265,6 +5270,7 @@ impl ToolCallEventStream {
allow_fs_write_all: request.allow_fs_write_all,
unsandboxed: request.unsandboxed,
write_paths: request.write_paths.clone(),
+ reason,
};
let options = acp_thread::PermissionOptions::Flat(vec![
acp::PermissionOption::new(
@@ -6858,7 +6864,13 @@ mod tests {
};
let authorize = cx.update(|cx| {
- event_stream.authorize_sandbox("Allow write access?", None, request.clone(), cx)
+ event_stream.authorize_sandbox(
+ "Allow write access?",
+ None,
+ request.clone(),
+ "needs to write build artifacts".to_string(),
+ cx,
+ )
});
let authorization = receiver.expect_authorization().await;
let details =
diff --git a/crates/agent/src/tools/evals/edit_file.rs b/crates/agent/src/tools/evals/edit_file.rs
index 3a821737fad..449b912dfab 100644
--- a/crates/agent/src/tools/evals/edit_file.rs
+++ b/crates/agent/src/tools/evals/edit_file.rs
@@ -373,6 +373,7 @@ impl EditToolTest {
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: cfg!(target_os = "linux"),
};
let templates = Templates::new();
template.render(&templates)?
diff --git a/crates/agent/src/tools/evals/terminal_tool.rs b/crates/agent/src/tools/evals/terminal_tool.rs
index 2441b5014f5..4cd0af86cec 100644
--- a/crates/agent/src/tools/evals/terminal_tool.rs
+++ b/crates/agent/src/tools/evals/terminal_tool.rs
@@ -232,6 +232,7 @@ impl TerminalToolTest {
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: cfg!(target_os = "linux"),
};
template.render(&Templates::new())?
};
diff --git a/crates/agent/src/tools/evals/write_file.rs b/crates/agent/src/tools/evals/write_file.rs
index b038bf1f8bf..04c00c91bdd 100644
--- a/crates/agent/src/tools/evals/write_file.rs
+++ b/crates/agent/src/tools/evals/write_file.rs
@@ -203,6 +203,7 @@ impl WriteToolTest {
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
user_agents_md: None,
sandboxing: false,
+ is_linux: cfg!(target_os = "linux"),
};
let templates = Templates::new();
template.render(&templates)?
diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs
index 08adc6795da..ceb949e1bf5 100644
--- a/crates/agent/src/tools/terminal_tool.rs
+++ b/crates/agent/src/tools/terminal_tool.rs
@@ -105,9 +105,21 @@ pub struct SandboxedTerminalToolInput {
/// commands that fetch or upload (installing dependencies, cloning,
/// pushing, downloading, etc.). Each entry must be a hostname or a
/// leading-`*.` subdomain wildcard; IP literals and other wildcards are
- /// rejected. Host-specific access is enforced by an HTTP/HTTPS proxy — use
- /// `https://` URLs rather than `git@`/`ssh://`. Requesting hosts triggers a
- /// user approval prompt, so only list hosts you expect the command to need.
+ /// rejected. Requesting network access triggers a user approval prompt, so
+ /// only list hosts you expect the command to need.
+ #[cfg_attr(
+ target_os = "macos",
+ doc = "\nHost-specific access is enforced by an HTTP/HTTPS proxy, so use \
+ `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` \
+ directly when per-host restriction isn't available."
+ )]
#[serde(default)]
pub allow_hosts: Vec<String>,
/// Set to `true` only if the command needs outbound network access to
@@ -121,12 +133,22 @@ pub struct SandboxedTerminalToolInput {
/// Paths the command needs to write to outside the default-writable
/// locations.
///
- /// Sandboxed commands can already write to the project worktree
- /// directories and a per-command temporary directory, so only list paths
- /// outside those. Provide absolute or worktree-relative paths; each
+ #[cfg_attr(
+ target_os = "macos",
+ doc = "Sandboxed commands can already write to the project worktree \
+ directories and a per-command temporary directory, so only list paths \
+ outside those."
+ )]
+ /// Provide absolute or worktree-relative paths; each
/// directory grants write access to its whole subtree. Prefer this over
/// `allow_fs_write_all` whenever you can enumerate the paths. Requesting
/// paths triggers a user approval prompt.
+ #[cfg_attr(
+ target_os = "linux",
+ doc = "\nOn Linux, every path here must be a directory that already exists. \
+ Requesting a file, or a path that does not exist yet, is an error. To create new \
+ files, request write access to the existing directory that will contain them."
+ )]
#[serde(default)]
pub fs_write_paths: Vec<String>,
/// Set to `true` only when the command needs to write outside the
@@ -146,6 +168,16 @@ pub struct SandboxedTerminalToolInput {
/// triggers a user approval prompt.
#[serde(default)]
pub unsandboxed: Option<bool>,
+ /// A short justification for why this command needs the sandbox
+ /// permission(s) it requests (`allow_network`, `fs_write_paths`,
+ /// `allow_fs_write_all`, or `unsandboxed`).
+ ///
+ /// Required whenever you request any of those permissions; omit it for
+ /// ordinary commands that request none. Write it in your own voice — it
+ /// is shown to the user, attributed to you, when they're asked to approve
+ /// the request.
+ #[serde(default)]
+ pub reason: Option<String>,
}
#[derive(Clone, Debug, Default)]
@@ -155,6 +187,7 @@ struct TerminalSandboxInput {
fs_write_paths: Vec<String>,
allow_fs_write_all: Option<bool>,
unsandboxed: Option<bool>,
+ reason: Option<String>,
}
struct TerminalToolRequest {
@@ -196,6 +229,7 @@ impl From<SandboxedTerminalToolInput> for TerminalToolRequest {
fs_write_paths: input.fs_write_paths,
allow_fs_write_all: input.allow_fs_write_all,
unsandboxed: input.unsandboxed,
+ reason: input.reason,
}),
}
}
@@ -349,11 +383,16 @@ async fn run_terminal_tool(
NetworkRequest::None
};
- // The host allowlist is enforced by a loopback proxy, which can't serve
- // a non-local project's terminal. Widen the request to "any host" before
- // prompting, so the approval the user grants matches what's actually
- // enforced (unrestricted egress) rather than naming hosts we can't pin.
- if !is_local_project && network.is_requested() {
+ // Host-specific network access is enforced by a loopback proxy that
+ // confines the sandbox to its port, and only macOS can do that. A
+ // non-local project's terminal can't reach the proxy, and the Linux
+ // sandbox (bwrap) has no host-restriction mechanism at all — it can only
+ // allow or deny the network wholesale. Whenever per-host restriction
+ // isn't enforceable, widen the request to "any host" before prompting, so
+ // the approval the user grants matches what's actually enforced
+ // (unrestricted egress) rather than naming hosts we can't pin.
+ let can_restrict_to_hosts = cfg!(target_os = "macos") && is_local_project;
+ if !can_restrict_to_hosts && network.is_requested() {
network = NetworkRequest::AnyHost;
}
@@ -370,6 +409,24 @@ async fn run_terminal_tool(
Vec::new()
};
+ // On Linux the sandbox (bwrap) can only bind a path that already exists,
+ // and granting a not-yet-existing path would silently widen the grant to
+ // its nearest existing ancestor directory. Reject anything that
+ // isn't an already-existing directory so the user is only ever asked to
+ // approve — and only ever grants — exactly the paths shown to them.
+ #[cfg(target_os = "linux")]
+ for path in &write_paths {
+ if !path.is_dir() {
+ return Err(format!(
+ "Cannot request sandbox write access to `{}`: on Linux, write access can only \
+ be granted to directories that already exist. To create or modify files, \
+ request write access to the existing directory that contains them, not the \
+ file path itself.",
+ path.display()
+ ));
+ }
+ }
+
let request = crate::sandboxing::SandboxRequest {
network,
allow_fs_write_all: !want_unsandboxed && want_fs_write_all,
@@ -378,10 +435,23 @@ async fn run_terminal_tool(
};
if request.needs_escalation() {
+ let reason = sandbox_input
+ .reason
+ .as_deref()
+ .map(str::trim)
+ .filter(|reason| !reason.is_empty());
+ let Some(reason) = reason else {
+ return Err(
+ "This command requests elevated sandbox permissions, so a `reason` is \
+ required: briefly justify why the command needs them, then run it again."
+ .to_string(),
+ );
+ };
let title = sandbox_approval_title(&request);
let command = Some(input.command.clone());
- let approve =
- cx.update(|cx| event_stream.authorize_sandbox(title, command, request.clone(), cx));
+ let approve = cx.update(|cx| {
+ event_stream.authorize_sandbox(title, command, request.clone(), reason.to_string(), cx)
+ });
if let Err(error) = approve.await {
if want_unsandboxed {
return Ok(format!(
@@ -396,6 +466,12 @@ async fn run_terminal_tool(
let extra_env = Vec::new();
+ // Build the sandbox request, then decide whether we can actually sandbox.
+ // The sandbox itself never silently runs a command unsandboxed: if it can't
+ // create the sandbox it aborts. As the consumer we fail *open* for now — we
+ // re-run the command without a sandbox so a missing/blocked `bwrap` doesn't
+ // break the terminal — but we tell the model we did, via `sandbox_fallback`.
+ let mut sandbox_fallback: Option<String> = None;
let sandbox_wrap = if sandboxing && !want_unsandboxed {
let sandbox_permissions = cx.update(|cx| {
agent_settings::AgentSettings::get_global(cx)
@@ -410,13 +486,33 @@ async fn run_terminal_tool(
.map(|w| w.read(cx).abs_path().to_path_buf())
.collect::<Vec<_>>()
});
- Some(acp_thread::SandboxWrap {
+ let wrap = acp_thread::SandboxWrap {
writable_paths,
extra_write_paths: effective.write_paths,
network: network_request_to_sandbox_network_access(&effective.network),
allow_fs_write: effective.allow_fs_write_all,
is_local: is_local_project,
- })
+ };
+
+ // The viability check runs a brief probe subprocess, so do it off the
+ // main thread.
+ let probe_wrap = wrap.clone();
+ let probe_cwd = working_dir.clone();
+ let availability = cx
+ .background_executor()
+ .spawn(async move { probe_wrap.can_create_sandbox(probe_cwd.as_deref()) })
+ .await;
+
+ match availability {
+ Ok(()) => Some(wrap),
+ Err(reason) => {
+ sandbox_fallback = Some(format!(
+ "Note: failed to create the sandbox ({reason}); ran this command \
+ WITHOUT a sandbox."
+ ));
+ None
+ }
+ }
} else {
None
};
@@ -486,13 +582,11 @@ async fn run_terminal_tool(
let output = terminal.current_output(cx).map_err(|e| e.to_string())?;
- Ok(process_content(
- output,
- &input.command,
- timed_out,
- user_stopped,
- selection,
- ))
+ let result = process_content(output, &input.command, timed_out, user_stopped, selection);
+ Ok(match sandbox_fallback {
+ Some(note) => format!("{note}\n\n{result}"),
+ None => result,
+ })
}
/// Resolve model-requested write paths into absolute paths.
@@ -551,9 +645,25 @@ fn network_request_to_sandbox_network_access(
match network {
NetworkRequest::None => acp_thread::SandboxNetworkAccess::None,
NetworkRequest::AnyHost => acp_thread::SandboxNetworkAccess::All,
- NetworkRequest::Hosts(hosts) => acp_thread::SandboxNetworkAccess::Restricted(
- http_proxy::Allowlist::from_patterns(hosts.iter().cloned()),
- ),
+ NetworkRequest::Hosts(hosts) => {
+ #[cfg(target_os = "macos")]
+ {
+ acp_thread::SandboxNetworkAccess::Restricted(http_proxy::Allowlist::from_patterns(
+ hosts.iter().cloned(),
+ ))
+ }
+ // Only macOS (Seatbelt plus the loopback proxy) can confine egress
+ // to an allowlist; other sandboxes can only toggle the network
+ // wholesale, so a host-specific grant becomes full network access.
+ // `run_terminal_tool` widens once-requests to `AnyHost` up front so
+ // the approval prompt matches — this guards the persistent-grant
+ // path (host grants restored from settings).
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = hosts;
+ acp_thread::SandboxNetworkAccess::All
+ }
+ }
}
}
@@ -2360,14 +2470,6 @@ mod tests {
}
}
- fn host_request(list: &[&str]) -> NetworkRequest {
- NetworkRequest::Hosts(
- list.iter()
- .map(|h| http_proxy::HostPattern::parse(h).unwrap())
- .collect(),
- )
- }
-
#[test]
fn test_join_write_paths_resolves_relative_and_absolute() {
let base = PathBuf::from(if cfg!(windows) {
@@ -2455,66 +2557,6 @@ mod tests {
);
}
- #[test]
- fn test_sandbox_approval_title_all_access_and_network() {
- assert_eq!(
- sandbox_approval_title(&sandbox_request(NetworkRequest::AnyHost, true, &[])),
- "Allow arbitrary network access and unrestricted filesystem writes?"
- );
- assert_eq!(
- sandbox_approval_title(&sandbox_request(NetworkRequest::AnyHost, false, &[])),
- "Allow arbitrary network access?"
- );
- assert_eq!(
- sandbox_approval_title(&sandbox_request(NetworkRequest::None, true, &[])),
- "Allow unrestricted filesystem writes?"
- );
- }
-
- #[test]
- fn test_sandbox_approval_title_specific_hosts() {
- assert_eq!(
- sandbox_approval_title(&sandbox_request(host_request(&["github.com"]), false, &[])),
- "Allow network access to github.com?"
- );
- assert_eq!(
- sandbox_approval_title(&sandbox_request(
- host_request(&["github.com", "*.npmjs.org"]),
- false,
- &[]
- )),
- "Allow network access to github.com and *.npmjs.org?"
- );
- assert_eq!(
- sandbox_approval_title(&sandbox_request(
- host_request(&["github.com", "npmjs.org", "pypi.org"]),
- false,
- &[]
- )),
- "Allow network access to github.com, npmjs.org, and pypi.org?"
- );
- }
-
- #[test]
- fn test_sandbox_approval_title_per_path_writes() {
- assert_eq!(
- sandbox_approval_title(&sandbox_request(
- NetworkRequest::None,
- false,
- &["/tmp/build"]
- )),
- "Allow write access to /tmp/build?"
- );
- assert_eq!(
- sandbox_approval_title(&sandbox_request(
- host_request(&["github.com"]),
- false,
- &["/tmp/build"]
- )),
- "Allow network access to github.com and write access to /tmp/build?"
- );
- }
-
#[test]
fn test_sandbox_approval_title_summarizes_multiple_paths_by_count() {
let title = sandbox_approval_title(&sandbox_request(
@@ -2525,76 +2567,6 @@ mod tests {
assert_eq!(title, "Allow write access to 4 paths?");
}
- #[test]
- fn test_all_access_takes_precedence_over_paths_in_title() {
- // When all-access is requested, the specific paths are redundant and
- // should not be listed.
- assert_eq!(
- sandbox_approval_title(&sandbox_request(
- NetworkRequest::None,
- true,
- &["/tmp/build"]
- )),
- "Allow unrestricted filesystem writes?"
- );
- }
-
- #[test]
- fn test_build_network_request_validates_and_classifies() {
- // No fields -> None.
- assert_eq!(
- build_network_request(&TerminalSandboxInput::default()).unwrap(),
- NetworkRequest::None
- );
- // allow_all_hosts -> AnyHost, even alongside specific hosts.
- assert_eq!(
- build_network_request(&TerminalSandboxInput {
- allow_hosts: vec!["github.com".into()],
- allow_all_hosts: Some(true),
- ..Default::default()
- })
- .unwrap(),
- NetworkRequest::AnyHost
- );
- // Valid hosts parse to patterns.
- assert_eq!(
- build_network_request(&TerminalSandboxInput {
- allow_hosts: vec!["github.com".into(), "*.npmjs.org".into()],
- ..Default::default()
- })
- .unwrap(),
- host_request(&["github.com", "*.npmjs.org"])
- );
- // An IP literal is rejected with an actionable message.
- let err = build_network_request(&TerminalSandboxInput {
- allow_hosts: vec!["127.0.0.1".into()],
- ..Default::default()
- })
- .unwrap_err();
- assert!(err.contains("127.0.0.1"), "unexpected error: {err}");
- }
-
- #[test]
- fn test_network_request_to_sandbox_network_access_uses_explicit_unrestricted_variant() {
- match network_request_to_sandbox_network_access(&NetworkRequest::None) {
- acp_thread::SandboxNetworkAccess::None => {}
- other => panic!("expected no network access, got {other:?}"),
- }
-
- match network_request_to_sandbox_network_access(&NetworkRequest::AnyHost) {
- acp_thread::SandboxNetworkAccess::All => {}
- other => panic!("expected unrestricted network access, got {other:?}"),
- }
-
- match network_request_to_sandbox_network_access(&host_request(&["github.com"])) {
- acp_thread::SandboxNetworkAccess::Restricted(allowlist) => {
- assert!(allowlist.allows("github.com"));
- assert!(!allowlist.allows("example.com"));
- }
- other => panic!("expected restricted network access, got {other:?}"),
- }
- }
-
#[test]
fn test_input_schema_includes_sandbox_flags() {
// The sandboxed terminal tool advertises these fields so the model can
@@ -2686,6 +2658,7 @@ mod tests {
"command": "echo hi",
"cd": "root",
"allow_fs_write": true,
+ "reason": "needs to write outside the project",
}))
.expect("legacy allow_fs_write should deserialize");
@@ -2779,6 +2752,7 @@ mod tests {
"allow_all_hosts": true,
"allow_fs_write_all": true,
"unsandboxed": true,
+ "reason": "needs full access for this task",
}))
.expect("unsandboxed input should deserialize");
@@ -2843,4 +2817,148 @@ mod tests {
assert!(result.contains("user denied permission to run outside the sandbox"));
assert_eq!(environment.terminal_creation_count(), 0);
}
+
+ fn host_request(list: &[&str]) -> NetworkRequest {
+ NetworkRequest::Hosts(
+ list.iter()
+ .map(|h| http_proxy::HostPattern::parse(h).unwrap())
+ .collect(),
+ )
+ }
+
+ #[test]
+ fn test_sandbox_approval_title_all_access_and_network() {
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(NetworkRequest::AnyHost, true, &[])),
+ "Allow arbitrary network access and unrestricted filesystem writes?"
+ );
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(NetworkRequest::AnyHost, false, &[])),
+ "Allow arbitrary network access?"
+ );
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(NetworkRequest::None, true, &[])),
+ "Allow unrestricted filesystem writes?"
+ );
+ }
+
+ #[test]
+ fn test_sandbox_approval_title_specific_hosts() {
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(host_request(&["github.com"]), false, &[])),
+ "Allow network access to github.com?"
+ );
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(
+ host_request(&["github.com", "*.npmjs.org"]),
+ false,
+ &[]
+ )),
+ "Allow network access to github.com and *.npmjs.org?"
+ );
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(
+ host_request(&["github.com", "npmjs.org", "pypi.org"]),
+ false,
+ &[]
+ )),
+ "Allow network access to github.com, npmjs.org, and pypi.org?"
+ );
+ }
+
+ #[test]
+ fn test_sandbox_approval_title_per_path_writes() {
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(
+ NetworkRequest::None,
+ false,
+ &["/tmp/build"]
+ )),
+ "Allow write access to /tmp/build?"
+ );
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(
+ host_request(&["github.com"]),
+ false,
+ &["/tmp/build"]
+ )),
+ "Allow network access to github.com and write access to /tmp/build?"
+ );
+ }
+
+ #[test]
+ fn test_all_access_takes_precedence_over_paths_in_title() {
+ // When all-access is requested, the specific paths are redundant and
+ // should not be listed.
+ assert_eq!(
+ sandbox_approval_title(&sandbox_request(
+ NetworkRequest::None,
+ true,
+ &["/tmp/build"]
+ )),
+ "Allow unrestricted filesystem writes?"
+ );
+ }
+
+ #[test]
+ fn test_build_network_request_validates_and_classifies() {
+ // No fields -> None.
+ assert_eq!(
+ build_network_request(&TerminalSandboxInput::default()).unwrap(),
+ NetworkRequest::None
+ );
+ // allow_all_hosts -> AnyHost, even alongside specific hosts.
+ assert_eq!(
+ build_network_request(&TerminalSandboxInput {
+ allow_hosts: vec!["github.com".into()],
+ allow_all_hosts: Some(true),
+ ..Default::default()
+ })
+ .unwrap(),
+ NetworkRequest::AnyHost
+ );
+ // Valid hosts parse to patterns.
+ assert_eq!(
+ build_network_request(&TerminalSandboxInput {
+ allow_hosts: vec!["github.com".into(), "*.npmjs.org".into()],
+ ..Default::default()
+ })
+ .unwrap(),
+ host_request(&["github.com", "*.npmjs.org"])
+ );
+ // An IP literal is rejected with an actionable message.
+ let err = build_network_request(&TerminalSandboxInput {
+ allow_hosts: vec!["127.0.0.1".into()],
+ ..Default::default()
+ })
+ .unwrap_err();
+ assert!(err.contains("127.0.0.1"), "unexpected error: {err}");
+ }
+
+ #[test]
+ fn test_network_request_to_sandbox_network_access_uses_explicit_unrestricted_variant() {
+ match network_request_to_sandbox_network_access(&NetworkRequest::None) {
+ acp_thread::SandboxNetworkAccess::None => {}
+ other => panic!("expected no network access, got {other:?}"),
+ }
+
+ match network_request_to_sandbox_network_access(&NetworkRequest::AnyHost) {
+ acp_thread::SandboxNetworkAccess::All => {}
+ other => panic!("expected unrestricted network access, got {other:?}"),
+ }
+
+ // Only macOS can confine egress to an allowlist; other platforms can
+ // only toggle the network wholesale, so a host request becomes full
+ // access there.
+ match network_request_to_sandbox_network_access(&host_request(&["github.com"])) {
+ #[cfg(target_os = "macos")]
+ acp_thread::SandboxNetworkAccess::Restricted(allowlist) => {
+ assert!(allowlist.allows("github.com"));
+ assert!(!allowlist.allows("example.com"));
+ }
+ #[cfg(not(target_os = "macos"))]
+ acp_thread::SandboxNetworkAccess::All => {}
+ other => panic!("unexpected network access for host request, got {other:?}"),
+ }
+ }
}
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 35e87029365..e37e115a474 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -7796,7 +7796,11 @@ impl ThreadView {
.command
.as_deref()
.filter(|command| !command.is_empty());
- if details.write_paths.is_empty() && !has_network && command.is_none() {
+ if details.write_paths.is_empty()
+ && !has_network
+ && command.is_none()
+ && details.reason.is_empty()
+ {
return Empty.into_any_element();
}
@@ -7971,19 +7975,86 @@ impl ThreadView {
.when(is_open && !paths.is_empty(), |this| {
this.child(
v_flex()
- .id(("sandbox-authorization-paths-list", entry_ix))
- .max_h_40()
- .overflow_y_scroll()
- .children(paths.iter().enumerate().map(|(path_ix, path)| {
- self.render_sandbox_authorization_path_row(
- entry_ix,
- path_ix,
- path,
- path_ix < paths.len() - 1,
- cx,
- )
+ .gap_0p5()
+ .child(
+ Label::new("Reason from agent")
+ .size(LabelSize::XSmall)
+ .color(Color::Muted)
+ .buffer_font(cx),
+ )
+ .child(Label::new(details.reason.clone()).size(LabelSize::Small)),
+ )
+ })
+ .when(!paths.is_empty(), |this| {
+ this.child(
+ h_flex()
+ .id(("sandbox-authorization-details-header", entry_ix))
+ .p_1()
+ .justify_between()
+ .cursor_pointer()
+ .hover(|style| style.bg(cx.theme().colors().element_hover))
+ .child(
+ h_flex()
+ .gap_1()
+ .child(
+ Label::new("Write access")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ .child(
+ Label::new("•")
+ .size(LabelSize::XSmall)
+ .color(Color::Disabled),
+ )
+ .child(
+ Label::new(format!(
+ "{} {}",
+ paths.len(),
+ if paths.len() == 1 { "path" } else { "paths" }
+ ))
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ ),
+ )
+ .child(
+ Disclosure::new(("sandbox-authorization-details", entry_ix), is_open)
+ .opened_icon(IconName::ChevronUp)
+ .closed_icon(IconName::ChevronDown),
+ )
+ .on_click(cx.listener({
+ let tool_call_id = tool_call_id.clone();
+ move |this, _event, _window, cx| {
+ if this
+ .collapsed_sandbox_authorization_details
+ .remove(&tool_call_id)
+ {
+ cx.notify();
+ return;
+ }
+
+ this.collapsed_sandbox_authorization_details
+ .insert(tool_call_id.clone());
+ cx.notify();
+ }
})),
)
+ .when(is_open, |this| {
+ this.child(
+ v_flex()
+ .id(("sandbox-authorization-paths-list", entry_ix))
+ .max_h_40()
+ .overflow_y_scroll()
+ .children(paths.iter().enumerate().map(|(path_ix, path)| {
+ self.render_sandbox_authorization_path_row(
+ entry_ix,
+ path_ix,
+ path,
+ path_ix < paths.len() - 1,
+ cx,
+ )
+ })),
+ )
+ })
})
.into_any_element()
}
diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml
index 9e7e4aa1e0d..cafdd75b5dc 100644
--- a/crates/sandbox/Cargo.toml
+++ b/crates/sandbox/Cargo.toml
@@ -11,6 +11,26 @@ workspace = true
[lib]
path = "src/sandbox.rs"
+[features]
+# Builds `bwrap_test_helper`, the behavior helper driven by the NixOS sandbox
+# VM tests in `nix/tests/sandboxing`. Off by default so normal builds don't
+# produce the test binary.
+nixos-test = []
+
+# Behavior test helper for the Linux Bubblewrap sandbox. Only built when the
+# `nixos-test` feature is enabled (and only meaningful on Linux).
+[[bin]]
+name = "bwrap_test_helper"
+path = "src/bwrap_test_helper.rs"
+required-features = ["nixos-test"]
+
+[target.'cfg(target_os = "linux")'.dependencies]
+anyhow.workspace = true
+libc.workspace = true
+
+[target.'cfg(target_os = "linux")'.dev-dependencies]
+tempfile.workspace = true
+
[target.'cfg(target_os = "macos")'.dependencies]
anyhow.workspace = true
tempfile.workspace = true
diff --git a/crates/sandbox/src/bwrap_test_helper.rs b/crates/sandbox/src/bwrap_test_helper.rs
new file mode 100644
index 00000000000..021fa6df058
--- /dev/null
+++ b/crates/sandbox/src/bwrap_test_helper.rs
@@ -0,0 +1,531 @@
+//! Test binary used exclusively in the NixOS integration test for bwrap at
+//! `nix/tests/sandboxing`. See the comment there.
+
+#![allow(
+ clippy::disallowed_methods,
+ reason = "a single-threaded test helper that intentionally blocks on child processes"
+)]
+
+#[cfg(not(target_os = "linux"))]
+fn main() {
+ eprintln!("bwrap_test_helper is only supported on Linux");
+ std::process::exit(1);
+}
+
+#[cfg(target_os = "linux")]
+fn main() {
+ imp::main();
+}
+
+#[cfg(target_os = "linux")]
+mod imp {
+ use std::path::{Path, PathBuf};
+ use std::process::Command;
+ use std::time::Duration;
+
+ use anyhow::{Context as _, Result, bail};
+ use sandbox::SandboxPermissions;
+ use sandbox::linux_bubblewrap::{LauncherStatus, StatusChannel, wrap_invocation};
+
+ /// Internal subcommand: attempt an outbound TCP connection to the given
+ /// `host:port`, exiting 0 on success and 1 on any failure. Run *inside* the
+ /// sandbox to check whether the network is reachable.
+ const SUBCOMMAND_NET_CHECK: &str = "__net_check";
+ /// Internal subcommand: create an `AF_UNIX` socket, exiting 0 on success. Used
+ /// to confirm local IPC still works while IP networking is denied.
+ const SUBCOMMAND_UNIX_CHECK: &str = "__unix_check";
+
+ pub fn main() {
+ // If we were re-exec'd as the sandbox launcher, this sets up the sandbox and
+ // execs the wrapped command without returning.
+ sandbox::run_sandbox_launcher_if_invoked();
+
+ let args: Vec<String> = std::env::args().collect();
+ let result = match args.get(1).map(String::as_str) {
+ Some(SUBCOMMAND_NET_CHECK) => run_net_check(args.get(2).map(String::as_str)),
+ Some(SUBCOMMAND_UNIX_CHECK) => run_unix_check(),
+ _ => run_tests(),
+ };
+
+ if let Err(error) = result {
+ eprintln!("[sandbox_test]: FAILED: {error:#}");
+ std::process::exit(1);
+ }
+ }
+
+ /// Inner command: try to open a TCP connection. Inside the sandbox's own
+ /// network namespace there is no route out, so this exits non-zero.
+ ///
+ /// A host like `echo:7000` can resolve to several addresses (e.g. IPv6 and
+ /// IPv4); we must try all of them and only fail if none connect. Trying just
+ /// the first would spuriously "fail" the allowed-network case whenever the
+ /// first address happens to be one with no route (commonly IPv6).
+ fn run_net_check(address: Option<&str>) -> Result<()> {
+ use std::net::ToSocketAddrs as _;
+ let address = address.context("net check requires a host:port argument")?;
+ let resolved = address
+ .to_socket_addrs()
+ .with_context(|| format!("failed to resolve {address:?}"))?;
+ let mut last_error = None;
+ for socket_address in resolved {
+ match std::net::TcpStream::connect_timeout(&socket_address, Duration::from_secs(5)) {
+ Ok(_) => return Ok(()),
+ Err(error) => last_error = Some(error),
+ }
+ }
+ match last_error {
+ Some(error) => Err(error).with_context(|| format!("failed to connect to {address}")),
+ None => bail!("{address:?} resolved to no socket addresses"),
+ }
+ }
+
+ /// Inner command: create an `AF_UNIX` socket. Local IPC is not categorically
+ /// blocked by the sandbox, so this must succeed even when IP networking is
+ /// denied.
+ fn run_unix_check() -> Result<()> {
+ std::os::unix::net::UnixDatagram::unbound().context("failed to create AF_UNIX socket")?;
+ Ok(())
+ }
+
+ /// The outcome of driving the launcher once.
+ struct LaunchResult {
+ /// The status the launcher reported back, if any.
+ status: Option<LauncherStatus>,
+ /// Whether the launched command exited successfully.
+ command_succeeded: bool,
+ }
+
+ /// Drive the sandbox launcher the same way Zed's terminal integration does:
+ /// bind a status channel, build the launcher invocation, spawn it, and collect
+ /// both the reported status and the command's exit result.
+ fn drive_launcher(
+ program: &str,
+ args: &[String],
+ writable_dirs: &[&Path],
+ cwd: Option<&Path>,
+ permissions: SandboxPermissions,
+ ) -> Result<LaunchResult> {
+ let launcher = std::env::current_exe().context("failed to resolve current executable")?;
+ let launcher = launcher
+ .to_str()
+ .context("current executable path is not valid UTF-8")?;
+
+ let channel = StatusChannel::bind().context("failed to bind status channel")?;
+ let (launcher_program, launcher_args) = wrap_invocation(
+ launcher,
+ Some(channel.name()),
+ permissions,
+ writable_dirs,
+ cwd,
+ program,
+ args,
+ );
+
+ let mut child = Command::new(&launcher_program)
+ .args(&launcher_args)
+ .spawn()
+ .context("failed to spawn sandbox launcher")?;
+
+ // The launcher connects and reports before it execs, so read the status
+ // while the command runs, then wait for the command to finish.
+ let status = channel.recv(Duration::from_secs(30));
+ let exit = child.wait().context("failed to wait for launcher")?;
+
+ Ok(LaunchResult {
+ status,
+ command_succeeded: exit.success(),
+ })
+ }
+
+ /// Run `sh -c <script>` inside the sandbox and report whether it succeeded.
+ fn run_in_sandbox(
+ script: &str,
+ writable_dirs: &[&Path],
+ permissions: SandboxPermissions,
+ ) -> Result<LaunchResult> {
+ drive_launcher(
+ "sh",
+ &["-c".to_string(), script.to_string()],
+ writable_dirs,
+ None,
+ permissions,
+ )
+ }
+
+ /// Tracks assertion results so we can report a summary and a single exit code.
+ struct Checks {
+ passed: usize,
+ failed: usize,
+ }
+
+ impl Checks {
+ fn new() -> Self {
+ Self {
+ passed: 0,
+ failed: 0,
+ }
+ }
+
+ fn check(&mut self, description: &str, condition: bool) {
+ if condition {
+ self.passed += 1;
+ println!("[sandbox_test]: PASS: {description}");
+ } else {
+ self.failed += 1;
+ println!("[sandbox_test]: FAIL: {description}");
+ }
+ }
+
+ fn finish(self) -> Result<()> {
+ println!(
+ "[sandbox_test]: summary: {} passed, {} failed",
+ self.passed, self.failed
+ );
+ if self.failed > 0 {
+ bail!("{} sandbox assertion(s) failed", self.failed);
+ }
+ Ok(())
+ }
+ }
+
+ fn run_tests() -> Result<()> {
+ let expect_enforced = std::env::var("ZED_TEST_SANDBOX_ENFORCED").unwrap_or_default() == "1";
+ let echo_address = std::env::var("ZED_TEST_ECHO_ADDR").ok();
+ let expected_degrade_status = std::env::var("ZED_TEST_EXPECTED_DEGRADE_STATUS").ok();
+
+ println!(
+ "[sandbox_test]: starting (expect_enforced={expect_enforced}, echo={echo_address:?}, \
+ expected_degrade={expected_degrade_status:?})"
+ );
+
+ // A host scratch tree the sandbox tests write into. Kept outside `/tmp`
+ // because the sandbox overlays a fresh tmpfs there, which would mask
+ // whether writes really hit (or were blocked from hitting) the host.
+ let base = PathBuf::from(format!("/sandbox-test-{}", std::process::id()));
+ let writable = base.join("writable");
+ let forbidden = base.join("forbidden");
+ let readable = base.join("readable");
+ std::fs::create_dir_all(&writable).context("failed to create writable scratch dir")?;
+ std::fs::create_dir_all(&forbidden).context("failed to create forbidden scratch dir")?;
+ std::fs::create_dir_all(&readable).context("failed to create readable scratch dir")?;
+ let _cleanup = Cleanup(base);
+
+ if expect_enforced {
+ run_enforced_tests(&writable, &forbidden, &readable, echo_address.as_deref())
+ } else {
+ // Outside the enforced scenario, the sandbox could not be set up. The
+ // scenario tells us *why* so we can assert the exact reported status.
+ let expected = match expected_degrade_status.as_deref() {
+ Some("bwrap_not_found") => LauncherStatus::BwrapNotFound,
+ Some("probe_failed") => LauncherStatus::SandboxProbeFailed,
+ other => bail!(
+ "ZED_TEST_EXPECTED_DEGRADE_STATUS must be `bwrap_not_found` or \
+ `probe_failed`, got {other:?}"
+ ),
+ };
+ run_degraded_tests(&forbidden, expected)
+ }
+ }
+
+ /// Enforced scenario: unprivileged user namespaces are available and `bwrap`
+ /// is present, so the sandbox must actually be enforced. We assert, for every
+ /// access the sandbox is supposed to *grant*, that it really is granted, and
+ /// for every restriction it is supposed to *impose*, that it really holds.
+ fn run_enforced_tests(
+ writable: &Path,
+ forbidden: &Path,
+ readable: &Path,
+ echo_address: Option<&str>,
+ ) -> Result<()> {
+ // First confirm this environment can enforce a sandbox at all. Nested
+ // virtualization quirks can leave a VM unable to set up user namespaces
+ // even when we expected it to; in that case skip (rather than fail) the
+ // enforcement assertions, which would otherwise be testing nothing.
+ let probe = drive_launcher("true", &[], &[], None, SandboxPermissions::default())?;
+ if probe.status != Some(LauncherStatus::Success) {
+ println!(
+ "[sandbox_test]: SKIP: this environment cannot enforce a bwrap sandbox \
+ (probe status: {:?})",
+ probe.status
+ );
+ return Ok(());
+ }
+
+ let default = SandboxPermissions::default();
+ let fs_write_all = SandboxPermissions {
+ allow_network: false,
+ allow_fs_write: true,
+ };
+ let network_allowed = SandboxPermissions {
+ allow_network: true,
+ allow_fs_write: false,
+ };
+ let mut checks = Checks::new();
+
+ // GRANT: writing into a writable bind succeeds and lands on the host file.
+ let writable_file = writable.join("from-sandbox.txt");
+ let write_writable = run_in_sandbox(
+ &format!("echo zed > {}", shell_quote(&writable_file)),
+ &[writable],
+ default,
+ )?;
+ checks.check(
+ "GRANT: write into a writable dir succeeds",
+ write_writable.command_succeeded,
+ );
+ checks.check(
+ "GRANT: write into a writable dir lands on the host",
+ writable_file.exists(),
+ );
+ checks.check(
+ "default run reports Success",
+ write_writable.status == Some(LauncherStatus::Success),
+ );
+
+ // RESTRICT: writing outside any writable bind is denied by the read-only
+ // root, and must not leak to the host.
+ let forbidden_file = forbidden.join("escaped.txt");
+ let write_forbidden = run_in_sandbox(
+ &format!("echo zed > {}", shell_quote(&forbidden_file)),
+ &[],
+ default,
+ )?;
+ checks.check(
+ "RESTRICT: write outside writable dirs is denied",
+ !write_forbidden.command_succeeded,
+ );
+ checks.check(
+ "RESTRICT: denied write did not leak to the host",
+ !forbidden_file.exists(),
+ );
+
+ // GRANT: the whole filesystem is readable (root is bound read-only), so a
+ // host file outside every writable dir can still be read.
+ let readable_file = readable.join("host-data.txt");
+ std::fs::write(&readable_file, "host data").context("failed to seed readable file")?;
+ let read_host = run_in_sandbox(
+ &format!("cat {}", shell_quote(&readable_file)),
+ &[],
+ default,
+ )?;
+ checks.check(
+ "GRANT: host files outside writable dirs are still readable",
+ read_host.command_succeeded,
+ );
+
+ // GRANT + RESTRICT: `/tmp` is a writable tmpfs, but it is ephemeral and
+ // must not leak to the host's real `/tmp`.
+ let tmp_path = PathBuf::from(format!("/tmp/zed-sandbox-ephemeral-{}", std::process::id()));
+ let write_tmp = run_in_sandbox(
+ &format!("echo zed > {}", shell_quote(&tmp_path)),
+ &[],
+ default,
+ )?;
+ checks.check(
+ "GRANT: writing to /tmp succeeds",
+ write_tmp.command_succeeded,
+ );
+ checks.check(
+ "RESTRICT: /tmp writes are ephemeral (do not leak to the host)",
+ !tmp_path.exists(),
+ );
+
+ // RESTRICT + GRANT: outbound TCP is denied by the network namespace, but
+ // works when network access is explicitly granted (the latter also proves
+ // the peer is reachable, so the denial is the sandbox's doing).
+ if let Some(echo_address) = echo_address {
+ let net_denied = drive_launcher(
+ &current_exe_str()?,
+ &[SUBCOMMAND_NET_CHECK.to_string(), echo_address.to_string()],
+ &[],
+ None,
+ default,
+ )?;
+ checks.check(
+ "RESTRICT: outbound TCP is blocked when network is denied",
+ !net_denied.command_succeeded,
+ );
+
+ let net_allowed = drive_launcher(
+ &current_exe_str()?,
+ &[SUBCOMMAND_NET_CHECK.to_string(), echo_address.to_string()],
+ &[],
+ None,
+ network_allowed,
+ )?;
+ checks.check(
+ "GRANT: outbound TCP works when network is allowed",
+ net_allowed.command_succeeded,
+ );
+ } else {
+ println!("[sandbox_test]: SKIP: no ZED_TEST_ECHO_ADDR; skipping network checks");
+ }
+
+ // GRANT: local AF_UNIX IPC keeps working even while IP networking is
+ // denied.
+ let unix_ok = drive_launcher(
+ &current_exe_str()?,
+ &[SUBCOMMAND_UNIX_CHECK.to_string()],
+ &[],
+ None,
+ default,
+ )?;
+ checks.check(
+ "GRANT: AF_UNIX sockets still work while network is denied",
+ unix_ok.command_succeeded,
+ );
+
+ // GRANT (escape hatch): `allow_fs_write` lets the command write anywhere,
+ // and the write reaches the host.
+ let escape_file = forbidden.join("escape-hatch.txt");
+ let write_escape = run_in_sandbox(
+ &format!("echo zed > {}", shell_quote(&escape_file)),
+ &[],
+ fs_write_all,
+ )?;
+ checks.check(
+ "GRANT: allow_fs_write lets the command write outside writable dirs",
+ write_escape.command_succeeded,
+ );
+ checks.check(
+ "GRANT: allow_fs_write write lands on the host",
+ escape_file.exists(),
+ );
+ checks.check(
+ "allow_fs_write run reports Success",
+ write_escape.status == Some(LauncherStatus::Success),
+ );
+
+ // RESTRICT: permissions are independent — granting filesystem writes must
+ // not also grant network access.
+ if let Some(echo_address) = echo_address {
+ let net_with_fs_write = drive_launcher(
+ &current_exe_str()?,
+ &[SUBCOMMAND_NET_CHECK.to_string(), echo_address.to_string()],
+ &[],
+ None,
+ fs_write_all,
+ )?;
+ checks.check(
+ "RESTRICT: allow_fs_write does not also grant network access",
+ !net_with_fs_write.command_succeeded,
+ );
+ }
+
+ // RESTRICT: a setuid-root bwrap must be refused, and the launcher must
+ // abort (not run the command). We run as root in the VM, so we can build
+ // one.
+ check_setuid_rejected(&mut checks)?;
+
+ checks.finish()
+ }
+
+ /// Degraded scenario: the sandbox could not be set up (user namespaces
+ /// disabled, or no `bwrap` present). The launcher must report the specific
+ /// reason *and abort* — it never runs the command unsandboxed. (Falling back
+ /// to an unsandboxed run is the consumer's choice; the launcher, and these
+ /// tests, fail closed.)
+ fn run_degraded_tests(forbidden: &Path, expected_status: LauncherStatus) -> Result<()> {
+ let mut checks = Checks::new();
+
+ let forbidden_file = forbidden.join("degraded.txt");
+ let result = run_in_sandbox(
+ &format!("echo zed > {}", shell_quote(&forbidden_file)),
+ &[],
+ SandboxPermissions::default(),
+ )?;
+
+ checks.check(
+ &format!("reports {expected_status:?} when the sandbox can't be created"),
+ result.status == Some(expected_status),
+ );
+ // Fail closed: the launcher aborted, so the command did not run and the
+ // otherwise-forbidden write never happened.
+ checks.check(
+ "command does not run when the sandbox can't be created (fail-closed)",
+ !result.command_succeeded && !forbidden_file.exists(),
+ );
+
+ checks.finish()
+ }
+
+ /// Build a setuid-root copy of `bwrap`, put it alone on `PATH`, and assert the
+ /// launcher refuses to run it (reporting `SetuidRejected`) and aborts without
+ /// running the command.
+ fn check_setuid_rejected(checks: &mut Checks) -> Result<()> {
+ let Some(real_bwrap) = find_on_path("bwrap") else {
+ println!("[sandbox_test]: SKIP: no bwrap on PATH; skipping setuid rejection check");
+ return Ok(());
+ };
+
+ let dir = PathBuf::from(format!("/sandbox-test-setuid-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).context("failed to create setuid test dir")?;
+ let _cleanup = Cleanup(dir.clone());
+ let fake_bwrap = dir.join("bwrap");
+ std::fs::copy(&real_bwrap, &fake_bwrap).context("failed to copy bwrap")?;
+
+ // chown root (we are root) and set the setuid bit: 04755.
+ use std::os::unix::fs::PermissionsExt as _;
+ std::fs::set_permissions(&fake_bwrap, std::fs::Permissions::from_mode(0o4755))
+ .context("failed to set setuid bit on fake bwrap")?;
+
+ // Make the setuid copy the *only* bwrap visible, so the launcher can't fall
+ // back to a different one.
+ let previous_path = std::env::var_os("PATH");
+ // SAFETY: the helper is single-threaded here.
+ unsafe {
+ std::env::set_var("PATH", &dir);
+ }
+ let result = drive_launcher("true", &[], &[], None, SandboxPermissions::default());
+ // SAFETY: still single-threaded; restore PATH regardless of the outcome.
+ unsafe {
+ match previous_path {
+ Some(path) => std::env::set_var("PATH", path),
+ None => std::env::remove_var("PATH"),
+ }
+ }
+ let result = result?;
+
+ checks.check(
+ "a setuid-root bwrap is rejected",
+ result.status == Some(LauncherStatus::SetuidRejected),
+ );
+ checks.check(
+ "command does not run after rejecting setuid bwrap (fail-closed)",
+ !result.command_succeeded,
+ );
+
+ Ok(())
+ }
+
+ fn current_exe_str() -> Result<String> {
+ Ok(std::env::current_exe()
+ .context("failed to resolve current executable")?
+ .to_str()
+ .context("current executable path is not valid UTF-8")?
+ .to_string())
+ }
+
+ /// Find an executable named `name` by walking `PATH`.
+ fn find_on_path(name: &str) -> Option<PathBuf> {
+ let path = std::env::var_os("PATH")?;
+ std::env::split_paths(&path)
+ .map(|directory| directory.join(name))
+ .find(|candidate| candidate.is_file())
+ }
+
+ /// Single-quote a path for safe interpolation into an `sh -c` script.
+ fn shell_quote(path: &Path) -> String {
+ let raw = path.to_string_lossy();
+ format!("'{}'", raw.replace('\'', "'\\''"))
+ }
+
+ /// Removes a directory tree on drop, so scratch dirs don't pile up across runs.
+ struct Cleanup(PathBuf);
+
+ impl Drop for Cleanup {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+}
diff --git a/crates/sandbox/src/linux_bubblewrap.rs b/crates/sandbox/src/linux_bubblewrap.rs
new file mode 100644
index 00000000000..254f9f9602e
--- /dev/null
+++ b/crates/sandbox/src/linux_bubblewrap.rs
@@ -0,0 +1,832 @@
+//! Linux sandbox integration built on Bubblewrap (`bwrap`) for both the
+//! filesystem and the network.
+//!
+//! `bwrap` is an unprivileged container launcher: it sets up mount, user,
+//! pid, and other namespaces, bind-mounts the host filesystem (read-only by
+//! default, read-write for an explicit set of directories), then `exec`s the
+//! wrapped command inside that view. Network access can be wholly
+//! enabled/disabled using `--unshare-net`. More granular access will require
+//! seccomp.
+//!
+//! ## The launcher
+//!
+//! We fork/exec the running zed binary because:
+//! - previously we used landlock, which can only restrict the *current
+//! process*, so we need a subprocess running our code to restrict.
+//! - seccomp is similar, and while we don't have that yet, we will in the
+//! future, so we keep the machinery for now.
+//!
+//! This approach also avoids `pre_exec`, which is scary.
+//!
+//! ## Status reporting
+//!
+//! There are three possible error cases relating to sandboxing:
+//! - there is no `bwrap` on the path
+//! - there is a `bwrap` on the path, but it's a setuid binary (which we reject
+//! for security reasons)
+//! - there is a `bwrap` on the path, but it fails to create the sandbox (see
+//! [`probe_bwrap`]).
+//!
+//! If one of these happens, we report it back to the parent over a `SOCK_DGRAM`
+//! and then *abort*: the launcher never runs the command unsandboxed on its own.
+//! What to do about a failure is the caller's decision — the agent currently
+//! fails open (re-runs the command without a sandbox and tells the model so via
+//! [`check_can_create_sandbox`]), while the NixOS tests fail closed (treat it as
+//! a hard error). There's no UI for the agent's fallback yet; that's coming
+//! soon.
+
+use std::ffi::OsString;
+use std::os::linux::net::SocketAddrExt as _;
+use std::os::unix::fs::MetadataExt as _;
+use std::os::unix::net::{SocketAddr, UnixDatagram};
+use std::os::unix::process::CommandExt as _;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::Duration;
+
+use anyhow::{Context as _, Result, anyhow, bail};
+
+use crate::SandboxPermissions;
+
+/// The outcome a sandbox launcher reports back to the process that spawned it.
+///
+/// Only [`Success`](LauncherStatus::Success) means the command actually ran
+/// fully sandboxed; every other variant means the launcher could not enforce
+/// the sandbox and ran the command without one (with the reason reported here).
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum LauncherStatus {
+ /// The sandbox was fully enforced: `bwrap` filesystem and (when requested)
+ /// network isolation.
+ Success,
+ /// No usable `bwrap` binary was found on `PATH` (or bundled).
+ BwrapNotFound,
+ /// The only `bwrap` found is setuid-root, which we refuse to execute.
+ SetuidRejected,
+ /// `bwrap` is present but failed to set up the sandbox with our arguments
+ /// (typically because unprivileged user namespaces are disabled).
+ SandboxProbeFailed,
+}
+
+impl LauncherStatus {
+ fn to_byte(self) -> u8 {
+ match self {
+ LauncherStatus::Success => 0,
+ LauncherStatus::BwrapNotFound => 1,
+ LauncherStatus::SetuidRejected => 2,
+ LauncherStatus::SandboxProbeFailed => 3,
+ }
+ }
+
+ fn from_byte(byte: u8) -> Option<Self> {
+ match byte {
+ 0 => Some(LauncherStatus::Success),
+ 1 => Some(LauncherStatus::BwrapNotFound),
+ 2 => Some(LauncherStatus::SetuidRejected),
+ 3 => Some(LauncherStatus::SandboxProbeFailed),
+ _ => None,
+ }
+ }
+
+ /// Whether the command ran fully sandboxed.
+ pub fn is_success(self) -> bool {
+ matches!(self, LauncherStatus::Success)
+ }
+
+ /// A human-readable explanation suitable for a `log::warn` on a non-success
+ /// outcome.
+ pub fn describe(self) -> &'static str {
+ match self {
+ LauncherStatus::Success => "the sandbox was created",
+ LauncherStatus::BwrapNotFound => "no usable `bwrap` binary was found on PATH",
+ LauncherStatus::SetuidRejected => {
+ "the only available `bwrap` is setuid-root, which Zed refuses to run"
+ }
+ LauncherStatus::SandboxProbeFailed => {
+ "`bwrap` is present but failed to create a sandbox (unprivileged user \
+ namespaces may be disabled)"
+ }
+ }
+ }
+}
+
+/// A one-shot datagram socket the spawning process binds so a launcher can
+/// report its [`LauncherStatus`] back.
+///
+/// Uses a Linux *abstract* `AF_UNIX` address (no filesystem entry to create,
+/// permission, or clean up). A connectionless `SOCK_DGRAM` socket is all we
+/// need here: the launcher sends exactly one datagram and the parent receives
+/// it once. Because the socket is bound before the launcher is spawned, the
+/// kernel queues the datagram even if it arrives before [`recv`](Self::recv)
+/// is called.
+pub struct StatusChannel {
+ socket: UnixDatagram,
+ name: String,
+}
+
+impl StatusChannel {
+ /// Bind a fresh status channel with a unique abstract address.
+ pub fn bind() -> Result<Self> {
+ let name = unique_socket_name();
+ let address = SocketAddr::from_abstract_name(name.as_bytes())
+ .context("failed to build abstract socket address")?;
+ let socket =
+ UnixDatagram::bind_addr(&address).context("failed to bind sandbox status socket")?;
+ Ok(Self { socket, name })
+ }
+
+ /// The abstract address to hand to the launcher (see [`wrap_invocation`]).
+ pub fn name(&self) -> &str {
+ &self.name
+ }
+
+ /// Wait up to `timeout` for the launcher's one-shot status datagram.
+ ///
+ /// Returns `None` if nothing arrived in time, or the launcher exited /
+ /// `exec`ed without reporting (in which case the sandbox state is unknown).
+ pub fn recv(self, timeout: Duration) -> Option<LauncherStatus> {
+ self.socket.set_read_timeout(Some(timeout)).ok()?;
+ let mut byte = [0u8; 1];
+ let count = self.socket.recv(&mut byte).ok()?;
+ if count == 0 {
+ return None;
+ }
+ LauncherStatus::from_byte(byte[0])
+ }
+}
+
+/// A process-unique abstract socket name. The pid plus a monotonically
+/// increasing counter and the current time make collisions between concurrent
+/// launches (and between Zed instances) effectively impossible.
+fn unique_socket_name() -> String {
+ static COUNTER: AtomicU64 = AtomicU64::new(0);
+ let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|duration| duration.as_nanos())
+ .unwrap_or(0);
+ format!(
+ "zed-sandbox-status-{}-{}-{}",
+ std::process::id(),
+ nanos,
+ counter
+ )
+}
+
+/// Where a `bwrap` lookup ended up.
+enum BwrapLocation {
+ /// A usable, non-setuid `bwrap` binary.
+ Found(PathBuf),
+ /// `bwrap` exists but every candidate is setuid-root (which we won't run).
+ OnlySetuid,
+ /// No `bwrap` binary was found at all.
+ NotFound,
+}
+
+/// Locate a usable `bwrap` binary, preferring one on `PATH` and falling back to
+/// a binary bundled with the application.
+///
+/// We refuse setuid-root binaries (see [`is_setuid_root`]); if the only
+/// candidates are setuid we report [`BwrapLocation::OnlySetuid`] separately
+/// from "not found" so the user gets an accurate explanation.
+///
+/// This runs once per launcher process, so it is intentionally not cached.
+fn locate_bwrap() -> BwrapLocation {
+ let mut saw_setuid = false;
+ for candidate in candidate_bwrap_paths() {
+ if !candidate.is_file() {
+ continue;
+ }
+ if is_setuid_root(&candidate) {
+ saw_setuid = true;
+ continue;
+ }
+ return BwrapLocation::Found(candidate);
+ }
+ if saw_setuid {
+ BwrapLocation::OnlySetuid
+ } else {
+ BwrapLocation::NotFound
+ }
+}
+
+/// `bwrap` candidates in priority order: a system binary on `PATH` first, then
+/// a binary bundled with the application.
+fn candidate_bwrap_paths() -> Vec<PathBuf> {
+ let mut candidates = Vec::new();
+ if let Some(system) = system_bwrap_path() {
+ candidates.push(system);
+ }
+ if let Some(bundled) = bundled_bwrap_path() {
+ candidates.push(bundled);
+ }
+ candidates
+}
+
+/// The first `bwrap` found by walking `PATH`, if any.
+fn system_bwrap_path() -> Option<PathBuf> {
+ let path = std::env::var_os("PATH")?;
+ std::env::split_paths(&path)
+ .map(|directory| directory.join("bwrap"))
+ .find(|candidate| candidate.is_file())
+}
+
+/// Path to a `bwrap` binary bundled alongside the application, if one ships.
+///
+/// Bundling a statically linked, non-setuid `bwrap` is not yet wired up, so
+/// this returns `None` for now and only system binaries are used.
+fn bundled_bwrap_path() -> Option<PathBuf> {
+ None
+}
+
+/// Whether `path` is a setuid-root binary.
+///
+/// We refuse to use (or even probe) such a binary: our sandbox is built
+/// entirely on unprivileged user namespaces, so a setuid `bwrap` buys no
+/// functionality, and *running* one would mean executing root-privileged setup
+/// with argv partly derived from model-influenced input — a
+/// privilege-escalation surface. Rejecting it keeps the whole pipeline
+/// unprivileged and means a planted setuid binary earlier on `PATH` can't trick
+/// us into executing it.
+fn is_setuid_root(path: &Path) -> bool {
+ match std::fs::metadata(path) {
+ Ok(metadata) => (metadata.mode() & libc::S_ISUID != 0) && metadata.uid() == 0,
+ Err(_) => false,
+ }
+}
+
+/// Run `bwrap <args> -- true` and report whether it succeeded, i.e. whether
+/// this environment can actually set up the sandbox we're about to use.
+///
+/// Probing with the *exact* argument list we'll `exec` (rather than a minimal
+/// canned one) means we catch failures specific to this command's policy —
+/// e.g. a writable bind that can't be mounted — not just whether user
+/// namespaces work at all.
+#[allow(
+ clippy::disallowed_methods,
+ reason = "the launcher is a short-lived, single-threaded process that must block on the probe child"
+)]
+fn probe_bwrap(bwrap: &Path, bwrap_args: &[String]) -> bool {
+ Command::new(bwrap)
+ .args(bwrap_args)
+ .arg("--")
+ .arg("true")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .map(|status| status.success())
+ .unwrap_or(false)
+}
+
+/// Build the `bwrap` argument list (everything after the `bwrap` program and
+/// before the trailing `-- <command>`) for the given policy.
+///
+/// The default view binds the whole filesystem read-only, overlays fresh
+/// `/dev` and `/proc`, mounts an ephemeral `tmpfs` over `/tmp` (so programs
+/// that hardcode `/tmp` have somewhere to write without touching the host's
+/// `/tmp`), then binds each writable directory read-write on top. When
+/// `permissions.allow_fs_write` is set the root is bound read-write instead
+/// and these overlays/binds are omitted. When `permissions.allow_network` is
+/// false the command is placed in its own network namespace (`--unshare-net`),
+/// leaving it with only loopback and no route out.
+///
+/// `writable_directories` should be the project's worktree paths (plus any
+/// user-approved paths), *not* the command's working directory, which is
+/// model-controlled and would let the model widen its own writable scope.
+pub fn build_bwrap_args(
+ writable_directories: &[&Path],
+ permissions: SandboxPermissions,
+ cwd: Option<&Path>,
+) -> Vec<String> {
+ let mut args = Vec::new();
+
+ let root_bind = if permissions.allow_fs_write {
+ "--bind"
+ } else {
+ "--ro-bind"
+ };
+ push_bind(&mut args, root_bind, "/", "/");
+
+ args.push("--dev".to_string());
+ args.push("/dev".to_string());
+ args.push("--proc".to_string());
+ args.push("/proc".to_string());
+
+ if !permissions.allow_fs_write {
+ // A writable, ephemeral `/tmp`. This sits before the writable binds
+ // below so any writable directory under `/tmp` (e.g. the per-thread
+ // terminal temp directory) is re-exposed on top of the tmpfs and
+ // keeps its real, persistent contents.
+ args.push("--tmpfs".to_string());
+ args.push("/tmp".to_string());
+
+ for directory in writable_directories {
+ // bwrap can only bind a path that exists. A writable target may
+ // not have been created yet (e.g. a command that creates
+ // `/tmp/foo.txt`), so bind the nearest existing ancestor and let
+ // the command create paths beneath it.
+ let Some(existing) = nearest_existing_ancestor(directory) else {
+ continue;
+ };
+ let canonical = existing.canonicalize().unwrap_or(existing);
+ let path = canonical.to_string_lossy().into_owned();
+ push_bind(&mut args, "--bind", &path, &path);
+ }
+ }
+
+ for flag in [
+ "--unshare-user",
+ "--unshare-ipc",
+ "--unshare-uts",
+ "--unshare-pid",
+ "--unshare-cgroup-try",
+ "--die-with-parent",
+ ] {
+ args.push(flag.to_string());
+ }
+
+ // Deny network by giving the command its own network namespace (loopback
+ // only, no route out). `bwrap` brings up `lo` inside it.
+ if !permissions.allow_network {
+ args.push("--unshare-net".to_string());
+ }
+
+ if let Some(cwd) = cwd {
+ args.push("--chdir".to_string());
+ args.push(cwd.to_string_lossy().into_owned());
+ }
+
+ args
+}
+
+fn push_bind(args: &mut Vec<String>, flag: &str, source: &str, destination: &str) {
+ args.push(flag.to_string());
+ args.push(source.to_string());
+ args.push(destination.to_string());
+}
+
+/// Return the nearest ancestor of `path` (including `path` itself) that exists
+/// on disk, or `None` if nothing up to the root exists.
+fn nearest_existing_ancestor(path: &Path) -> Option<PathBuf> {
+ let mut candidate = Some(path);
+ while let Some(current) = candidate {
+ if current.exists() {
+ return Some(current.to_path_buf());
+ }
+ candidate = current.parent();
+ }
+ None
+}
+
+/// Marker passed as the first argument when this binary is re-executed as a
+/// sandbox launcher (see [`wrap_invocation`]). Intentionally unlikely to
+/// collide with a real argument.
+pub const SANDBOX_LAUNCHER_FLAG: &str = "--zed-linux-sandbox-exec";
+
+/// A decoded launcher invocation: the raw sandbox policy plus the command to
+/// run. The launcher itself turns this into a `bwrap` command line.
+struct LauncherInvocation {
+ /// Abstract address of the [`StatusChannel`] to report back on, if any.
+ status_socket: Option<String>,
+ permissions: SandboxPermissions,
+ cwd: Option<PathBuf>,
+ writable_dirs: Vec<PathBuf>,
+ program: OsString,
+ args: Vec<OsString>,
+}
+
+/// Build a self-exec launcher invocation.
+///
+/// Returns `(launcher_program, launcher_args)`, where running
+/// `launcher_program` with `launcher_args` re-execs this binary as the
+/// launcher. The launcher locates `bwrap`, assembles the sandbox command line,
+/// and reports its outcome on the [`StatusChannel`] named by
+/// `status_socket_name` (when given).
+///
+/// The encoding is positional, one value per argv entry, so paths and
+/// arguments containing spaces round-trip without escaping:
+/// `[FLAG, socket, allow_network, allow_fs_write, cwd, N, writable_1.., program, args..]`.
+pub fn wrap_invocation(
+ launcher_program: &str,
+ status_socket_name: Option<&str>,
+ permissions: SandboxPermissions,
+ writable_dirs: &[&Path],
+ cwd: Option<&Path>,
+ program: &str,
+ args: &[String],
+) -> (String, Vec<String>) {
+ let mut launcher_args = Vec::with_capacity(writable_dirs.len() + args.len() + 7);
+ launcher_args.push(SANDBOX_LAUNCHER_FLAG.to_string());
+ launcher_args.push(status_socket_name.unwrap_or("").to_string());
+ launcher_args.push(encode_bool(permissions.allow_network));
+ launcher_args.push(encode_bool(permissions.allow_fs_write));
+ launcher_args.push(
+ cwd.map(|cwd| cwd.to_string_lossy().into_owned())
+ .unwrap_or_default(),
+ );
+ launcher_args.push(writable_dirs.len().to_string());
+ for directory in writable_dirs {
+ launcher_args.push(directory.to_string_lossy().into_owned());
+ }
+ launcher_args.push(program.to_string());
+ launcher_args.extend(args.iter().cloned());
+ (launcher_program.to_string(), launcher_args)
+}
+
+/// If this process was re-executed as a sandbox launcher (its first argument
+/// is [`SANDBOX_LAUNCHER_FLAG`]), set up the sandbox and `exec` the wrapped
+/// command. This never returns when the marker is present.
+///
+/// Call this at the very top of `main`, before any argument parsing: the
+/// wrapped command's own arguments are appended verbatim and would otherwise
+/// confuse an argument parser.
+pub fn run_launcher_if_invoked() {
+ let Some(invocation) = parse_launcher_args(std::env::args_os()) else {
+ return;
+ };
+ let invocation = match invocation {
+ Ok(invocation) => invocation,
+ Err(error) => {
+ eprintln!("zed: malformed sandbox launcher invocation: {error:#}");
+ std::process::exit(127);
+ }
+ };
+ run_launcher(invocation);
+}
+
+/// Exit code the launcher uses when it could not create the sandbox. Distinct
+/// from a normal command's exit codes so the failure is unambiguous in logs;
+/// the authoritative signal to the parent is the [`LauncherStatus`] datagram.
+const SANDBOX_SETUP_FAILED_EXIT_CODE: i32 = 126;
+
+/// Set up the sandbox and `exec` the command. Never returns.
+///
+/// If the sandbox cannot be created for any reason, this reports the reason to
+/// the parent and **aborts** — it never runs the command unsandboxed. Falling
+/// back to an unsandboxed run is a policy decision that belongs to the caller
+/// (see [`check_can_create_sandbox`]), not to the sandbox itself.
+fn run_launcher(invocation: LauncherInvocation) -> ! {
+ let socket = invocation.status_socket.clone();
+ let writable: Vec<&Path> = invocation
+ .writable_dirs
+ .iter()
+ .map(PathBuf::as_path)
+ .collect();
+
+ let (bwrap, bwrap_args) =
+ match prepare_sandbox(&writable, invocation.permissions, invocation.cwd.as_deref()) {
+ Ok(prepared) => prepared,
+ Err(status) => {
+ report_status(socket.as_deref(), status);
+ eprintln!(
+ "zed: could not create sandbox: {}; aborting",
+ status.describe()
+ );
+ std::process::exit(SANDBOX_SETUP_FAILED_EXIT_CODE);
+ }
+ };
+
+ // Everything is in place: report success, then `exec` the sandboxed command.
+ // A failure of the final `exec` is fail-closed (a hard error, never a silent
+ // unsandboxed run).
+ report_status(socket.as_deref(), LauncherStatus::Success);
+ let error = Command::new(&bwrap)
+ .args(&bwrap_args)
+ .arg("--")
+ .arg(&invocation.program)
+ .args(&invocation.args)
+ .exec();
+ eprintln!(
+ "zed: failed to exec sandboxed command via bwrap: {error}; refusing to run unsandboxed"
+ );
+ std::process::exit(SANDBOX_SETUP_FAILED_EXIT_CODE);
+}
+
+/// Locate a usable `bwrap` and verify it can actually create a sandbox with the
+/// exact arguments implied by the policy (by running `bwrap <args> -- true`).
+///
+/// Returns the `bwrap` path and the assembled argument list on success, or the
+/// reason it can't on failure. Shared by the launcher (which then `exec`s) and
+/// by [`check_can_create_sandbox`] (which the parent uses to decide whether to
+/// fall back to an unsandboxed run).
+fn prepare_sandbox(
+ writable_dirs: &[&Path],
+ permissions: SandboxPermissions,
+ cwd: Option<&Path>,
+) -> Result<(PathBuf, Vec<String>), LauncherStatus> {
+ let bwrap = match locate_bwrap() {
+ BwrapLocation::Found(path) => path,
+ BwrapLocation::OnlySetuid => return Err(LauncherStatus::SetuidRejected),
+ BwrapLocation::NotFound => return Err(LauncherStatus::BwrapNotFound),
+ };
+ let bwrap_args = build_bwrap_args(writable_dirs, permissions, cwd);
+ if !probe_bwrap(&bwrap, &bwrap_args) {
+ return Err(LauncherStatus::SandboxProbeFailed);
+ }
+ Ok((bwrap, bwrap_args))
+}
+
+/// Check whether an OS sandbox can be created for this policy, returning the
+/// reason it can't (as a [`LauncherStatus`]) on failure.
+///
+/// This runs the same locate + probe the launcher does, so a caller can decide
+/// *before* spawning whether to run sandboxed, fall back to an unsandboxed run
+/// (fail-open), or refuse (fail-closed). The launcher still performs its own
+/// check and aborts on failure, so this is purely advisory — the sandbox is
+/// never silently skipped on the strength of this result alone.
+pub fn check_can_create_sandbox(
+ writable_dirs: &[&Path],
+ permissions: SandboxPermissions,
+ cwd: Option<&Path>,
+) -> std::result::Result<(), LauncherStatus> {
+ prepare_sandbox(writable_dirs, permissions, cwd).map(|_| ())
+}
+
+/// Send a one-shot `status` datagram to the status channel (if one was given).
+///
+/// Best-effort: if the parent has gone away or the send fails there is nothing
+/// useful to do, and we must never block the command on a diagnostic channel.
+/// This runs in the launcher (host network namespace) before `exec`, so it is
+/// unaffected by the command's own `--unshare-net` isolation.
+fn report_status(socket_name: Option<&str>, status: LauncherStatus) {
+ let Some(name) = socket_name else {
+ return;
+ };
+ let Ok(address) = SocketAddr::from_abstract_name(name.as_bytes()) else {
+ return;
+ };
+ let Ok(socket) = UnixDatagram::unbound() else {
+ return;
+ };
+ // Ignore send errors: the report is advisory and the parent may have
+ // already stopped listening.
+ let _ = socket.send_to_addr(&[status.to_byte()], &address);
+}
+
+/// Decode launcher arguments produced by [`wrap_invocation`].
+///
+/// `args` is the full process argv (including argv[0]). Returns `None` when
+/// this isn't a launcher invocation, or `Some(Err(_))` when the marker is
+/// present but the encoding is malformed.
+fn parse_launcher_args(
+ args: impl IntoIterator<Item = OsString>,
+) -> Option<Result<LauncherInvocation>> {
+ let mut args = args.into_iter();
+ // argv[0] is the executable; the marker, if any, is argv[1].
+ args.next()?;
+ if args.next()?.to_str() != Some(SANDBOX_LAUNCHER_FLAG) {
+ return None;
+ }
+ Some(decode_launcher_args(args))
+}
+
+fn decode_launcher_args(mut args: impl Iterator<Item = OsString>) -> Result<LauncherInvocation> {
+ let status_socket = {
+ let value = args.next().context("missing status socket argument")?;
+ let value = value
+ .into_string()
+ .map_err(|_| anyhow!("status socket name is not valid UTF-8"))?;
+ if value.is_empty() { None } else { Some(value) }
+ };
+ let allow_network = decode_bool(&args.next().context("missing allow_network flag")?)?;
+ let allow_fs_write = decode_bool(&args.next().context("missing allow_fs_write flag")?)?;
+ let cwd = {
+ let value = args.next().context("missing cwd argument")?;
+ if value.is_empty() {
+ None
+ } else {
+ Some(PathBuf::from(value))
+ }
+ };
+ let count = args
+ .next()
+ .context("missing writable directory count")?
+ .to_str()
+ .context("writable directory count is not valid UTF-8")?
+ .parse::<usize>()
+ .context("invalid writable directory count")?;
+ let mut writable_dirs = Vec::with_capacity(count);
+ for _ in 0..count {
+ writable_dirs.push(PathBuf::from(
+ args.next().context("missing writable directory")?,
+ ));
+ }
+ let program = args.next().context("missing program to run")?;
+ let args: Vec<OsString> = args.collect();
+
+ Ok(LauncherInvocation {
+ status_socket,
+ permissions: SandboxPermissions {
+ allow_network,
+ allow_fs_write,
+ },
+ cwd,
+ writable_dirs,
+ program,
+ args,
+ })
+}
+
+fn encode_bool(value: bool) -> String {
+ if value { "1" } else { "0" }.to_string()
+}
+
+fn decode_bool(value: &OsString) -> Result<bool> {
+ match value.to_str() {
+ Some("0") => Ok(false),
+ Some("1") => Ok(true),
+ other => bail!("invalid boolean launcher argument: {other:?}"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn launcher_argv(launcher: String, args: Vec<String>) -> Vec<OsString> {
+ std::iter::once(launcher)
+ .chain(args)
+ .map(OsString::from)
+ .collect()
+ }
+
+ #[test]
+ fn test_launcher_status_byte_round_trip() {
+ for status in [
+ LauncherStatus::Success,
+ LauncherStatus::BwrapNotFound,
+ LauncherStatus::SetuidRejected,
+ LauncherStatus::SandboxProbeFailed,
+ ] {
+ assert_eq!(LauncherStatus::from_byte(status.to_byte()), Some(status));
+ }
+ assert_eq!(LauncherStatus::from_byte(200), None);
+ }
+
+ #[test]
+ fn test_nearest_existing_ancestor() {
+ let dir = tempfile::tempdir().unwrap();
+ let existing = dir.path();
+ let missing = existing.join("a").join("b").join("c.txt");
+
+ assert_eq!(
+ nearest_existing_ancestor(&missing).unwrap(),
+ existing.to_path_buf()
+ );
+ assert_eq!(
+ nearest_existing_ancestor(existing).unwrap(),
+ existing.to_path_buf()
+ );
+ }
+
+ #[test]
+ fn test_build_bwrap_args_default_binds_writable_dirs_read_write() {
+ let writable = tempfile::tempdir().unwrap();
+ let args = build_bwrap_args(
+ &[writable.path()],
+ SandboxPermissions::default(),
+ Some(writable.path()),
+ );
+
+ // Root is read-only, the writable dir is bound read-write, and (since
+ // network is denied by default) the command gets its own net namespace.
+ assert!(windows_contains(&args, &["--ro-bind", "/", "/"]));
+ let writable_path = writable.path().canonicalize().unwrap();
+ let writable_str = writable_path.to_string_lossy().into_owned();
+ assert!(windows_contains(
+ &args,
+ &["--bind", &writable_str, &writable_str]
+ ));
+ assert!(windows_contains(&args, &["--tmpfs", "/tmp"]));
+ assert!(args.iter().any(|arg| arg == "--chdir"));
+ assert!(args.iter().any(|arg| arg == "--unshare-net"));
+ }
+
+ #[test]
+ fn test_build_bwrap_args_network_namespace_follows_permission() {
+ let denied = build_bwrap_args(&[], SandboxPermissions::default(), None);
+ assert!(denied.iter().any(|arg| arg == "--unshare-net"));
+
+ let allowed = build_bwrap_args(
+ &[],
+ SandboxPermissions {
+ allow_network: true,
+ allow_fs_write: false,
+ },
+ None,
+ );
+ assert!(!allowed.iter().any(|arg| arg == "--unshare-net"));
+ }
+
+ #[test]
+ fn test_build_bwrap_args_allow_fs_write_binds_root_read_write() {
+ let permissions = SandboxPermissions {
+ allow_network: false,
+ allow_fs_write: true,
+ };
+ let args = build_bwrap_args(&[], permissions, None);
+ assert!(windows_contains(&args, &["--bind", "/", "/"]));
+ assert!(!windows_contains(&args, &["--ro-bind", "/", "/"]));
+ // With unrestricted writes the host's real `/tmp` stays writable, so
+ // no ephemeral tmpfs is layered over it.
+ assert!(!windows_contains(&args, &["--tmpfs", "/tmp"]));
+ }
+
+ #[test]
+ fn test_launcher_args_round_trip() {
+ let writable = PathBuf::from("/home/user/project dir");
+ let cwd = PathBuf::from("/home/user/project dir/sub");
+ let program = "/bin/sh".to_string();
+ let args = vec!["-c".to_string(), "echo hi there".to_string()];
+ let permissions = SandboxPermissions {
+ allow_network: false,
+ allow_fs_write: false,
+ };
+
+ let (launcher, launcher_args) = wrap_invocation(
+ "/path/to/zed",
+ Some("zed-sandbox-status-abc"),
+ permissions,
+ &[writable.as_path()],
+ Some(cwd.as_path()),
+ &program,
+ &args,
+ );
+ assert_eq!(launcher, "/path/to/zed");
+
+ let decoded = parse_launcher_args(launcher_argv(launcher, launcher_args))
+ .expect("should be recognized as a launcher invocation")
+ .expect("should decode successfully");
+
+ assert_eq!(
+ decoded.status_socket.as_deref(),
+ Some("zed-sandbox-status-abc")
+ );
+ assert_eq!(decoded.permissions, permissions);
+ assert_eq!(decoded.cwd.as_deref(), Some(cwd.as_path()));
+ assert_eq!(decoded.writable_dirs, vec![writable]);
+ assert_eq!(decoded.program, OsString::from(program));
+ assert_eq!(
+ decoded.args,
+ args.into_iter().map(OsString::from).collect::<Vec<_>>()
+ );
+ }
+
+ #[test]
+ fn test_launcher_args_round_trip_minimal() {
+ let program = "/bin/true".to_string();
+ let permissions = SandboxPermissions {
+ allow_network: true,
+ allow_fs_write: true,
+ };
+ let (launcher, launcher_args) =
+ wrap_invocation("/path/to/zed", None, permissions, &[], None, &program, &[]);
+
+ let decoded = parse_launcher_args(launcher_argv(launcher, launcher_args))
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(decoded.status_socket, None);
+ assert_eq!(decoded.permissions, permissions);
+ assert_eq!(decoded.cwd, None);
+ assert!(decoded.writable_dirs.is_empty());
+ assert_eq!(decoded.program, OsString::from("/bin/true"));
+ assert!(decoded.args.is_empty());
+ }
+
+ #[test]
+ fn test_parse_launcher_args_ignores_non_launcher_argv() {
+ let raw: Vec<OsString> = ["/path/to/zed", "--foo", "bar"]
+ .into_iter()
+ .map(OsString::from)
+ .collect();
+ assert!(parse_launcher_args(raw).is_none());
+ }
+
+ #[test]
+ fn test_status_channel_round_trip() {
+ // The launcher side (`report_status`) and parent side
+ // (`StatusChannel::recv`) agree over a real abstract socket.
+ let channel = StatusChannel::bind().unwrap();
+ let name = channel.name().to_string();
+ let reader = std::thread::spawn(move || channel.recv(Duration::from_secs(5)));
+ report_status(Some(&name), LauncherStatus::SandboxProbeFailed);
+ assert_eq!(
+ reader.join().unwrap(),
+ Some(LauncherStatus::SandboxProbeFailed)
+ );
+ }
+
+ #[test]
+ fn test_status_channel_times_out_without_report() {
+ let channel = StatusChannel::bind().unwrap();
+ assert_eq!(channel.recv(Duration::from_millis(50)), None);
+ }
+
+ /// Whether `args` contains `needle` as a contiguous run.
+ fn windows_contains(args: &[String], needle: &[&str]) -> bool {
+ args.windows(needle.len())
+ .any(|window| window.iter().zip(needle).all(|(a, b)| a == b))
+ }
+}
diff --git a/crates/sandbox/src/sandbox.rs b/crates/sandbox/src/sandbox.rs
index 64095d11da2..22c23f04e37 100644
--- a/crates/sandbox/src/sandbox.rs
+++ b/crates/sandbox/src/sandbox.rs
@@ -5,8 +5,48 @@
//! its `target_os` cfg so callers reach for the right one explicitly and
//! non-host targets don't carry dead code.
//!
-//! Today only macOS has an integration ([`macos_seatbelt`]), wrapping
-//! Apple's Seatbelt / `sandbox-exec` framework.
+//! macOS has an integration ([`macos_seatbelt`]) wrapping Apple's Seatbelt
+//! / `sandbox-exec` framework, and Linux has one ([`linux_bubblewrap`]) built
+//! on Bubblewrap (`bwrap`) for both the filesystem and the network.
+
+#[cfg(target_os = "linux")]
+pub mod linux_bubblewrap;
#[cfg(target_os = "macos")]
pub mod macos_seatbelt;
+
+/// Per-command relaxations of the default Bubblewrap (Linux) sandbox.
+///
+/// All-false is the default, fully-sandboxed run. Setting any field
+/// requires user approval before the command is launched.
+///
+/// Network access is a plain on/off toggle here because Bubblewrap can only
+/// enforce it wholesale (an `--unshare-net` namespace, loopback only). macOS
+/// can additionally confine egress to an allowlist via Seatbelt and the
+/// in-process proxy, so it uses its own richer
+/// [`macos_seatbelt::SandboxPermissions`] instead of this type. Some baseline
+/// operations remain denied regardless of these flags; the only way to lift
+/// those is to skip the sandbox entirely, which these integrations
+/// deliberately don't expose.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct SandboxPermissions {
+ /// Allow network access for the command.
+ pub allow_network: bool,
+ /// Allow unrestricted filesystem writes.
+ pub allow_fs_write: bool,
+}
+
+/// Handle a possible re-exec of this binary as a sandbox launcher.
+///
+/// On Linux, the terminal integration sandboxes commands by re-executing
+/// this binary as a launcher (see
+/// [`linux_bubblewrap::run_launcher_if_invoked`]); when that marker is present
+/// this sets up the `bwrap` sandbox and `exec`s the wrapped command, never
+/// returning. On every other platform, and for normal launches, it returns
+/// immediately.
+///
+/// Call this at the very top of `main`, before any argument parsing.
+pub fn run_sandbox_launcher_if_invoked() {
+ #[cfg(target_os = "linux")]
+ linux_bubblewrap::run_launcher_if_invoked();
+}
diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml
index 5e125b7ec34..82c4f6ee409 100644
--- a/crates/zed/Cargo.toml
+++ b/crates/zed/Cargo.toml
@@ -178,6 +178,7 @@ repl.workspace = true
reqwest.workspace = true
reqwest_client.workspace = true
rope.workspace = true
+sandbox.workspace = true
search.workspace = true
serde.workspace = true
serde_json.workspace = true
diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs
index 01d2c7b08fe..31e3f0b0157 100644
--- a/crates/zed/src/main.rs
+++ b/crates/zed/src/main.rs
@@ -202,6 +202,13 @@ static STARTUP_TIME: OnceLock<Instant> = OnceLock::new();
fn main() {
STARTUP_TIME.get_or_init(|| Instant::now());
+ // If this process was re-executed as a sandbox launcher (Linux
+ // bwrap/seccomp), install the seccomp policy and exec the wrapped command
+ // without returning. Must run before argument parsing: the wrapped
+ // command's args are appended verbatim and would otherwise be
+ // misinterpreted as Zed's own arguments.
+ sandbox::run_sandbox_launcher_if_invoked();
+
#[cfg(unix)]
util::prevent_root_execution();
diff --git a/nix/modules/packages.nix b/nix/modules/packages.nix
index 9c6cf5e10ce..5c9b7391d11 100644
--- a/nix/modules/packages.nix
+++ b/nix/modules/packages.nix
@@ -18,8 +18,11 @@
};
}
// lib.optionalAttrs (lib.hasSuffix "linux" system) {
- checks.a11y-test = import ../tests/a11y.nix {
- inherit pkgs inputs;
- };
+ checks = {
+ a11y-test = import ../tests/a11y.nix {
+ inherit pkgs inputs;
+ };
+ }
+ // import ../tests/sandboxing { inherit pkgs inputs; };
};
}
diff --git a/nix/tests/sandboxing/bwrap_smoke_test.sh b/nix/tests/sandboxing/bwrap_smoke_test.sh
new file mode 100644
index 00000000000..9a6d6d4afa0
--- /dev/null
+++ b/nix/tests/sandboxing/bwrap_smoke_test.sh
@@ -0,0 +1,117 @@
+#!/usr/bin/env bash
+# Ad-hoc smoke test for the static `bwrap` binary. Exercises filesystem
+# read/write isolation and network isolation by trying to "break out" of the
+# sandbox in ways that must fail, alongside controls that must succeed.
+#
+# Usage: bwrap_smoke_test.sh /path/to/bwrap
+set -u
+
+BWRAP=${1:?usage: bwrap_smoke_test.sh /path/to/bwrap}
+
+# Resolve real binaries (works on NixOS, where /bin is mostly empty).
+CAT=$(command -v cat)
+TOUCH=$(command -v touch)
+SH=$(command -v sh)
+PY=$(command -v python3)
+
+# Bind enough of the host (read-only) for dynamically-linked helpers to run.
+# On NixOS that means the closure under /nix/store; /usr/bin elsewhere.
+BASE=(--ro-bind /nix /nix --ro-bind /run /run --proc /proc --dev /dev --unshare-user)
+[ -d /usr ] && BASE+=(--ro-bind /usr /usr)
+[ -e /bin ] && BASE+=(--ro-bind /bin /bin)
+[ -e /lib ] && BASE+=(--ro-bind /lib /lib)
+[ -e /lib64 ] && BASE+=(--ro-bind /lib64 /lib64)
+[ -e /etc ] && BASE+=(--ro-bind /etc /etc)
+
+PASS=0
+FAIL=0
+ok() { echo "PASS: $1"; PASS=$((PASS + 1)); }
+bad() { echo "FAIL: $1"; FAIL=$((FAIL + 1)); }
+
+# expect_ok <desc> <cmd...> -> command must exit 0
+expect_ok() {
+ desc=$1; shift
+ if "$@"; then ok "$desc"; else bad "$desc (expected success, got exit $?)"; fi
+}
+# expect_fail <desc> <cmd...> -> command must exit non-zero
+expect_fail() {
+ desc=$1; shift
+ if "$@"; then bad "$desc (expected failure, but it succeeded)"; else ok "$desc"; fi
+}
+
+# ---------------------------------------------------------------------------
+# Set up a host scratch tree:
+# $ROOT/secret/secret.txt -> must NOT be visible unless explicitly bound
+# $ROOT/allowed/note.txt -> bound read-only into the sandbox
+# $ROOT/writable/ -> bound read-write into the sandbox
+# ---------------------------------------------------------------------------
+ROOT=$(mktemp -d /tmp/bwrap-smoke.XXXXXX)
+trap 'rm -rf "$ROOT"' EXIT
+mkdir -p "$ROOT/secret" "$ROOT/allowed" "$ROOT/writable"
+echo "TOP SECRET" > "$ROOT/secret/secret.txt"
+echo "you may read me" > "$ROOT/allowed/note.txt"
+
+echo "=================================================================="
+echo "bwrap: $BWRAP"
+"$BWRAP" --version
+echo "=================================================================="
+echo "## Filesystem isolation"
+
+# The host secret must be invisible: sandbox sees a fresh tmpfs at $ROOT,
+# so the secret path simply doesn't exist.
+expect_fail "host secret file is NOT readable from sandbox" \
+ "$BWRAP" "${BASE[@]}" --tmpfs "$ROOT" "$CAT" "$ROOT/secret/secret.txt"
+
+# Likewise nothing under /tmp leaks in by default (no bind for it).
+expect_fail "host /tmp is NOT visible from sandbox" \
+ "$BWRAP" "${BASE[@]}" --tmpfs /tmp "$CAT" "$ROOT/allowed/note.txt"
+
+# An explicitly read-only bind IS readable...
+expect_ok "explicitly ro-bound file IS readable" \
+ "$BWRAP" "${BASE[@]}" --ro-bind "$ROOT/allowed" /data "$CAT" /data/note.txt
+
+# ...but writing to a read-only bind must fail.
+expect_fail "writing to a ro-bound dir is denied" \
+ "$BWRAP" "${BASE[@]}" --ro-bind "$ROOT/allowed" /data "$TOUCH" /data/evil
+
+# Confirm the host file was not modified/created behind the sandbox's back.
+expect_fail "ro-bind write did not leak to host" test -e "$ROOT/allowed/evil"
+
+# A read-write bind allows writes...
+expect_ok "writing to a rw-bound dir succeeds" \
+ "$BWRAP" "${BASE[@]}" --bind "$ROOT/writable" /data "$TOUCH" /data/hello
+
+# ...and the write really lands on the host file (proves the bind, not a tmpfs).
+expect_ok "rw-bind write is visible on host" test -e "$ROOT/writable/hello"
+
+# Writing to a tmpfs overlay succeeds inside, but must NOT touch the host dir.
+expect_ok "writing into a tmpfs works inside sandbox" \
+ "$BWRAP" "${BASE[@]}" --tmpfs "$ROOT/writable" "$TOUCH" "$ROOT/writable/ephemeral"
+expect_fail "tmpfs write did not leak to host" test -e "$ROOT/writable/ephemeral"
+
+echo "------------------------------------------------------------------"
+echo "## Network isolation"
+
+NETCHECK='import socket; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.settimeout(5); s.connect(("1.1.1.1",53)); print("connected")'
+
+# With --unshare-net the sandbox has only loopback: outbound TCP must fail.
+expect_fail "outbound TCP is blocked with --unshare-net" \
+ "$BWRAP" "${BASE[@]}" --unshare-net "$PY" -c "$NETCHECK"
+
+# Loopback still exists inside the isolated netns.
+expect_ok "loopback is up inside --unshare-net" \
+ "$BWRAP" "${BASE[@]}" --unshare-net "$PY" -c \
+ 'import socket; socket.socket().bind(("127.0.0.1",0)); print("lo ok")'
+
+# Without --unshare-net the host network is shared, so the same connect works
+# (skipped automatically if the host itself has no outbound connectivity).
+if timeout 6 "$PY" -c "$NETCHECK" >/dev/null 2>&1; then
+ expect_ok "outbound TCP works when network is shared" \
+ "$BWRAP" "${BASE[@]}" "$PY" -c "$NETCHECK"
+else
+ echo "SKIP: host has no outbound TCP; cannot test shared-network case"
+fi
+
+echo "=================================================================="
+echo "Summary: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/nix/tests/sandboxing/default.nix b/nix/tests/sandboxing/default.nix
new file mode 100644
index 00000000000..f97336d317b
--- /dev/null
+++ b/nix/tests/sandboxing/default.nix
@@ -0,0 +1,146 @@
+# NixOS VM tests for the Linux Bubblewrap (`bwrap`) sandbox.
+#
+# Unlike the old Landlock tests, bwrap's filesystem isolation does not scale
+# with the kernel ABI: any kernel with unprivileged user namespaces gives the
+# same guarantees. So instead of a kernel matrix we keep scenarios that capture
+# the cases that actually change behavior:
+#
+# sandbox-userns-enabled - bwrap present and unprivileged user namespaces
+# available; the sandbox must be enforced. The helper
+# asserts every grant the sandbox makes and every
+# restriction it imposes.
+# sandbox-userns-disabled - bwrap present but user namespaces disabled via
+# sysctl; the launcher must report SandboxProbeFailed
+# and degrade to an unsandboxed run.
+# sandbox-no-bwrap - no bwrap on PATH at all; the launcher must report
+# BwrapNotFound and degrade. This mirrors a machine
+# where the sandboxing feature is enabled but bwrap
+# simply isn't installed.
+#
+# The point of a VM is that whether bwrap can enforce a sandbox depends on
+# kernel configuration we can only set at boot. A second node runs a TCP echo
+# server so network isolation can be exercised against a real peer.
+#
+# Build one scenario:
+# nix build .#checks.x86_64-linux.sandbox-userns-enabled
+# Interactive:
+# nix run .#checks.x86_64-linux.sandbox-userns-enabled.driverInteractive
+{
+ pkgs,
+ inputs,
+}:
+let
+ lib = pkgs.lib;
+
+ bwrap-test-helper = import ./helper.nix { inherit pkgs inputs; };
+
+ echoPort = 7000;
+
+ mkTest =
+ {
+ name,
+ # Whether a `bwrap` binary is on the machine's PATH.
+ installBwrap ? true,
+ # Whether to disable unprivileged user namespaces at boot.
+ usernsDisabled ? false,
+ # For degraded scenarios, the exact status the launcher should report.
+ expectedDegradeStatus ? null,
+ }:
+ let
+ # The sandbox is only actually enforced when bwrap is present *and* user
+ # namespaces are available.
+ enforced = installBwrap && !usernsDisabled;
+ in
+ pkgs.testers.nixosTest {
+ inherit name;
+
+ nodes = {
+ # TCP echo server, so the network checks have a real peer to (fail to)
+ # reach from inside the sandbox.
+ echo =
+ { pkgs, ... }:
+ {
+ networking.firewall.allowedTCPPorts = [ echoPort ];
+ systemd.services.echo-server = {
+ description = "TCP echo server";
+ wantedBy = [ "multi-user.target" ];
+ after = [ "network.target" ];
+ serviceConfig = {
+ ExecStart = "${pkgs.socat}/bin/socat -d TCP-LISTEN:${toString echoPort},reuseaddr,fork EXEC:cat";
+ DynamicUser = true;
+ Restart = "on-failure";
+ };
+ };
+ };
+
+ # The machine under test.
+ machine =
+ { ... }:
+ {
+ boot.consoleLogLevel = lib.mkForce 3; # be quiet pls :)
+ services.journald.extraConfig = lib.mkAfter "MaxLevelConsole=notice";
+
+ # Disable unprivileged user namespaces for the degradation scenario.
+ # Capping the count at 0 makes `bwrap --unshare-user` fail, which is
+ # exactly what a hardened host looks like.
+ boot.kernel.sysctl = lib.mkIf usernsDisabled {
+ "user.max_user_namespaces" = 0;
+ };
+
+ # `bwrap` itself (the helper locates it on PATH) plus the helper.
+ # The no-bwrap scenario deliberately omits bubblewrap.
+ environment.systemPackages = [
+ bwrap-test-helper
+ ]
+ ++ lib.optionals installBwrap [ pkgs.bubblewrap ];
+
+ # The helper reads its expectations from the environment; setting
+ # them here means `machine.execute` picks them up via /etc/profile.
+ environment.variables = {
+ ZED_TEST_SANDBOX_ENFORCED = if enforced then "1" else "0";
+ ZED_TEST_ECHO_ADDR = "echo:${toString echoPort}";
+ }
+ // lib.optionalAttrs (expectedDegradeStatus != null) {
+ ZED_TEST_EXPECTED_DEGRADE_STATUS = expectedDegradeStatus;
+ };
+
+ virtualisation = {
+ memorySize = 1024;
+ cores = 2;
+ };
+ };
+ };
+
+ testScript = ''
+ start_all()
+
+ echo.wait_for_unit("echo-server.service")
+ echo.wait_for_open_port(${toString echoPort})
+
+ machine.wait_for_unit("multi-user.target")
+ machine.wait_until_succeeds("getent hosts echo", timeout=30)
+
+ # The helper logs each check to stdout/stderr tagged `[sandbox_test]:`,
+ # which the test backdoor wires to the serial console, so the lines
+ # appear inline in this log. `succeed` fails the test on a non-zero exit.
+ machine.succeed("bwrap_test_helper")
+ '';
+ };
+in
+{
+ sandbox-userns-enabled = mkTest {
+ name = "sandbox-userns-enabled";
+ };
+
+ sandbox-userns-disabled = mkTest {
+ name = "sandbox-userns-disabled";
+ usernsDisabled = true;
+ expectedDegradeStatus = "probe_failed";
+ };
+
+ sandbox-no-bwrap = mkTest {
+ name = "sandbox-no-bwrap";
+ installBwrap = false;
+ expectedDegradeStatus = "bwrap_not_found";
+ };
+}
diff --git a/nix/tests/sandboxing/helper.nix b/nix/tests/sandboxing/helper.nix
new file mode 100644
index 00000000000..85bc6d1d020
--- /dev/null
+++ b/nix/tests/sandboxing/helper.nix
@@ -0,0 +1,70 @@
+# Builds the `bwrap_test_helper` binary (sandbox crate, `nixos-test` feature)
+# used by the Bubblewrap sandbox VM tests in this directory.
+{
+ pkgs,
+ inputs,
+}:
+let
+ lib = pkgs.lib;
+
+ rustBin = inputs.rust-overlay.lib.mkRustBin { } pkgs;
+ rustToolchain = rustBin.fromRustupToolchainFile ../../../rust-toolchain.toml;
+ craneLib = (inputs.crane.mkLib pkgs).overrideToolchain rustToolchain;
+
+ src = builtins.path {
+ path = ../../../.;
+ filter =
+ path: type:
+ let
+ root = toString ../../../. + "/";
+ relPath = lib.removePrefix root path;
+ firstComp = builtins.head (lib.path.subpath.components relPath);
+ in
+ builtins.elem firstComp [
+ "crates"
+ "assets"
+ "extensions"
+ "script"
+ "tooling"
+ "Cargo.toml"
+ ".config"
+ ".cargo"
+ ];
+ name = "bwrap-test-helper-source";
+ };
+
+ commonArgs = {
+ pname = "bwrap-test-helper";
+ version = "0.0.0";
+ inherit src;
+ cargoLock = ../../../Cargo.lock;
+ cargoExtraArgs = "-p sandbox --bin bwrap_test_helper --features sandbox/nixos-test --locked";
+ CARGO_PROFILE = "dev";
+ doCheck = false;
+
+ cargoVendorDir = craneLib.vendorCargoDeps {
+ inherit src;
+ cargoLock = ../../../Cargo.lock;
+ };
+ };
+
+ cargoArtifacts = craneLib.buildDepsOnly commonArgs;
+in
+craneLib.buildPackage (
+ commonArgs
+ // {
+ inherit cargoArtifacts;
+
+ installPhase = ''
+ runHook preInstall
+ mkdir -p $out/bin
+ cp target/debug/bwrap_test_helper $out/bin/bwrap_test_helper
+ runHook postInstall
+ '';
+
+ meta = {
+ description = "Bubblewrap sandbox behavior test helper";
+ platforms = lib.platforms.linux;
+ };
+ }
+)
diff --git a/sandbox-bubblewrap-next-steps.md b/sandbox-bubblewrap-next-steps.md
new file mode 100644
index 00000000000..74eeff477f1
--- /dev/null
+++ b/sandbox-bubblewrap-next-steps.md
@@ -0,0 +1,65 @@
+# 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-`.
+
+## 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.
diff --git a/tooling/xtask/src/main.rs b/tooling/xtask/src/main.rs
index 655401af759..ca4eed8ac53 100644
--- a/tooling/xtask/src/main.rs
+++ b/tooling/xtask/src/main.rs
@@ -21,6 +21,8 @@ enum CliCommand {
PackageConformity(tasks::package_conformity::PackageConformityArgs),
/// Publishes GPUI and its dependencies to crates.io.
PublishGpui(tasks::publish_gpui::PublishGpuiArgs),
+ /// Runs the Linux Bubblewrap sandboxing NixOS VM tests.
+ SandboxTests(tasks::sandbox_tests::SandboxTestsArgs),
/// Downloads the pinned `webrtc-sys` release and configures `LK_CUSTOM_WEBRTC`.
SetupWebrtc(tasks::setup_webrtc::SetupWebrtcArgs),
/// Builds GPUI web examples and serves them.
@@ -40,6 +42,7 @@ fn main() -> Result<()> {
tasks::package_conformity::run_package_conformity(args)
}
CliCommand::PublishGpui(args) => tasks::publish_gpui::run_publish_gpui(args),
+ CliCommand::SandboxTests(args) => tasks::sandbox_tests::run_sandbox_tests(args),
CliCommand::SetupWebrtc(args) => tasks::setup_webrtc::run_setup_webrtc(args),
CliCommand::WebExamples(args) => tasks::web_examples::run_web_examples(args),
CliCommand::Workflows(args) => tasks::workflows::run_workflows(args),
diff --git a/tooling/xtask/src/tasks.rs b/tooling/xtask/src/tasks.rs
index affde2565c4..79aa9efe7b6 100644
--- a/tooling/xtask/src/tasks.rs
+++ b/tooling/xtask/src/tasks.rs
@@ -3,6 +3,7 @@ pub mod compliance;
pub mod licenses;
pub mod package_conformity;
pub mod publish_gpui;
+pub mod sandbox_tests;
pub mod setup_webrtc;
pub mod web_examples;
pub mod workflow_checks;
diff --git a/tooling/xtask/src/tasks/sandbox_tests.rs b/tooling/xtask/src/tasks/sandbox_tests.rs
new file mode 100644
index 00000000000..c885d97e8e0
--- /dev/null
+++ b/tooling/xtask/src/tasks/sandbox_tests.rs
@@ -0,0 +1,121 @@
+#![allow(clippy::disallowed_methods, reason = "tooling is exempt")]
+
+use std::process::Command;
+
+use anyhow::{Context as _, Result, bail};
+use clap::Parser;
+
+/// Runs the Linux Bubblewrap sandboxing NixOS VM tests (see `nix/tests/sandboxing`).
+///
+/// Each test boots a real kernel under QEMU to exercise bwrap behavior: one
+/// scenario with unprivileged user namespaces available (the sandbox must be
+/// enforced) and one with them disabled (the launcher must report the failure
+/// and degrade gracefully). They therefore only run on Linux with `/dev/kvm`
+/// available, and require `nix` with flakes enabled.
+#[derive(Parser)]
+pub struct SandboxTestsArgs {
+ /// Names of specific tests to run (e.g. `sandbox-userns-enabled`). Defaults
+ /// to all.
+ tests: Vec<String>,
+
+ /// Nix system to build for. Defaults to the host system.
+ #[arg(long)]
+ system: Option<String>,
+
+ /// Force already-built tests to re-run instead of returning the cached
+ /// result (passes `--rebuild` to `nix build`).
+ ///
+ /// This only works once a test has been built at least once; after changing
+ /// the test code the derivation changes, so run without `--rebuild` first.
+ #[arg(long)]
+ rebuild: bool,
+
+ /// List the available tests and exit without running anything.
+ #[arg(long)]
+ list: bool,
+}
+
+/// Tests in `nix/tests/sandboxing` are exposed as flake checks with this prefix.
+const TEST_PREFIX: &str = "sandbox-";
+
+pub fn run_sandbox_tests(args: SandboxTestsArgs) -> Result<()> {
+ let system = args.system.unwrap_or_else(host_system);
+ let available = available_tests(&system)?;
+
+ if args.list {
+ for name in &available {
+ println!("{name}");
+ }
+ return Ok(());
+ }
+
+ let selected = if args.tests.is_empty() {
+ available
+ } else {
+ for name in &args.tests {
+ if !available.contains(name) {
+ bail!(
+ "unknown sandbox test {name:?}; available: {}",
+ available.join(", ")
+ );
+ }
+ }
+ args.tests
+ };
+
+ if selected.is_empty() {
+ bail!("no sandbox tests found for system `{system}`");
+ }
+
+ let mut command = Command::new("nix");
+ command.args(["build", "-L", "--keep-going"]);
+ if args.rebuild {
+ command.arg("--rebuild");
+ }
+ for name in &selected {
+ command.arg(format!(".#checks.{system}.{name}"));
+ }
+
+ eprintln!("Running sandbox tests: {}", selected.join(", "));
+ let status = command.status().context("failed to run `nix build`")?;
+ if !status.success() {
+ bail!("sandbox tests failed");
+ }
+ Ok(())
+}
+
+/// The Nix system double for the host. These tests are Linux-only, so we always
+/// target a `*-linux` system (overridable via `--system`).
+fn host_system() -> String {
+ format!("{}-linux", std::env::consts::ARCH)
+}
+
+/// Query the flake for the names of the sandbox-test checks, so the task stays
+/// in sync with `nix/tests/sandboxing` without a hardcoded list.
+fn available_tests(system: &str) -> Result<Vec<String>> {
+ let output = Command::new("nix")
+ .args([
+ "eval",
+ &format!(".#checks.{system}"),
+ "--apply",
+ "checks: builtins.concatStringsSep \"\\n\" (builtins.attrNames checks)",
+ "--raw",
+ ])
+ .output()
+ .context("failed to run `nix eval` to list checks (is `nix` installed?)")?;
+ if !output.status.success() {
+ bail!(
+ "`nix eval` failed: {}",
+ String::from_utf8_lossy(&output.stderr).trim()
+ );
+ }
+
+ let names = String::from_utf8(output.stdout).context("`nix eval` output was not UTF-8")?;
+ let mut tests: Vec<String> = names
+ .lines()
+ .filter(|name| name.starts_with(TEST_PREFIX))
+ .map(str::to_string)
+ .collect();
+ tests.sort();
+ Ok(tests)
+}