diff --git a/Cargo.lock b/Cargo.lock
index 56940017e2c..069a21006e7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -524,6 +524,7 @@ dependencies = [
"remote_server",
"reqwest_client",
"rope",
+ "sandbox",
"schemars 1.0.4",
"search",
"semver",
@@ -15933,8 +15934,12 @@ name = "sandbox"
version = "0.1.0"
dependencies = [
"anyhow",
+ "futures 0.3.32",
+ "http_proxy",
"libc",
"log",
+ "serde",
+ "serde_json",
"smol",
"tempfile",
]
diff --git a/README.md b/README.md
index 9f641fb3841..36f8f1d2986 100644
--- a/README.md
+++ b/README.md
@@ -46,3 +46,12 @@ Zed is developed by **Zed Industries, Inc.**, a for-profit company.
If you’d like to financially support the project, you can do so via GitHub Sponsors.
Sponsorships go directly to Zed Industries and are used as general company revenue.
There are no perks or entitlements associated with sponsorship.
+
+
+
+- me: do a nixos integration test (using KVM)
+- agent: i need to turn off the sandbox
+- me: "allow for this thread"
+- agent: runs the tests unsandboxed
+- me: use the terminal to ls this directory
+- agent: runs `ls` *sandboxed*
\ No newline at end of file
diff --git a/assets/icons/lock_outlined_off.svg b/assets/icons/lock_outlined_off.svg
new file mode 100644
index 00000000000..74e5851dd75
--- /dev/null
+++ b/assets/icons/lock_outlined_off.svg
@@ -0,0 +1,7 @@
+
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index e11e9cbe590..cabdddfba19 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -60,45 +60,6 @@ impl std::fmt::Display for MaxOutputTokensError {
impl std::error::Error for MaxOutputTokensError {}
-/// Resolve the socket path(s) the sandbox may allow for the inherited
-/// `SSH_AUTH_SOCK`. The value is validated against the resolved directory
-/// environment the child command will actually run with, not Zed's own process
-/// environment, since the two can differ (direnv, a login shell, etc.).
-///
-/// Returns both the path as the child will pass it to `connect()` and its
-/// canonical form, because the two diverge when `SSH_AUTH_SOCK` points through
-/// a symlink (e.g. `/tmp` -> `/private/tmp` on macOS) and it isn't guaranteed
-/// which form Seatbelt matches the `remote unix-socket` literal against.
-#[cfg(unix)]
-fn trusted_ssh_auth_socket_paths(path: impl Into) -> Vec {
- let path = path.into();
- if !path.is_absolute() {
- return Vec::new();
- }
-
- let Ok(canonical) = path.canonicalize() else {
- return Vec::new();
- };
- let Ok(metadata) = std::fs::metadata(&canonical) else {
- return Vec::new();
- };
- use std::os::unix::fs::FileTypeExt as _;
- if !metadata.file_type().is_socket() {
- return Vec::new();
- }
-
- if canonical == path {
- vec![canonical]
- } else {
- vec![path, canonical]
- }
-}
-
-#[cfg(not(unix))]
-fn trusted_ssh_auth_socket_paths(_path: impl Into) -> Vec {
- Vec::new()
-}
-
/// Key used in ACP ToolCall meta to store the tool's programmatic name.
/// This is a workaround since ACP's ToolCall doesn't have a dedicated name field.
pub const TOOL_NAME_META_KEY: &str = "tool_name";
@@ -214,6 +175,7 @@ pub struct SandboxAuthorizationDetails {
/// builds still render the network request.
#[serde(default, alias = "network")]
pub network_all_hosts: bool,
+ /// Whether the command requested access to protected `.git` directories.
#[serde(default)]
pub allow_git_access: bool,
#[serde(default)]
@@ -3529,22 +3491,7 @@ impl AcpThread {
let terminal_task = cx.spawn({
let terminal_id = terminal_id.clone();
async move |_this, cx| {
- let mut env = env.await;
- let mut sandbox_wrap = sandbox_wrap;
- // Only expose the inherited SSH agent socket once Git access has
- // been approved. The workflow that needs it (commit signing)
- // already requires writing to `.git`, so gating it here keeps the
- // agent socket out of reach of ordinary sandboxed commands.
- // Validate the value the child will actually connect to, taken
- // from its resolved environment rather than Zed's own.
- if let Some(sandbox_wrap) = &mut sandbox_wrap
- && sandbox_wrap.allow_git_access
- && let Some(ssh_auth_socket) = env.get("SSH_AUTH_SOCK")
- {
- sandbox_wrap
- .allowed_unix_socket_paths
- .extend(trusted_ssh_auth_socket_paths(ssh_auth_socket.clone()));
- }
+ let env = env.await;
let shell = project
.update(cx, |project, cx| {
project
@@ -3552,107 +3499,66 @@ impl AcpThread {
.and_then(|r| r.read(cx).default_system_shell())
})
.unwrap_or_else(|| get_default_system_shell_preferring_bash());
- // Spawn the network proxy (if the wrap requests network) before
- // generating the sandbox policy, since the policy must pin the
- // child to the proxy's loopback port. This also injects the
- // child's proxy env vars. On Windows the WSL sandbox can only
- // toggle the network wholesale, so this never spawns a proxy
- // there, but it still resolves the allow/deny `network_policy`.
- let (proxy_handle, network_policy) =
- setup_network_proxy(sandbox_wrap.as_ref(), &mut env, cx)?;
+ // The sandbox owns the network proxy (for restricted-network
+ // policies) and injects the child's proxy env vars, returning
+ // the env to spawn with. On Windows, restricted host access is
+ // rejected inside the sandbox before command preparation.
#[cfg(target_os = "windows")]
- let (task_command, task_args, sandbox_config, spawn_cwd) =
- if let Some(sandbox_wrap) = sandbox_wrap {
- // Run the wrap on a background task: it probes WSL
- // (possibly booting its VM) and stats UNC paths,
- // either of which can take seconds and must not block
- // the foreground thread this task runs on. Bound it
- // with a timeout so a wedged `wsl.exe` can't stall
- // this command forever; on timeout, dropping the task
- // cancels the wrap future, which kills any in-flight
- // `wsl.exe` child (see `windows_wsl::wrap_invocation`).
- let wrap = cx.background_spawn(apply_windows_wsl_sandbox_wrap(
- command.clone(),
- args.clone(),
+ let (task_command, task_args, task_env, sandbox, spawn_cwd) =
+ if sandbox_wrap.is_some() {
+ let (task_command, task_args) = task::ShellBuilder::new(
+ &Shell::Program("/bin/sh".to_string()),
+ false,
+ )
+ .non_interactive()
+ .redirect_stdin_to_dev_null()
+ .build(Some(command.clone()), &args);
+ let wrap = cx.background_spawn(prepare_sandbox_wrap(
+ task_command,
+ task_args,
cwd.clone(),
sandbox_wrap,
- network_policy,
- env.clone(),
+ env,
));
let timeout = cx.background_executor().timer(WSL_SANDBOX_WRAP_TIMEOUT);
- let (task_command, task_args, sandbox_config) = futures::select_biased! {
+ let (task_command, task_args, task_env, sandbox) = futures::select_biased! {
result = wrap.fuse() => result?,
- // A wedged `wsl.exe` is an environment failure, so
- // surface it as `WslSandboxUnavailable` (like the
- // probe failures inside `wrap_invocation`) so the
- // agent offers the run-unsandboxed fallback rather
- // than returning a bad request to the model.
_ = timeout.fuse() => return Err(anyhow::Error::new(
- sandbox::windows_wsl::WslSandboxUnavailable::new(format!(
- "WSL did not respond within {} seconds while preparing the \
- sandboxed command",
+ sandbox::SandboxError::WslUnavailable(format!(
+ "WSL did not respond within {} seconds while preparing the sandboxed command",
WSL_SANDBOX_WRAP_TIMEOUT.as_secs()
)),
)),
};
- (task_command, task_args, sandbox_config, None)
+ (task_command, task_args, task_env, sandbox, None)
} else {
// No sandbox wrap means we're running unsandboxed, and
// on Windows that deliberately changes the shell: the
// sandboxed path runs under WSL's Linux bash, but this
- // fallback uses the host's `shell` (resolved above via
- // `get_default_system_shell_preferring_bash`) against
- // the native cwd. That resolution prefers Git Bash (or
- // scoop's bash), only dropping to the native Windows
- // shell (PowerShell/cmd) when no bash is installed — so
- // the interpreter usually stays bash-compatible, but its
- // path conventions differ from WSL's (e.g. `/c/...` or
- // native `C:\...` rather than `/mnt/c/...`). This is
- // unlike Linux/macOS, where the unsandboxed path (the
- // `#[cfg(not(target_os = "windows"))]` block below)
- // reuses the exact same shell and merely omits the bwrap
- // wrapper, so shell semantics are preserved untouched.
- //
- // The shell switch is intentional on Windows. The only
- // ways to reach this branch are: the model asking for
- // `unsandboxed: true` (often to run a Windows program),
- // the user choosing "run unsandboxed" after a sandbox-
- // creation failure, the `allow_unsandboxed` setting, or a
- // per-thread fallback grant. For the fallback cases the
- // command isn't one the model chose to run unsandboxed,
- // so the terminal tool's `sandbox_not_applied` note
- // warns it that the command ran without a sandbox *and*,
- // on Windows, that the shell and its path conventions
- // changed too (see `sandbox_note` in the terminal tool),
- // so it can adapt a command written for WSL.
+ // fallback uses the host's `shell` against the native cwd.
let (task_command, task_args) =
ShellBuilder::new(&Shell::Program(shell), is_windows)
.redirect_stdin_to_dev_null()
.build(Some(command.clone()), &args);
- (task_command, task_args, None, cwd.clone())
+ (task_command, task_args, env, None, cwd.clone())
};
- // On Linux/macOS the same shell (`/bin/sh`) is used whether or
- // not we sandbox: `ShellBuilder` builds the command, and
- // `apply_sandbox_wrap` either wraps it in bwrap (`Some`) or
- // returns it untouched (`None`). Either way the interpreter is
- // identical, so the unsandboxed fallback keeps shell semantics
- // intact — unlike Windows, which falls back to the host shell.
#[cfg(not(target_os = "windows"))]
- let (task_command, task_args, sandbox_config, spawn_cwd) = {
+ let (task_command, task_args, task_env, sandbox, spawn_cwd) = {
let (task_command, task_args) =
ShellBuilder::new(&Shell::Program(shell), is_windows)
.redirect_stdin_to_dev_null()
.build(Some(command.clone()), &args);
- let (task_command, task_args, sandbox_config) = apply_sandbox_wrap(
+ let (task_command, task_args, task_env, sandbox) = prepare_sandbox_wrap(
task_command,
task_args,
- cwd.as_deref(),
+ cwd.clone(),
sandbox_wrap,
- network_policy,
- )?;
- (task_command, task_args, sandbox_config, cwd.clone())
+ env,
+ )
+ .await?;
+ (task_command, task_args, task_env, sandbox, cwd.clone())
};
let terminal = project
.update(cx, |project, cx| {
@@ -3661,7 +3567,7 @@ impl AcpThread {
command: Some(task_command),
args: task_args,
cwd: spawn_cwd,
- env,
+ env: task_env,
..Default::default()
},
cx,
@@ -3677,8 +3583,7 @@ impl AcpThread {
output_byte_limit.map(|l| l as usize),
terminal,
language_registry,
- sandbox_config,
- proxy_handle,
+ sandbox,
cx,
)
}))
@@ -3761,7 +3666,6 @@ impl AcpThread {
// External terminal providers manage their own sandboxing
// (if any). We don't wrap their commands.
None,
- None,
cx,
)
});
@@ -3954,34 +3858,6 @@ mod tests {
});
}
- #[cfg(unix)]
- #[test]
- fn test_trusted_ssh_auth_socket_path_requires_socket() {
- use std::os::unix::net::UnixListener;
-
- // Bind under `/tmp`: the default temp dir on macOS (`/var/folders/...`)
- // overflows the `sun_path` limit for Unix sockets. `TempDir` still
- // cleans up on drop, even if the test panics.
- let temp_dir = tempfile::Builder::new()
- .prefix("zed-sock-")
- .tempdir_in("/tmp")
- .expect("temporary socket directory should be created");
- let socket_path = temp_dir.path().join("agent.sock");
- let listener = UnixListener::bind(&socket_path).expect("test socket should bind");
-
- // A real socket resolves to (at least) its canonical path.
- let canonical = socket_path
- .canonicalize()
- .expect("socket path should canonicalize");
- assert!(trusted_ssh_auth_socket_paths(socket_path).contains(&canonical));
-
- // A directory is not a socket, and a relative path is rejected outright.
- assert!(trusted_ssh_auth_socket_paths(temp_dir.path().to_path_buf()).is_empty());
- assert!(trusted_ssh_auth_socket_paths("relative.sock").is_empty());
-
- drop(listener);
- }
-
#[test]
fn sandbox_authorization_details_deserialize_legacy_network_bool() {
// Older builds persisted `network: bool`; the `alias` on
diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs
index 975d360e1a8..9bc9702728f 100644
--- a/crates/acp_thread/src/terminal.rs
+++ b/crates/acp_thread/src/terminal.rs
@@ -1,16 +1,15 @@
use agent_client_protocol::schema::v1 as acp;
-#[cfg(target_os = "linux")]
-use anyhow::Context as _;
use anyhow::Result;
use collections::HashMap;
use futures::{FutureExt as _, future::Shared};
use gpui::{App, AppContext, AsyncApp, Context, Entity, Task};
-use http_proxy::{Allowlist, ProxyConfig, ProxyEvent, ProxyHandle, UpstreamProxy};
+use http_proxy::Allowlist;
use language::LanguageRegistry;
use markdown::Markdown;
use project::Project;
use serde::{Deserialize, Serialize};
use std::{
+ collections::HashMap as StdHashMap,
path::PathBuf,
process::ExitStatus,
sync::{
@@ -35,10 +34,9 @@ use util::get_default_system_shell_preferring_bash;
#[derive(Clone, Debug, Default)]
pub struct SandboxWrap {
/// Directory subtrees the sandbox should allow writes to. Pass the
- /// project's worktree paths, Git metadata directories only when Git access
- /// has been approved, and any per-command scratch directory here — *not*
- /// the command's working directory, which is model-controlled and would
- /// let the model widen its own writable scope.
+ /// project's worktree paths (and any per-command scratch directory)
+ /// here — *not* the command's working directory, which is model-
+ /// controlled and would let the model widen its own writable scope.
pub writable_paths: Vec,
/// Additional write subtrees the user explicitly approved for this
/// command (per-path write grants). Kept separate from `writable_paths`
@@ -46,19 +44,15 @@ pub struct SandboxWrap {
/// model-requested paths that passed a user-approval prompt. They are
/// merged with `writable_paths` when generating the sandbox policy.
pub extra_write_paths: Vec,
- /// Paths whose file data reads and writes should be blocked even when they
- /// are inside a writable project directory. Metadata reads remain allowed.
- pub protected_paths: Vec,
- /// Unix domain sockets the sandbox should allow local IPC to. These come
- /// from trusted process environment, not from the model-controlled command.
- /// This does not permit IP networking or sending packets to other machines.
- pub allowed_unix_socket_paths: Vec,
- /// Whether the user approved Git metadata access for this command. When set,
- /// `.git` directories are writable (they are absent from `protected_paths`)
- /// and the inherited SSH agent socket may be exposed for commit signing.
- pub allow_git_access: bool,
/// Outbound network access explicitly approved for this command.
pub network: SandboxNetworkAccess,
+ /// The project's `.git` directories (worktree `.git`, linked-worktree common
+ /// dirs, discovered repos). Protected by default; made writable when
+ /// `allow_git_access` is set. Computed by the agent because locating them
+ /// needs Git knowledge the sandbox layer can't derive itself.
+ pub git_dirs: Vec,
+ /// Whether the user approved access to the protected `.git` directories.
+ pub allow_git_access: bool,
/// Allow unrestricted filesystem writes (ignores all writable paths).
pub allow_fs_write: bool,
/// Whether the project (and therefore this terminal) is local. The
@@ -80,18 +74,9 @@ pub enum SandboxNetworkAccess {
All,
}
-impl SandboxNetworkAccess {
- fn restricted_allowlist(&self) -> Option<&Allowlist> {
- match self {
- Self::Restricted(allowlist) => Some(allowlist),
- Self::None | Self::All => None,
- }
- }
-}
-
/// A structured, serializable reason the OS sandbox could not be created for a
-/// command. Mirrors the Linux/WSL launcher's failure modes (Bubblewrap);
-/// surfaced to the user (and persisted in tool-call metadata) so the UI can
+/// command. Mirrors the Linux/WSL Bubblewrap failure modes; surfaced to the user
+/// (and persisted in tool-call metadata) so the UI can
/// explain what went wrong.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum LinuxWslSandboxError {
@@ -106,6 +91,17 @@ pub enum LinuxWslSandboxError {
Other(String),
}
+impl From for LinuxWslSandboxError {
+ fn from(error: sandbox::SandboxError) -> Self {
+ match error {
+ sandbox::SandboxError::BwrapNotFound => Self::BwrapNotFound,
+ sandbox::SandboxError::BwrapSetuidRejected => Self::SetuidRejected,
+ sandbox::SandboxError::SandboxProbeFailed => Self::SandboxProbeFailed,
+ error => Self::Other(error.to_string()),
+ }
+ }
+}
+
impl LinuxWslSandboxError {
/// A short, user-facing explanation of why the sandbox couldn't be created,
/// suitable for display in the agent panel.
@@ -145,53 +141,41 @@ impl SandboxWrap {
&self,
cwd: Option<&std::path::Path>,
) -> Result<(), LinuxWslSandboxError> {
- #[cfg(target_os = "linux")]
- {
- use sandbox::linux_bubblewrap::LauncherStatus;
+ sandbox::Sandbox::can_create(&self.to_policy(), cwd).map_err(LinuxWslSandboxError::from)
+ }
- let writable: Vec<&std::path::Path> = self
- .writable_paths
- .iter()
- .chain(self.extra_write_paths.iter())
- .map(|path| path.as_path())
- .collect();
- let protected: Vec<&std::path::Path> = self
- .protected_paths
- .iter()
- .map(|path| path.as_path())
- .collect();
- let allowed_unix_sockets: Vec<&std::path::Path> = self
- .allowed_unix_socket_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,
- &protected,
- &allowed_unix_sockets,
- permissions,
- cwd,
- )
- .map_err(|status| match status {
- LauncherStatus::BwrapNotFound => LinuxWslSandboxError::BwrapNotFound,
- LauncherStatus::SetuidRejected => LinuxWslSandboxError::SetuidRejected,
- LauncherStatus::SandboxProbeFailed => LinuxWslSandboxError::SandboxProbeFailed,
- // `Success` never appears in the `Err` arm; map defensively.
- LauncherStatus::Success => {
- LinuxWslSandboxError::Other(status.describe().to_string())
- }
- })
- }
- #[cfg(not(target_os = "linux"))]
- {
- let _ = cwd;
- Ok(())
- }
+ /// Translate this request into the cross-platform [`sandbox::SandboxPolicy`].
+ fn to_policy(&self) -> sandbox::SandboxPolicy {
+ let fs = if self.allow_fs_write {
+ sandbox::SandboxFsPolicy::Unrestricted
+ } else {
+ sandbox::SandboxFsPolicy::Restricted {
+ writable_paths: self
+ .writable_paths
+ .iter()
+ .cloned()
+ .chain(self.extra_write_paths.iter().cloned())
+ .collect(),
+ }
+ };
+ let network = match &self.network {
+ SandboxNetworkAccess::None => sandbox::SandboxNetPolicy::Blocked,
+ SandboxNetworkAccess::All => sandbox::SandboxNetPolicy::Unrestricted,
+ SandboxNetworkAccess::Restricted(allowlist) => sandbox::SandboxNetPolicy::Restricted {
+ allowed_domains: allowlist
+ .patterns()
+ .iter()
+ .map(|pattern| pattern.to_string())
+ .collect(),
+ },
+ };
+ let git_dirs = self.git_dirs.clone();
+ let git = if self.allow_git_access {
+ sandbox::GitSandboxPolicy::Allowed { git_dirs }
+ } else {
+ sandbox::GitSandboxPolicy::Denied { git_dirs }
+ };
+ sandbox::SandboxPolicy { fs, network, git }
}
}
@@ -206,439 +190,67 @@ impl SandboxWrap {
/// grow their own failure cases later without a migration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SandboxNotAppliedReason {
- /// The user allowed unsandboxed execution for the rest of this thread after
- /// an earlier sandbox failure. There is always a preceding tool call whose
- /// reason is [`SandboxNotAppliedReason::ErrorLinuxWsl`].
+ /// The user disabled the sandbox for the rest of this thread, so the command
+ /// ran without one. This happens either when the user approved a
+ /// model-requested `unsandboxed: true` escape "for this thread", or when
+ /// they chose to run unsandboxed for the thread after a sandbox-creation
+ /// failure (in which case a preceding tool call's reason is
+ /// [`SandboxNotAppliedReason::ErrorLinuxWsl`]).
DisabledForThisThread,
/// The Linux/WSL (Bubblewrap) sandbox could not be created for this command.
ErrorLinuxWsl(LinuxWslSandboxError),
}
-/// 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
-/// whose only job is to drop with the entity.
-pub type SandboxConfigHandle = Box;
+/// The live sandbox kept alive for its per-command resources (the network proxy
+/// and, on macOS, the Seatbelt policy file) until the terminal exits.
+type SandboxConfigHandle = sandbox::Sandbox;
-/// The outbound-network policy resolved for a sandboxed command.
-pub(crate) enum NetworkPolicy {
- /// The command requested no outbound network.
- Denied,
- /// Egress is confined to the in-process proxy on this loopback port.
- Proxied(u16),
- /// The command explicitly requested, and the user approved, unrestricted
- /// outbound network access.
- Unrestricted,
-}
-
-/// Apply a [`SandboxWrap`] to a `(program, args)` pair, substituting the
-/// 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`].
-///
-/// 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 routes the command through WSL and runs it under Bubblewrap
-/// there, but that path is async (it performs `wsl.exe` round-trips), so it
-/// lives in [`apply_windows_wsl_sandbox_wrap`] rather than this synchronous
-/// function.
-/// * All other platforms pass the command through unchanged — we have no
-/// sandbox integration there, so the command runs with the agent's ambient
-/// permissions.
-#[cfg(not(target_os = "windows"))]
-pub(crate) fn apply_sandbox_wrap(
- program: String,
- args: Vec,
- cwd: Option<&std::path::Path>,
- sandbox_wrap: Option,
- network_policy: NetworkPolicy,
-) -> anyhow::Result<(String, Vec, Option)> {
- let Some(sandbox_wrap) = sandbox_wrap else {
- return Ok((program, args, None));
- };
-
- #[cfg(target_os = "macos")]
- {
- use sandbox::macos_seatbelt::NetworkAccess;
-
- let _ = cwd;
- let writable: Vec<&std::path::Path> = sandbox_wrap
- .writable_paths
- .iter()
- .chain(sandbox_wrap.extra_write_paths.iter())
- .map(|p| p.as_path())
- .collect();
- let protected: Vec<&std::path::Path> = sandbox_wrap
- .protected_paths
- .iter()
- .map(|path| path.as_path())
- .collect();
- let allowed_unix_sockets: Vec<&std::path::Path> = sandbox_wrap
- .allowed_unix_socket_paths
- .iter()
- .map(|path| path.as_path())
- .collect();
- let network = match network_policy {
- NetworkPolicy::Proxied(port) => NetworkAccess::LocalhostPort(port),
- NetworkPolicy::Unrestricted => NetworkAccess::All,
- NetworkPolicy::Denied => NetworkAccess::None,
- };
- let permissions = sandbox::macos_seatbelt::SandboxPermissions {
- network,
- allow_fs_write: sandbox_wrap.allow_fs_write,
- };
- let (new_program, new_args, config_file) = sandbox::macos_seatbelt::wrap_invocation(
- &program,
- &args,
- &writable,
- &protected,
- &allowed_unix_sockets,
- permissions,
- )?;
- Ok((
- new_program,
- new_args,
- Some(Box::new(config_file) as SandboxConfigHandle),
- ))
- }
- #[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 protected: Vec<&std::path::Path> = sandbox_wrap
- .protected_paths
- .iter()
- .map(|p| p.as_path())
- .collect();
- let allowed_unix_sockets: Vec<&std::path::Path> = sandbox_wrap
- .allowed_unix_socket_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,
- &protected,
- &allowed_unix_sockets,
- 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(not(any(target_os = "macos", target_os = "linux")))]
- {
- // 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, cwd);
- Ok((program, args, None))
- }
-}
-
-/// Upper bound on preparing a WSL-sandboxed command (the probe and path
-/// resolution `wsl.exe` round-trips in [`apply_windows_wsl_sandbox_wrap`]).
-/// Deliberately generous: the first invocation after the WSL utility VM has
-/// shut down (or after boot) has to start the VM and the distro, which
-/// routinely takes 10-30 seconds on slow disks or under antivirus scanning.
-/// The point is not latency policing but turning a wedged `wsl.exe` (a real
-/// failure mode when the WSL service is unhealthy) into an actionable error
-/// instead of a terminal command that never starts.
+/// Upper bound on preparing a WSL-sandboxed command. Deliberately generous:
+/// the first invocation after the WSL utility VM has shut down (or after boot)
+/// has to start the VM and the distro, which routinely takes 10-30 seconds on
+/// slow disks or under antivirus scanning.
#[cfg(target_os = "windows")]
pub(crate) const WSL_SANDBOX_WRAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
-/// Wrap a terminal command so it runs under Bubblewrap inside WSL (see
-/// [`sandbox::windows_wsl`]).
+/// Wrap `(program, args)` for sandboxed execution, returning the wrapped
+/// invocation (program, argv, env) plus the live [`sandbox::Sandbox`] that must
+/// be kept alive for the command's duration. When `sandbox_wrap` is `None` the
+/// command is returned unchanged.
///
-/// Async because it performs `wsl.exe` round-trips and UNC-path stats that
-/// can take seconds when the WSL VM is cold; callers must run it on a
-/// background executor so the UI thread is never blocked, and should bound
-/// it with [`WSL_SANDBOX_WRAP_TIMEOUT`]. Parameters are owned so the future
-/// is `Send + 'static`. Dropping the future (timeout or caller cancellation)
-/// kills any in-flight `wsl.exe` child rather than leaking it.
-///
-/// The Windows sandbox (Bubblewrap inside WSL) can only toggle network access
-/// wholesale, so `network_policy` collapses to allow/deny here just as it does
-/// on Linux. `setup_network_proxy` never resolves to `Proxied` on Windows.
-#[cfg(target_os = "windows")]
-pub(crate) async fn apply_windows_wsl_sandbox_wrap(
- command: String,
+/// The sandbox owns the network proxy (for restricted-network policies) and any
+/// per-command policy file; the env it returns already routes through that
+/// proxy when applicable.
+pub(crate) async fn prepare_sandbox_wrap(
+ program: String,
args: Vec,
- cwd: Option,
- sandbox_wrap: SandboxWrap,
- network_policy: NetworkPolicy,
- env: collections::HashMap,
-) -> anyhow::Result<(String, Vec, Option)> {
- let allow_network = match network_policy {
- NetworkPolicy::Denied => false,
- NetworkPolicy::Unrestricted => true,
- NetworkPolicy::Proxied(port) => {
- // Bubblewrap (in WSL) 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 Windows;
- // deny network rather than silently widening access.
- log::debug!(
- "[sandbox/network] ignoring proxy port {port}; bubblewrap in WSL can't confine to a loopback port"
- );
- false
- }
- };
- let (program, args) = task::ShellBuilder::new(&Shell::Program("/bin/sh".to_string()), false)
- .non_interactive()
- .redirect_stdin_to_dev_null()
- .build(Some(command), &args);
- let writable: Vec = sandbox_wrap
- .writable_paths
- .into_iter()
- .chain(sandbox_wrap.extra_write_paths)
- .collect();
- let permissions = sandbox::SandboxPermissions {
- allow_network,
- allow_fs_write: sandbox_wrap.allow_fs_write,
- };
- let (program, args) =
- sandbox::windows_wsl::wrap_invocation(program, args, writable, permissions, cwd, env)
- .await?;
- Ok((program, args, None))
-}
-
-/// Spawn the in-process network proxy for a sandboxed command with restricted
-/// network access, and wire the child's environment to route through it.
-///
-/// Returns the proxy handle (which must outlive the command) alongside the
-/// resolved [`NetworkPolicy`] the sandbox should enforce. The handle is `Some`
-/// only when a proxy was actually spawned. Unrestricted network access skips
-/// proxy setup and resolves to [`NetworkPolicy::Unrestricted`]. Restricted
-/// network access requires a local macOS project so the sandbox can confine
-/// egress to the proxy; otherwise this rejects the command instead of widening
-/// it.
-pub(crate) fn setup_network_proxy(
- sandbox_wrap: Option<&SandboxWrap>,
- env: &mut HashMap,
- cx: &mut AsyncApp,
-) -> Result<(Option, NetworkPolicy)> {
+ cwd: Option,
+ sandbox_wrap: Option,
+ env: HashMap,
+) -> anyhow::Result<(
+ String,
+ Vec,
+ HashMap,
+ Option,
+)> {
let Some(sandbox_wrap) = sandbox_wrap else {
- return Ok((None, NetworkPolicy::Denied));
- };
- let Some(allowlist) = sandbox_wrap.network.restricted_allowlist() else {
- let policy = match &sandbox_wrap.network {
- SandboxNetworkAccess::None => NetworkPolicy::Denied,
- SandboxNetworkAccess::All => NetworkPolicy::Unrestricted,
- SandboxNetworkAccess::Restricted(_) => unreachable!(),
- };
- return Ok((None, policy));
+ return Ok((program, args, env, None));
};
- // The proxy only buys us anything when a Seatbelt sandbox confines the
- // child to its loopback port, and only works for local projects.
- if !cfg!(target_os = "macos") || !sandbox_wrap.is_local {
- anyhow::bail!("restricted network access requested, but no enforcing proxy is available");
- }
-
- // Chain through the user's real upstream proxy if the command's environment
- // names one. A malformed value shouldn't break the terminal, so log and skip.
- let upstream = match upstream_proxy_from_child_env(env) {
- Ok(upstream) => upstream,
- Err(error) => {
- log::warn!("[sandbox/network] ignoring upstream proxy env: {error:#}");
- None
- }
+ let mut sandbox =
+ sandbox::Sandbox::new(sandbox_wrap.to_policy()).map_err(anyhow::Error::new)?;
+ let command = sandbox::CommandAndArgs {
+ program,
+ args,
+ env: env.into_iter().collect::>(),
+ cwd,
};
-
- let (events_tx, events_rx) = futures::channel::mpsc::unbounded();
- let handle = ProxyHandle::spawn(ProxyConfig {
- allowlist: allowlist.clone(),
- upstream,
- events: events_tx,
- })?;
- let port = handle.port();
-
- apply_proxy_env(env, port);
- spawn_proxy_event_logger(events_rx, cx);
-
- Ok((Some(handle), NetworkPolicy::Proxied(port)))
-}
-
-fn upstream_proxy_from_child_env(env: &HashMap) -> Result