Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
sandbox: Linux domain filtering and some more cleanup (#59790)
Cameron Mcloughlinc49a29f46179
diff --git a/Cargo.lock b/Cargo.lockindex 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.mdindex 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 filediff --git a/assets/icons/lock_outlined_off.svg b/assets/icons/lock_outlined_off.svgnew file mode 100644index 00000000000..74e5851dd75--- /dev/null+++ b/assets/icons/lock_outlined_off.svg@@ -0,0 +1,7 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M5 5C5 3.89543 5.89543 3 7 3H9C10.1046 3 11 3.89543 11 5V6H5V5Z" stroke="black" stroke-width="1.2"/>+<path d="M8 9V11" stroke="black" stroke-width="1.2" stroke-linecap="round"/>+<circle cx="8" cy="9" r="1" fill="black"/>+<rect x="3.75" y="5.75" width="8.5" height="7.5" rx="1.25" stroke="black" stroke-width="1.2" stroke-linejoin="round"/>+<path d="M2.5 2.5L13.5 13.5" stroke="black" stroke-width="1.2" stroke-linecap="round"/>+</svg>diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 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<PathBuf>) -> Vec<PathBuf> {- 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<PathBuf>) -> Vec<PathBuf> {- 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` ondiff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rsindex 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<PathBuf>,/// 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<PathBuf>,- /// 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<PathBuf>,- /// 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<PathBuf>,- /// 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<PathBuf>,+ /// 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<sandbox::SandboxError> 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;-- 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(())- }+ sandbox::Sandbox::can_create(&self.to_policy(), cwd).map_err(LinuxWslSandboxError::from)+ }++ /// 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<dyn std::any::Any + Send>;--/// 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,-}+/// 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;-/// 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<String>,- cwd: Option<&std::path::Path>,- sandbox_wrap: Option<SandboxWrap>,- network_policy: NetworkPolicy,-) -> anyhow::Result<(String, Vec<String>, Option<SandboxConfigHandle>)> {- 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<String>,- cwd: Option<std::path::PathBuf>,- sandbox_wrap: SandboxWrap,- network_policy: NetworkPolicy,- env: collections::HashMap<String, String>,-) -> anyhow::Result<(String, Vec<String>, Option<SandboxConfigHandle>)> {- 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<std::path::PathBuf> = 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<String, String>,- cx: &mut AsyncApp,-) -> Result<(Option<ProxyHandle>, NetworkPolicy)> {+ cwd: Option<PathBuf>,+ sandbox_wrap: Option<SandboxWrap>,+ env: HashMap<String, String>,+) -> anyhow::Result<(+ String,+ Vec<String>,+ HashMap<String, String>,+ Option<SandboxConfigHandle>,+)> {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::<StdHashMap<_, _>>(),+ 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<String, String>) -> Result<Option<UpstreamProxy>> {- let url = first_nonempty_env_value(- env,- &[- "HTTPS_PROXY",- "https_proxy",- "ALL_PROXY",- "all_proxy",- "HTTP_PROXY",- "http_proxy",- ],- );- let no_proxy = first_nonempty_env_value(env, &["NO_PROXY", "no_proxy"]);- UpstreamProxy::parse(url, no_proxy)-}--fn first_nonempty_env_value<'a>(- env: &'a HashMap<String, String>,- names: &[&str],-) -> Option<&'a str> {- for name in names {- if let Some(value) = env.get(*name)- && !value.trim().is_empty()- {- return Some(value.as_str());- }- }- None-}--/// Point the child's proxy env vars at the in-process proxy and strip any-/// inherited `NO_PROXY`.-///-/// Both upper- and lower-case forms are set because some clients (notably-/// curl on macOS) only honor the lowercase variant. `NO_PROXY` is blanked-/// out so all egress goes through our proxy unconditionally: an inherited-/// `NO_PROXY` matching an allowlisted host would make the client attempt a-/// direct connection, which the Seatbelt rule blocks — surfacing as a-/// confusing "connection refused" instead of a clean policy decision.-fn apply_proxy_env(env: &mut HashMap<String, String>, port: u16) {- let url = format!("http://127.0.0.1:{port}");- for key in [- "HTTPS_PROXY",- "https_proxy",- "HTTP_PROXY",- "http_proxy",- "ALL_PROXY",- "all_proxy",- ] {- env.insert(key.to_string(), url.clone());- }- for key in ["NO_PROXY", "no_proxy"] {- env.insert(key.to_string(), String::new());- }-}--/// Drain the proxy's event channel, logging each event. v1 surfacing only;-/// future integrations (UI, telemetry) can replace or fan out this consumer.-fn spawn_proxy_event_logger(- mut events: futures::channel::mpsc::UnboundedReceiver<ProxyEvent>,- cx: &mut AsyncApp,-) {- cx.background_spawn(async move {- use futures::StreamExt as _;- while let Some(event) = events.next().await {- log_proxy_event(&event);- }- })- .detach();-}--fn log_proxy_event(event: &ProxyEvent) {- match event {- ProxyEvent::Ready { .. } => {}- ProxyEvent::RequestAttempt {- host,- port,- method,- outcome,- } => {- log::debug!(- "[sandbox/network] {} {host}:{port} → {outcome:?}",- method.as_str()- );- }- ProxyEvent::RequestCompleted {- host,- port,- method,- bytes_to_remote,- bytes_from_remote,- duration_ms,- } => {- log::debug!(- "[sandbox/network] completed {} {host}:{port} sent={bytes_to_remote} recv={bytes_from_remote} duration={duration_ms}ms",- method.as_str(),- );- }- }+ let wrapped = sandbox.wrap(&command).await.map_err(anyhow::Error::new)?;+ Ok((+ wrapped.program,+ wrapped.args,+ wrapped.env.into_iter().collect(),+ Some(sandbox),+ ))}pub struct Terminal {@@ -654,11 +266,11 @@ pub struct Terminal {/// (e.g., clicking the Stop button). This is set before kill() is called/// so that code awaiting wait_for_exit() can check it deterministically.user_stopped: Arc<AtomicBool>,- /// Seatbelt config kept alive until the sandboxed command exits.- /// `None` when the command isn't sandboxed or after it finishes.- _sandbox_config: Option<SandboxConfigHandle>,- /// In-process network proxy kept alive until the sandboxed command exits.- _network_proxy: Option<ProxyHandle>,+ /// The live sandbox (Seatbelt policy file and/or network proxy) kept alive+ /// until the sandboxed command exits. `None` when the command isn't+ /// sandboxed or after it finishes. Dropping it tears down the proxy on a+ /// background thread (see `sandbox::Sandbox`'s `Drop`).+ _sandbox: Option<SandboxConfigHandle>,}pub struct TerminalOutput {@@ -677,15 +289,26 @@ impl Terminal {output_byte_limit: Option<usize>,terminal: Entity<terminal::Terminal>,language_registry: Arc<LanguageRegistry>,- sandbox_config: Option<SandboxConfigHandle>,- network_proxy: Option<ProxyHandle>,+ sandbox: Option<SandboxConfigHandle>,cx: &mut Context<Self>,) -> Self {let command_task = terminal.read(cx).wait_for_completed_task(cx);+ // Tear the sandbox down on a GPUI background thread when this entity is+ // released, rather than relying on `Sandbox`'s `Drop` (which would spawn+ // a throwaway thread) on whatever thread releases us. `on_release` hands+ // us an `App`, so we can drive the teardown through the background+ // executor with `drop_on_current_thread`.+ cx.on_release(|this, cx| {+ if let Some(sandbox) = this._sandbox.take() {+ cx.background_executor()+ .spawn(async move { sandbox.drop_on_current_thread() })+ .detach();+ }+ })+ .detach();Self {id,- _sandbox_config: sandbox_config,- _network_proxy: network_proxy,+ _sandbox: sandbox,command: cx.new(|cx| {Markdown::new(format!("```\n{}\n```", command_label).into(),@@ -715,14 +338,16 @@ impl Terminal {original_content_len,content_line_count,});- // Dropping the proxy handle joins its listener thread- // (after a loopback wakeup connect); do that off the- // foreground thread so a slow/wedged shutdown can't- // stall the UI.- if let Some(proxy) = this._network_proxy.take() {- cx.background_spawn(async move { drop(proxy) }).detach();+ // Free the sandbox (and its network proxy) as soon as+ // the command finishes, rather than holding it until+ // this entity is released. The proxy's teardown joins a+ // listener thread, so run it on the background executor+ // to keep it off the foreground thread.+ if let Some(sandbox) = this._sandbox.take() {+ cx.background_executor()+ .spawn(async move { sandbox.drop_on_current_thread() })+ .detach();}- this._sandbox_config = None;cx.notify();}).ok();@@ -894,77 +519,3 @@ pub async fn create_terminal_entity(}).await}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn only_restricted_network_access_uses_proxy_allowlist() {- assert!(SandboxNetworkAccess::None.restricted_allowlist().is_none());- assert!(SandboxNetworkAccess::All.restricted_allowlist().is_none());- assert!(- SandboxNetworkAccess::Restricted(Allowlist::from_patterns([- http_proxy::HostPattern::parse("example.com").unwrap()- ]))- .restricted_allowlist()- .is_some()- );- }-- #[test]- fn upstream_proxy_from_child_env_uses_from_env_precedence() {- let mut env = HashMap::default();- env.insert("HTTPS_PROXY".to_string(), " ".to_string());- env.insert("https_proxy".to_string(), "http://lower:1111".to_string());- env.insert("ALL_PROXY".to_string(), "http://all:2222".to_string());- env.insert("HTTP_PROXY".to_string(), "http://http:3333".to_string());- env.insert("NO_PROXY".to_string(), "".to_string());- env.insert("no_proxy".to_string(), "internal.example".to_string());-- let upstream = upstream_proxy_from_child_env(&env)- .expect("proxy env should parse")- .expect("proxy env should configure an upstream");-- assert_eq!(upstream.host, "lower");- assert_eq!(upstream.port, 1111);- assert!(upstream.bypasses("internal.example", 443));- assert!(!upstream.bypasses("zed.dev", 443));- }-- #[test]- fn apply_proxy_env_points_all_proxy_vars_at_proxy_and_blanks_no_proxy() {- let mut env = HashMap::default();- env.insert("HTTPS_PROXY".to_string(), "http://corp:3128".to_string());- env.insert("NO_PROXY".to_string(), "internal.example".to_string());- env.insert("PATH".to_string(), "/usr/bin".to_string());-- apply_proxy_env(&mut env, 54321);-- for key in [- "HTTPS_PROXY",- "https_proxy",- "HTTP_PROXY",- "http_proxy",- "ALL_PROXY",- "all_proxy",- ] {- assert_eq!(- env.get(key).map(String::as_str),- Some("http://127.0.0.1:54321"),- "{key} should point at the in-process proxy"- );- }- // An inherited NO_PROXY would make clients attempt direct- // connections that the Seatbelt rule blocks; it must be blanked.- for key in ["NO_PROXY", "no_proxy"] {- assert_eq!(- env.get(key).map(String::as_str),- Some(""),- "{key} should be blanked"- );- }- // Unrelated variables pass through.- assert_eq!(env.get("PATH").map(String::as_str), Some("/usr/bin"));- }-}diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 172b8b9a1ec..e9abeef5a22 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -17,6 +17,10 @@ pub use db::*;use itertools::Itertools;pub use native_agent_server::NativeAgentServer;pub use pattern_extraction::*;+pub use sandboxing::{+ ThreadSandbox, sandbox_worktree_writable_paths, settings_sandbox_policy,+ settings_thread_sandbox,+};pub use shell_command_parser::extract_commands;pub use templates::*;pub use thread::*;diff --git a/crates/agent/src/db.rs b/crates/agent/src/db.rsindex 793577146db..6dafddb3c94 100644--- a/crates/agent/src/db.rs+++ b/crates/agent/src/db.rs@@ -83,6 +83,42 @@ pub struct DbThread {pub ui_scroll_position: Option<SerializedScrollPosition>,#[serde(default)]pub sandboxed_terminal_temp_dir: Option<PathBuf>,+ /// Sandbox escalations the user approved "for the rest of this thread".+ /// Persisted so reopening a thread keeps its grants. See+ /// [`crate::sandboxing::ThreadSandboxGrants`].+ #[serde(default)]+ pub sandbox_grants: DbSandboxGrants,+}++/// Serialized form of the sandbox permissions the user granted "for the rest of+/// this thread" (the "Allow for this thread" prompt option). Stored inside the+/// thread blob; round-trips with [`crate::sandboxing::ThreadSandboxGrants`].+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub struct DbSandboxGrants {+ /// Canonicalized paths granted write access; each covers its whole subtree.+ #[serde(default)]+ pub write_paths: Vec<PathBuf>,+ /// Host patterns granted network access, in canonical string form (e.g.+ /// `github.com`, `*.npmjs.org`). Parsed back into patterns on load.+ #[serde(default)]+ pub network_hosts: Vec<String>,+ /// Whether arbitrary-host network access was granted.+ #[serde(default)]+ pub network_any_host: bool,+ /// Whether unrestricted filesystem writes (the broad escape hatch) were+ /// granted.+ #[serde(default)]+ pub allow_fs_write_all: bool,+ /// Whether access to protected Git directories (`.git`) was granted.+ #[serde(default)]+ pub allow_git_access: bool,+ /// Whether the model-requested fully-unsandboxed escape was granted.+ #[serde(default)]+ pub unsandboxed: bool,+ /// Whether running commands unsandboxed was allowed because the OS sandbox+ /// could not be created (the fallback prompt's "for this thread" option).+ #[serde(default)]+ pub sandbox_fallback: bool,}#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]@@ -133,6 +169,7 @@ impl SharedThread {draft_prompt: None,ui_scroll_position: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: DbSandboxGrants::default(),}}@@ -317,6 +354,7 @@ impl DbThread {draft_prompt: None,ui_scroll_position: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: DbSandboxGrants::default(),})}}@@ -768,6 +806,7 @@ mod tests {draft_prompt: None,ui_scroll_position: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: DbSandboxGrants::default(),}}@@ -887,6 +926,55 @@ mod tests {);}+ #[test]+ fn test_sandbox_grants_default_when_absent() {+ let json = r#"{+ "title": "Old Thread",+ "messages": [],+ "updated_at": "2024-01-01T00:00:00Z"+ }"#;++ let db_thread: DbThread = serde_json::from_str(json).expect("Failed to deserialize");++ assert_eq!(+ db_thread.sandbox_grants,+ DbSandboxGrants::default(),+ "Legacy threads without sandbox_grants should default to empty grants"+ );+ }++ #[gpui::test]+ async fn test_sandbox_grants_roundtrip_through_save_load(cx: &mut TestAppContext) {+ let database = ThreadsDatabase::new(cx.executor()).unwrap();+ let thread_id = session_id("sandbox-grants-thread");+ let mut thread = make_thread(+ "Sandbox Grants Thread",+ Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),+ );+ let grants = DbSandboxGrants {+ write_paths: vec![PathBuf::from("/tmp/build")],+ network_hosts: vec!["github.com".to_string(), "*.npmjs.org".to_string()],+ network_any_host: false,+ allow_git_access: true,+ allow_fs_write_all: false,+ unsandboxed: true,+ sandbox_fallback: true,+ };+ thread.sandbox_grants = grants.clone();++ database+ .save_thread(thread_id.clone(), thread, PathList::default())+ .await+ .unwrap();++ let loaded = database+ .load_thread(thread_id)+ .await+ .unwrap()+ .expect("thread should exist");+ assert_eq!(loaded.sandbox_grants, grants);+ }+#[gpui::test]async fn test_sandboxed_terminal_temp_dir_roundtrips_through_save_load(cx: &mut TestAppContext,diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rsindex fe6d37a4c28..c930751135d 100644--- a/crates/agent/src/sandboxing.rs+++ b/crates/agent/src/sandboxing.rs@@ -30,9 +30,153 @@ use feature_flags::{FeatureFlagAppExt as _, SandboxingFeatureFlag};use gpui::App;use http_proxy::HostPattern;use project::Project;+use sandbox::{GitSandboxPolicy, SandboxFsPolicy, SandboxNetPolicy, SandboxPolicy};use settings::Settings;use std::path::PathBuf;+/// The directory subtrees the sandbox always grants write access to for a+/// project: its worktree roots. This is the single source of truth shared by+/// the terminal tool (which hands these to the sandbox as+/// [`acp_thread::SandboxWrap::writable_paths`]) and the status UI (which lists+/// them), so the two can't drift if the set ever changes.+pub fn sandbox_worktree_writable_paths(project: &Project, cx: &App) -> Vec<PathBuf> {+ project+ .worktrees(cx)+ .map(|worktree| worktree.read(cx).abs_path().to_path_buf())+ .collect()+}++/// The `.git` directories the sandbox protects (or, when Git access is granted,+/// makes writable) for a project. Locating these requires Git knowledge the+/// sandbox layer can't derive itself: a worktree's `.git`, a linked worktree's+/// common dir (which lives outside the worktree), and every discovered+/// repository's git/common dirs. Shared by the terminal tool (enforcement) and+/// the status UI so the two can't drift.+pub fn sandbox_git_dirs(project: &Project, cx: &App) -> Vec<PathBuf> {+ let mut git_dirs = Vec::new();++ for worktree in project.worktrees(cx) {+ let worktree = worktree.read(cx);+ let worktree_abs_path = worktree.abs_path();+ // Protect `<worktree>/.git` even when it doesn't exist yet, so a command+ // can't `git init` and then write to the freshly created metadata.+ git_dirs.push(worktree_abs_path.join(".git"));+ if let Some(root_repo_common_dir) = worktree.root_repo_common_dir() {+ git_dirs.push(root_repo_common_dir.to_path_buf());+ }+ }++ for repository in project.git_store().read(cx).repositories().values() {+ let repository = repository.read(cx);+ git_dirs.push(repository.dot_git_abs_path.to_path_buf());+ git_dirs.push(repository.repository_dir_abs_path.to_path_buf());+ git_dirs.push(repository.common_dir_abs_path.to_path_buf());+ }++ git_dirs.sort();+ git_dirs.dedup();+ git_dirs+}++/// What sandbox a thread applies to agent terminal commands, as one value the+/// UI renders and enforcement builds from. "No sandbox" is its own variant+/// rather than a maximally-permissive [`SandboxPolicy`] so that a wide-open but+/// real sandbox (e.g. `allow_fs_write_all` + `allow_all_hosts`) stays+/// distinguishable from running with no sandbox at all — the two grant the same+/// filesystem/network reach but only the latter means the command runs with+/// ambient permissions.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum ThreadSandbox {+ /// No OS sandbox is applied; commands run with ambient permissions.+ Unsandboxed,+ /// A sandbox is applied with this scope.+ Sandboxed(SandboxPolicy),+}++impl ThreadSandbox {+ /// Combine two layers (e.g. the persistent settings and this thread's+ /// grants).+ ///+ /// This is treated as an allowlist - i.e. merging a sandbox that allows+ /// resource A with a sandbox that allows resource B creates a sandbox with+ /// access to both resource A and resource B.+ pub fn merge(self, other: ThreadSandbox) -> ThreadSandbox {+ match (self, other) {+ (ThreadSandbox::Unsandboxed, _) | (_, ThreadSandbox::Unsandboxed) => {+ ThreadSandbox::Unsandboxed+ }+ (ThreadSandbox::Sandboxed(a), ThreadSandbox::Sandboxed(b)) => {+ ThreadSandbox::Sandboxed(a.merge(b))+ }+ }+ }++ /// Whether no OS sandbox is applied.+ pub fn is_unsandboxed(&self) -> bool {+ matches!(self, ThreadSandbox::Unsandboxed)+ }++ /// Attach the project's Git policy to a sandboxed layer. The settings/grants+ /// don't know the project's `.git` locations, so the caller computes them+ /// (via [`sandbox_git_dirs`]) and passes whether this layer grants Git+ /// access. A no-op for the `Unsandboxed` variant.+ pub fn with_git(self, allowed: bool, git_dirs: Vec<PathBuf>) -> ThreadSandbox {+ match self {+ ThreadSandbox::Unsandboxed => ThreadSandbox::Unsandboxed,+ ThreadSandbox::Sandboxed(policy) => {+ let git = if allowed {+ GitSandboxPolicy::Allowed { git_dirs }+ } else {+ GitSandboxPolicy::Denied { git_dirs }+ };+ ThreadSandbox::Sandboxed(policy.with_git(git))+ }+ }+ }+}++/// The sandbox the user's persistent settings establish for every thread, as a+/// [`ThreadSandbox`]. The persistent `allow_unsandboxed` setting removes the+/// sandbox entirely; otherwise the writable-path and host grants form its+/// scope. The per-thread overrides come from [`ThreadSandboxGrants::thread_sandbox`].+pub fn settings_thread_sandbox(persistent: &SandboxPermissions) -> ThreadSandbox {+ if persistent.allow_unsandboxed {+ ThreadSandbox::Unsandboxed+ } else {+ ThreadSandbox::Sandboxed(settings_sandbox_policy(persistent))+ }+}++/// Translate the persistent "allow always" sandbox settings into the+/// cross-platform [`SandboxPolicy`] used for display. This is the "from your+/// settings" half of the sandbox status surface; the per-thread overrides come+/// from [`ThreadSandboxGrants::to_policy`].+pub fn settings_sandbox_policy(persistent: &SandboxPermissions) -> SandboxPolicy {+ let fs = if persistent.allow_fs_write_all {+ SandboxFsPolicy::Unrestricted+ } else {+ SandboxFsPolicy::Restricted {+ writable_paths: persistent.write_paths.clone(),+ }+ };+ let network = if persistent.allow_all_hosts {+ SandboxNetPolicy::Unrestricted+ } else if persistent.network_hosts.is_empty() {+ SandboxNetPolicy::Blocked+ } else {+ SandboxNetPolicy::Restricted {+ allowed_domains: persistent.network_hosts.clone(),+ }+ };+ // The persistent settings don't know the project's `.git` locations; the UI+ // layer attaches the real Git policy via `SandboxPolicy::with_git`.+ SandboxPolicy {+ fs,+ network,+ git: GitSandboxPolicy::default(),+ }+}+/// 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 {@@ -50,11 +194,20 @@ pub(crate) fn sandboxing_enabled(cx: &App) -> bool {/// prompt in place, since the model is still operating in the sandbox model and/// only escaping individual commands (tracked in `ThreadSandboxGrants`).pub(crate) fn sandboxing_enabled_for_project(project: &Project, cx: &App) -> bool {- sandboxing_enabled(cx)- && project.is_local()+ sandboxing_available_for_project(project, cx)&& !AgentSettings::get_global(cx).sandbox_permissions.allow_unsandboxed+}++/// Whether sandboxing is *applicable* for this project at all — the feature is+/// enabled, the project is local, and the platform has a sandbox integration —+/// independent of the persistent `allow_unsandboxed` setting. Used by the UI to+/// distinguish "sandboxing isn't relevant here" (don't show the indicator) from+/// "sandboxing is available but turned off in settings" (show it, struck out).+pub(crate) fn sandboxing_available_for_project(project: &Project, cx: &App) -> bool {+ sandboxing_enabled(cx)+ && project.is_local()&& cfg!(any(target_os = "macos",target_os = "linux",@@ -236,6 +389,20 @@ impl ThreadSandboxGrants {self.sandbox_fallback}+ /// Whether the user approved running model-requested `unsandboxed: true`+ /// commands for the rest of the thread. Once granted, every command in the+ /// thread runs without a sandbox (the model can no longer scope access),+ /// mirroring the `sandbox_fallback` grant.+ pub fn unsandboxed_granted(&self) -> bool {+ self.unsandboxed+ }++ /// Whether the user approved access to protected Git directories for the+ /// rest of the thread.+ pub fn git_access_granted(&self) -> bool {+ self.allow_git_access+ }+/// Record that the user approved running commands unsandboxed for the rest/// of the thread when the sandbox can't be created. Only the Bubblewrap/// sandboxes (Linux directly, Windows via WSL) can fail to create a@@ -245,6 +412,97 @@ impl ThreadSandboxGrants {self.sandbox_fallback = true;}+ /// The sandbox this thread's grants establish on top of the settings, as a+ /// [`ThreadSandbox`]. A standing "run unsandboxed" grant (a model-requested+ /// escape approved for the thread, or the sandbox-creation fallback) removes+ /// the sandbox entirely; otherwise the granted writable paths and hosts form+ /// its scope. This is the "overridden in this thread" half of the sandbox+ /// status surface; the persistent half comes from [`settings_thread_sandbox`].+ pub fn thread_sandbox(&self) -> ThreadSandbox {+ if self.unsandboxed || self.sandbox_fallback {+ ThreadSandbox::Unsandboxed+ } else {+ ThreadSandbox::Sandboxed(self.to_policy())+ }+ }++ /// Translate the per-thread overrides into the cross-platform+ /// [`SandboxPolicy`] used for display. This is the "overridden in this+ /// thread" half of the sandbox status surface; the persistent half comes+ /// from [`settings_sandbox_policy`].+ pub fn to_policy(&self) -> SandboxPolicy {+ let fs = if self.allow_fs_write_all {+ SandboxFsPolicy::Unrestricted+ } else {+ SandboxFsPolicy::Restricted {+ writable_paths: self.write_paths.clone(),+ }+ };+ let network = if self.network_any_host {+ SandboxNetPolicy::Unrestricted+ } else if self.network_hosts.is_empty() {+ SandboxNetPolicy::Blocked+ } else {+ SandboxNetPolicy::Restricted {+ allowed_domains: self+ .network_hosts+ .iter()+ .map(|host| host.to_string())+ .collect(),+ }+ };+ // Grants don't carry the project's `.git` locations; the UI layer+ // attaches the real Git policy via `SandboxPolicy::with_git`.+ SandboxPolicy {+ fs,+ network,+ git: GitSandboxPolicy::default(),+ }+ }++ /// Serialize these grants for persistence in the thread's database row.+ /// Host patterns are written in canonical string form so they round-trip+ /// through [`HostPattern::parse`] on load.+ pub fn to_db(&self) -> crate::db::DbSandboxGrants {+ crate::db::DbSandboxGrants {+ write_paths: self.write_paths.clone(),+ network_hosts: self+ .network_hosts+ .iter()+ .map(|host| host.to_string())+ .collect(),+ network_any_host: self.network_any_host,+ allow_git_access: self.allow_git_access,+ allow_fs_write_all: self.allow_fs_write_all,+ unsandboxed: self.unsandboxed,+ sandbox_fallback: self.sandbox_fallback,+ }+ }++ /// Rebuild thread grants from the persisted form. Host patterns that no+ /// longer parse (e.g. after a hand-edit) are dropped with a warning rather+ /// than failing the whole thread load.+ pub fn from_db(db: &crate::db::DbSandboxGrants) -> Self {+ let mut network_hosts = Vec::new();+ for raw in &db.network_hosts {+ match HostPattern::parse(raw) {+ Ok(pattern) => insert_host_pattern(&mut network_hosts, pattern),+ Err(error) => {+ log::warn!("ignoring invalid persisted sandbox network host '{raw}': {error}")+ }+ }+ }+ Self {+ network_any_host: db.network_any_host,+ network_hosts,+ allow_git_access: db.allow_git_access,+ allow_fs_write_all: db.allow_fs_write_all,+ unsandboxed: db.unsandboxed,+ sandbox_fallback: db.sandbox_fallback,+ write_paths: db.write_paths.clone(),+ }+ }+/// Record everything in `request` as granted for the rest of the thread,/// pruning entries that become redundant.pub fn record(&mut self, request: &SandboxRequest) {@@ -382,6 +640,188 @@ mod tests {}}+ #[test]+ fn thread_sandbox_merge_unsandboxed_wins_else_unions_scopes() {+ let policy = |paths: &[&str], hosts: &[&str]| SandboxPolicy {+ fs: SandboxFsPolicy::Restricted {+ writable_paths: paths.iter().map(PathBuf::from).collect(),+ },+ network: if hosts.is_empty() {+ SandboxNetPolicy::Blocked+ } else {+ SandboxNetPolicy::Restricted {+ allowed_domains: hosts.iter().map(|h| h.to_string()).collect(),+ }+ },+ git: GitSandboxPolicy::default(),+ };++ // Unsandboxed on either side wins — the agent runs with ambient access.+ assert!(+ ThreadSandbox::Unsandboxed+ .merge(ThreadSandbox::Sandboxed(policy(&["/a"], &["a.com"])))+ .is_unsandboxed()+ );+ assert!(+ ThreadSandbox::Sandboxed(policy(&["/a"], &["a.com"]))+ .merge(ThreadSandbox::Unsandboxed)+ .is_unsandboxed()+ );++ // Two sandboxed layers union their scopes.+ assert_eq!(+ ThreadSandbox::Sandboxed(policy(&["/a"], &["a.com"]))+ .merge(ThreadSandbox::Sandboxed(policy(&["/b"], &["b.com"]))),+ ThreadSandbox::Sandboxed(policy(&["/a", "/b"], &["a.com", "b.com"]))+ );+ }++ #[test]+ fn settings_thread_sandbox_reflects_allow_unsandboxed() {+ let unsandboxed = SandboxPermissions {+ allow_unsandboxed: true,+ ..Default::default()+ };+ assert!(settings_thread_sandbox(&unsandboxed).is_unsandboxed());+ assert!(matches!(+ settings_thread_sandbox(&SandboxPermissions::default()),+ ThreadSandbox::Sandboxed(_)+ ));+ }++ #[test]+ fn thread_grants_sandbox_reflects_unsandboxed_grant() {+ let mut grants = ThreadSandboxGrants::default();+ assert!(matches!(+ grants.thread_sandbox(),+ ThreadSandbox::Sandboxed(_)+ ));+ grants.record(&unsandboxed_request());+ assert!(grants.thread_sandbox().is_unsandboxed());+ }++ #[test]+ fn grants_roundtrip_through_db_form() {+ let mut grants = ThreadSandboxGrants::default();+ grants.record(&request(+ hosts(&["github.com", "*.npmjs.org"]),+ false,+ &["/tmp/build"],+ ));+ grants.record(&unsandboxed_request());++ let restored = ThreadSandboxGrants::from_db(&grants.to_db());++ // The restored grants cover exactly what the originals did.+ assert!(covers(+ &restored,+ &request(hosts(&["api.npmjs.org"]), false, &["/tmp/build/cache"])+ ));+ assert!(covers(&restored, &unsandboxed_request()));+ assert_eq!(restored.network_hosts, grants.network_hosts);+ assert_eq!(restored.write_paths, grants.write_paths);+ assert_eq!(restored.unsandboxed, grants.unsandboxed);+ }++ #[test]+ fn db_form_preserves_any_host_and_write_all() {+ let mut grants = ThreadSandboxGrants::default();+ grants.record(&request(NetworkRequest::AnyHost, true, &[]));++ let restored = ThreadSandboxGrants::from_db(&grants.to_db());+ assert!(restored.network_any_host);+ assert!(restored.allow_fs_write_all);+ assert!(covers(+ &restored,+ &request(NetworkRequest::AnyHost, true, &["/anywhere"])+ ));+ }++ #[test]+ fn thread_grants_to_policy_maps_paths_and_domains() {+ use sandbox::{SandboxFsPolicy, SandboxNetPolicy};++ let mut grants = ThreadSandboxGrants::default();+ grants.record(&request(hosts(&["github.com"]), false, &["/tmp/build"]));+ let policy = grants.to_policy();+ assert_eq!(+ policy.fs,+ SandboxFsPolicy::Restricted {+ writable_paths: vec![PathBuf::from("/tmp/build")]+ }+ );+ assert_eq!(+ policy.network,+ SandboxNetPolicy::Restricted {+ allowed_domains: vec!["github.com".to_string()]+ }+ );++ // No grants at all: writes restricted to nothing, network blocked.+ let empty = ThreadSandboxGrants::default().to_policy();+ assert_eq!(+ empty.fs,+ SandboxFsPolicy::Restricted {+ writable_paths: Vec::new()+ }+ );+ assert_eq!(empty.network, SandboxNetPolicy::Blocked);++ // The broad escapes map to the unrestricted variants.+ let mut broad = ThreadSandboxGrants::default();+ broad.record(&request(NetworkRequest::AnyHost, true, &[]));+ let policy = broad.to_policy();+ assert_eq!(policy.fs, SandboxFsPolicy::Unrestricted);+ assert_eq!(policy.network, SandboxNetPolicy::Unrestricted);+ }++ #[test]+ fn settings_policy_maps_persistent_permissions() {+ use sandbox::{SandboxFsPolicy, SandboxNetPolicy};++ let persistent = SandboxPermissions {+ write_paths: vec![PathBuf::from("/var/log")],+ network_hosts: vec!["*.npmjs.org".to_string()],+ ..Default::default()+ };+ let policy = settings_sandbox_policy(&persistent);+ assert_eq!(+ policy.fs,+ SandboxFsPolicy::Restricted {+ writable_paths: vec![PathBuf::from("/var/log")]+ }+ );+ assert_eq!(+ policy.network,+ SandboxNetPolicy::Restricted {+ allowed_domains: vec!["*.npmjs.org".to_string()]+ }+ );++ let unrestricted = SandboxPermissions {+ allow_all_hosts: true,+ allow_fs_write_all: true,+ ..Default::default()+ };+ let policy = settings_sandbox_policy(&unrestricted);+ assert_eq!(policy.fs, SandboxFsPolicy::Unrestricted);+ assert_eq!(policy.network, SandboxNetPolicy::Unrestricted);+ }++ #[test]+ fn db_form_drops_unparsable_persisted_hosts() {+ let db = crate::db::DbSandboxGrants {+ // IP literals are explicitly rejected by the host-pattern parser.+ network_hosts: vec!["github.com".to_string(), "10.0.0.1".to_string()],+ ..Default::default()+ };+ let restored = ThreadSandboxGrants::from_db(&db);+ assert_eq!(+ restored.network_hosts,+ vec![HostPattern::parse("github.com").unwrap()]+ );+ }+fn covers(grants: &ThreadSandboxGrants, request: &SandboxRequest) -> bool {grants.covers_with_persistent(request, &SandboxPermissions::default())}diff --git a/crates/agent/src/templates/system_prompt.hbs b/crates/agent/src/templates/system_prompt.hbsindex 025fe464241..ef31bc0a361 100644--- a/crates/agent/src/templates/system_prompt.hbs+++ b/crates/agent/src/templates/system_prompt.hbs@@ -183,14 +183,6 @@ The `terminal` tool runs commands inside a sandbox with these permissions:{{/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}}{{#if is_windows}}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.@@ -199,13 +191,12 @@ 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.+Host-scoped network access works through an HTTP/HTTPS proxy (standard proxy environment variables are set for the command). When access is scoped to specific hosts, tools that don't honor proxy environment variables (SSH, FTP, raw sockets, etc.) can't reach them, 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}}+- `allow_all_hosts: true` — lift the network restriction entirely: outbound access to any host over any protocol, so SSH, FTP, and raw sockets work too (unlike `allow_hosts`, which is HTTP/HTTPS-only). 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_git_access: true` — lift the default block on Git metadata, allowing reads and writes of file contents under `.git` directories (including worktree metadata that may live outside the project directories). Any command that touches `.git` needs this, including ones that invoke Git only incidentally (e.g. build scripts calling `git describe`/`git rev-parse`, or commit hooks). When approved, the inherited SSH agent socket also becomes reachable for SSH-based Git commit signing (local Unix-socket IPC only — it does not allow packet-sending network access); GPG commit signing via gpg-agent is not available in the sandbox.diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 9e4adfc39bb..975aacdaeaa 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -11,7 +11,10 @@ use acp_thread::{MentionUri, UserMessageId};use action_log::ActionLog;use agent_settings::UserAgentsMd;-use crate::sandboxing::{SandboxRequest, ThreadSandboxGrants, sandboxing_enabled_for_project};+use crate::sandboxing::{+ SandboxRequest, ThreadSandbox, ThreadSandboxGrants, sandboxing_available_for_project,+ sandboxing_enabled_for_project,+};use agent_client_protocol::schema::v1 as acp;use agent_settings::{AgentProfileId, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT,@@ -1583,6 +1586,7 @@ impl Thread {Some(self.project.read(cx).fs().clone()),cancellation_rx,self.sandbox_grants.clone(),+ Some(cx.weak_entity()),);tool.replay(tool_use.input.clone(), output, tool_event_stream, cx).log_err();@@ -1739,10 +1743,57 @@ impl Thread {running_subagents: Vec::new(),inherits_parent_model_settings: true,sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir,- sandbox_grants: Rc::new(RefCell::new(ThreadSandboxGrants::default())),+ sandbox_grants: Rc::new(RefCell::new(ThreadSandboxGrants::from_db(+ &db_thread.sandbox_grants,+ ))),}}+ /// The sandbox that currently applies to agent terminal commands in this+ /// thread, as two layers: the user's persistent settings and this thread's+ /// overrides (see [`ThreadSandbox`]). Returns `None` when sandboxing isn't+ /// applicable to the project at all, so the UI shows no indicator.+ ///+ /// The layers are returned pre-merge so the UI can show their provenance+ /// separately; [`ThreadSandbox::merge`] combines them into what is enforced.+ pub fn sandbox_status(&self, cx: &App) -> Option<(ThreadSandbox, ThreadSandbox)> {+ if !self.sandboxing_available(cx) {+ return None;+ }+ let persistent = AgentSettings::get_global(cx).sandbox_permissions.clone();+ // The project's `.git` locations are the same for both layers; whether+ // they're writable differs (settings grant vs. thread grant).+ let git_dirs = crate::sandboxing::sandbox_git_dirs(self.project.read(cx), cx);+ let grants = self.sandbox_grants.borrow();+ let settings = crate::sandboxing::settings_thread_sandbox(&persistent)+ .with_git(persistent.allow_git_access, git_dirs.clone());+ let thread = grants+ .thread_sandbox()+ .with_git(grants.git_access_granted(), git_dirs);+ Some((settings, thread))+ }++ /// Whether agent terminal commands are sandboxed for this thread's project,+ /// so the UI can decide whether to surface the sandbox status at all.+ pub fn sandboxing_enabled(&self, cx: &App) -> bool {+ sandboxing_enabled_for_project(self.project.read(cx), cx)+ }++ /// Whether sandboxing is *applicable* for this thread's project (feature on,+ /// local project, supported platform), regardless of whether it's been+ /// turned off in settings. The UI shows the sandbox indicator whenever this+ /// is true, drawing it struck-out when sandboxing is disabled.+ pub fn sandboxing_available(&self, cx: &App) -> bool {+ sandboxing_available_for_project(self.project.read(cx), cx)+ }++ /// The directory subtrees the sandbox always grants write access to for this+ /// thread's project (its worktree roots), derived from the same source the+ /// terminal tool uses when it actually builds the sandbox.+ pub fn sandbox_baseline_writable_paths(&self, cx: &App) -> Vec<PathBuf> {+ crate::sandboxing::sandbox_worktree_writable_paths(self.project.read(cx), cx)+ }+pub fn to_db(&self, cx: &App) -> Task<DbThread> {let initial_project_snapshot = self.initial_project_snapshot.clone();let mut thread = DbThread {@@ -1768,6 +1819,7 @@ impl Thread {}}),sandboxed_terminal_temp_dir: self.sandboxed_terminal_temp_dir.clone(),+ sandbox_grants: self.sandbox_grants.borrow().to_db(),};cx.background_spawn(async move {@@ -3322,6 +3374,7 @@ impl Thread {Some(fs),cancellation_rx,self.sandbox_grants.clone(),+ Some(cx.weak_entity()),);tool_event_stream.update_fields(acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),@@ -5084,6 +5137,10 @@ pub struct ToolCallEventStream {cancellation_rx: watch::Receiver<bool>,/// Shared, thread-scoped sandbox grants (see [`Thread::sandbox_grants`]).sandbox_grants: Rc<RefCell<ThreadSandboxGrants>>,+ /// The owning thread, used to trigger a save when a "for this thread"+ /// sandbox grant is recorded so it survives reopening. `None` in tests and+ /// for streams not tied to a live thread.+ thread: Option<WeakEntity<Thread>>,}impl ToolCallEventStream {@@ -5097,9 +5154,7 @@ impl ToolCallEventStream {/// thread-scoped sandbox grants. This mirrors how a real [`Thread`] builds a/// distinct event stream per tool call while sharing one set of grants, so/// tests can exercise sequences of tool calls within the same conversation.- // Only the macOS-gated terminal sandbox regression test uses this, so match- // its `cfg` to avoid a dead-code error on other platforms.- #[cfg(all(test, target_os = "macos"))]+ #[cfg(test)]pub(crate) fn test_with_grants(sandbox_grants: Rc<RefCell<ThreadSandboxGrants>>,) -> (Self, ToolCallEventStreamReceiver) {@@ -5112,6 +5167,7 @@ impl ToolCallEventStream {None,cancellation_rx,sandbox_grants,+ None,);(stream, ToolCallEventStreamReceiver(events_rx))@@ -5128,6 +5184,7 @@ impl ToolCallEventStream {None,cancellation_rx,Rc::new(RefCell::new(ThreadSandboxGrants::default())),+ None,);(@@ -5149,6 +5206,7 @@ impl ToolCallEventStream {fs: Option<Arc<dyn Fs>>,cancellation_rx: watch::Receiver<bool>,sandbox_grants: Rc<RefCell<ThreadSandboxGrants>>,+ thread: Option<WeakEntity<Thread>>,) -> Self {Self {tool_use_id,@@ -5156,9 +5214,29 @@ impl ToolCallEventStream {fs,cancellation_rx,sandbox_grants,+ thread,}}+ /// Whether the owning thread is a subagent, so prompts can say "for this+ /// subagent" instead of "for this thread".+ fn is_subagent(&self, cx: &App) -> bool {+ self.thread+ .as_ref()+ .and_then(|thread| thread.upgrade())+ .is_some_and(|thread| thread.read(cx).is_subagent())+ }++ /// Persist the thread so a freshly recorded "for this thread" sandbox grant+ /// survives a reopen. Saving is driven by the agent's `observe` on the+ /// thread entity, so a no-op `notify` is enough to schedule it.+ fn persist_thread_grants(thread: &Option<WeakEntity<Thread>>, cx: &AsyncApp) {+ let Some(thread) = thread else { return };+ cx.update(|cx| {+ thread.update(cx, |_thread, cx| cx.notify()).ok();+ });+ }+/// Returns a future that resolves when the user cancels the tool call./// Tools should select on this alongside their main work to detect user cancellation.pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {@@ -5349,8 +5427,6 @@ impl ToolCallEventStream {/// settings-driven authorization flow for regular tools.pub(crate) fn authorize_sandbox(&self,- title: impl Into<String>,- command: Option<String>,request: SandboxRequest,reason: String,cx: &mut App,@@ -5359,7 +5435,6 @@ impl ToolCallEventStream {return Task::ready(Ok(()));}- let title = title.into();let (network_hosts, network_all_hosts) = match &request.network {crate::sandboxing::NetworkRequest::None => (Vec::new(), false),crate::sandboxing::NetworkRequest::AnyHost => (Vec::new(), true),@@ -5368,7 +5443,10 @@ impl ToolCallEventStream {}};let sandbox_authorization_details = acp_thread::SandboxAuthorizationDetails {- command,+ // The command stays in the tool-call title (set by the terminal+ // tool), so the approval card keeps showing it; the details only+ // describe the requested access and the agent's reason.+ command: None,network_hosts,network_all_hosts,allow_git_access: request.allow_git_access,@@ -5377,6 +5455,11 @@ impl ToolCallEventStream {write_paths: request.write_paths.clone(),reason,};+ let allow_thread_label = if self.is_subagent(cx) {+ "Allow for this subagent"+ } else {+ "Allow for this thread"+ };let options = acp_thread::PermissionOptions::Flat(vec![acp::PermissionOption::new(acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),@@ -5385,7 +5468,7 @@ impl ToolCallEventStream {),acp::PermissionOption::new(acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),- "Allow for this thread",+ allow_thread_label,acp::PermissionOptionKind::AllowAlways,),acp::PermissionOption::new(@@ -5404,6 +5487,7 @@ impl ToolCallEventStream {let stream = self.stream.clone();let tool_use_id = self.tool_use_id.clone();let sandbox_grants = self.sandbox_grants.clone();+ let thread = self.thread.clone();let auto_allow_outcome = match auto_resolve_permission_outcome(&options, true) {Ok(outcome) => outcome,Err(error) => return Task::ready(Err(error)),@@ -5416,7 +5500,9 @@ impl ToolCallEventStream {ToolCallAuthorization {tool_call: acp::ToolCallUpdate::new(tool_use_id.to_string(),- acp::ToolCallUpdateFields::new().title(title),+ // Leave the title untouched so the card keeps+ // showing the command (matching the fallback flow).+ acp::ToolCallUpdateFields::new(),).meta(acp_thread::meta_with_sandbox_authorization(sandbox_authorization_details,@@ -5453,6 +5539,7 @@ impl ToolCallEventStream {&outcome,&request,sandbox_grants.clone(),+ thread.clone(),fs.clone(),cx,);@@ -5491,6 +5578,7 @@ impl ToolCallEventStream {outcome: &acp_thread::SelectedPermissionOutcome,request: &SandboxRequest,sandbox_grants: Rc<RefCell<ThreadSandboxGrants>>,+ thread: Option<WeakEntity<Thread>>,fs: Option<Arc<dyn Fs>>,cx: &AsyncApp,) -> Result<()> {@@ -5503,6 +5591,7 @@ impl ToolCallEventStream {Some(acp_thread::SandboxPermission::AllowOnce) => Ok(()),Some(acp_thread::SandboxPermission::AllowThread) => {sandbox_grants.borrow_mut().record(request);+ Self::persist_thread_grants(&thread, cx);Ok(())}Some(acp_thread::SandboxPermission::AllowAlways) => {@@ -5604,6 +5693,13 @@ impl ToolCallEventStream {self.sandbox_grants.borrow().fallback_granted_for_thread()}+ /// Whether the user approved a model-requested `unsandboxed: true` escape+ /// for the rest of this thread. Like the fallback grant, this makes every+ /// command in the thread run without a sandbox.+ pub(crate) fn unsandboxed_granted_for_thread(&self) -> bool {+ self.sandbox_grants.borrow().unsandboxed_granted()+ }+/// Ask the user how to proceed when the OS sandbox could not be created/// for a command (for example, `bwrap` is missing or user namespaces are/// disabled).@@ -5634,6 +5730,11 @@ impl ToolCallEventStream {} else {format!("Retry (attempt {retries})")};+ let allow_thread_label = if self.is_subagent(cx) {+ "Run without sandbox for this subagent"+ } else {+ "Run without sandbox for this thread"+ };let options = acp_thread::PermissionOptions::Flat(vec![// Retry isn't an allow/deny choice; the UI renders it with its own// icon and we dispatch on the option id, so the kind here only@@ -5652,7 +5753,7 @@ impl ToolCallEventStream {),acp::PermissionOption::new(acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),- "Run without sandbox for this thread",+ allow_thread_label,acp::PermissionOptionKind::AllowAlways,),acp::PermissionOption::new(@@ -5671,6 +5772,7 @@ impl ToolCallEventStream {let stream = self.stream.clone();let tool_use_id = self.tool_use_id.clone();let sandbox_grants = self.sandbox_grants.clone();+ let thread = self.thread.clone();cx.spawn(async move |cx| {let (response_tx, response_rx) = oneshot::channel();if let Err(error) = stream@@ -5716,10 +5818,12 @@ impl ToolCallEventStream {}Some(acp_thread::SandboxPermission::AllowThread) => {sandbox_grants.borrow_mut().record_fallback();+ Self::persist_thread_grants(&thread, cx);Ok(SandboxFallbackDecision::RunUnsandboxed)}Some(acp_thread::SandboxPermission::AllowAlways) => {sandbox_grants.borrow_mut().record_fallback();+ Self::persist_thread_grants(&thread, cx);Self::persist_sandbox_unsandboxed_permission(fs, cx);Ok(SandboxFallbackDecision::RunUnsandboxed)}@@ -7196,8 +7300,6 @@ mod tests {let authorize = cx.update(|cx| {event_stream.authorize_sandbox(- "Allow write access?",- None,request.clone(),"needs to write build artifacts".to_string(),cx,diff --git a/crates/agent/src/thread_store.rs b/crates/agent/src/thread_store.rsindex bf483e428bb..97ae2bf5aa2 100644--- a/crates/agent/src/thread_store.rs+++ b/crates/agent/src/thread_store.rs@@ -168,6 +168,7 @@ mod tests {draft_prompt: None,ui_scroll_position: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: Default::default(),}}diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rsindex 9974642d5e6..5282019cc00 100644--- a/crates/agent/src/tools/terminal_tool.rs+++ b/crates/agent/src/tools/terminal_tool.rs@@ -110,17 +110,16 @@ pub struct SandboxedTerminalToolInput {/// rejected. Requesting network access triggers a user approval prompt, so/// only list hosts you expect the command to need.#[cfg_attr(- target_os = "macos",+ any(target_os = "macos", target_os = "linux"),doc = "\nHost-specific access is enforced by an HTTP/HTTPS proxy, so use \`https://` URLs rather than `git@`/`ssh://`.")]#[cfg_attr(- any(target_os = "linux", target_os = "windows"),- doc = "\nNOTE: on Linux and Windows the sandbox cannot restrict network access to \- specific hosts. Any value here grants the command unrestricted outbound network \- access (exactly like `allow_all_hosts`), and the user is asked to approve access \- to all hosts rather than the ones you list. Prefer setting `allow_all_hosts` \- directly when per-host restriction isn't available."+ target_os = "windows",+ doc = "\nNOTE: on Windows the sandbox cannot currently restrict network \+ access to specific hosts. Do not set `allow_hosts` on Windows; request \+ `allow_all_hosts: true` if the command needs network access, or omit \+ network permissions entirely.")]#[serde(default)]pub allow_hosts: Vec<String>,@@ -161,12 +160,14 @@ pub struct SandboxedTerminalToolInput {/// set of paths is known. Requesting it triggers a user approval prompt.#[serde(default, alias = "allow_fs_write")]pub allow_fs_write_all: Option<bool>,- /// Set to `true` when the command needs Git metadata access.+ /// Set to `true` when the command needs to read or write protected Git+ /// metadata.///- /// Sandboxed commands cannot read file contents from, or write to, protected- /// `.git` paths for opened worktrees and discovered repositories by default.- /// Set this for Git operations that need those paths. Requesting it- /// triggers a user approval prompt.+ /// By default sandboxed commands can't read the file contents of, or write+ /// to, the `.git` directories of opened worktrees and discovered+ /// repositories (their metadata stays visible). Set this for Git operations+ /// that need those paths (commit, fetch, rebase, …). Requesting it triggers+ /// a user approval prompt.#[serde(default)]pub allow_git_access: Option<bool>,/// Set to `true` only as a last resort, to run the command fully outside@@ -188,9 +189,8 @@ pub struct SandboxedTerminalToolInput {#[serde(default)]pub unsandboxed: Option<bool>,/// A short justification for why this command needs the sandbox- /// permission(s) it requests (`allow_hosts`, `allow_all_hosts`,- /// `fs_write_paths`, `allow_fs_write_all`, `allow_git_access`, or- /// `unsandboxed`).+ /// 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@@ -393,31 +393,101 @@ async fn run_terminal_tool(authorize.await.map_err(|e| e.to_string())?;- let want_git_access = sandboxing && sandbox_input.allow_git_access == Some(true);let want_fs_write_all = sandboxing && sandbox_input.allow_fs_write_all == Some(true);let want_unsandboxed = sandboxing && sandbox_input.unsandboxed == Some(true);+ let want_all_hosts = sandboxing && sandbox_input.allow_all_hosts == Some(true);+ let want_git_access = sandboxing && sandbox_input.allow_git_access == Some(true);++ let persistent = cx.update(|cx| {+ agent_settings::AgentSettings::get_global(cx)+ .sandbox_permissions+ .clone()+ });++ // Standing permissions the user already approved — in settings or "for this+ // thread" — that every command in the thread inherits and that the model+ // cannot narrow. The actually-enforced policy is always at least this+ // permissive, so a request asking for something *more* restrictive would be+ // silently widened to the floor and mislead the model about its real access.+ // Reject such requests with an explanation instead of running them.+ let floor = event_stream+ .effective_sandbox_request(&crate::sandboxing::SandboxRequest::default(), &persistent);+ let unsandboxed_floor = sandboxing+ && (event_stream.unsandboxed_granted_for_thread()+ || event_stream.sandbox_fallback_granted_for_thread());+ let fs_unrestricted_floor = sandboxing && floor.allow_fs_write_all;+ let net_unrestricted_floor = sandboxing && matches!(floor.network, NetworkRequest::AnyHost);++ if sandboxing && !want_unsandboxed {+ if unsandboxed_floor {+ // The user turned the sandbox off for this thread, so every command+ // runs without one and no sandbox-scoping field can take effect.+ // Name exactly which ones the model set so it can drop them.+ let mut ineffective = Vec::new();+ if !sandbox_input.allow_hosts.is_empty() {+ ineffective.push("`allow_hosts`");+ }+ if sandbox_input.allow_all_hosts == Some(true) {+ ineffective.push("`allow_all_hosts`");+ }+ if !sandbox_input.fs_write_paths.is_empty() {+ ineffective.push("`fs_write_paths`");+ }+ if sandbox_input.allow_fs_write_all == Some(true) {+ ineffective.push("`allow_fs_write_all`");+ }+ if !ineffective.is_empty() {+ return Err(format!(+ "Sandboxing is disabled for this thread, so every command runs without an OS \+ sandbox and these fields have no effect: {}. Remove them and rerun the \+ command (it will run unsandboxed), or pass `unsandboxed: true` to acknowledge \+ it runs without a sandbox.",+ ineffective.join(", "),+ ));+ }+ } else {+ if fs_unrestricted_floor+ && !want_fs_write_all+ && !sandbox_input.fs_write_paths.is_empty()+ {+ return Err(+ "Unrestricted filesystem writes are enabled for this thread, so every command \+ can already write anywhere; `fs_write_paths` cannot narrow that. Remove \+ `fs_write_paths`."+ .to_string(),+ );+ }+ if net_unrestricted_floor && !want_all_hosts && !sandbox_input.allow_hosts.is_empty() {+ return Err(+ "Unrestricted network access is enabled for this thread, so every command can \+ already reach any host; `allow_hosts` cannot narrow that. Remove `allow_hosts`."+ .to_string(),+ );+ }+ }+ }// Validate the model-supplied host patterns up front. Malformed input is// the model's responsibility, so surface it back as a tool-call error// (the model retries) rather than letting the user approve a request that// then fails.- let mut network = if sandboxing && !want_unsandboxed {+ let network = if sandboxing && !want_unsandboxed {build_network_request(&sandbox_input)?} else {NetworkRequest::None};// 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;+ // confines the sandbox to its port. A non-local project's terminal can't+ // reach the proxy, and Windows does not support this path yet. Reject the+ // narrower request rather than silently widening it to all-host access.+ let can_restrict_to_hosts =+ (cfg!(target_os = "macos") || cfg!(target_os = "linux")) && is_local_project;+ if !can_restrict_to_hosts && matches!(network, NetworkRequest::Hosts(_)) {+ return Err(+ "This platform or project cannot restrict sandboxed network access to specific hosts. Use `allow_all_hosts: true` if the command needs network access."+ .to_string(),+ );}let write_paths: Vec<PathBuf> = if sandboxing && !want_unsandboxed {@@ -472,11 +542,8 @@ async fn run_terminal_tool(.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(), reason.to_string(), cx)- });+ let approve =+ cx.update(|cx| event_stream.authorize_sandbox(request.clone(), reason.to_string(), cx));if let Err(error) = approve.await {if want_unsandboxed {return Ok(format!(@@ -496,40 +563,42 @@ async fn run_terminal_tool(// create the sandbox it aborts. As the consumer we may still run the command// without a sandbox (when the user has opted into that), but we record// *why* in `sandbox_not_applied` so we can warn the user and tell the agent.- // Only the Linux/Windows sandbox-creation fallbacks (and the matching- // "for this thread" grant) ever reassign this, so on other platforms the- // binding stays `None` and wouldn't need `mut`.+ // A standing "run unsandboxed for this thread" grant (any platform) and the+ // Linux/Windows sandbox-creation fallbacks reassign this; on platforms+ // without a sandbox integration the binding stays `None` and wouldn't need+ // `mut`.#[cfg_attr(- not(any(target_os = "linux", target_os = "windows")),+ not(any(target_os = "macos", target_os = "linux", target_os = "windows")),allow(unused_mut))]let mut sandbox_not_applied: Option<acp_thread::SandboxNotAppliedReason> = None;let sandbox_wrap = if sandboxing && !want_unsandboxed {- let sandbox_permissions = cx.update(|cx| {- agent_settings::AgentSettings::get_global(cx)- .sandbox_permissions- .clone()- });-- if event_stream.sandbox_fallback_granted_for_thread() {- // The user allowed unsandboxed execution for the rest of this- // thread after an earlier sandbox failure (Linux and Windows, which- // share the `authorize_sandbox_fallback` flow).- #[cfg(any(target_os = "linux", target_os = "windows"))]- {- sandbox_not_applied =- Some(acp_thread::SandboxNotAppliedReason::DisabledForThisThread);- }+ if unsandboxed_floor {+ // Every command in this thread runs unsandboxed because the user+ // approved it — a model-requested "run unsandboxed" escape granted+ // for the thread, or the sandbox-creation fallback after a failure.+ // Record why so the model is told it ran without isolation.+ sandbox_not_applied = Some(acp_thread::SandboxNotAppliedReason::DisabledForThisThread);None} else {- let effective = event_stream.effective_sandbox_request(&request, &sandbox_permissions);- let sandbox_paths =- cx.update(|cx| sandbox_paths(project.read(cx), effective.allow_git_access, cx));+ let effective = event_stream.effective_sandbox_request(&request, &persistent);+ if !can_restrict_to_hosts && matches!(effective.network, NetworkRequest::Hosts(_)) {+ return Err(+ "This platform or project has a saved host-specific network grant, but cannot enforce host-specific sandboxed network access. Request `allow_all_hosts: true` if the command needs network access."+ .to_string(),+ );+ }+ let (writable_paths, git_dirs) = cx.update(|cx| {+ let project = project.read(cx);+ (+ crate::sandboxing::sandbox_worktree_writable_paths(project, cx),+ crate::sandboxing::sandbox_git_dirs(project, cx),+ )+ });let wrap = acp_thread::SandboxWrap {- writable_paths: sandbox_paths.writable_paths,+ writable_paths,extra_write_paths: effective.write_paths,- protected_paths: sandbox_paths.protected_paths,- allowed_unix_socket_paths: Vec::new(),+ git_dirs,allow_git_access: effective.allow_git_access,network: network_request_to_sandbox_network_access(&effective.network),allow_fs_write: effective.allow_fs_write_all,@@ -661,8 +730,11 @@ async fn run_terminal_tool(// already running unsandboxed — goes straight back to the model.let Some(message) = effective_wrap.as_ref().and_then(|_| {error- .downcast_ref::<sandbox::windows_wsl::WslSandboxUnavailable>()- .map(|unavailable| unavailable.message().to_string())+ .downcast_ref::<sandbox::SandboxError>()+ .and_then(|error| match error {+ sandbox::SandboxError::WslUnavailable(message) => Some(message.clone()),+ _ => None,+ })}) else {return Err(format!("{error:#}"));};@@ -921,22 +993,16 @@ fn network_request_to_sandbox_network_access(NetworkRequest::None => acp_thread::SandboxNetworkAccess::None,NetworkRequest::AnyHost => acp_thread::SandboxNetworkAccess::All,NetworkRequest::Hosts(hosts) => {- #[cfg(target_os = "macos")]+ #[cfg(any(target_os = "macos", target_os = "linux"))]{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"))]+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]{let _ = hosts;- acp_thread::SandboxNetworkAccess::All+ acp_thread::SandboxNetworkAccess::None}}}@@ -968,68 +1034,6 @@ fn build_network_request(sandbox: &TerminalSandboxInput) -> Result<NetworkRequesOk(NetworkRequest::Hosts(patterns))}-/// User-facing title for the sandbox-escalation approval prompt. Only called-/// when the request actually asks for something (see-/// [`crate::sandboxing::SandboxRequest::needs_escalation`]).-fn sandbox_approval_title(request: &crate::sandboxing::SandboxRequest) -> String {- if request.unsandboxed {- return "Allow this command to run outside the sandbox?".to_string();- }-- let mut parts: Vec<String> = Vec::new();- if let Some(network_clause) = network_clause(&request.network) {- parts.push(network_clause);- }- if request.allow_git_access {- parts.push("Git metadata access".to_string());- }- if request.allow_fs_write_all {- parts.push("unrestricted filesystem writes".to_string());- } else if !request.write_paths.is_empty() {- parts.push(format!(- "write access to {}",- write_path_summary(&request.write_paths)- ));- }- match parts.as_slice() {- [] => "Allow this command extra permissions?".to_string(),- [only] => format!("Allow {only}?"),- [first, second] => format!("Allow {first} and {second}?"),- _ => format!("Allow {}?", parts.join(", ")),- }-}--/// The network clause for the approval title, or `None` when no network was-/// requested.-fn network_clause(network: &NetworkRequest) -> Option<String> {- match network {- NetworkRequest::None => None,- NetworkRequest::AnyHost => Some("arbitrary network access".to_string()),- NetworkRequest::Hosts(hosts) => Some(format_hosts_clause(hosts)),- }-}--fn format_hosts_clause(hosts: &[http_proxy::HostPattern]) -> String {- let names: Vec<String> = hosts.iter().map(|host| host.to_string()).collect();- match names.as_slice() {- [] => "network access".to_string(),- [single] => format!("network access to {single}"),- [first, second] => format!("network access to {first} and {second}"),- _ => {- let (last, init) = names.split_last().expect("non-empty");- format!("network access to {}, and {last}", init.join(", "))- }- }-}--fn write_path_summary(paths: &[PathBuf]) -> String {- match paths {- [] => "0 paths".to_string(),- [path] => path.display().to_string(),- paths => format!("{} paths", paths.len()),- }-}-#[derive(Clone, Copy, Debug, Default)]struct TerminalOutputSelection {head_lines: Option<usize>,@@ -1180,59 +1184,6 @@ fn process_content(content}-struct SandboxPaths {- writable_paths: Vec<PathBuf>,- protected_paths: Vec<PathBuf>,-}--fn sandbox_paths(project: &Project, allow_git_access: bool, cx: &App) -> SandboxPaths {- let mut writable_paths = Vec::new();- let mut git_paths = Vec::new();-- for worktree in project.worktrees(cx) {- let worktree = worktree.read(cx);- let worktree_abs_path = worktree.abs_path();- writable_paths.push(worktree_abs_path.to_path_buf());- // Protect `<worktree>/.git` even when it doesn't exist yet, so a command- // can't `git init` and then write to the freshly created metadata.- git_paths.push(worktree_abs_path.join(".git"));-- // `Worktree` derefs to `Snapshot`; read the field directly instead of- // cloning the whole snapshot just for this path.- if let Some(root_repo_common_dir) = worktree.root_repo_common_dir() {- git_paths.push(root_repo_common_dir.to_path_buf());- }- }-- // `Repository` derefs to `RepositorySnapshot`, so read the few path fields- // directly rather than cloning the entire snapshot (which carries the- // per-path status tree) for each repository.- for repository in project.git_store().read(cx).repositories().values() {- let repository = repository.read(cx);- git_paths.push(repository.dot_git_abs_path.to_path_buf());- git_paths.push(repository.repository_dir_abs_path.to_path_buf());- git_paths.push(repository.common_dir_abs_path.to_path_buf());- }-- git_paths.sort();- git_paths.dedup();-- let protected_paths = if allow_git_access {- writable_paths.extend(git_paths);- Vec::new()- } else {- git_paths- };-- writable_paths.sort();- writable_paths.dedup();-- SandboxPaths {- writable_paths,- protected_paths,- }-}-fn working_dir(cd: &str, project: &Entity<Project>, cx: &mut App) -> Result<Option<PathBuf>> {let project = project.read(cx);@@ -1270,7 +1221,6 @@ fn working_dir(cd: &str, project: &Entity<Project>, cx: &mut App) -> Result<Opti#[cfg(test)]mod tests {use super::*;- use fs::Fs;#[test]fn test_initial_title_shows_full_multiline_command() {@@ -1302,91 +1252,6 @@ mod tests {)}- #[gpui::test]- async fn test_sandbox_paths_protect_git_paths_until_git_access_is_allowed(- cx: &mut gpui::TestAppContext,- ) {- crate::tests::init_test(cx);-- let fs = fs::FakeFs::new(cx.executor());- fs.insert_tree(- "/main_repo",- serde_json::json!({- ".git": {},- "file.txt": "content",- }),- )- .await;- fs.add_linked_worktree_for_repo(- Path::new("/main_repo/.git"),- false,- git::repository::Worktree {- path: PathBuf::from("/linked_worktree"),- ref_name: Some("refs/heads/feature".into()),- sha: "abc123".into(),- is_main: false,- is_bare: false,- },- )- .await;- fs.write(Path::new("/linked_worktree/file.txt"), b"content")- .await- .expect("linked worktree file should be written");-- let project = project::Project::test(fs, [Path::new("/linked_worktree")], cx).await;- let paths_without_git_access = cx.update(|cx| sandbox_paths(project.read(cx), false, cx));-- assert!(- paths_without_git_access- .writable_paths- .contains(&PathBuf::from("/linked_worktree"))- );- assert!(- paths_without_git_access- .protected_paths- .contains(&PathBuf::from("/linked_worktree/.git"))- );- assert!(- !paths_without_git_access- .protected_paths- .contains(&PathBuf::from("/linked_worktree/.gitignore"))- );- assert!(- paths_without_git_access- .protected_paths- .contains(&PathBuf::from("/main_repo/.git"))- );- assert!(- paths_without_git_access- .protected_paths- .contains(&PathBuf::from("/main_repo/.git/worktrees/feature"))- );-- let paths_with_git_access = cx.update(|cx| sandbox_paths(project.read(cx), true, cx));-- assert!(paths_with_git_access.protected_paths.is_empty());- assert!(- paths_with_git_access- .writable_paths- .contains(&PathBuf::from("/linked_worktree"))- );- assert!(- paths_with_git_access- .writable_paths- .contains(&PathBuf::from("/linked_worktree/.git"))- );- assert!(- paths_with_git_access- .writable_paths- .contains(&PathBuf::from("/main_repo/.git"))- );- assert!(- paths_with_git_access- .writable_paths- .contains(&PathBuf::from("/main_repo/.git/worktrees/feature"))- );- }-#[test]fn test_process_content_user_stopped() {let output = acp::TerminalOutputResponse::new("partial output".to_string(), false);@@ -2906,20 +2771,6 @@ mod tests {);}- fn sandbox_request(- network: NetworkRequest,- all: bool,- paths: &[&str],- ) -> crate::sandboxing::SandboxRequest {- crate::sandboxing::SandboxRequest {- network,- allow_git_access: false,- allow_fs_write_all: all,- unsandboxed: false,- write_paths: paths.iter().map(PathBuf::from).collect(),- }- }-#[test]fn test_join_write_paths_resolves_relative_and_absolute() {let base = PathBuf::from(if cfg!(windows) {@@ -3033,26 +2884,6 @@ mod tests {assert_eq!(joined, vec![expected_escape, expected_abs]);}- #[test]- fn test_sandbox_approval_title_unsandboxed() {- let mut request = sandbox_request(NetworkRequest::AnyHost, true, &["/tmp/build"]);- request.unsandboxed = true;- assert_eq!(- sandbox_approval_title(&request),- "Allow this command to run outside the sandbox?"- );- }-- #[test]- fn test_sandbox_approval_title_summarizes_multiple_paths_by_count() {- let title = sandbox_approval_title(&sandbox_request(- NetworkRequest::None,- false,- &["/a", "/b", "/c", "/d"],- ));- assert_eq!(title, "Allow write access to 4 paths?");- }-#[test]fn test_input_schema_includes_sandbox_flags() {// The sandboxed terminal tool advertises these fields so the model can@@ -3076,10 +2907,6 @@ mod tests {schema.contains("allow_fs_write_all"),"schema should advertise allow_fs_write_all: {schema}");- assert!(- schema.contains("allow_git_access"),- "schema should advertise allow_git_access: {schema}"- );assert!(schema.contains("unsandboxed"),"schema should advertise unsandboxed: {schema}"@@ -3101,7 +2928,6 @@ mod tests {assert_eq!(input.allow_all_hosts, None);assert!(input.fs_write_paths.is_empty());assert_eq!(input.allow_fs_write_all, None);- assert_eq!(input.allow_git_access, None);assert_eq!(input.unsandboxed, None);}@@ -3161,7 +2987,6 @@ mod tests {.expect("legacy allow_fs_write should request sandbox authorization details");assert!(details.network_hosts.is_empty());assert!(!details.network_all_hosts);- assert!(!details.allow_git_access);assert!(details.allow_fs_write_all);assert!(!details.unsandboxed);assert!(details.write_paths.is_empty());@@ -3251,16 +3076,14 @@ mod tests {let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx));let authorization = receiver.expect_authorization().await;- assert_eq!(- authorization.tool_call.fields.title.as_deref(),- Some("Allow this command to run outside the sandbox?")- );+ // The sandbox approval deliberately leaves the tool-call title untouched+ // so the card keeps showing the command being approved.+ assert_eq!(authorization.tool_call.fields.title, None);let details =acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta).expect("unsandboxed should request sandbox authorization details");assert!(details.network_hosts.is_empty());assert!(!details.network_all_hosts);- assert!(!details.allow_git_access);assert!(!details.allow_fs_write_all);assert!(details.unsandboxed);assert!(details.write_paths.is_empty());@@ -3436,93 +3259,183 @@ mod tests {assert_eq!(environment2.terminal_creation_count(), 0);}- fn host_request(list: &[&str]) -> NetworkRequest {- NetworkRequest::Hosts(- list.iter()- .map(|h| http_proxy::HostPattern::parse(h).unwrap())- .collect(),- )+ /// Set up a sandboxing-enabled, auto-allowing project for the floor-+ /// enforcement tests, with the given persistent settings and thread grants.+ async fn floor_test_tool(+ cx: &mut gpui::TestAppContext,+ persistent: agent_settings::SandboxPermissions,+ grants: crate::sandboxing::ThreadSandboxGrants,+ ) -> (+ std::sync::Arc<SandboxedTerminalTool>,+ crate::ToolCallEventStream,+ crate::ToolCallEventStreamReceiver,+ std::rc::Rc<crate::tests::FakeThreadEnvironment>,+ ) {+ use feature_flags::FeatureFlagAppExt as _;++ crate::tests::init_test(cx);+ cx.update(|cx| {+ cx.update_flags(true, vec!["sandboxing".to_string()]);+ let mut settings = agent_settings::AgentSettings::get_global(cx).clone();+ settings.tool_permissions.default = settings::ToolPermissionMode::Allow;+ settings.tool_permissions.tools.remove(TerminalTool::NAME);+ settings.sandbox_permissions = persistent;+ agent_settings::AgentSettings::override_global(settings, cx);+ });++ let fs = fs::FakeFs::new(cx.executor());+ fs.insert_tree("/root", serde_json::json!({})).await;+ let project = project::Project::test(fs, ["/root".as_ref()], cx).await;++ let environment = std::rc::Rc::new(cx.update(|cx| {+ crate::tests::FakeThreadEnvironment::default().with_terminal(+ crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0),+ )+ }));+ #[allow(clippy::arc_with_non_send_sync)]+ let tool = std::sync::Arc::new(SandboxedTerminalTool::new(project, environment.clone()));+ let grants = std::rc::Rc::new(std::cell::RefCell::new(grants));+ let (event_stream, receiver) = crate::ToolCallEventStream::test_with_grants(grants);+ (tool, event_stream, receiver, environment)}- #[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?"- );+ /// A standing "run unsandboxed for this thread" grant makes an ordinary+ /// command (one that requests no escalation) run without a sandbox, and the+ /// model is told so in the output.+ #[gpui::test]+ async fn test_unsandboxed_thread_grant_runs_bare_command_unsandboxed(+ cx: &mut gpui::TestAppContext,+ ) {+ let mut grants = crate::sandboxing::ThreadSandboxGrants::default();+ grants.record(&crate::sandboxing::SandboxRequest {+ unsandboxed: true,+ ..Default::default()+ });+ let (tool, event_stream, _receiver, environment) =+ floor_test_tool(cx, agent_settings::SandboxPermissions::default(), grants).await;- let mut request = sandbox_request(NetworkRequest::AnyHost, false, &[]);- request.allow_git_access = true;- assert_eq!(- sandbox_approval_title(&request),- "Allow arbitrary network access and Git metadata access?"+ let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({+ "command": "echo hi",+ "cd": "root",+ }))+ .unwrap();+ let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx));+ let result = task.await.expect("bare command should run");+ assert_eq!(environment.terminal_creation_count(), 1);+ assert!(+ result.contains("WITHOUT an OS sandbox"),+ "a bare command in an unsandboxed thread must run unsandboxed: {result}");}- #[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?"+ /// Once the thread is unsandboxed, the model must not be able to ask for a+ /// scoped sandbox (it would silently run unsandboxed instead) — the call is+ /// rejected so the model fixes its request.+ #[gpui::test]+ async fn test_unsandboxed_thread_grant_rejects_scoping_request(cx: &mut gpui::TestAppContext) {+ let mut grants = crate::sandboxing::ThreadSandboxGrants::default();+ grants.record(&crate::sandboxing::SandboxRequest {+ unsandboxed: true,+ ..Default::default()+ });+ let (tool, event_stream, _receiver, environment) =+ floor_test_tool(cx, agent_settings::SandboxPermissions::default(), grants).await;++ let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({+ "command": "touch build/out",+ "cd": "root",+ "fs_write_paths": ["build"],+ "allow_all_hosts": true,+ "reason": "write build artifacts",+ }))+ .unwrap();+ let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx));+ let error = task+ .await+ .expect_err("scoping a request in an unsandboxed thread should be rejected");+ assert!(+ error.contains("Sandboxing is disabled for this thread"),+ "unexpected error: {error}");- 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?"+ // The error must name exactly the fields that have no effect.+ assert!(+ error.contains("`fs_write_paths`") && error.contains("`allow_all_hosts`"),+ "error should name the ineffective fields: {error}");+ assert_eq!(environment.terminal_creation_count(), 0);}- #[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?"+ /// A persistent "allow unrestricted filesystem writes" setting makes scoping+ /// writes to specific paths meaningless, so such a request is rejected.+ #[gpui::test]+ async fn test_unrestricted_fs_setting_rejects_scoped_write_paths(+ cx: &mut gpui::TestAppContext,+ ) {+ let persistent = agent_settings::SandboxPermissions {+ allow_fs_write_all: true,+ ..Default::default()+ };+ let (tool, event_stream, _receiver, environment) = floor_test_tool(+ cx,+ persistent,+ crate::sandboxing::ThreadSandboxGrants::default(),+ )+ .await;++ let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({+ "command": "touch build/out",+ "cd": "root",+ "fs_write_paths": ["build"],+ "reason": "write build artifacts",+ }))+ .unwrap();+ let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx));+ let error = task+ .await+ .expect_err("scoping writes when FS is unrestricted should be rejected");+ assert!(+ error.contains("Unrestricted filesystem writes are enabled for this thread"),+ "unexpected error: {error}");+ assert_eq!(environment.terminal_creation_count(), 0);}- #[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?"+ /// A standing "any host" network grant makes scoping to specific hosts+ /// meaningless, so such a request is rejected.+ #[gpui::test]+ async fn test_unrestricted_network_grant_rejects_scoped_hosts(cx: &mut gpui::TestAppContext) {+ let mut grants = crate::sandboxing::ThreadSandboxGrants::default();+ grants.record(&crate::sandboxing::SandboxRequest {+ network: NetworkRequest::AnyHost,+ ..Default::default()+ });+ let (tool, event_stream, _receiver, environment) =+ floor_test_tool(cx, agent_settings::SandboxPermissions::default(), grants).await;++ let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({+ "command": "curl https://github.com",+ "cd": "root",+ "allow_hosts": ["github.com"],+ "reason": "fetch from github",+ }))+ .unwrap();+ let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx));+ let error = task+ .await+ .expect_err("scoping hosts when network is unrestricted should be rejected");+ assert!(+ error.contains("Unrestricted network access is enabled for this thread"),+ "unexpected error: {error}");+ 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]@@ -3572,17 +3485,15 @@ mod tests {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.+ // macOS and Linux confine host requests through the allowlist proxy.match network_request_to_sandbox_network_access(&host_request(&["github.com"])) {- #[cfg(target_os = "macos")]+ #[cfg(any(target_os = "macos", target_os = "linux"))]acp_thread::SandboxNetworkAccess::Restricted(allowlist) => {assert!(allowlist.allows("github.com"));assert!(!allowlist.allows("example.com"));}- #[cfg(not(target_os = "macos"))]- acp_thread::SandboxNetworkAccess::All => {}+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]+ acp_thread::SandboxNetworkAccess::None => {}other => panic!("unexpected network access for host request, got {other:?}"),}}diff --git a/crates/agent_ui/Cargo.toml b/crates/agent_ui/Cargo.tomlindex 48fee9ffa34..bd1ed2b0ff9 100644--- a/crates/agent_ui/Cargo.toml+++ b/crates/agent_ui/Cargo.toml@@ -90,6 +90,7 @@ release_channel.workspace = trueremote.workspace = trueremote_connection.workspace = truerope.workspace = true+sandbox.workspace = trueschemars.workspace = truesearch.workspace = trueserde.workspace = truediff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex ffdcfc890b7..39507fa45aa 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -11009,6 +11009,7 @@ mod tests {draft_prompt: None,ui_scroll_position: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: Default::default(),};let thread_store = cx.update(|cx| ThreadStore::global(cx));diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex d0e17015b0c..d305cdb69f5 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -12,11 +12,12 @@ use acp_thread::{ContentBlock, PlanEntry, SandboxAuthorizationDetails, SandboxFallbackAuthorizationDetails,SandboxNotAppliedReason,};-use agent::{SkillLoadingIssue, SkillLoadingIssueKind, SkillLoadingIssuesUpdated};+use agent::{SkillLoadingIssue, SkillLoadingIssueKind, SkillLoadingIssuesUpdated, ThreadSandbox};use agent_settings::UserAgentsMd;use agent_skills::MAX_SKILL_DESCRIPTION_LEN;use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};use editor::actions::OpenExcerpts;+use sandbox::{GitSandboxPolicy, SandboxFsPolicy, SandboxNetPolicy, SandboxPolicy};use crate::completion_provider::AvailableSkill;use crate::message_editor::SharedSessionCapabilities;@@ -664,6 +665,19 @@ enum ToolCallLayout {Floating,}+impl ToolCallLayout {+ /// Stable discriminant used to disambiguate element ids when the same tool+ /// call is rendered in more than one layout at once (e.g. inline in the+ /// list *and* in the floating awaiting-permission row).+ fn id_str(self) -> &'static str {+ match self {+ ToolCallLayout::Standalone => "standalone",+ ToolCallLayout::Embedded => "embedded",+ ToolCallLayout::Floating => "floating",+ }+ }+}+fn full_path_for_empty_project_path(file: &dyn language::File, cx: &App) -> Option<String> {if file.path().file_name().is_some() {return None;@@ -4150,6 +4164,7 @@ impl ThreadView {.gap_0p5().child(self.render_add_context_button(cx)).child(self.render_follow_toggle(cx))+ .children(self.render_sandbox_status(cx)).children(self.render_fast_mode_control(cx)).children(self.render_thinking_control(cx)),)@@ -4552,6 +4567,71 @@ impl ThreadView {.unwrap_or(false)}+ /// A small lock icon summarizing the sandbox state. Hovering shows the+ /// write-access paths and network-access domains from the user's settings+ /// and the per-thread overrides. The lock is struck through when sandboxing+ /// is turned off (in settings, or for this thread). Shown whenever+ /// sandboxing is *applicable* to the project, even when disabled, so the+ /// user can always see and change the state. Clicking opens the settings.+ fn render_sandbox_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {+ let thread = self.as_native_thread(cx)?;+ let thread = thread.read(cx);+ let (settings_sandbox, thread_sandbox) = thread.sandbox_status(cx)?;+ let baseline = thread.sandbox_baseline_writable_paths(cx);++ // The lock is struck only when the *merged* result is unsandboxed (the+ // agent runs with ambient permissions). A layer that is merely wide open+ // but still sandboxed keeps the closed lock.+ let icon = if settings_sandbox+ .clone()+ .merge(thread_sandbox.clone())+ .is_unsandboxed()+ {+ IconName::LockOutlinedOff+ } else {+ IconName::LockOutlined+ };++ let state = match (settings_sandbox, thread_sandbox) {+ // No sandbox at all because the user turned it off in settings: the+ // per-thread layer is moot, so don't show it.+ (ThreadSandbox::Unsandboxed, _) => SandboxTooltipState::DisabledInSettings,+ // Sandboxed by settings, but disabled for this thread: show the+ // settings scope (greyed) for context above the disabled status.+ (ThreadSandbox::Sandboxed(settings_policy), ThreadSandbox::Unsandboxed) => {+ SandboxTooltipState::DisabledForThread {+ settings: augment_settings_sandbox_policy(settings_policy, baseline),+ }+ }+ (+ ThreadSandbox::Sandboxed(settings_policy),+ ThreadSandbox::Sandboxed(thread_policy),+ ) => SandboxTooltipState::Enabled {+ settings: augment_settings_sandbox_policy(settings_policy, baseline),+ thread: thread_policy,+ },+ };++ Some(+ IconButton::new("sandbox-status", icon)+ .icon_size(IconSize::Small)+ .icon_color(Color::Muted)+ .tooltip(Tooltip::element(move |_window, cx| {+ render_sandbox_status_tooltip(&state, cx)+ }))+ .on_click(|_, window, cx| {+ window.dispatch_action(+ Box::new(zed_actions::OpenSettingsAt {+ path: zed_actions::AGENT_SANDBOX_SETTINGS_PATH.to_string(),+ target: None,+ }),+ cx,+ );+ })+ .into_any_element(),+ )+ }+fn render_fast_mode_control(&self, cx: &mut Context<Self>) -> Option<AnyElement> {if !self.fast_mode_available(cx) {return None;@@ -5464,6 +5544,279 @@ impl Render for TokenUsageTooltip {}}+/// Which sandbox state the status tooltip describes.+#[derive(Clone)]+enum SandboxTooltipState {+ /// Sandboxing is on: show the settings policy and the per-thread overrides.+ Enabled {+ settings: SandboxPolicy,+ thread: SandboxPolicy,+ },+ /// Turned off via the persistent `allow_unsandboxed` setting.+ DisabledInSettings,+ /// Turned off for this thread (the "run without sandbox for this thread"+ /// fallback). The settings policy is still shown, greyed out, for context.+ DisabledForThread { settings: SandboxPolicy },+}++/// Build the hover tooltip for the sandbox status icon. Always opens with a+/// "Sandboxing settings" title, then describes the active state.+///+/// Returns the raw content only: `Tooltip::element` wraps it in the tooltip+/// container, so wrapping it again here would double the background.+fn render_sandbox_status_tooltip(state: &SandboxTooltipState, cx: &App) -> AnyElement {+ let mut body = v_flex()+ .min_w(rems(15.))+ .gap_2()+ .child(Label::new("Sandboxing settings"))+ .child(Divider::horizontal());++ match state {+ SandboxTooltipState::DisabledInSettings => {+ body = body.child(+ Label::new("Sandboxing is disabled in settings")+ .size(LabelSize::Small)+ .color(Color::Muted),+ );+ }+ SandboxTooltipState::DisabledForThread { settings } => {+ // The settings policy is moot while disabled, so show it greyed out+ // for context above the active "disabled for this thread" status.+ let settings_section =+ render_sandbox_policy_section("From your settings", settings, true, cx);+ body = body+ .children(+ settings_section+ .map(|section| div().opacity(0.5).child(section).into_any_element()),+ )+ .child(Divider::horizontal())+ .child(Label::new("Sandboxing is disabled for this thread").size(LabelSize::Small));+ }+ SandboxTooltipState::Enabled { settings, thread } => {+ let settings_section =+ render_sandbox_policy_section("From your settings", settings, true, cx);+ let thread_section =+ render_sandbox_policy_section("Allowed in this thread", thread, false, cx);+ body = body.children(settings_section);+ if let Some(section) = thread_section {+ body = body.child(Divider::horizontal()).child(section);+ }+ }+ }++ body.into_any_element()+}++/// Render one section of the sandbox status tooltip.+///+/// When `show_empty` is true the section is always rendered, and groups that+/// grant nothing show "None". When false, empty groups are omitted and the+/// whole section is dropped (`None`) if it grants nothing at all.+/// Fold the always-granted baseline writable paths (the project's worktree+/// roots, derived from the same source the terminal tool uses) and, on Linux,+/// the host-isolated `/tmp` overlay into a settings policy for display. These+/// are part of what the sandbox grants whenever it's active but aren't+/// persistent-settings entries, so they're shown in the "from your settings"+/// section rather than stored. A no-op when the fs is unrestricted (rendered as+/// "All paths"), since there's nothing to scope.+fn augment_settings_sandbox_policy(+ mut policy: SandboxPolicy,+ baseline: Vec<PathBuf>,+) -> SandboxPolicy {+ if let SandboxFsPolicy::Restricted { writable_paths } = &mut policy.fs {+ let mut merged = baseline;+ for path in writable_paths.drain(..) {+ if !merged.contains(&path) {+ merged.push(path);+ }+ }+ // The ephemeral, host-isolated tmpfs at /tmp is Linux-specific (the+ // bwrap `--tmpfs /tmp` overlay). It's a display-only label, not a real+ // host path, so it can't come from the path source above.+ #[cfg(target_os = "linux")]+ merged.push(PathBuf::from("/tmp (isolated)"));+ *writable_paths = merged;+ }+ policy+}++fn render_sandbox_policy_section(+ title: &str,+ policy: &SandboxPolicy,+ show_empty: bool,+ cx: &App,+) -> Option<AnyElement> {+ let write_rows = sandbox_fs_rows(&policy.fs, cx);+ let network_rows = sandbox_network_rows(&policy.network, cx);+ let write_empty = fs_grants_nothing(&policy.fs);+ let network_empty = network_grants_nothing(&policy.network);+ // Git access is only ever surfaced when *granted* (the `.git` dirs become+ // writable), so it never shows a "None" row — unlike write/network, it's+ // omitted entirely when denied, regardless of `show_empty`.+ let git_empty = git_grants_nothing(&policy.git);++ if !show_empty && write_empty && network_empty && git_empty {+ return None;+ }++ let write_group =+ (show_empty || !write_empty).then(|| sandbox_status_group("Write access", write_rows));+ let network_group = (show_empty || !network_empty)+ .then(|| sandbox_status_group("Network access", network_rows));+ let git_group = (!git_empty)+ .then(|| sandbox_status_group("Git metadata access", sandbox_git_rows(&policy.git, cx)));++ Some(+ v_flex()+ .gap_1()+ .child(Label::new(title.to_string()))+ .children(write_group)+ .children(network_group)+ .children(git_group)+ .into_any_element(),+ )+}++/// Git access grants nothing to surface unless `.git` writes are allowed *and*+/// at least one `.git` directory is known.+fn git_grants_nothing(git: &GitSandboxPolicy) -> bool {+ !git.allows_writes() || git.git_dirs().is_empty()+}++/// Rows for the Git-access group: one row per writable `.git` directory (these+/// may live outside the project for a linked worktree).+fn sandbox_git_rows(git: &GitSandboxPolicy, cx: &App) -> Vec<AnyElement> {+ match git {+ GitSandboxPolicy::Allowed { git_dirs } if !git_dirs.is_empty() => git_dirs+ .iter()+ .map(|path| sandbox_git_path_row(path, cx))+ .collect(),+ _ => Vec::new(),+ }+}++/// A `.git` directory row, tagged with a Git icon to distinguish it from plain+/// writable paths.+fn sandbox_git_path_row(path: &Path, cx: &App) -> AnyElement {+ h_flex()+ .min_w_0()+ .gap_1()+ .child(+ Icon::new(IconName::GitBranch)+ .color(Color::Muted)+ .size(IconSize::Small),+ )+ .child(+ Label::new(path.display().to_string())+ .size(LabelSize::XSmall)+ .buffer_font(cx),+ )+ .into_any_element()+}++fn fs_grants_nothing(fs: &SandboxFsPolicy) -> bool {+ matches!(fs, SandboxFsPolicy::Restricted { writable_paths } if writable_paths.is_empty())+}++fn network_grants_nothing(network: &SandboxNetPolicy) -> bool {+ match network {+ SandboxNetPolicy::Blocked => true,+ SandboxNetPolicy::Restricted { allowed_domains } => allowed_domains.is_empty(),+ SandboxNetPolicy::Unrestricted => false,+ }+}++/// Rows for the write-access group: a message for the "all"/"none" cases, or one+/// row per granted path.+fn sandbox_fs_rows(fs: &SandboxFsPolicy, cx: &App) -> Vec<AnyElement> {+ match fs {+ SandboxFsPolicy::Unrestricted => vec![sandbox_message_row("All paths (unrestricted)")],+ SandboxFsPolicy::Restricted { writable_paths } if writable_paths.is_empty() => {+ vec![sandbox_message_row("None")]+ }+ SandboxFsPolicy::Restricted { writable_paths } => writable_paths+ .iter()+ .map(|path| sandbox_path_row(path, cx))+ .collect(),+ }+}++/// Rows for the network-access group: a message for the "all"/"none" cases, or+/// one row per allowed domain.+fn sandbox_network_rows(network: &SandboxNetPolicy, cx: &App) -> Vec<AnyElement> {+ match network {+ SandboxNetPolicy::Unrestricted => vec![sandbox_message_row("All domains (unrestricted)")],+ SandboxNetPolicy::Blocked => vec![sandbox_message_row("None")],+ SandboxNetPolicy::Restricted { allowed_domains } if allowed_domains.is_empty() => {+ vec![sandbox_message_row("None")]+ }+ SandboxNetPolicy::Restricted { allowed_domains } => allowed_domains+ .iter()+ .map(|domain| sandbox_domain_row(domain, cx))+ .collect(),+ }+}++/// A "Write access" / "Network access" group: a muted header, then the indented+/// rows.+fn sandbox_status_group(heading: &str, rows: Vec<AnyElement>) -> impl IntoElement {+ v_flex()+ .gap_0p5()+ .child(+ Label::new(heading.to_string())+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .child(v_flex().pl_3().gap_0p5().children(rows))+}++/// A non-path row (e.g. "All paths (unrestricted)", "None") in a status group.+fn sandbox_message_row(message: &str) -> AnyElement {+ Label::new(message.to_string())+ .size(LabelSize::XSmall)+ .color(Color::Muted)+ .into_any_element()+}++fn sandbox_path_row(path: &Path, cx: &App) -> AnyElement {+ let display_path = path.display().to_string();+ let icon = FileIcons::get_icon(path, cx)+ .map(Icon::from_path)+ .map(|icon| icon.color(Color::Muted).size(IconSize::Small))+ .unwrap_or_else(|| {+ Icon::new(IconName::Folder)+ .color(Color::Muted)+ .size(IconSize::Small)+ });+ h_flex()+ .min_w_0()+ .gap_1()+ .child(icon)+ .child(+ Label::new(display_path)+ .size(LabelSize::XSmall)+ .buffer_font(cx),+ )+ .into_any_element()+}++fn sandbox_domain_row(domain: &str, cx: &App) -> AnyElement {+ h_flex()+ .min_w_0()+ .gap_1()+ .child(+ Icon::new(IconName::Public)+ .color(Color::Muted)+ .size(IconSize::Small),+ )+ .child(+ Label::new(domain.to_string())+ .size(LabelSize::XSmall)+ .buffer_font(cx),+ )+ .into_any_element()+}+impl ThreadView {fn render_entries(&mut self, cx: &mut Context<Self>) -> List {let max_content_width = AgentSettings::get_global(cx).max_content_width;@@ -6930,6 +7283,12 @@ impl ThreadView {style.container_style.text.font_size = Some(rems_from_px(12.).into());style.container_style.text.line_height = Some(rems_from_px(17.).into());style.height_is_multiple_of_line_height = true;+ // Soft-wrap the command instead of horizontally scrolling it: the card is+ // narrow, and in scroll mode a long command wraps anyway but its wrapped+ // lines don't pick up the code block's left padding. Wrap mode lays the+ // text out as a normal block inside the padded content box, so every+ // line (wrapped or not) is padded consistently.+ style.code_block_overflow_x_scroll = false;let header_bg = self.tool_card_header_bg(cx);let run_command_label = if is_preview {@@ -6954,7 +7313,8 @@ impl ThreadView {wrap_button_visibility: markdown::WrapButtonVisibility::Hidden,border: false,});- let copy_button = CopyButton::new("copy-command", command_text)+ let copy_button_id = SharedString::from(format!("{group}-copy-command"));+ let copy_button = CopyButton::new(copy_button_id, command_text).tooltip_label("Copy Command").visible_on_hover(group.clone());@@ -7366,10 +7726,22 @@ impl ThreadView {layout: ToolCallLayout,window: &Window,cx: &Context<Self>,- ) -> Div {+ ) -> Stateful<Div> {let has_terminals = tool_call.terminals().next().is_some();- div().w_full().map(|this| {+ // Give every tool-call subtree a unique element-id prefix derived from+ // the globally-unique tool call id and the layout. This single wrapper+ // is what keeps all the `entry_ix`-keyed element ids inside the card+ // collision-free, even when the same tool call is rendered in multiple+ // places at once (inline list + floating awaiting-permission row) or+ // when subagent entries are inlined into the parent view's element tree.+ let container_id = ElementId::Name(SharedString::from(format!(+ "tool-call-{}-{}",+ tool_call.id.0,+ layout.id_str()+ )));++ div().w_full().id(container_id).map(|this| {if tool_call.is_subagent() {this.child(self.render_subagent_tool_call(@@ -7423,7 +7795,7 @@ impl ThreadView {cx: &Context<Self>,) -> Div {let has_location = tool_call.locations.len() == 1;- let card_header_id = SharedString::from("inner-tool-call-header");+ let card_header_id = SharedString::from(format!("inner-tool-call-header-{entry_ix}"));let failed_or_canceled = match &tool_call.status {ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,@@ -7928,15 +8300,11 @@ impl ThreadView {cx: &Context<Self>,) -> AnyElement {let has_network = details.network_all_hosts || !details.network_hosts.is_empty();- let has_git_access = details.allow_git_access;- let command = details- .command- .as_deref()- .filter(|command| !command.is_empty());- if details.write_paths.is_empty()- && !has_network- && !has_git_access- && command.is_none()+ let has_write = details.allow_fs_write_all || !details.write_paths.is_empty();+ if !has_network+ && !has_write+ && !details.allow_git_access+ && !details.unsandboxed&& details.reason.is_empty(){return Empty.into_any_element();@@ -7967,7 +8335,10 @@ impl ThreadView {.child(h_flex().id(("sandbox-network-details-header", entry_ix))- .p_1()+ // Align text with the allow/deny button icons below,+ // which sit at p_1 (container) + Base04 (button) ≈ px_2.+ .px_2()+ .py_1().justify_between().when(has_host_list, |this| {this.cursor_pointer()@@ -8025,17 +8396,12 @@ impl ThreadView {.children(hosts.iter().enumerate().map(|(host_ix, host)| {h_flex().min_w_0()- .p_1p5()- .gap_2()+ .px_2()+ .py_1p5().bg(cx.theme().colors().editor_background).when(host_ix < hosts.len() - 1, |this| {this.border_b_1().border_color(cx.theme().colors().border)})- .child(- Icon::new(IconName::Public)- .color(Color::Muted)- .size(IconSize::Small),- ).child(Label::new(host.clone()).size(LabelSize::XSmall)@@ -8046,121 +8412,54 @@ impl ThreadView {})});- let git_access_section = has_git_access.then(|| {- v_flex()- .p_1()- .gap_0p5()- .child(- h_flex()- .gap_1()- .child(- Icon::new(IconName::GitBranch)- .color(Color::Muted)- .size(IconSize::Small),- )- .child(- Label::new("Git metadata access")- .size(LabelSize::Small)- .color(Color::Muted),- ),- )- .child(- Label::new(- "Allows reading and writing .git directories, which may include repositories outside this project, and exposes the inherited SSH agent for commit signing.",- )- .size(LabelSize::XSmall)- .color(Color::Muted),+ let write_section = has_write.then(|| {+ let summary = if details.allow_fs_write_all {+ "unrestricted".to_string()+ } else {+ format!(+ "{} {}",+ details.write_paths.len(),+ if details.write_paths.len() == 1 {+ "path"+ } else {+ "paths"+ })- .into_any_element()- });-- if details.write_paths.is_empty() {- return v_flex()- .border_t_1()- .border_color(self.tool_card_border_color(cx))- .when_some(command, |this, command| {- this.child(Self::render_sandbox_authorization_command(- entry_ix, command, cx,- ))- })- .children(network_section)- .children(git_access_section)- .into_any_element();- }-- let is_open = !self- .collapsed_sandbox_authorization_details- .contains(tool_call_id);- let mut paths = details.write_paths.clone();- paths.sort();-- v_flex()- .border_t_1()- .border_color(self.tool_card_border_color(cx))- .when_some(command, |this, command| {- this.child(Self::render_sandbox_authorization_command(- entry_ix, command, cx,- ))- })- .children(network_section)- .children(git_access_section)- .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(- 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;- }+ };+ let has_path_list = !details.allow_fs_write_all && !details.write_paths.is_empty();+ let is_open = !self+ .collapsed_sandbox_authorization_details+ .contains(tool_call_id);+ let mut paths = details.write_paths.clone();+ paths.sort();- this.collapsed_sandbox_authorization_details- .insert(tool_call_id.clone());- cx.notify();- }- })),- )- .when(is_open && !paths.is_empty(), |this| {- this.child(- v_flex()- .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(+ v_flex()+ .child(h_flex().id(("sandbox-authorization-details-header", entry_ix))- .p_1()+ .px_2()+ .py_1().justify_between()- .cursor_pointer()- .hover(|style| style.bg(cx.theme().colors().element_hover))+ .when(has_path_list, |this| {+ this.cursor_pointer()+ .hover(|style| style.bg(cx.theme().colors().element_hover))+ .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();+ }+ }))+ }).child(h_flex().gap_1()@@ -8175,38 +8474,23 @@ impl ThreadView {.color(Color::Disabled),).child(- Label::new(format!(- "{} {}",- paths.len(),- if paths.len() == 1 { "path" } else { "paths" }- ))- .size(LabelSize::Small)- .color(Color::Muted),+ Label::new(summary)+ .size(LabelSize::Small)+ .color(Color::Muted),),)- .child(- Disclosure::new(("sandbox-authorization-details", entry_ix), is_open)+ .when(has_path_list, |this| {+ this.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| {+ .when(has_path_list && is_open, |this| {this.child(v_flex().id(("sandbox-authorization-paths-list", entry_ix))@@ -8223,7 +8507,66 @@ impl ThreadView {})),)})- })+ });++ let unsandboxed_section = details.unsandboxed.then(|| {+ h_flex()+ .px_2()+ .py_1()+ .gap_1p5()+ .child(+ Icon::new(IconName::Warning)+ .color(Color::Warning)+ .size(IconSize::Small),+ )+ .child(+ Label::new("Runs without the OS sandbox")+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ });++ let git_access_section = details.allow_git_access.then(|| {+ v_flex().px_2().py_1().gap_0p5().child(+ h_flex()+ .gap_1()+ .child(+ Icon::new(IconName::GitBranch)+ .color(Color::Muted)+ .size(IconSize::Small),+ )+ .child(+ Label::new("Git metadata access")+ .size(LabelSize::Small)+ .color(Color::Muted),+ ),+ )+ });++ let reason_section = (!details.reason.is_empty()).then(|| {+ v_flex()+ .px_2()+ .py_1()+ .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))+ });++ // The command stays in the tool-call title above; here we show what the+ // command is asking for (paths / domains) and the agent's reason.+ v_flex()+ .border_t_1()+ .border_color(self.tool_card_border_color(cx))+ .children(network_section)+ .children(write_section)+ .children(git_access_section)+ .children(unsandboxed_section)+ .children(reason_section).into_any_element()}@@ -8264,49 +8607,6 @@ impl ThreadView {.into_any_element()}- fn render_sandbox_authorization_command(entry_ix: usize, command: &str, cx: &App) -> Div {- let group = SharedString::from(format!("sandbox-authorization-command-{entry_ix}"));- let command = SharedString::from(command.to_string());-- v_flex()- .group(group.clone())- .relative()- .p_1p5()- .gap_1()- .bg(cx.theme().colors().editor_background)- .child(- Label::new("Command")- .size(LabelSize::XSmall)- .color(Color::Muted),- )- .child(- div()- .id(("sandbox-authorization-command-scroll", entry_ix))- .flex()- .flex_1()- .w_full()- .min_w_0()- .overflow_x_scroll()- .whitespace_nowrap()- .rounded_sm()- .border_1()- .border_color(cx.theme().colors().border)- .p_1()- .child(- Label::new(command.clone())- .buffer_font(cx)- .size(LabelSize::XSmall),- ),- )- .child(- div().absolute().top_1().right_1().child(- CopyButton::new("copy-sandbox-authorization-command", command)- .tooltip_label("Copy Command")- .visible_on_hover(group),- ),- )- }-fn render_sandbox_authorization_path_row(&self,entry_ix: usize,@@ -8324,22 +8624,14 @@ impl ThreadView {let parent = parent.display().to_string();(!parent.is_empty()).then_some(parent)});- let path_icon = FileIcons::get_icon(path, cx)- .map(Icon::from_path)- .map(|icon| icon.color(Color::Muted).size(IconSize::Small))- .unwrap_or_else(|| {- Icon::new(IconName::Folder)- .color(Color::Muted)- .size(IconSize::Small)- });h_flex().id(SharedString::from(format!("sandbox-authorization-path-{entry_ix}-{path_ix}"))).min_w_0()- .p_1p5()- .gap_2()+ .px_2()+ .py_1p5().bg(cx.theme().colors().editor_background).when(show_border, |this| {this.border_b_1().border_color(cx.theme().colors().border)@@ -8351,7 +8643,6 @@ impl ThreadView {))).min_w_0().gap_0p5()- .child(path_icon).child(Label::new(file_name).size(LabelSize::XSmall)@@ -9919,7 +10210,13 @@ impl ThreadView {div().pb_1().min_h_0()- .id(format!("subagent-entries-{}", session_id))+ // Include the tool call id so the same subagent session+ // rendered in multiple parent cards gets distinct element+ // ids for its inlined entries (avoids duplicate a11y ids).+ .id(format!(+ "subagent-entries-{}-{}",+ session_id, tool_call.id.0+ )).track_scroll(&scroll_handle).children(rendered_entries),)diff --git a/crates/agent_ui/src/thread_metadata_store.rs b/crates/agent_ui/src/thread_metadata_store.rsindex 1959b25c0e8..1f0b0eb46d3 100644--- a/crates/agent_ui/src/thread_metadata_store.rs+++ b/crates/agent_ui/src/thread_metadata_store.rs@@ -1852,6 +1852,7 @@ mod tests {draft_prompt: None,ui_scroll_position: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: Default::default(),}}diff --git a/crates/http_proxy/Cargo.toml b/crates/http_proxy/Cargo.tomlindex efce7a8e5c2..239cd9657d8 100644--- a/crates/http_proxy/Cargo.toml+++ b/crates/http_proxy/Cargo.toml@@ -11,6 +11,15 @@ workspace = true[lib]path = "src/http_proxy.rs"+[features]+# Compiles in the `ZED_SANDBOX_PROXY_ALLOW_LOCAL_IPS` escape hatch that lets the+# proxy reach loopback/private/link-local addresses. This disables the proxy's+# DNS-rebinding/SSRF protection, so it must NEVER be enabled in a real Zed+# build (debug or release) — it exists solely for the NixOS sandbox integration+# tests, whose echo servers live on the VM's private network. Enabled only via+# `sandbox/nixos-test` when building `bwrap_test_helper`.+nixos-integration-tests = []+[dependencies]anyhow.workspace = truebase64.workspace = truediff --git a/crates/http_proxy/src/proxy.rs b/crates/http_proxy/src/proxy.rsindex bb51bf995a4..62050359b61 100644--- a/crates/http_proxy/src/proxy.rs+++ b/crates/http_proxy/src/proxy.rs@@ -17,7 +17,12 @@ use crate::allowlist::Allowlist;use anyhow::{Context, Result};use futures::channel::mpsc;use std::net::{Ipv4Addr, TcpListener, TcpStream};+#[cfg(unix)]+use std::os::unix::net::{UnixListener, UnixStream};+use std::path::{Path, PathBuf};use std::sync::Arc;+#[cfg(unix)]+use std::sync::atomic::AtomicU64;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::thread;@@ -140,6 +145,8 @@ pub enum ProxyEvent {/// connection threads finish on their own as soon as either side closes.pub struct ProxyHandle {port: u16,+ socket_path: Option<PathBuf>,+ cleanup_directory: Option<PathBuf>,/// Listener thread sees this flip to `true` after `accept` returns and/// then exits.shutdown: Arc<AtomicBool>,@@ -187,15 +194,90 @@ impl ProxyHandle {Ok(ProxyHandle {port,+ socket_path: None,+ cleanup_directory: None,shutdown,listener_thread: Some(listener_thread),})}- /// The bound port. Stable for the lifetime of this handle.+ /// Spawns the proxy on a fresh pathname Unix socket under the system temp+ /// directory and reserves a loopback port number for the in-sandbox bridge.+ #[cfg(unix)]+ pub fn spawn_unix_temp(config: ProxyConfig) -> Result<ProxyHandle> {+ let directory = unique_temp_socket_directory();+ let path = directory.join("proxy.sock");+ Self::spawn_unix_with_cleanup(path, Some(directory), config)+ }++ /// Spawns the proxy on a pathname Unix socket and reserves a loopback port+ /// number for the in-sandbox bridge to listen on.+ #[cfg(unix)]+ pub fn spawn_unix(path: impl AsRef<Path>, config: ProxyConfig) -> Result<ProxyHandle> {+ Self::spawn_unix_with_cleanup(path.as_ref().to_path_buf(), None, config)+ }++ #[cfg(unix)]+ fn spawn_unix_with_cleanup(+ path: PathBuf,+ cleanup_directory: Option<PathBuf>,+ config: ProxyConfig,+ ) -> Result<ProxyHandle> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).with_context(|| {+ format!(+ "failed to create proxy socket directory {}",+ parent.display()+ )+ })?;+ }+ if path.exists() {+ std::fs::remove_file(&path).with_context(|| {+ format!("failed to remove stale proxy socket {}", path.display())+ })?;+ }++ let listener = UnixListener::bind(&path)+ .with_context(|| format!("failed to bind proxy Unix socket {}", path.display()))?;+ let port = reserve_loopback_port()?;++ let _ = config.events.unbounded_send(ProxyEvent::Ready { port });++ let shutdown = Arc::new(AtomicBool::new(false));+ let runtime_state = Arc::new(RuntimeState {+ allowlist: config.allowlist,+ upstream: config.upstream,+ events: config.events,+ active_connections: AtomicUsize::new(0),+ });++ let listener_thread = thread::Builder::new()+ .name("http-proxy-unix-listener".to_string())+ .stack_size(128 * 1024)+ .spawn({+ let shutdown = shutdown.clone();+ move || run_unix_listener(listener, runtime_state, shutdown)+ })+ .context("failed to spawn proxy Unix listener thread")?;++ Ok(ProxyHandle {+ port,+ socket_path: Some(path),+ cleanup_directory,+ shutdown,+ listener_thread: Some(listener_thread),+ })+ }++ /// The loopback TCP port clients should use for proxy environment variables.pub fn port(&self) -> u16 {self.port}++ /// Path of the Unix socket listener, for Linux bridge mode.+ pub fn socket_path(&self) -> Option<&Path> {+ self.socket_path.as_deref()+ }}impl Drop for ProxyHandle {@@ -207,7 +289,14 @@ impl Drop for ProxyHandle {// listener wakes up, accepts the connection, sees the shutdown// flag, breaks the loop. The accepted connection's worker thread// will read the empty stream and exit too.- let _ = TcpStream::connect((Ipv4Addr::LOCALHOST, self.port));+ if let Some(path) = &self.socket_path {+ #[cfg(unix)]+ let _ = UnixStream::connect(path);+ #[cfg(not(unix))]+ let _ = path;+ } else {+ let _ = TcpStream::connect((Ipv4Addr::LOCALHOST, self.port));+ }if let Some(thread) = self.listener_thread.take() {// Give the listener a chance to clean up. A join error means the@@ -217,9 +306,41 @@ impl Drop for ProxyHandle {log::warn!("[http_proxy] listener thread panicked");}}+ if let Some(path) = &self.socket_path+ && let Err(error) = std::fs::remove_file(path)+ && error.kind() != std::io::ErrorKind::NotFound+ {+ log::debug!(+ "[http_proxy] failed to remove proxy Unix socket {}: {error}",+ path.display()+ );+ }+ if let Some(directory) = &self.cleanup_directory+ && let Err(error) = std::fs::remove_dir(directory)+ && error.kind() != std::io::ErrorKind::NotFound+ {+ log::debug!(+ "[http_proxy] failed to remove proxy socket directory {}: {error}",+ directory.display()+ );+ }}}+#[cfg(unix)]+fn unique_temp_socket_directory() -> PathBuf {+ 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);+ std::env::temp_dir().join(format!(+ "zed-proxy-{}-{nanos}-{counter}",+ std::process::id()+ ))+}+/// State shared across all connection threads for a single proxy instance.pub(crate) struct RuntimeState {pub(crate) allowlist: Allowlist,@@ -238,6 +359,16 @@ impl Drop for ConnectionSlot {}}+#[cfg(unix)]+fn reserve_loopback_port() -> Result<u16> {+ let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))+ .context("failed to reserve proxy bridge port")?;+ Ok(listener+ .local_addr()+ .context("failed to read reserved proxy bridge port")?+ .port())+}+fn run_listener(listener: TcpListener, state: Arc<RuntimeState>, shutdown: Arc<AtomicBool>) {for stream in listener.incoming() {if shutdown.load(Ordering::SeqCst) {@@ -245,34 +376,7 @@ fn run_listener(listener: TcpListener, state: Arc<RuntimeState>, shutdown: Arc<Abreak;}match stream {- Ok(stream) => {- let previous = state.active_connections.fetch_add(1, Ordering::SeqCst);- if previous >= MAX_CONCURRENT_CONNECTIONS {- state.active_connections.fetch_sub(1, Ordering::SeqCst);- log::warn!(- "[http_proxy] dropping connection: {MAX_CONCURRENT_CONNECTIONS} \- connections already active"- );- drop(stream);- continue;- }- let slot = ConnectionSlot(state.clone());- let state = state.clone();- let result = thread::Builder::new()- .name("http-proxy-conn".to_string())- // Connection workers do bidir copy with a 64 KiB buffer- // and a few syscall stack frames. 128 KiB is plenty.- .stack_size(128 * 1024)- .spawn(move || {- let _slot = slot;- if let Err(e) = connection::handle(stream, state) {- log::debug!("[http_proxy] connection handler error: {e}");- }- });- if let Err(e) = result {- log::warn!("[http_proxy] failed to spawn connection thread: {e}");- }- }+ Ok(stream) => spawn_connection(connection::ClientStream::Tcp(stream), &state),Err(e) => {// EMFILE / per-process fd exhaustion is the realistic// failure here. Log and keep going — accept errors are@@ -282,3 +386,44 @@ fn run_listener(listener: TcpListener, state: Arc<RuntimeState>, shutdown: Arc<A}}}++#[cfg(unix)]+fn run_unix_listener(listener: UnixListener, state: Arc<RuntimeState>, shutdown: Arc<AtomicBool>) {+ for stream in listener.incoming() {+ if shutdown.load(Ordering::SeqCst) {+ log::debug!("[http_proxy] Unix listener stopping (shutdown signaled)");+ break;+ }+ match stream {+ Ok(stream) => spawn_connection(connection::ClientStream::Unix(stream), &state),+ Err(error) => log::warn!("[http_proxy] Unix accept failed: {error}"),+ }+ }+}++fn spawn_connection(stream: connection::ClientStream, state: &Arc<RuntimeState>) {+ let previous = state.active_connections.fetch_add(1, Ordering::SeqCst);+ if previous >= MAX_CONCURRENT_CONNECTIONS {+ state.active_connections.fetch_sub(1, Ordering::SeqCst);+ log::warn!(+ "[http_proxy] dropping connection: {MAX_CONCURRENT_CONNECTIONS} \+ connections already active"+ );+ drop(stream);+ return;+ }+ let slot = ConnectionSlot(state.clone());+ let state = state.clone();+ let result = thread::Builder::new()+ .name("http-proxy-conn".to_string())+ .stack_size(128 * 1024)+ .spawn(move || {+ let _slot = slot;+ if let Err(error) = connection::handle(stream, state) {+ log::debug!("[http_proxy] connection handler error: {error}");+ }+ });+ if let Err(error) = result {+ log::warn!("[http_proxy] failed to spawn connection thread: {error}");+ }+}diff --git a/crates/http_proxy/src/proxy/connection.rs b/crates/http_proxy/src/proxy/connection.rsindex 65aa0a0b02c..06ae8ea73d0 100644--- a/crates/http_proxy/src/proxy/connection.rs+++ b/crates/http_proxy/src/proxy/connection.rs@@ -18,6 +18,8 @@ use anyhow::{Context, Result, anyhow, bail};use base64::Engine as _;use std::io::{Read, Write};use std::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, TcpStream, ToSocketAddrs as _};+#[cfg(unix)]+use std::os::unix::net::UnixStream;use std::sync::Arc;use std::thread;use std::time::{Duration, Instant};@@ -52,11 +54,82 @@ const UPSTREAM_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);/// Top-level entry from the listener thread. Owns the client connection/// and the runtime state; emits events; never returns errors that escape/// the connection (those are logged at the listener level).-pub(crate) fn handle(client: TcpStream, state: Arc<RuntimeState>) -> Result<()> {- // Performance baseline: TCP_NODELAY eliminates the Nagle delay that- // otherwise stalls small interactive payloads (git protocol negotiation,- // npm metadata pings, etc.).- if let Err(error) = client.set_nodelay(true) {+pub(crate) enum ClientStream {+ Tcp(TcpStream),+ #[cfg(unix)]+ Unix(UnixStream),+}++impl ClientStream {+ fn try_clone(&self) -> std::io::Result<Self> {+ match self {+ Self::Tcp(stream) => stream.try_clone().map(Self::Tcp),+ #[cfg(unix)]+ Self::Unix(stream) => stream.try_clone().map(Self::Unix),+ }+ }++ fn set_read_timeout(&self, duration: Option<Duration>) -> std::io::Result<()> {+ match self {+ Self::Tcp(stream) => stream.set_read_timeout(duration),+ #[cfg(unix)]+ Self::Unix(stream) => stream.set_read_timeout(duration),+ }+ }+}++impl Read for ClientStream {+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {+ match self {+ Self::Tcp(stream) => stream.read(buf),+ #[cfg(unix)]+ Self::Unix(stream) => stream.read(buf),+ }+ }+}++impl Write for ClientStream {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ match self {+ Self::Tcp(stream) => stream.write(buf),+ #[cfg(unix)]+ Self::Unix(stream) => stream.write(buf),+ }+ }++ fn flush(&mut self) -> std::io::Result<()> {+ match self {+ Self::Tcp(stream) => stream.flush(),+ #[cfg(unix)]+ Self::Unix(stream) => stream.flush(),+ }+ }+}++trait StreamIo: Read + Write + Send + 'static {+ fn shutdown(&self, how: Shutdown) -> std::io::Result<()>;+}++impl StreamIo for ClientStream {+ fn shutdown(&self, how: Shutdown) -> std::io::Result<()> {+ match self {+ Self::Tcp(stream) => stream.shutdown(how),+ #[cfg(unix)]+ Self::Unix(stream) => stream.shutdown(how),+ }+ }+}++impl StreamIo for TcpStream {+ fn shutdown(&self, how: Shutdown) -> std::io::Result<()> {+ TcpStream::shutdown(self, how)+ }+}++pub(crate) fn handle(client: ClientStream, state: Arc<RuntimeState>) -> Result<()> {+ if let ClientStream::Tcp(stream) = &client+ && let Err(error) = stream.set_nodelay(true)+ {log::debug!("[http_proxy] failed to set TCP_NODELAY on client socket: {error}");}@@ -106,7 +179,7 @@ pub(crate) fn handle(client: TcpStream, state: Arc<RuntimeState>) -> Result<()>/// Reads request headers (until `\r\n\r\n`) from the client. Returns the/// full buffer (which may include some bytes after the headers) and the/// offset where the headers ended. Capped at [`MAX_HEADER_BYTES`].-fn read_request_headers(client: &mut TcpStream) -> Result<(Vec<u8>, usize)> {+fn read_request_headers(client: &mut ClientStream) -> Result<(Vec<u8>, usize)> {let mut buf = Vec::with_capacity(4096);let mut tmp = [0u8; 4096];let mut searched = 0usize;@@ -418,6 +491,16 @@ fn plan_route(host: &str, port: u16, state: &RuntimeState) -> Result<Route, Rout/// already blocks them for direct connections from the sandbox; the proxy/// (which runs outside the sandbox) must not reopen them.fn is_forbidden_ip(ip: IpAddr) -> bool {+ // Escape hatch for the NixOS sandbox integration tests only: their echo+ // servers live on the VM's private network, which this filter would+ // otherwise reject. It is compiled in ONLY under the+ // `nixos-integration-tests` feature (enabled via `sandbox/nixos-test` when+ // building `bwrap_test_helper`), so in a real Zed build the env var has no+ // effect and cannot disable DNS-rebinding/SSRF protection.+ #[cfg(feature = "nixos-integration-tests")]+ if std::env::var_os("ZED_SANDBOX_PROXY_ALLOW_LOCAL_IPS").is_some() {+ return false;+ }match ip {IpAddr::V4(v4) => is_forbidden_ipv4(v4),IpAddr::V6(v6) => {@@ -448,7 +531,7 @@ fn is_forbidden_ipv4(ip: Ipv4Addr) -> bool {}fn handle_connect(- mut client: TcpStream,+ mut client: ClientStream,host: String,port: u16,leftover_body: Vec<u8>,@@ -540,7 +623,7 @@ fn handle_connect(}fn handle_http_forward(- mut client: TcpStream,+ mut client: ClientStream,method: String,host: String,port: u16,@@ -741,7 +824,7 @@ fn connect_via_upstream(/// Send a 511 response with `Via` and `Proxy-Status` headers and an/// explanatory body. Closes the connection afterwards.fn deny_request(- client: &mut TcpStream,+ client: &mut ClientStream,state: &RuntimeState,host: String,port: u16,@@ -809,7 +892,7 @@ fn emit(state: &RuntimeState, event: ProxyEvent) {/// Returns `(client→remote bytes, remote→client bytes)`. Errors are/// swallowed — partial transfer is fine, the caller just emits whatever/// totals we got.-fn pump_bidir(client: TcpStream, upstream: TcpStream) -> (u64, u64) {+fn pump_bidir(client: ClientStream, upstream: TcpStream) -> (u64, u64) {// Two clones per direction so each side owns the half it touches.// `try_clone` dups the underlying fd, so reads/writes on the two// halves don't contend for the same kernel state.@@ -852,7 +935,7 @@ fn pump_bidir(client: TcpStream, upstream: TcpStream) -> (u64, u64) {/// Copy bytes from `from` to `to` until EOF on the read side or write/// failure. Half-closes `to` for writes when done so the partner sees EOF.-fn copy_one_way(mut from: TcpStream, mut to: TcpStream) -> u64 {+fn copy_one_way(mut from: impl Read, mut to: impl StreamIo) -> u64 {let mut total = 0u64;let mut buf = vec![0u8; PUMP_BUFFER_SIZE];loop {diff --git a/crates/http_proxy/tests/end_to_end.rs b/crates/http_proxy/tests/end_to_end.rsindex 076d07f8b28..0bc3536aa0f 100644--- a/crates/http_proxy/tests/end_to_end.rs+++ b/crates/http_proxy/tests/end_to_end.rs@@ -13,6 +13,8 @@ use http_proxy::{};use std::io::{Read, Write};use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};+#[cfg(unix)]+use std::os::unix::net::UnixStream;use std::thread;use std::time::Duration;@@ -95,13 +97,30 @@ fn spawn_proxy_with_upstream(}).expect("proxy spawn");- // Drain the Ready event so callers see RequestAttempt as the first.+ drain_ready(&proxy, &mut events_rx);+ (proxy, events_rx)+}++#[cfg(unix)]+fn spawn_unix_proxy(allowlist: Allowlist) -> (ProxyHandle, mpsc::UnboundedReceiver<ProxyEvent>) {+ let (events_tx, mut events_rx) = mpsc::unbounded();+ let proxy = ProxyHandle::spawn_unix_temp(ProxyConfig {+ allowlist,+ upstream: None,+ events: events_tx,+ })+ .expect("proxy spawn");++ drain_ready(&proxy, &mut events_rx);+ (proxy, events_rx)+}++fn drain_ready(proxy: &ProxyHandle, events_rx: &mut mpsc::UnboundedReceiver<ProxyEvent>) {let ready = futures::executor::block_on(events_rx.next());match ready {Some(ProxyEvent::Ready { port }) => assert_eq!(port, proxy.port()),other => panic!("expected Ready event first, got {other:?}"),}- (proxy, events_rx)}fn next_event(events: &mut mpsc::UnboundedReceiver<ProxyEvent>) -> ProxyEvent {@@ -170,6 +189,46 @@ fn connect_allowed_host_completes_tunnel_and_emits_events() {}}+#[cfg(unix)]+#[test]+fn unix_listener_denied_host_returns_511() {+ let allowlist = Allowlist::from_patterns([HostPattern::parse("github.com").unwrap()]);+ let (proxy, mut events) = spawn_unix_proxy(allowlist);+ let socket_path = proxy+ .socket_path()+ .expect("Unix proxy socket path")+ .to_path_buf();++ let mut client = UnixStream::connect(socket_path).unwrap();+ client.set_read_timeout(Some(TEST_TIMEOUT)).unwrap();+ client+ .write_all(b"CONNECT denied.example:443 HTTP/1.1\r\nHost: denied.example:443\r\n\r\n")+ .unwrap();++ let mut response = String::new();+ client.read_to_string(&mut response).unwrap();+ assert!(+ response.starts_with("HTTP/1.1 511 "),+ "expected 511, got: {response}"+ );+ assert!(response.contains("denied.example"));++ match next_event(&mut events) {+ ProxyEvent::RequestAttempt {+ host,+ port,+ method,+ outcome,+ } => {+ assert_eq!(host, "denied.example");+ assert_eq!(port, 443);+ assert_eq!(method, RequestMethod::Connect);+ assert!(matches!(outcome, RequestOutcome::Denied { .. }));+ }+ other => panic!("expected RequestAttempt(Denied), got {other:?}"),+ }+}+#[test]fn connect_denied_host_returns_511_with_via_header() {let allowlist = Allowlist::from_patterns([HostPattern::parse("github.com").unwrap()]);diff --git a/crates/icons/src/icons.rs b/crates/icons/src/icons.rsindex 72f6b32221f..6588d3f07f3 100644--- a/crates/icons/src/icons.rs+++ b/crates/icons/src/icons.rs@@ -184,6 +184,7 @@ pub enum IconName {LoadCircle,LocationEdit,LockOutlined,+ LockOutlinedOff,MagnifyingGlass,Maximize,MaximizeAlt,diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rsindex 50d6a7671ad..5a033c17bbb 100644--- a/crates/markdown/src/markdown.rs+++ b/crates/markdown/src/markdown.rs@@ -2836,8 +2836,12 @@ fn render_wrap_code_block_button(} else {(IconName::TextWrap, "Wrap Content")};+ let button_id = ElementId::NamedChild(+ Arc::new(ElementId::from(("wrap-code-block", markdown.entity_id()))),+ id.to_string().into(),+ );- IconButton::new(("wrap-code-block", id), icon)+ IconButton::new(button_id, icon).icon_size(IconSize::Small).icon_color(Color::Muted).tooltip(Tooltip::text(tooltip))@@ -2854,7 +2858,13 @@ fn render_copy_code_block_button(code: String,markdown: Entity<Markdown>,) -> impl IntoElement {- let id = ElementId::named_usize("copy-markdown-code", id);+ let id = ElementId::NamedChild(+ Arc::new(ElementId::from((+ "copy-markdown-code",+ markdown.entity_id(),+ ))),+ id.to_string().into(),+ );CopyButton::new(id.clone(), code.clone()).custom_on_click({let markdown = markdown;@@ -3934,6 +3944,52 @@ mod tests {});}+ #[gpui::test]+ fn test_code_block_controls_are_unique_across_markdown_entities(cx: &mut TestAppContext) {+ struct TestWindow;++ impl Render for TestWindow {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ div()+ }+ }++ struct TestMarkdowns {+ first_markdown: Entity<Markdown>,+ second_markdown: Entity<Markdown>,+ }++ impl Render for TestMarkdowns {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ div()+ .child(MarkdownElement::new(+ self.first_markdown.clone(),+ MarkdownStyle::default(),+ ))+ .child(MarkdownElement::new(+ self.second_markdown.clone(),+ MarkdownStyle::default(),+ ))+ }+ }++ ensure_theme_initialized(cx);++ let (_, cx) = cx.add_window_view(|_, _| TestWindow);+ let markdown = "```sh\necho hello\n```";+ let first_markdown = cx.new(|cx| Markdown::new(markdown.into(), None, None, cx));+ let second_markdown = cx.new(|cx| Markdown::new(markdown.into(), None, None, cx));+ cx.run_until_parked();++ cx.draw(Default::default(), size(px(600.0), px(600.0)), |_, cx| {+ cx.new(|_| TestMarkdowns {+ first_markdown: first_markdown.clone(),+ second_markdown: second_markdown.clone(),+ })+ .into_any_element()+ });+ }+#[gpui::test]fn test_mappings(cx: &mut TestAppContext) {// Formatting.diff --git a/crates/markdown/src/mermaid.rs b/crates/markdown/src/mermaid.rsindex 6ecb3f07ff3..d6ab9524963 100644--- a/crates/markdown/src/mermaid.rs+++ b/crates/markdown/src/mermaid.rs@@ -444,6 +444,17 @@ fn render_mermaid_tab_header(showing_code: bool,markdown: Entity<Markdown>,) -> impl IntoElement {+ let preview_id = ElementId::NamedChild(+ Arc::new(ElementId::from((+ "mermaid-tab-preview",+ markdown.entity_id(),+ ))),+ source_offset.to_string().into(),+ );+ let code_id = ElementId::NamedChild(+ Arc::new(ElementId::from(("mermaid-tab-code", markdown.entity_id()))),+ source_offset.to_string().into(),+ );let preview_markdown = markdown.clone();let code_markdown = markdown;@@ -451,38 +462,32 @@ fn render_mermaid_tab_header(.gap_0p5().mb_2p5().child(- Button::new(- ElementId::named_usize("mermaid-tab-preview", source_offset),- "Preview",- )- .label_size(LabelSize::Small)- .selected_style(ButtonStyle::Tinted(TintColor::Accent))- .toggle_state(!showing_code)- .on_click(move |_event, _window, cx| {- preview_markdown.update(cx, |md, cx| {- if md.is_mermaid_showing_code(source_offset) {- md.toggle_mermaid_tab(source_offset);- cx.notify();- }- });- }),+ Button::new(preview_id, "Preview")+ .label_size(LabelSize::Small)+ .selected_style(ButtonStyle::Tinted(TintColor::Accent))+ .toggle_state(!showing_code)+ .on_click(move |_event, _window, cx| {+ preview_markdown.update(cx, |md, cx| {+ if md.is_mermaid_showing_code(source_offset) {+ md.toggle_mermaid_tab(source_offset);+ cx.notify();+ }+ });+ }),).child(- Button::new(- ElementId::named_usize("mermaid-tab-code", source_offset),- "Code",- )- .label_size(LabelSize::Small)- .selected_style(ButtonStyle::Tinted(TintColor::Accent))- .toggle_state(showing_code)- .on_click(move |_event, _window, cx| {- code_markdown.update(cx, |md, cx| {- if !md.is_mermaid_showing_code(source_offset) {- md.toggle_mermaid_tab(source_offset);- cx.notify();- }- });- }),+ Button::new(code_id, "Code")+ .label_size(LabelSize::Small)+ .selected_style(ButtonStyle::Tinted(TintColor::Accent))+ .toggle_state(showing_code)+ .on_click(move |_event, _window, cx| {+ code_markdown.update(cx, |md, cx| {+ if !md.is_mermaid_showing_code(source_offset) {+ md.toggle_mermaid_tab(source_offset);+ cx.notify();+ }+ });+ }),)}@@ -491,7 +496,10 @@ fn render_mermaid_copy_button(code: String,markdown: Entity<Markdown>,) -> impl IntoElement {- let id = ElementId::named_usize("copy-mermaid-code", source_offset);+ let id = ElementId::NamedChild(+ Arc::new(ElementId::from(("copy-mermaid-code", markdown.entity_id()))),+ source_offset.to_string().into(),+ );div().absolute().top_1().right_1().justify_end().child(CopyButton::new(id.clone(), code.clone())diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.tomlindex 7e98d4b3608..6a65e2a0984 100644--- a/crates/sandbox/Cargo.toml+++ b/crates/sandbox/Cargo.toml@@ -14,8 +14,14 @@ 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 = []+# produce the test binary. Pulls in serde only when enabled (the helper parses+# its check list as JSON), and enables the matching `http_proxy` escape hatch so+# the in-process proxy can reach the VM's private-network echo servers.+nixos-test = [+ "dep:serde",+ "dep:serde_json",+ "http_proxy/nixos-integration-tests",+]# Builds `wsl_sandbox_test_helper`, the Windows analog of `bwrap_test_helper`.# It drives the real WSL/Bubblewrap sandbox end-to-end (see@@ -37,18 +43,24 @@ name = "wsl_sandbox_test_helper"path = "src/wsl_sandbox_test_helper.rs"required-features = ["wsl-test"]-[target.'cfg(target_os = "linux")'.dependencies]+[dependencies]anyhow.workspace = true+futures.workspace = true+http_proxy.workspace = true+log.workspace = true+# Used only by the `nixos-test` helper binary to parse its check list; gated+# behind the `nixos-test` feature so normal builds don't pull it in.+serde = { workspace = true, optional = true }+serde_json = { workspace = true, optional = true }++[target.'cfg(target_os = "linux")'.dependencies]libc.workspace = true[target.'cfg(target_os = "linux")'.dev-dependencies]tempfile.workspace = true[target.'cfg(target_os = "macos")'.dependencies]-anyhow.workspace = truetempfile.workspace = true[target.'cfg(target_os = "windows")'.dependencies]-anyhow.workspace = true-log.workspace = truesmol.workspace = truediff --git a/crates/sandbox/src/bwrap_test_helper.rs b/crates/sandbox/src/bwrap_test_helper.rsindex 7a5e962fb9e..27c8523ce32 100644--- a/crates/sandbox/src/bwrap_test_helper.rs+++ b/crates/sandbox/src/bwrap_test_helper.rs@@ -1,5 +1,14 @@-//! Test binary used exclusively in the NixOS integration test for bwrap at-//! `nix/tests/sandboxing`. See the comment there.+//! Test binary used exclusively by the NixOS integration tests for the+//! Bubblewrap sandbox at `nix/tests/sandboxing`. See the comment there.+//!+//! It drives the sandbox crate's *public* API only (`Sandbox`, `SandboxPolicy`,+//! …) — never platform internals — so it doubles as a check that the public API+//! is sufficient to express and enforce the policies the agent needs.+//!+//! The list of checks to run is *data*, declared by the Nix test and handed to+//! this binary as a JSON file (path in `ZED_SANDBOX_CHECKS`). Each check+//! describes a sandbox policy, an operation to attempt under that policy, and+//! the expected outcome; this binary executes each and asserts the result.#![allow(clippy::disallowed_methods,@@ -19,32 +28,35 @@ fn main() {#[cfg(target_os = "linux")]mod imp {+ use std::io::{Read as _, Write as _};+ use std::net::TcpStream;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};+ use sandbox::{+ CommandAndArgs, Sandbox, SandboxError, SandboxFsPolicy, SandboxNetPolicy, SandboxPolicy,+ };+ use serde::Deserialize;- /// 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";+ /// Internal subcommand: round-trip a byte through the echo server at the+ /// given `host:port`, honoring `HTTP_PROXY` when set (the restricted-network+ /// case routes through the sandbox proxy via HTTP CONNECT). Exits 0 on a+ /// successful round-trip, non-zero otherwise. Run *inside* the sandbox.+ const SUBCOMMAND_ECHO_CHECK: &str = "__echo_check";++ /// Default port for echo targets given as a bare hostname (e.g. `echo1`).+ const DEFAULT_ECHO_PORT: &str = "7000";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.+ // If we were re-exec'd as the restricted-network bridge, this starts the+ // bridge 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(),+ Some(SUBCOMMAND_ECHO_CHECK) => run_echo_check(args.get(2).map(String::as_str)),+ _ => run_checks(),};if let Err(error) = result {@@ -53,107 +65,349 @@ mod imp {}}- /// 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.+ /// Filesystem policy as declared in a check (`fs` field).+ #[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)]+ #[serde(rename_all = "lowercase")]+ enum FsMode {+ /// Reads allowed everywhere; writes confined to `writablePaths`.+ #[default]+ Restricted,+ /// Writes allowed anywhere.+ Unrestricted,+ }++ /// Network policy as declared in a check (`networkAccess` field).+ #[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)]+ #[serde(rename_all = "lowercase")]+ enum NetMode {+ /// All outbound network blocked.+ #[default]+ Blocked,+ /// All outbound network allowed.+ Unrestricted,+ /// Outbound HTTP(S) allowed only to `allowedDomains`.+ Restricted,+ }++ /// One declarative check: a sandbox policy, an operation, and the expected+ /// result. Deserialized from the JSON the Nix test produces.///- /// 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),- }+ /// Exactly one operation field (`read`, `write`, `network`, or `canCreate`)+ /// must be set. Policy fields default to the most-confined policy+ /// (restricted filesystem with no writable paths, blocked network).+ #[derive(Debug, Default, Deserialize)]+ #[serde(rename_all = "camelCase", deny_unknown_fields)]+ struct Check {+ /// Optional human label; falls back to an auto-generated description.+ #[serde(default)]+ name: Option<String>,++ // ---- policy ----+ #[serde(default)]+ fs: FsMode,+ #[serde(default)]+ writable_paths: Vec<String>,+ #[serde(default)]+ network_access: NetMode,+ #[serde(default)]+ allowed_domains: Vec<String>,++ // ---- operation (exactly one) ----+ /// Read this host path from inside the sandbox.+ #[serde(default)]+ read: Option<String>,+ /// Write to this host path from inside the sandbox.+ #[serde(default)]+ write: Option<String>,+ /// Connect to this echo host (`hostname` or `hostname:port`) from inside+ /// the sandbox.+ #[serde(default)]+ network: Option<String>,+ /// Assert that `Sandbox::can_create` for this policy matches the value:+ /// `true` => the sandbox can be created, `false` => it cannot.+ #[serde(default)]+ can_create: Option<bool>,++ // ---- expectation ----+ /// Expected outcome for `read` / `write` / `network`.+ #[serde(default)]+ succeeds: Option<bool>,+ /// Expected error kind for `canCreate = false`+ /// (`bwrap_not_found` | `setuid_rejected` | `probe_failed`). When+ /// omitted, any creation failure is accepted.+ #[serde(default)]+ error: Option<String>,+ }++ fn run_checks() -> Result<()> {+ // The restricted-network proxy runs in *this* process and the echo+ // servers live on the VM's private network, which the proxy's+ // DNS-rebinding protection would otherwise reject. The proxy only honors+ // this var when built with `http_proxy/nixos-integration-tests` (pulled+ // in by `sandbox/nixos-test`, which this binary requires), so it has no+ // effect in a real Zed build.+ // SAFETY: single-threaded at this point.+ unsafe {+ std::env::set_var("ZED_SANDBOX_PROXY_ALLOW_LOCAL_IPS", "1");}- match last_error {- Some(error) => Err(error).with_context(|| format!("failed to connect to {address}")),- None => bail!("{address:?} resolved to no socket addresses"),++ let checks_path =+ std::env::var("ZED_SANDBOX_CHECKS").context("ZED_SANDBOX_CHECKS must be set")?;+ let raw = std::fs::read_to_string(&checks_path)+ .with_context(|| format!("failed to read checks file {checks_path}"))?;+ let specs: Vec<Check> =+ serde_json::from_str(&raw).context("failed to parse checks JSON")?;+ let echo_port =+ std::env::var("ZED_TEST_ECHO_PORT").unwrap_or_else(|_| DEFAULT_ECHO_PORT.to_string());++ println!("[sandbox_test]: running {} check(s)", specs.len());++ let mut checks = Checks::new();+ for spec in &specs {+ run_check(spec, &echo_port, &mut checks)?;}+ checks.finish()}- /// 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(())+ fn policy_of(check: &Check) -> SandboxPolicy {+ let fs = match check.fs {+ FsMode::Unrestricted => SandboxFsPolicy::Unrestricted,+ FsMode::Restricted => SandboxFsPolicy::Restricted {+ writable_paths: check.writable_paths.iter().map(PathBuf::from).collect(),+ },+ };+ let network = match check.network_access {+ NetMode::Unrestricted => SandboxNetPolicy::Unrestricted,+ NetMode::Blocked => SandboxNetPolicy::Blocked,+ NetMode::Restricted => SandboxNetPolicy::Restricted {+ allowed_domains: check.allowed_domains.clone(),+ },+ };+ SandboxPolicy {+ fs,+ network,+ git: sandbox::GitSandboxPolicy::default(),+ }}- /// 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,+ fn describe(check: &Check) -> String {+ if let Some(name) = &check.name {+ return name.clone();+ }+ let policy = format!("fs={:?},net={:?}", check.fs, check.network_access);+ let op = if let Some(path) = &check.read {+ format!("read {path}")+ } else if let Some(path) = &check.write {+ format!("write {path}")+ } else if let Some(host) = &check.network {+ format!("network {host}")+ } else if let Some(expected) = check.can_create {+ format!("can_create == {expected}")+ } else {+ "<no operation>".to_string()+ };+ format!("[{policy}] {op}")}- /// 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(),- })+ fn run_check(check: &Check, echo_port: &str, checks: &mut Checks) -> Result<()> {+ let label = describe(check);+ let policy = policy_of(check);++ if let Some(expect_can_create) = check.can_create {+ let outcome = Sandbox::can_create(&policy, None);+ let passed = match (&outcome, expect_can_create) {+ (Ok(()), true) => true,+ (Ok(()), false) => false,+ (Err(_), true) => false,+ (Err(error), false) => check+ .error+ .as_deref()+ .map(|expected| error_matches(error, expected))+ .unwrap_or(true),+ };+ checks.check(&format!("{label} (got {outcome:?})"), passed);+ return Ok(());+ }++ let succeeds = check+ .succeeds+ .with_context(|| format!("check {label:?} has an operation but no `succeeds`"))?;++ let actual = if let Some(path) = &check.read {+ run_read(&policy, path)?+ } else if let Some(path) = &check.write {+ run_write(&policy, path)?+ } else if let Some(host) = &check.network {+ run_network(&policy, host, echo_port)?+ } else {+ bail!("check {label:?} has no operation");+ };++ checks.check(&label, actual == succeeds);+ Ok(())}- /// 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(+ /// Seed a host file, then `cat` it from inside the sandbox. Reads are always+ /// granted (root is bound read-only), so this proves the sandbox doesn't+ /// *block* reads of existing host files.+ fn run_read(policy: &SandboxPolicy, path: &str) -> Result<bool> {+ let path = Path::new(path);+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)+ .with_context(|| format!("failed to create parent of {}", path.display()))?;+ }+ std::fs::write(path, b"sandbox-test\n")+ .with_context(|| format!("failed to seed readable file {}", path.display()))?;++ let mut sandbox = Sandbox::new(policy.clone()).map_err(sandbox_err)?;+ run_command(+ &mut sandbox,+ "sh",+ &["-c", &format!("cat {}", shell_quote(path))],+ )+ }++ /// Attempt to write a host file from inside the sandbox. "Succeeded" means+ /// the command exited 0 *and* the bytes actually landed on the host file —+ /// a write that only hits the sandbox's ephemeral tmpfs counts as blocked,+ /// since it never escaped the sandbox.+ fn run_write(policy: &SandboxPolicy, path: &str) -> Result<bool> {+ let path = Path::new(path);+ if let Some(parent) = path.parent() {+ // Create the parent on the host so the only thing under test is the+ // sandbox's write permission, not a missing directory.+ std::fs::create_dir_all(parent)+ .with_context(|| format!("failed to create parent of {}", path.display()))?;+ }+ // Start from a clean slate so `exists()` afterwards is meaningful.+ let _ = std::fs::remove_file(path);++ let mut sandbox = Sandbox::new(policy.clone()).map_err(sandbox_err)?;+ let command_ok = run_command(+ &mut sandbox,"sh",- &["-c".to_string(), script.to_string()],- writable_dirs,- None,- permissions,+ &[+ "-c",+ &format!("printf sandbox-test > {}", shell_quote(path)),+ ],+ )?;+ Ok(command_ok && path.exists())+ }++ /// Connect to `host` (`hostname` or `hostname:port`) from inside the+ /// sandbox via the `__echo_check` subcommand, which honors `HTTP_PROXY` for+ /// the restricted-network case.+ fn run_network(policy: &SandboxPolicy, host: &str, echo_port: &str) -> Result<bool> {+ let target = if host.contains(':') {+ host.to_string()+ } else {+ format!("{host}:{echo_port}")+ };+ let exe = current_exe_str()?;+ let mut sandbox = Sandbox::new(policy.clone()).map_err(sandbox_err)?;+ run_command(&mut sandbox, &exe, &[SUBCOMMAND_ECHO_CHECK, &target])+ }++ fn error_matches(error: &SandboxError, expected: &str) -> bool {+ matches!(+ (error, expected),+ (SandboxError::BwrapNotFound, "bwrap_not_found")+ | (SandboxError::BwrapSetuidRejected, "setuid_rejected")+ | (SandboxError::SandboxProbeFailed, "probe_failed"))}+ fn sandbox_err(error: SandboxError) -> anyhow::Error {+ anyhow::anyhow!("failed to create sandbox: {error}")+ }++ /// Inner command: prove (or fail to prove) reachability of an echo server.+ ///+ /// With `HTTP_PROXY` set we open an HTTP `CONNECT` tunnel through the proxy+ /// and then echo a byte; a policy denial shows up as a non-200 status. With+ /// no proxy we connect directly. Either way, a clean round-trip means the+ /// destination was reachable under the active network policy.+ fn run_echo_check(target: Option<&str>) -> Result<()> {+ let target = target.context("echo check requires a host:port argument")?;+ let proxy = std::env::var("HTTP_PROXY")+ .ok()+ .filter(|value| !value.trim().is_empty())+ .or_else(|| {+ std::env::var("http_proxy")+ .ok()+ .filter(|value| !value.trim().is_empty())+ });++ let mut stream = match proxy {+ Some(proxy_url) => {+ let proxy_addr = proxy_url+ .trim()+ .strip_prefix("http://")+ .unwrap_or(proxy_url.trim())+ .trim_end_matches('/')+ .to_string();+ let mut stream = TcpStream::connect(&proxy_addr)+ .with_context(|| format!("failed to connect to proxy {proxy_addr}"))?;+ stream.set_read_timeout(Some(Duration::from_secs(10)))?;+ write!(+ stream,+ "CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n"+ )+ .context("failed to send CONNECT to proxy")?;+ let status = read_status_line(&mut stream)?;+ if !status.contains(" 200") {+ bail!("proxy refused CONNECT to {target}: {status:?}");+ }+ stream+ }+ None => {+ let stream = TcpStream::connect(target)+ .with_context(|| format!("failed to connect to {target}"))?;+ stream.set_read_timeout(Some(Duration::from_secs(10)))?;+ stream+ }+ };++ stream+ .write_all(b"ping\n")+ .context("failed to write to echo server")?;+ let mut buffer = [0u8; 32];+ let read = stream+ .read(&mut buffer)+ .context("failed to read from echo server")?;+ let echoed = String::from_utf8_lossy(&buffer[..read]);+ if echoed.contains("ping") {+ Ok(())+ } else {+ bail!("echo server returned unexpected data: {echoed:?}");+ }+ }++ /// Read an HTTP status line (up to the first CRLF), then drain the rest of+ /// the header block (up to the blank line) so the stream is positioned at+ /// the tunneled body.+ fn read_status_line(stream: &mut TcpStream) -> Result<String> {+ let mut header = Vec::new();+ let mut byte = [0u8; 1];+ loop {+ let read = stream+ .read(&mut byte)+ .context("failed reading proxy reply")?;+ if read == 0 {+ break;+ }+ header.push(byte[0]);+ if header.ends_with(b"\r\n\r\n") {+ break;+ }+ if header.len() > 64 * 1024 {+ bail!("proxy reply headers too large");+ }+ }+ let text = String::from_utf8_lossy(&header);+ Ok(text.lines().next().unwrap_or_default().to_string())+ }+/// Tracks assertion results so we can report a summary and a single exit code.struct Checks {passed: usize,@@ -190,314 +444,17 @@ mod imp {}}- 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(- ¤t_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(- ¤t_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(- ¤t_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(- ¤t_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(());+ /// Wrap and run a command inside `sandbox`, returning whether it exited 0.+ fn run_command(sandbox: &mut Sandbox, program: &str, args: &[&str]) -> Result<bool> {+ let command = CommandAndArgs {+ program: program.to_string(),+ args: args.iter().map(|arg| arg.to_string()).collect(),+ env: Default::default(),+ cwd: None,};-- 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(())+ let output = futures::executor::block_on(sandbox.execute(&command))+ .map_err(|error| anyhow::anyhow!("failed to run sandboxed command: {error}"))?;+ Ok(output.status.success())}fn current_exe_str() -> Result<String> {@@ -508,26 +465,9 @@ mod imp {.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.rsindex d20790b6f3f..781a90f84df 100644--- a/crates/sandbox/src/linux_bubblewrap.rs+++ b/crates/sandbox/src/linux_bubblewrap.rs@@ -1,103 +1,87 @@-//! Linux sandbox integration built on Bubblewrap (`bwrap`) for both the-//! filesystem and the network.+//! Linux sandbox integration built on Bubblewrap (`bwrap`) for filesystem and+//! network confinement.//!-//! `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.+//! We can use `--bind` and `--ro-bind` (read-only) to bind host filesystem+//! paths to paths in the sandbox. If networking is restricted, we also set+//! `--unshare-net` to disable *all* network access.//!-//! ## The launcher+//! When restricting network access, we:+//! - set `--unshare-net` - any requests to `example.com` will fail+//! - requests to `localhost` will succeed, but it will be an isolated localhost+//! from the host system.+//! - create a unix socket, and mount it in the sandbox with `--bind`+//! - run a bridge process inside the sandbox that:+//! - listens on `localhost:<port>` and forwards reads/writes to the socket+//! - then, runs the untrusted command+//! - on the zed side, we listen to the socket and forward reads/writes to the+//! internal HTTP proxy//!-//! 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.+//! If networking is fully blocked or fully allowed, we don't bother with the+//! proxy/socket at all (and simply set/unset `--unshare-net`).//!-//! 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.+//! This design for networking avoids needing seccomp, a fork/exec dance, and+//! eliminates a race condition involving BPF user notifications.+use anyhow::{Context as _, Result, anyhow, bail};use std::ffi::OsString;-use std::os::linux::net::SocketAddrExt as _;+use std::io::{Read, Write};+use std::net::{Ipv4Addr, Shutdown, TcpListener, TcpStream};use std::os::unix::fs::MetadataExt as _;-use std::os::unix::net::{SocketAddr, UnixDatagram};-use std::os::unix::process::CommandExt as _;+use std::os::unix::net::UnixStream;+use std::os::unix::process::ExitStatusExt as _;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use std::sync::atomic::{AtomicU64, Ordering};-use std::time::Duration;+use std::thread;-use anyhow::{Context as _, Result, anyhow, bail};+const BRIDGE_FLAG: &str = "--zed-linux-sandbox-bridge";+const PROXY_SOCKET_SANDBOX_PATH_PREFIX: &str = "/tmp/zed-sandbox";+const SANDBOX_SETUP_FAILED_EXIT_CODE: i32 = 126;+const PUMP_BUFFER_SIZE: usize = 64 * 1024;-use crate::SandboxPermissions;+/// Network-access setting for a sandboxed command.+///+/// Mirrors [`crate::macos_seatbelt::NetworkAccess`] so Linux and macOS expose+/// the same public shape.+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub enum NetworkAccess {+ /// All outbound network blocked (own network namespace).+ #[default]+ None,+ /// Outbound HTTP(S) is available through a loopback proxy port inside the+ /// sandbox. The port is bridged to a host-side Unix socket proxy that+ /// enforces the hostname allowlist.+ LocalhostPort(u16),+ /// All outbound network allowed.+ All,+}-/// The outcome a sandbox launcher reports back to the process that spawned it.+/// Per-command relaxations of the default Bubblewrap (Linux) sandbox.///-/// 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).+/// Mirrors [`crate::macos_seatbelt::SandboxPermissions`].+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub struct SandboxPermissions {+ /// Network access policy for the command.+ pub network: NetworkAccess,+ /// Allow unrestricted filesystem writes.+ pub allow_fs_write: bool,+}++/// The outcome of preparing a Linux sandbox.#[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).+ /// `bwrap` is present but failed to set up the sandbox with our arguments.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.+ /// A human-readable explanation suitable for diagnostics.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"@@ -110,69 +94,6 @@ impl LauncherStatus {}}-/// 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.@@ -183,14 +104,6 @@ enum BwrapLocation {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() {@@ -210,8 +123,6 @@ fn locate_bwrap() -> BwrapLocation {}}-/// `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() {@@ -223,7 +134,6 @@ fn candidate_bwrap_paths() -> Vec<PathBuf> {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)@@ -231,23 +141,10 @@ fn system_bwrap_path() -> Option<PathBuf> {.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,@@ -255,16 +152,9 @@ fn is_setuid_root(path: &Path) -> bool {}}-/// 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"+ reason = "the probe is a short-lived background operation that must block on bwrap")]fn probe_bwrap(bwrap: &Path, bwrap_args: &[String]) -> bool {Command::new(bwrap)@@ -282,36 +172,36 @@ fn probe_bwrap(bwrap: &Path, bwrap_args: &[String]) -> bool {/// 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.-///-/// `protected_paths` are paths whose contents must stay inaccessible even when-/// they sit under a writable directory or the root is bound read-write (e.g.-/// `.git` metadata when Git access hasn't been approved). Each is shadowed: a-/// directory with an ephemeral `tmpfs` (real contents hidden, writes land in-/// throwaway storage) and a file with an empty read-only bind of `/dev/null`.-///-/// `allowed_unix_socket_paths` are Unix domain sockets to re-expose on top of-/// any overlay that would otherwise hide them (notably `--tmpfs /tmp`), so-/// local IPC such as the inherited SSH agent socket keeps working. AF_UNIX-/// connectivity is unaffected by `--unshare-net`, so this grants no IP network-/// access.+/// `proxy_socket_path` is the host pathname Unix socket used for+/// [`NetworkAccess::LocalhostPort`]. It is bind-mounted to a unique path inside+/// the sandbox where the bridge connects to it.pub fn build_bwrap_args(writable_directories: &[&Path],- protected_paths: &[&Path],- allowed_unix_socket_paths: &[&Path],+ protected_git_dirs: &[&Path],permissions: SandboxPermissions,cwd: Option<&Path>,+ proxy_socket_path: Option<&Path>,+) -> Vec<String> {+ let proxy_socket_sandbox_path = proxy_socket_path+ .filter(|_| matches!(permissions.network, NetworkAccess::LocalhostPort(_)))+ .map(|_| unique_proxy_socket_sandbox_path());+ build_bwrap_args_with_proxy_socket_sandbox_path(+ writable_directories,+ protected_git_dirs,+ permissions,+ cwd,+ proxy_socket_path,+ proxy_socket_sandbox_path.as_deref(),+ )+}++fn build_bwrap_args_with_proxy_socket_sandbox_path(+ writable_directories: &[&Path],+ protected_git_dirs: &[&Path],+ permissions: SandboxPermissions,+ cwd: Option<&Path>,+ proxy_socket_path: Option<&Path>,+ proxy_socket_sandbox_path: Option<&Path>,) -> Vec<String> {let mut args = Vec::new();@@ -328,72 +218,47 @@ pub fn build_bwrap_args(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 {+ // Bind each writable directory at its *exact* path. We must never+ // fall back to an existing ancestor: that would grant write access+ // to a broader tree than was requested and approved (e.g. binding+ // `$HOME` for a not-yet-created `~/.cache/...`, or re-binding the+ // host `/tmp` over the tmpfs established above). `wrap_invocation`+ // creates the requested directories before launch so they exist+ // here; any that still don't are skipped rather than widened.+ if !directory.exists() {continue;- };- let canonical = existing.canonicalize().unwrap_or(existing);+ }+ let canonical = directory+ .canonicalize()+ .unwrap_or_else(|_| directory.to_path_buf());let path = canonical.to_string_lossy().into_owned();push_bind(&mut args, "--bind", &path, &path);}- }- // Shadow protected paths last among the filesystem binds so the overlay- // wins over the root bind and any writable bind above it. Unlike the macOS- // Seatbelt policy (which denies `file-read-data` while leaving metadata- // readable), bwrap hides the real contents entirely behind an empty- // overlay; the security goal — keeping the real path unreadable and- // unwritable — is the same.- for protected_path in protected_paths {- // Resolve through an existing parent when the leaf is missing so a- // not-yet-created `.git` (before `git init`) overlays the same real path- // the writable bind above uses, even on a symlinked root.- let canonical = crate::canonicalize_allowing_missing_leaf(protected_path);- let destination = canonical.to_string_lossy().into_owned();- match std::fs::symlink_metadata(&canonical) {- Ok(metadata) if metadata.is_dir() => {- args.push("--tmpfs".to_string());- args.push(destination);- }- Ok(_) => {- // A file (e.g. a linked worktree's `.git` gitlink): mask it- // with an empty, read-only `/dev/null`.- push_bind(&mut args, "--ro-bind", "/dev/null", &destination);- }- Err(_) => {- // Doesn't exist yet: still overlay a tmpfs so a command can't- // `git init` and write real metadata into a writable worktree.- args.push("--tmpfs".to_string());- args.push(destination);+ // Protect Git directories by re-binding them read-only *over* the rw+ // worktree binds above (order matters: later binds win). Unlike+ // Seatbelt, bwrap can't deny content reads while keeping metadata, so on+ // Linux a protected `.git` is read-only — its contents stay readable but+ // can't be written. A not-yet-existing `.git` can't be bound, so it's+ // skipped (a documented gap vs. macOS, which denies it even before it+ // exists). When Git access is granted these dirs are in+ // `writable_directories` instead and this list is empty.+ for git_dir in protected_git_dirs {+ if !git_dir.exists() {+ continue;}+ let canonical = git_dir+ .canonicalize()+ .unwrap_or_else(|_| git_dir.to_path_buf());+ let path = canonical.to_string_lossy().into_owned();+ push_bind(&mut args, "--ro-bind", &path, &path);}}- // Re-expose explicitly allowed Unix domain sockets on top of any overlay- // that would otherwise hide them. Done after the protected overlays and the- // `/tmp` tmpfs so the socket always wins.- for socket_path in allowed_unix_socket_paths {- let canonical = socket_path- .canonicalize()- .unwrap_or_else(|_| socket_path.to_path_buf());- if !canonical.exists() {- continue;- }- let path = canonical.to_string_lossy().into_owned();- push_bind(&mut args, "--bind", &path, &path);- }-for flag in ["--unshare-user","--unshare-ipc",@@ -405,10 +270,19 @@ pub fn build_bwrap_args(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());+ match permissions.network {+ NetworkAccess::None => args.push("--unshare-net".to_string()),+ NetworkAccess::LocalhostPort(_) => {+ args.push("--unshare-net".to_string());+ if let Some((proxy_socket_path, proxy_socket_sandbox_path)) =+ proxy_socket_path.zip(proxy_socket_sandbox_path)+ {+ let source = proxy_socket_path.to_string_lossy().into_owned();+ let destination = proxy_socket_sandbox_path.to_string_lossy().into_owned();+ push_bind(&mut args, "--bind", &source, &destination);+ }+ }+ NetworkAccess::All => {}}if let Some(cwd) = cwd {@@ -419,355 +293,344 @@ pub fn build_bwrap_args(args}+/// A unique destination path for the proxy socket bind mount *inside* the+/// sandbox. Each sandboxed command runs in its own mount namespace, so the path+/// only needs to be unique enough to avoid colliding with anything a previous+/// command in the same namespace lineage may have created; combining the pid+/// with a monotonic counter is sufficient and keeps the path predictable for+/// diagnostics.+fn unique_proxy_socket_sandbox_path() -> PathBuf {+ static COUNTER: AtomicU64 = AtomicU64::new(0);+ let counter = COUNTER.fetch_add(1, Ordering::Relaxed);+ PathBuf::from(format!(+ "{PROXY_SOCKET_SANDBOX_PATH_PREFIX}-{}-{counter}.sock",+ std::process::id()+ ))+}+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();+fn resolve_bwrap() -> std::result::Result<PathBuf, LauncherStatus> {+ match locate_bwrap() {+ BwrapLocation::Found(path) => Ok(path),+ BwrapLocation::OnlySetuid => Err(LauncherStatus::SetuidRejected),+ BwrapLocation::NotFound => Err(LauncherStatus::BwrapNotFound),}- 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";+fn prepare_sandbox(+ writable_dirs: &[&Path],+ permissions: SandboxPermissions,+ cwd: Option<&Path>,+ proxy_socket_path: Option<&Path>,+) -> std::result::Result<(PathBuf, Vec<String>), LauncherStatus> {+ let bwrap = resolve_bwrap()?;+ // The probe only checks whether a sandbox can be created at all, so Git+ // protection (which doesn't affect createability) is irrelevant here.+ let bwrap_args = build_bwrap_args(writable_dirs, &[], permissions, cwd, proxy_socket_path);+ if !probe_bwrap(&bwrap, &bwrap_args) {+ return Err(LauncherStatus::SandboxProbeFailed);+ }+ Ok((bwrap, bwrap_args))+}-/// 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>,+/// Check whether an OS sandbox can be created for this policy.+pub fn check_can_create_sandbox(+ writable_dirs: &[&Path],permissions: SandboxPermissions,- cwd: Option<PathBuf>,- writable_dirs: Vec<PathBuf>,- protected_paths: Vec<PathBuf>,- allowed_unix_socket_paths: Vec<PathBuf>,- program: OsString,- args: Vec<OsString>,+ cwd: Option<&Path>,+) -> std::result::Result<(), LauncherStatus> {+ prepare_sandbox(writable_dirs, permissions, cwd, None).map(|_| ())}-/// Build a self-exec launcher invocation.+/// Build the final command line that runs `program` inside Bubblewrap.///-/// 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).+/// `bridge_program` should be the current Zed executable. It is only used for+/// [`NetworkAccess::LocalhostPort`], where it runs in bridge mode inside the+/// sandbox before spawning the real command.///-/// The encoding is positional, one value per argv entry, so paths and-/// arguments containing spaces round-trip without escaping. Each path list is a-/// count followed by that many entries:-/// `[FLAG, socket, allow_network, allow_fs_write, cwd,-/// N_writable, writable.., N_protected, protected.., N_sockets, sockets..,-/// program, args..]`.+/// The host `proxy_socket_path` is bind-mounted to a per-invocation unique path+/// inside the sandbox, and that same in-sandbox path is handed to the bridge.pub fn wrap_invocation(- launcher_program: &str,- status_socket_name: Option<&str>,+ bridge_program: &str,permissions: SandboxPermissions,writable_dirs: &[&Path],- protected_paths: &[&Path],- allowed_unix_socket_paths: &[&Path],+ protected_git_dirs: &[&Path],cwd: Option<&Path>,program: &str,args: &[String],-) -> (String, Vec<String>) {- let mut launcher_args = Vec::with_capacity(- writable_dirs.len()- + protected_paths.len()- + allowed_unix_socket_paths.len()- + args.len()- + 9,- );- 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(),- );- push_path_list(&mut launcher_args, writable_dirs);- push_path_list(&mut launcher_args, protected_paths);- push_path_list(&mut launcher_args, allowed_unix_socket_paths);- launcher_args.push(program.to_string());- launcher_args.extend(args.iter().cloned());- (launcher_program.to_string(), launcher_args)-}+ proxy_socket_path: Option<&Path>,+) -> Result<(String, Vec<String>)> {+ if matches!(permissions.network, NetworkAccess::LocalhostPort(_)) && proxy_socket_path.is_none()+ {+ bail!("restricted Linux network access requires a proxy Unix socket path");+ }++ // Create the requested writable directories up front, with the agent's+ // ambient permissions, so each can be bind-mounted at its exact path (see+ // `build_bwrap_args`). Without this a not-yet-existing writable path could+ // not be bound, and the command could not create it either (its parent is+ // read-only inside the sandbox). Best-effort: a directory we can't create is+ // left unbound rather than widening the sandbox to an existing ancestor.+ if !permissions.allow_fs_write {+ for directory in writable_dirs {+ if let Err(error) = std::fs::create_dir_all(directory) {+ log::warn!(+ "[sandbox] could not create writable directory {}: {error}",+ directory.display()+ );+ }+ }+ }-/// Encode a path list as a count followed by one argv entry per path.-fn push_path_list(launcher_args: &mut Vec<String>, paths: &[&Path]) {- launcher_args.push(paths.len().to_string());- for path in paths {- launcher_args.push(path.to_string_lossy().into_owned());+ let bwrap = resolve_bwrap().map_err(|status| anyhow!(status.describe()))?;+ let proxy_socket_sandbox_path = match permissions.network {+ NetworkAccess::LocalhostPort(_) => Some(unique_proxy_socket_sandbox_path()),+ NetworkAccess::None | NetworkAccess::All => None,+ };+ let mut bwrap_args = build_bwrap_args_with_proxy_socket_sandbox_path(+ writable_dirs,+ protected_git_dirs,+ permissions,+ cwd,+ proxy_socket_path,+ proxy_socket_sandbox_path.as_deref(),+ );+ bwrap_args.push("--".to_string());++ match permissions.network {+ NetworkAccess::LocalhostPort(port) => {+ let proxy_socket_sandbox_path = proxy_socket_sandbox_path+ .as_ref()+ .context("missing in-sandbox proxy socket path")?;+ bwrap_args.push(bridge_program.to_string());+ bwrap_args.push(BRIDGE_FLAG.to_string());+ bwrap_args.push(proxy_socket_sandbox_path.to_string_lossy().into_owned());+ bwrap_args.push(port.to_string());+ bwrap_args.push("--".to_string());+ }+ NetworkAccess::None | NetworkAccess::All => {}}++ bwrap_args.push(program.to_string());+ bwrap_args.extend(args.iter().cloned());++ let bwrap = bwrap+ .to_str()+ .with_context(|| format!("bwrap path contains invalid UTF-8: {}", bwrap.display()))?;+ Ok((bwrap.to_string(), bwrap_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.+/// Handle a possible re-exec of this binary as the in-sandbox proxy bridge.pub fn run_launcher_if_invoked() {- let Some(invocation) = parse_launcher_args(std::env::args_os()) else {+ let Some(invocation) = parse_bridge_args(std::env::args_os()) else {return;};let invocation = match invocation {Ok(invocation) => invocation,Err(error) => {- eprintln!("zed: malformed sandbox launcher invocation: {error:#}");+ eprintln!("zed: malformed sandbox bridge invocation: {error:#}");std::process::exit(127);}};- run_launcher(invocation);+ run_bridge(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;+struct BridgeInvocation {+ socket_path: PathBuf,+ port: u16,+ program: OsString,+ args: Vec<OsString>,+}-/// 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 protected: Vec<&Path> = invocation- .protected_paths- .iter()- .map(PathBuf::as_path)- .collect();- let allowed_unix_sockets: Vec<&Path> = invocation- .allowed_unix_socket_paths- .iter()- .map(PathBuf::as_path)- .collect();-- let (bwrap, bwrap_args) = match prepare_sandbox(- &writable,- &protected,- &allowed_unix_sockets,- 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()- );+fn parse_bridge_args(args: impl IntoIterator<Item = OsString>) -> Option<Result<BridgeInvocation>> {+ let mut args = args.into_iter();+ args.next()?;+ if args.next()?.to_str() != Some(BRIDGE_FLAG) {+ return None;+ }+ Some(decode_bridge_args(args))+}++fn decode_bridge_args(mut args: impl Iterator<Item = OsString>) -> Result<BridgeInvocation> {+ let socket_path = PathBuf::from(args.next().context("missing proxy socket path")?);+ let port = args+ .next()+ .context("missing proxy bridge port")?+ .to_str()+ .context("proxy bridge port is not valid UTF-8")?+ .parse::<u16>()+ .context("invalid proxy bridge port")?;+ let separator = args.next().context("missing bridge argument separator")?;+ if separator != "--" {+ bail!("missing bridge argument separator");+ }+ let program = args.next().context("missing program to run")?;+ let args = args.collect();+ Ok(BridgeInvocation {+ socket_path,+ port,+ program,+ args,+ })+}++#[allow(+ clippy::disallowed_methods,+ reason = "the bridge is an in-sandbox process that must synchronously spawn and wait for the command"+)]+fn run_bridge(invocation: BridgeInvocation) -> ! {+ let listener = match TcpListener::bind((Ipv4Addr::LOCALHOST, invocation.port)) {+ Ok(listener) => listener,+ Err(error) => {+ eprintln!("zed: failed to bind sandbox proxy bridge: {error}");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);-}+ let socket_path = invocation.socket_path.clone();+ if let Err(error) = thread::Builder::new()+ .name("zed-sandbox-bridge".to_string())+ .stack_size(128 * 1024)+ .spawn(move || run_bridge_listener(listener, socket_path))+ {+ eprintln!("zed: failed to spawn sandbox proxy bridge: {error}");+ 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],- protected_paths: &[&Path],- allowed_unix_socket_paths: &[&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 mut child = match Command::new(&invocation.program)+ .args(&invocation.args)+ .spawn()+ {+ Ok(child) => child,+ Err(error) => {+ eprintln!("zed: failed to spawn sandboxed command: {error}");+ std::process::exit(SANDBOX_SETUP_FAILED_EXIT_CODE);+ }};- let bwrap_args = build_bwrap_args(- writable_dirs,- protected_paths,- allowed_unix_socket_paths,- permissions,- cwd,- );- if !probe_bwrap(&bwrap, &bwrap_args) {- return Err(LauncherStatus::SandboxProbeFailed);++ match child.wait() {+ Ok(status) => {+ if let Some(code) = status.code() {+ std::process::exit(code);+ }+ let signal = status.signal().unwrap_or(1);+ std::process::exit(128 + signal);+ }+ Err(error) => {+ eprintln!("zed: failed to wait for sandboxed command: {error}");+ std::process::exit(SANDBOX_SETUP_FAILED_EXIT_CODE);+ }}- 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],- protected_paths: &[&Path],- allowed_unix_socket_paths: &[&Path],- permissions: SandboxPermissions,- cwd: Option<&Path>,-) -> std::result::Result<(), LauncherStatus> {- prepare_sandbox(- writable_dirs,- protected_paths,- allowed_unix_socket_paths,- permissions,- cwd,- )- .map(|_| ())+fn run_bridge_listener(listener: TcpListener, socket_path: PathBuf) {+ for stream in listener.incoming() {+ match stream {+ Ok(stream) => {+ let socket_path = socket_path.clone();+ if let Err(error) = thread::Builder::new()+ .name("zed-sandbox-bridge-conn".to_string())+ .stack_size(128 * 1024)+ .spawn(move || forward_bridge_connection(stream, socket_path))+ {+ eprintln!("zed: failed to spawn sandbox bridge connection thread: {error}");+ }+ }+ Err(error) => eprintln!("zed: sandbox bridge accept failed: {error}"),+ }+ }}-/// 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;+fn forward_bridge_connection(tcp_stream: TcpStream, socket_path: PathBuf) {+ let unix_stream = match UnixStream::connect(&socket_path) {+ Ok(stream) => stream,+ Err(error) => {+ eprintln!(+ "zed: sandbox bridge failed to connect to proxy socket {}: {error}",+ socket_path.display()+ );+ return;+ }};- let Ok(address) = SocketAddr::from_abstract_name(name.as_bytes()) else {- return;+ copy_bidirectional(tcp_stream, unix_stream);+}++fn copy_bidirectional(tcp_stream: TcpStream, unix_stream: UnixStream) {+ let tcp_read = match tcp_stream.try_clone() {+ Ok(stream) => stream,+ Err(error) => {+ eprintln!("zed: sandbox bridge failed to clone TCP stream: {error}");+ return;+ }};- let Ok(socket) = UnixDatagram::unbound() else {- return;+ let unix_read = match unix_stream.try_clone() {+ Ok(stream) => stream,+ Err(error) => {+ eprintln!("zed: sandbox bridge failed to clone Unix stream: {error}");+ 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;+ let tcp_write = tcp_stream;+ let unix_write = unix_stream;+ let to_proxy = match thread::Builder::new()+ .name("zed-sandbox-bridge-out".to_string())+ .stack_size(128 * 1024)+ .spawn(move || copy_one_way(tcp_read, unix_write))+ {+ Ok(handle) => handle,+ Err(error) => {+ eprintln!("zed: failed to spawn sandbox bridge pump thread: {error}");+ return;+ }+ };+ copy_one_way(unix_read, tcp_write);+ if to_proxy.join().is_err() {+ eprintln!("zed: sandbox bridge pump thread panicked");}- 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 writable_dirs = decode_path_list(&mut args, "writable directory")?;- let protected_paths = decode_path_list(&mut args, "protected path")?;- let allowed_unix_socket_paths = decode_path_list(&mut args, "allowed unix socket")?;- 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,- protected_paths,- allowed_unix_socket_paths,- program,- args,- })+trait BridgeStream: Read + Write {+ fn shutdown(&self, how: Shutdown) -> std::io::Result<()>;}-/// Decode a path list (a count followed by that many entries) produced by-/// [`push_path_list`]. `what` names the list for error messages.-fn decode_path_list(args: &mut impl Iterator<Item = OsString>, what: &str) -> Result<Vec<PathBuf>> {- let count = args- .next()- .with_context(|| format!("missing {what} count"))?- .to_str()- .with_context(|| format!("{what} count is not valid UTF-8"))?- .parse::<usize>()- .with_context(|| format!("invalid {what} count"))?;- let mut paths = Vec::with_capacity(count);- for _ in 0..count {- paths.push(PathBuf::from(- args.next()- .with_context(|| format!("missing {what} entry"))?,- ));+impl BridgeStream for TcpStream {+ fn shutdown(&self, how: Shutdown) -> std::io::Result<()> {+ TcpStream::shutdown(self, how)}- Ok(paths)}-fn encode_bool(value: bool) -> String {- if value { "1" } else { "0" }.to_string()+impl BridgeStream for UnixStream {+ fn shutdown(&self, how: Shutdown) -> std::io::Result<()> {+ UnixStream::shutdown(self, how)+ }}-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:?}"),+fn copy_one_way(mut from: impl Read, mut to: impl BridgeStream) {+ let mut buffer = vec![0; PUMP_BUFFER_SIZE];+ loop {+ let count = match from.read(&mut buffer) {+ Ok(0) => break,+ Ok(count) => count,+ Err(_) => break,+ };+ if to.write_all(&buffer[..count]).is_err() {+ break;+ }}+ let _ = to.shutdown(Shutdown::Write);}#[cfg(test)]mod tests {use super::*;- fn launcher_argv(launcher: String, args: Vec<String>) -> Vec<OsString> {+ fn bridge_argv(launcher: &str, args: Vec<&str>) -> Vec<OsString> {std::iter::once(launcher).chain(args).map(OsString::from)@@ -775,31 +638,31 @@ mod tests {}#[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() {+ fn test_build_bwrap_args_binds_exact_path_never_widens_to_ancestor() {+ // A requested writable path that doesn't exist must NOT be bound, and in+ // particular must never cause an existing ancestor (here the tempdir) to+ // be bound read-write — that was a sandbox-escape (scope widening).let dir = tempfile::tempdir().unwrap();- let existing = dir.path();- let missing = existing.join("a").join("b").join("c.txt");+ let existing = dir.path().canonicalize().unwrap();+ let missing = existing.join("does-not-exist").join("nested");- assert_eq!(- nearest_existing_ancestor(&missing).unwrap(),- existing.to_path_buf()+ let args = build_bwrap_args(+ &[missing.as_path()],+ &[],+ SandboxPermissions::default(),+ None,+ None,);- assert_eq!(- nearest_existing_ancestor(existing).unwrap(),- existing.to_path_buf()++ let existing_str = existing.to_string_lossy().into_owned();+ assert!(+ !windows_contains(&args, &["--bind", &existing_str, &existing_str]),+ "a missing writable path must not widen the bind to an existing ancestor: {args:?}"+ );+ let missing_str = missing.to_string_lossy().into_owned();+ assert!(+ !windows_contains(&args, &["--bind", &missing_str, &missing_str]),+ "a missing writable path must not be bound: {args:?}");}@@ -809,13 +672,11 @@ mod tests {let args = build_bwrap_args(&[writable.path()],&[],- &[],SandboxPermissions::default(),Some(writable.path()),+ None,);- // 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();@@ -830,236 +691,159 @@ mod tests {#[test]fn test_build_bwrap_args_network_namespace_follows_permission() {- let denied = build_bwrap_args(&[], &[], &[], SandboxPermissions::default(), None);+ let denied = build_bwrap_args(&[], &[], SandboxPermissions::default(), None, None);assert!(denied.iter().any(|arg| arg == "--unshare-net"));let allowed = build_bwrap_args(- &[],&[],&[],SandboxPermissions {- allow_network: true,+ network: NetworkAccess::All,allow_fs_write: false,},None,+ None,);assert!(!allowed.iter().any(|arg| arg == "--unshare-net"));++ let socket = PathBuf::from("/tmp/zed-proxy.sock");+ let restricted = build_bwrap_args(+ &[],+ &[],+ SandboxPermissions {+ network: NetworkAccess::LocalhostPort(8080),+ allow_fs_write: false,+ },+ None,+ Some(socket.as_path()),+ );+ assert!(restricted.iter().any(|arg| arg == "--unshare-net"));+ let sandbox_destination = proxy_socket_bind_destination(&restricted)+ .expect("restricted run should bind the proxy socket into the sandbox");+ assert!(sandbox_destination.starts_with(PROXY_SOCKET_SANDBOX_PATH_PREFIX));}#[test]fn test_build_bwrap_args_allow_fs_write_binds_root_read_write() {let permissions = SandboxPermissions {- allow_network: false,+ network: NetworkAccess::None,allow_fs_write: true,};- let args = build_bwrap_args(&[], &[], &[], permissions, None);+ let args = build_bwrap_args(&[], &[], permissions, None, 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_build_bwrap_args_shadows_protected_directory_with_tmpfs() {- let project = tempfile::tempdir().unwrap();- let git_dir = project.path().join(".git");- std::fs::create_dir(&git_dir).unwrap();-- let args = build_bwrap_args(- &[project.path()],- &[git_dir.as_path()],- &[],- SandboxPermissions::default(),- None,- );-- let git_canonical = git_dir.canonicalize().unwrap();- let git_str = git_canonical.to_string_lossy().into_owned();- // The writable project is bound rw, then the `.git` directory is shadowed- // with a tmpfs on top so its real contents can't be read or written.- assert!(windows_contains(&args, &["--tmpfs", &git_str]));-- let project_canonical = project.path().canonicalize().unwrap();- let project_str = project_canonical.to_string_lossy().into_owned();- let tmpfs_index = args- .windows(2)- .position(|w| w == ["--tmpfs".to_string(), git_str.clone()])- .unwrap();- let bind_index = args- .windows(3)- .position(|w| {- w == [- "--bind".to_string(),- project_str.clone(),- project_str.clone(),- ]- })- .unwrap();- assert!(- bind_index < tmpfs_index,- "the protected tmpfs must be applied after the writable bind so it wins"- );- }-- #[test]- fn test_build_bwrap_args_masks_protected_file_with_dev_null() {- let project = tempfile::tempdir().unwrap();- let gitlink = project.path().join(".git");- std::fs::write(&gitlink, "gitdir: /elsewhere\n").unwrap();-- let args = build_bwrap_args(- &[project.path()],- &[gitlink.as_path()],- &[],- SandboxPermissions::default(),- None,+ fn test_bridge_args_round_trip() {+ let sandbox_socket_path = "/tmp/zed-sandbox-1234-0.sock";+ let argv = bridge_argv(+ "/path/to/zed",+ vec![+ BRIDGE_FLAG,+ sandbox_socket_path,+ "8080",+ "--",+ "/bin/sh",+ "-c",+ "echo hi there",+ ],);- let gitlink_canonical = gitlink.canonicalize().unwrap();- let gitlink_str = gitlink_canonical.to_string_lossy().into_owned();- assert!(windows_contains(- &args,- &["--ro-bind", "/dev/null", &gitlink_str]- ));- }-- #[test]- fn test_build_bwrap_args_rebinds_allowed_unix_socket() {- let dir = tempfile::tempdir().unwrap();- // `build_bwrap_args` only checks that the path exists, so a regular file- // stands in for a socket here (binding a real socket under a long temp- // path would overflow `sun_path`).- let socket = dir.path().join("agent.sock");- std::fs::write(&socket, b"").unwrap();+ let decoded = parse_bridge_args(argv)+ .expect("should be recognized as bridge invocation")+ .expect("should decode successfully");- let args = build_bwrap_args(- &[],- &[],- &[socket.as_path()],- SandboxPermissions::default(),- None,+ assert_eq!(decoded.socket_path, PathBuf::from(sandbox_socket_path));+ assert_eq!(decoded.port, 8080);+ assert_eq!(decoded.program, OsString::from("/bin/sh"));+ assert_eq!(+ decoded.args,+ vec![OsString::from("-c"), OsString::from("echo hi there")]);-- let socket_canonical = socket.canonicalize().unwrap();- let socket_str = socket_canonical.to_string_lossy().into_owned();- assert!(windows_contains(- &args,- &["--bind", &socket_str, &socket_str]- ));}#[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()];+ fn test_wrap_invocation_uses_bridge_for_restricted_network() {+ let socket = PathBuf::from("/tmp/zed-proxy.sock");let permissions = SandboxPermissions {- allow_network: false,+ network: NetworkAccess::LocalhostPort(8080),allow_fs_write: false,};-- let protected = PathBuf::from("/home/user/project dir/.git");- let socket = PathBuf::from("/tmp/ssh agent/sock");- let (launcher, launcher_args) = wrap_invocation(+ let args = build_wrapped_args_for_test("/path/to/zed",- Some("zed-sandbox-status-abc"),permissions,- &[writable.as_path()],- &[protected.as_path()],- &[socket.as_path()],- Some(cwd.as_path()),- &program,- &args,+ "/bin/sh",+ &["-c".to_string(), "echo hi".to_string()],+ Some(socket.as_path()),);- 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.protected_paths, vec![protected]);- assert_eq!(decoded.allowed_unix_socket_paths, vec![socket]);- assert_eq!(decoded.program, OsString::from(program));- assert_eq!(- decoded.args,- args.into_iter().map(OsString::from).collect::<Vec<_>>()- );+ // The bind destination inside the sandbox and the path handed to the+ // bridge must be the same unique path.+ let sandbox_destination = proxy_socket_bind_destination(&args)+ .expect("restricted run should bind the proxy socket into the sandbox");+ assert!(sandbox_destination.starts_with(PROXY_SOCKET_SANDBOX_PATH_PREFIX));+ assert!(windows_contains(+ &args,+ &[+ "/path/to/zed",+ BRIDGE_FLAG,+ &sandbox_destination,+ "8080",+ "--"+ ]+ ));}- #[test]- fn test_launcher_args_round_trip_minimal() {- let program = "/bin/true".to_string();- let permissions = SandboxPermissions {- allow_network: true,- allow_fs_write: true,+ fn build_wrapped_args_for_test(+ bridge_program: &str,+ permissions: SandboxPermissions,+ program: &str,+ program_args: &[String],+ proxy_socket_path: Option<&Path>,+ ) -> Vec<String> {+ let proxy_socket_sandbox_path = match permissions.network {+ NetworkAccess::LocalhostPort(_) => Some(unique_proxy_socket_sandbox_path()),+ NetworkAccess::None | NetworkAccess::All => None,};- let (launcher, launcher_args) = wrap_invocation(- "/path/to/zed",- None,- permissions,- &[],+ let mut bwrap_args = build_bwrap_args_with_proxy_socket_sandbox_path(&[],&[],+ permissions,None,- &program,- &[],+ proxy_socket_path,+ proxy_socket_sandbox_path.as_deref(),);-- 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!(decoded.protected_paths.is_empty());- assert!(decoded.allowed_unix_socket_paths.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);+ bwrap_args.push("--".to_string());+ if let NetworkAccess::LocalhostPort(port) = permissions.network {+ let proxy_socket_sandbox_path =+ proxy_socket_sandbox_path.expect("restricted network needs a sandbox socket path");+ bwrap_args.push(bridge_program.to_string());+ bwrap_args.push(BRIDGE_FLAG.to_string());+ bwrap_args.push(proxy_socket_sandbox_path.to_string_lossy().into_owned());+ bwrap_args.push(port.to_string());+ bwrap_args.push("--".to_string());+ }+ bwrap_args.push(program.to_string());+ bwrap_args.extend(program_args.iter().cloned());+ bwrap_args+ }++ /// Returns the in-sandbox destination of the proxy socket `--bind`, if any.+ fn proxy_socket_bind_destination(args: &[String]) -> Option<String> {+ args.windows(3).find_map(|window| {+ if window[0] == "--bind" && window[1] == "/tmp/zed-proxy.sock" {+ Some(window[2].clone())+ } else {+ 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))+ fn windows_contains(haystack: &[String], needle: &[&str]) -> bool {+ haystack+ .windows(needle.len())+ .any(|window| window.iter().map(String::as_str).eq(needle.iter().copied()))}}diff --git a/crates/sandbox/src/sandbox.rs b/crates/sandbox/src/sandbox.rsindex 2060d5d1898..9979715fd42 100644--- a/crates/sandbox/src/sandbox.rs+++ b/crates/sandbox/src/sandbox.rs@@ -1,76 +1,951 @@-//! Per-OS sandbox integrations for terminal commands run on behalf of the-//! agent.+//! Cross-platform sandboxing for commands run on behalf of the agent.//!-//! Each supported operating system has its own module here, gated behind-//! its `target_os` cfg so callers reach for the right one explicitly and-//! non-host targets don't carry dead code.-//!-//! 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. Windows-//! routes commands through WSL and runs them under Bubblewrap there (see-//! [`windows_wsl`]).+//! The public API is intentionally platform-neutral. Internally, macOS uses+//! Seatbelt (`sandbox-exec`), Linux uses Bubblewrap (`bwrap`), and Windows uses+//! Bubblewrap inside WSL. Restricted-network policies are enforced by an+//! in-process HTTP/HTTPS proxy (the `http_proxy` crate) that this crate+//! constructs and owns; callers only describe intent via [`SandboxPolicy`].++use std::{+ collections::HashMap,+ fmt,+ path::{Path, PathBuf},+ process::Output,+};++use http_proxy::ProxyHandle;+#[cfg(not(target_os = "windows"))]+use http_proxy::{Allowlist, HostPattern, ProxyConfig, ProxyEvent, UpstreamProxy};#[cfg(target_os = "linux")]-pub mod linux_bubblewrap;+mod linux_bubblewrap;#[cfg(target_os = "macos")]-pub mod macos_seatbelt;+mod macos_seatbelt;#[cfg(target_os = "windows")]-pub mod windows_wsl;+mod windows_wsl;-/// Marker prefix for [`windows_wsl`] errors that mean the sandboxing-/// *environment* is unavailable (WSL missing or failing to start, no usable-/// `bwrap`, the probe/path-resolution protocol breaking down) — as opposed-/// to per-request errors such as a writable path that doesn't exist, which-/// never carry this prefix.-///-/// The agent matches on this prefix to decide whether a failed sandboxed-/// command should offer the user the option of turning sandboxing off-/// (an environment that can't sandbox at all) or simply report the error-/// back to the model (a fixable bad request). Defined here rather than in-/// [`windows_wsl`] so non-Windows builds of the agent can still reference-/// it.-pub const WSL_SANDBOX_UNAVAILABLE_PREFIX: &str = "Windows sandboxing via WSL is unavailable";--/// 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. Windows reuses-/// this type, mapping it onto Bubblewrap inside WSL. 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,+#[cfg(target_os = "windows")]+pub(crate) const WSL_SANDBOX_UNAVAILABLE_PREFIX: &str = "Windows sandboxing via WSL is unavailable";++/// What a command is allowed to do, expressed as intent. This is the entire+/// public configuration surface; how each policy is enforced (Seatbelt rules,+/// Bubblewrap flags, a loopback proxy, …) is an implementation detail.+#[derive(Clone, Debug, Eq, PartialEq)]+pub struct SandboxPolicy {+ pub fs: SandboxFsPolicy,+ pub network: SandboxNetPolicy,+ pub git: GitSandboxPolicy,+}++/// Filesystem policy for a sandboxed command.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum SandboxFsPolicy {/// Allow unrestricted filesystem writes.- pub allow_fs_write: bool,+ Unrestricted,+ /// Reads are allowed everywhere; writes are confined to these directory+ /// subtrees (and the standard ephemeral locations the platform provides).+ Restricted { writable_paths: Vec<PathBuf> },+}++/// Outbound-network policy for a sandboxed command.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum SandboxNetPolicy {+ /// Allow unrestricted outbound network access.+ Unrestricted,+ /// Block all outbound network access.+ Blocked,+ /// Allow outbound HTTP(S) only to these hostnames (exact hosts or+ /// leading-`*.` subdomain wildcards), enforced by an in-process proxy.+ Restricted { allowed_domains: Vec<String> },+}++/// Policy for the project's Git directories (`.git`). The agent computes the+/// directory list because locating it requires Git knowledge the sandbox layer+/// can't derive itself — a linked worktree's `.git` is a gitlink pointing at a+/// common dir elsewhere, and discovered repositories can live outside the+/// project. Both variants carry the same dirs; the variant selects how they're+/// treated.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum GitSandboxPolicy {+ /// `.git` contents are protected: read-only on Linux; content reads and+ /// writes denied on macOS (metadata stays visible either way).+ Denied { git_dirs: Vec<PathBuf> },+ /// `.git` contents are writable (these dirs are made writable).+ Allowed { git_dirs: Vec<PathBuf> },+}++impl Default for GitSandboxPolicy {+ /// Git directories protected, none known — the safe default.+ fn default() -> Self {+ GitSandboxPolicy::Denied {+ git_dirs: Vec::new(),+ }+ }+}++impl GitSandboxPolicy {+ /// The `.git` directories this policy governs, regardless of variant.+ pub fn git_dirs(&self) -> &[PathBuf] {+ match self {+ GitSandboxPolicy::Denied { git_dirs } | GitSandboxPolicy::Allowed { git_dirs } => {+ git_dirs+ }+ }+ }++ /// Whether `.git` contents are writable.+ pub fn allows_writes(&self) -> bool {+ matches!(self, GitSandboxPolicy::Allowed { .. })+ }++ /// Combine two layers: `Allowed` (more permissive) wins, and the governed+ /// `.git` directories union.+ pub fn merge(self, other: GitSandboxPolicy) -> GitSandboxPolicy {+ let allowed = self.allows_writes() || other.allows_writes();+ let (GitSandboxPolicy::Denied { mut git_dirs }+ | GitSandboxPolicy::Allowed { mut git_dirs }) = self;+ let (GitSandboxPolicy::Denied {+ git_dirs: other_dirs,+ }+ | GitSandboxPolicy::Allowed {+ git_dirs: other_dirs,+ }) = other;+ for path in other_dirs {+ if !git_dirs.contains(&path) {+ git_dirs.push(path);+ }+ }+ if allowed {+ GitSandboxPolicy::Allowed { git_dirs }+ } else {+ GitSandboxPolicy::Denied { git_dirs }+ }+ }+}++impl SandboxPolicy {+ /// Combine two policies into the least-restrictive policy that satisfies+ /// both (a set union per dimension). Used to layer the user's persistent+ /// settings, this thread's grants, and a command's request into the single+ /// policy that is actually enforced.+ pub fn merge(self, other: SandboxPolicy) -> SandboxPolicy {+ SandboxPolicy {+ fs: self.fs.merge(other.fs),+ network: self.network.merge(other.network),+ git: self.git.merge(other.git),+ }+ }++ /// Replace the Git policy, keeping the fs/network policy. The UI builds the+ /// fs/network halves from settings/grants (which don't know the project's+ /// `.git` locations) and then attaches the agent-computed Git policy here.+ pub fn with_git(mut self, git: GitSandboxPolicy) -> Self {+ self.git = git;+ self+ }+}++impl SandboxFsPolicy {+ /// Unrestricted access dominates; otherwise the writable subtrees union.+ pub fn merge(self, other: SandboxFsPolicy) -> SandboxFsPolicy {+ match (self, other) {+ (SandboxFsPolicy::Unrestricted, _) | (_, SandboxFsPolicy::Unrestricted) => {+ SandboxFsPolicy::Unrestricted+ }+ (+ SandboxFsPolicy::Restricted {+ writable_paths: mut a,+ },+ SandboxFsPolicy::Restricted { writable_paths: b },+ ) => {+ for path in b {+ if !a.contains(&path) {+ a.push(path);+ }+ }+ SandboxFsPolicy::Restricted { writable_paths: a }+ }+ }+ }+}++impl SandboxNetPolicy {+ /// Unrestricted access dominates and `Blocked` is the identity; otherwise the+ /// allowed domains union.+ pub fn merge(self, other: SandboxNetPolicy) -> SandboxNetPolicy {+ match (self, other) {+ (SandboxNetPolicy::Unrestricted, _) | (_, SandboxNetPolicy::Unrestricted) => {+ SandboxNetPolicy::Unrestricted+ }+ (SandboxNetPolicy::Blocked, other) | (other, SandboxNetPolicy::Blocked) => other,+ (+ SandboxNetPolicy::Restricted {+ allowed_domains: mut a,+ },+ SandboxNetPolicy::Restricted { allowed_domains: b },+ ) => {+ for domain in b {+ if !a.contains(&domain) {+ a.push(domain);+ }+ }+ SandboxNetPolicy::Restricted { allowed_domains: a }+ }+ }+ }+}++/// A command and its execution environment, before sandbox wrapping.+#[derive(Clone, Debug, Default, Eq, PartialEq)]+pub struct CommandAndArgs {+ /// Program to execute.+ pub program: String,+ /// Arguments passed to `program`.+ pub args: Vec<String>,+ /// Environment variables for the spawned process.+ pub env: HashMap<String, String>,+ /// Working directory for the spawned process.+ pub cwd: Option<PathBuf>,+}++/// A command transformed to run inside the platform sandbox. Plain data: spawn+/// it however you like (PTY, `std::process`, …). The resources that must+/// outlive the spawned process live in the [`Sandbox`] that produced this, not+/// here — keep the `Sandbox` alive for the command's duration.+#[derive(Clone, Debug, Default, Eq, PartialEq)]+pub struct WrappedCommand {+ pub program: String,+ pub args: Vec<String>,+ pub env: HashMap<String, String>,+ pub cwd: Option<PathBuf>,+}++/// Errors returned by the sandbox abstraction.+#[derive(Debug, Clone, Eq, PartialEq)]+pub enum SandboxError {+ /// No sandbox implementation is available for this platform.+ UnsupportedPlatform,+ /// No usable Bubblewrap executable was found.+ BwrapNotFound,+ /// The only Bubblewrap executable found is setuid-root, which is refused.+ BwrapSetuidRejected,+ /// Bubblewrap was found but failed to create the sandbox.+ SandboxProbeFailed,+ /// The sandbox bridge executable path could not be resolved.+ BridgeExecutableUnavailable(String),+ /// Windows sandboxing through WSL is unavailable.+ WslUnavailable(String),+ /// The requested sandbox policy is not supported on this platform.+ UnsupportedPolicy(String),+ /// The sandbox request is invalid (e.g. a malformed allowed-domain).+ InvalidRequest(String),+ /// An I/O error occurred (e.g. spawning the network proxy).+ Io(String),+ /// Any other sandbox setup failure.+ Other(String),+}++impl fmt::Display for SandboxError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ SandboxError::UnsupportedPlatform => {+ write!(formatter, "sandboxing is not supported on this platform")+ }+ SandboxError::BwrapNotFound => {+ write!(formatter, "no usable `bwrap` binary was found on PATH")+ }+ SandboxError::BwrapSetuidRejected => write!(+ formatter,+ "the only available `bwrap` is setuid-root, which Zed refuses to run"+ ),+ SandboxError::SandboxProbeFailed => {+ write!(+ formatter,+ "`bwrap` is present but failed to create a sandbox"+ )+ }+ SandboxError::BridgeExecutableUnavailable(message) => write!(+ formatter,+ "failed to resolve sandbox bridge executable: {message}"+ ),+ SandboxError::WslUnavailable(message) => write!(formatter, "{message}"),+ SandboxError::UnsupportedPolicy(message) => write!(formatter, "{message}"),+ SandboxError::InvalidRequest(message) => write!(formatter, "{message}"),+ SandboxError::Io(message) => write!(formatter, "{message}"),+ SandboxError::Other(message) => write!(formatter, "{message}"),+ }+ }+}++impl std::error::Error for SandboxError {}++/// Resolved filesystem setup derived from [`SandboxFsPolicy`].+struct FsSetup {+ allow_fs_write: bool,+ writable_paths: Vec<PathBuf>,}-/// Handle a possible re-exec of this binary as a sandbox launcher.+/// Resolved network plan derived from [`SandboxNetPolicy`]. For the restricted+/// case the allowlist is parsed up front; the proxy itself is spawned lazily on+/// the first [`Sandbox::wrap`] so its upstream-proxy chaining can read the+/// command's environment.+enum NetSetup {+ Unrestricted,+ Blocked,+ // Restricted networking is rejected up front on Windows, so this variant is+ // never constructed there.+ #[cfg(not(target_os = "windows"))]+ Restricted {+ allowlist: Allowlist,+ },+}++/// A live sandbox: it owns the per-policy resources (the network proxy, and on+/// macOS the temporary Seatbelt policy file) and produces sandboxed command+/// invocations via [`Sandbox::wrap`] / [`Sandbox::execute`].///-/// 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.+/// Keep it alive for as long as commands wrapped by it are running; dropping it+/// tears down the proxy.+pub struct Sandbox {+ fs: FsSetup,+ network: NetSetup,+ /// The project's `.git` directories and whether they're writable. Enforced+ /// on macOS/Linux; ignored by the WSL sandbox for now.+ git: GitSandboxPolicy,+ /// In-process network proxy for the restricted-network case, spawned on the+ /// first `wrap`. Dropped on a background thread (the join blocks).+ proxy: Option<ProxyHandle>,+ #[cfg(target_os = "macos")]+ seatbelt_config: Option<macos_seatbelt::SeatbeltConfigFile>,+}++impl Sandbox {+ /// Create a sandbox for `policy`, validating it for the current platform.+ ///+ /// This does not spawn the network proxy or probe `bwrap`; the proxy is+ /// created lazily on the first [`Sandbox::wrap`] (so it can chain through an+ /// upstream proxy named in the command's environment), and `bwrap`+ /// availability is checked separately via [`Sandbox::can_create`].+ pub fn new(policy: SandboxPolicy) -> Result<Self, SandboxError> {+ let fs = match policy.fs {+ SandboxFsPolicy::Unrestricted => FsSetup {+ allow_fs_write: true,+ writable_paths: Vec::new(),+ },+ SandboxFsPolicy::Restricted { writable_paths } => FsSetup {+ allow_fs_write: false,+ writable_paths,+ },+ };++ let network = match policy.network {+ SandboxNetPolicy::Unrestricted => NetSetup::Unrestricted,+ SandboxNetPolicy::Blocked => NetSetup::Blocked,+ SandboxNetPolicy::Restricted { allowed_domains } => {+ resolve_restricted_network(&allowed_domains)?+ }+ };++ Ok(Self {+ fs,+ network,+ git: policy.git,+ proxy: None,+ #[cfg(target_os = "macos")]+ seatbelt_config: None,+ })+ }++ /// Check whether the platform sandbox can be created for `policy` without+ /// actually building a command or spawning the proxy. On Linux this runs a+ /// brief `bwrap` probe (call it off the main thread).+ pub fn can_create(policy: &SandboxPolicy, cwd: Option<&Path>) -> Result<(), SandboxError> {+ #[cfg(target_os = "linux")]+ {+ let writable = policy_writable_paths(policy);+ let writable: Vec<&Path> = writable.iter().map(PathBuf::as_path).collect();+ let permissions = linux_bubblewrap::SandboxPermissions {+ network: linux_probe_network(&policy.network),+ allow_fs_write: matches!(policy.fs, SandboxFsPolicy::Unrestricted),+ };+ linux_bubblewrap::check_can_create_sandbox(&writable, permissions, cwd)+ .map_err(map_linux_status)+ }+ #[cfg(target_os = "windows")]+ {+ let _ = cwd;+ if matches!(policy.network, SandboxNetPolicy::Restricted { .. }) {+ return Err(unsupported_restricted_network_on_windows());+ }+ Ok(())+ }+ #[cfg(not(any(target_os = "linux", target_os = "windows")))]+ {+ let _ = (policy, cwd);+ Ok(())+ }+ }++ /// Transform `command` into the invocation that runs it inside this sandbox.+ /// The returned [`WrappedCommand`] is plain data; keep `self` alive while it+ /// runs (it owns the proxy and any per-command policy file).+ pub async fn wrap(&mut self, command: &CommandAndArgs) -> Result<WrappedCommand, SandboxError> {+ #[cfg(target_os = "linux")]+ {+ self.wrap_linux(command)+ }+ #[cfg(target_os = "macos")]+ {+ self.wrap_macos(command)+ }+ #[cfg(target_os = "windows")]+ {+ self.wrap_windows(command).await+ }+ #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]+ {+ let _ = command;+ Err(SandboxError::UnsupportedPlatform)+ }+ }++ /// Run `command` inside the sandbox to completion and collect its output.+ /// Convenience for non-interactive callers; interactive callers (PTYs) use+ /// [`Sandbox::wrap`].+ #[allow(+ clippy::disallowed_methods,+ reason = "this is the blocking convenience API; interactive callers use `wrap`"+ )]+ pub async fn execute(&mut self, command: &CommandAndArgs) -> Result<Output, SandboxError> {+ let wrapped = self.wrap(command).await?;+ let mut process = std::process::Command::new(&wrapped.program);+ process.args(&wrapped.args).envs(&wrapped.env);+ if let Some(cwd) = &wrapped.cwd {+ process.current_dir(cwd);+ }+ process+ .output()+ .map_err(|error| SandboxError::Io(error.to_string()))+ }++ /// Drop this sandbox on the *current* thread, tearing down the network proxy+ /// inline (its `Drop` joins a listener thread after a loopback wakeup+ /// connect).+ ///+ /// The blanket [`Drop`] impl instead offloads that join to a fresh thread,+ /// so an accidental drop on a latency-sensitive thread (e.g. the UI thread)+ /// can never block. Call this only when you are *already* on a background+ /// thread or executor and want the teardown to finish before the surrounding+ /// task completes — it avoids spawning a throwaway thread to do work the+ /// current one can do.+ pub fn drop_on_current_thread(mut self) {+ // Drop the proxy here, synchronously, so the `Drop` impl below sees+ // `None` and doesn't spawn a thread to repeat the work.+ drop(self.proxy.take());+ }++ /// Spawn the restricted-network proxy if it isn't running yet, point the+ /// command env at it, and return its `(port, host socket path)`. Returns+ /// `None` for non-restricted network policies.+ #[cfg(not(target_os = "windows"))]+ fn ensure_restricted_proxy(+ &mut self,+ env: &mut HashMap<String, String>,+ ) -> Result<Option<(u16, Option<PathBuf>)>, SandboxError> {+ let NetSetup::Restricted { allowlist } = &self.network else {+ return Ok(None);+ };++ if self.proxy.is_none() {+ let upstream = upstream_proxy_from_env(env);+ let (events_tx, events_rx) = futures::channel::mpsc::unbounded();+ let config = ProxyConfig {+ allowlist: allowlist.clone(),+ upstream,+ events: events_tx,+ };+ #[cfg(target_os = "linux")]+ let handle = ProxyHandle::spawn_unix_temp(config);+ #[cfg(not(target_os = "linux"))]+ let handle = ProxyHandle::spawn(config);+ let handle = handle.map_err(|error| {+ SandboxError::Io(format!("failed to start network proxy: {error:#}"))+ })?;+ spawn_proxy_event_logger(events_rx);+ self.proxy = Some(handle);+ }++ let proxy = self+ .proxy+ .as_ref()+ .expect("proxy was just ensured to be present");+ let port = proxy.port();+ apply_proxy_env(env, port);+ Ok(Some((port, proxy.socket_path().map(PathBuf::from))))+ }++ /// Split the policy's `.git` directories into (writable, protected) sets for+ /// the enforcement layers. When the whole filesystem is writable the split+ /// is empty (Git protection is moot); otherwise `Allowed` git dirs are+ /// writable and `Denied` git dirs are protected.+ #[cfg(any(target_os = "macos", target_os = "linux"))]+ fn git_path_split(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {+ if self.fs.allow_fs_write {+ return (Vec::new(), Vec::new());+ }+ match &self.git {+ GitSandboxPolicy::Allowed { git_dirs } => (git_dirs.clone(), Vec::new()),+ GitSandboxPolicy::Denied { git_dirs } => (Vec::new(), git_dirs.clone()),+ }+ }++ #[cfg(target_os = "linux")]+ fn wrap_linux(&mut self, command: &CommandAndArgs) -> Result<WrappedCommand, SandboxError> {+ let mut env = command.env.clone();+ let proxy = self.ensure_restricted_proxy(&mut env)?;++ let network = match &self.network {+ NetSetup::Unrestricted => linux_bubblewrap::NetworkAccess::All,+ NetSetup::Blocked => linux_bubblewrap::NetworkAccess::None,+ NetSetup::Restricted { .. } => linux_bubblewrap::NetworkAccess::LocalhostPort(+ proxy.as_ref().map(|(port, _)| *port).unwrap_or(0),+ ),+ };+ let proxy_socket_path = proxy.as_ref().and_then(|(_, socket)| socket.clone());++ let permissions = linux_bubblewrap::SandboxPermissions {+ network,+ allow_fs_write: self.fs.allow_fs_write,+ };+ let (git_writable, git_protected) = self.git_path_split();+ let mut writable: Vec<&Path> = self+ .fs+ .writable_paths+ .iter()+ .map(PathBuf::as_path)+ .collect();+ writable.extend(git_writable.iter().map(PathBuf::as_path));+ let protected_git_dirs: Vec<&Path> = git_protected.iter().map(PathBuf::as_path).collect();++ let bridge_program = std::env::current_exe()+ .map_err(|error| SandboxError::BridgeExecutableUnavailable(error.to_string()))?;+ let bridge_program = bridge_program.to_str().ok_or_else(|| {+ SandboxError::BridgeExecutableUnavailable(format!(+ "current executable path contains invalid UTF-8: {}",+ bridge_program.display()+ ))+ })?;++ let (program, args) = linux_bubblewrap::wrap_invocation(+ bridge_program,+ permissions,+ &writable,+ &protected_git_dirs,+ command.cwd.as_deref(),+ &command.program,+ &command.args,+ proxy_socket_path.as_deref(),+ )+ .map_err(map_anyhow_error)?;++ Ok(WrappedCommand {+ program,+ args,+ env,+ cwd: command.cwd.clone(),+ })+ }++ #[cfg(target_os = "macos")]+ fn wrap_macos(&mut self, command: &CommandAndArgs) -> Result<WrappedCommand, SandboxError> {+ let mut env = command.env.clone();+ let proxy = self.ensure_restricted_proxy(&mut env)?;++ let network = match &self.network {+ NetSetup::Unrestricted => macos_seatbelt::NetworkAccess::All,+ NetSetup::Blocked => macos_seatbelt::NetworkAccess::None,+ NetSetup::Restricted { .. } => macos_seatbelt::NetworkAccess::LocalhostPort(+ proxy.as_ref().map(|(port, _)| *port).unwrap_or(0),+ ),+ };++ let permissions = macos_seatbelt::SandboxPermissions {+ network,+ allow_fs_write: self.fs.allow_fs_write,+ };+ let (git_writable, git_protected) = self.git_path_split();+ let mut writable: Vec<&Path> = self+ .fs+ .writable_paths+ .iter()+ .map(PathBuf::as_path)+ .collect();+ writable.extend(git_writable.iter().map(PathBuf::as_path));+ let protected: Vec<&Path> = git_protected.iter().map(PathBuf::as_path).collect();++ // SSH-agent socket handling (commit signing) is deferred, so no unix+ // sockets are allowed for now.+ let (program, args, config) = macos_seatbelt::wrap_invocation(+ &command.program,+ &command.args,+ &writable,+ &protected,+ &[],+ permissions,+ )+ .map_err(map_anyhow_error)?;+ // Keep the temporary Seatbelt policy file alive for the command's life.+ self.seatbelt_config = Some(config);++ Ok(WrappedCommand {+ program,+ args,+ env,+ cwd: command.cwd.clone(),+ })+ }++ #[cfg(target_os = "windows")]+ async fn wrap_windows(+ &mut self,+ command: &CommandAndArgs,+ ) -> Result<WrappedCommand, SandboxError> {+ // Restricted host network access is rejected at `new` time on Windows.+ // Git-dir protection isn't enforced for the WSL sandbox yet, so the+ // policy's Git directories are intentionally ignored here.+ let _ = self.git.git_dirs();+ let permissions = windows_wsl::SandboxPermissions {+ allow_network: matches!(self.network, NetSetup::Unrestricted),+ allow_fs_write: self.fs.allow_fs_write,+ };+ let (program, args) = windows_wsl::wrap_invocation(+ command.program.clone(),+ command.args.clone(),+ self.fs.writable_paths.clone(),+ permissions,+ command.cwd.clone(),+ command.env.clone(),+ )+ .await+ .map_err(map_anyhow_error)?;++ Ok(WrappedCommand {+ program,+ args,+ env: command.env.clone(),+ cwd: command.cwd.clone(),+ })+ }+}++impl Drop for Sandbox {+ fn drop(&mut self) {+ // Dropping a `ProxyHandle` joins its listener thread after a loopback+ // wakeup connect; do that off whatever (possibly UI) thread is dropping+ // the sandbox so a slow shutdown can't stall it. Callers already on a+ // background executor should prefer `drop_on_current_thread` to avoid+ // this throwaway thread.+ if let Some(proxy) = self.proxy.take() {+ std::thread::spawn(move || drop(proxy));+ }+ }+}++/// Handle a possible re-exec of this binary as an in-sandbox helper.///-/// Call this at the very top of `main`, before any argument parsing.+/// Linux restricted-network runs launch this binary in bridge mode inside the+/// sandbox network namespace before spawning the real command. Call this at the+/// top of `main`, before normal argument parsing.+#[doc(hidden)]pub fn run_sandbox_launcher_if_invoked() {#[cfg(target_os = "linux")]linux_bubblewrap::run_launcher_if_invoked();}+#[cfg(target_os = "linux")]+fn policy_writable_paths(policy: &SandboxPolicy) -> Vec<PathBuf> {+ match &policy.fs {+ SandboxFsPolicy::Unrestricted => Vec::new(),+ SandboxFsPolicy::Restricted { writable_paths } => writable_paths.clone(),+ }+}++#[cfg(not(target_os = "windows"))]+fn resolve_restricted_network(allowed_domains: &[String]) -> Result<NetSetup, SandboxError> {+ let mut patterns = Vec::with_capacity(allowed_domains.len());+ for domain in allowed_domains {+ let pattern = HostPattern::parse(domain).map_err(|error| {+ SandboxError::InvalidRequest(format!("invalid network host '{domain}': {error}"))+ })?;+ patterns.push(pattern);+ }+ Ok(NetSetup::Restricted {+ allowlist: Allowlist::from_patterns(patterns),+ })+}++#[cfg(target_os = "windows")]+fn resolve_restricted_network(_allowed_domains: &[String]) -> Result<NetSetup, SandboxError> {+ Err(unsupported_restricted_network_on_windows())+}++#[cfg(target_os = "windows")]+fn unsupported_restricted_network_on_windows() -> SandboxError {+ SandboxError::UnsupportedPolicy(+ "restricted host network access is not yet supported for Windows sandboxes".to_string(),+ )+}++#[cfg(target_os = "linux")]+fn linux_probe_network(network: &SandboxNetPolicy) -> linux_bubblewrap::NetworkAccess {+ match network {+ SandboxNetPolicy::Unrestricted => linux_bubblewrap::NetworkAccess::All,+ SandboxNetPolicy::Blocked => linux_bubblewrap::NetworkAccess::None,+ // The probe only needs the network namespace flag, not a real port.+ SandboxNetPolicy::Restricted { .. } => linux_bubblewrap::NetworkAccess::LocalhostPort(0),+ }+}++#[cfg(not(target_os = "windows"))]+fn upstream_proxy_from_env(env: &HashMap<String, String>) -> Option<UpstreamProxy> {+ let url = first_nonempty_env_value(+ env,+ &[+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+ "HTTP_PROXY",+ "http_proxy",+ ],+ );+ let no_proxy = first_nonempty_env_value(env, &["NO_PROXY", "no_proxy"]);+ match UpstreamProxy::parse(url, no_proxy) {+ Ok(upstream) => upstream,+ Err(error) => {+ log::warn!("[sandbox/network] ignoring upstream proxy env: {error:#}");+ None+ }+ }+}++#[cfg(not(target_os = "windows"))]+fn first_nonempty_env_value<'a>(+ env: &'a HashMap<String, String>,+ names: &[&str],+) -> Option<&'a str> {+ for name in names {+ if let Some(value) = env.get(*name)+ && !value.trim().is_empty()+ {+ return Some(value.as_str());+ }+ }+ None+}++/// Point the child's proxy env vars at the in-process proxy and strip any+/// inherited `NO_PROXY`.+///+/// Both upper- and lower-case forms are set because some clients (notably curl+/// on macOS) only honor the lowercase variant. `NO_PROXY` is blanked so all+/// egress goes through our proxy unconditionally: an inherited `NO_PROXY`+/// matching an allowlisted host would make the client attempt a direct+/// connection, which the sandbox blocks — surfacing as a confusing "connection+/// refused" instead of a clean policy decision.+#[cfg(not(target_os = "windows"))]+fn apply_proxy_env(env: &mut HashMap<String, String>, port: u16) {+ let url = format!("http://127.0.0.1:{port}");+ for key in [+ "HTTPS_PROXY",+ "https_proxy",+ "HTTP_PROXY",+ "http_proxy",+ "ALL_PROXY",+ "all_proxy",+ ] {+ env.insert(key.to_string(), url.clone());+ }+ for key in ["NO_PROXY", "no_proxy"] {+ env.insert(key.to_string(), String::new());+ }+}++/// Drain the proxy's event channel on a background thread, logging each event.+/// v1 surfacing only; future integrations (UI, telemetry) can replace this.+/// The thread exits when the proxy is dropped and the channel closes.+#[cfg(not(target_os = "windows"))]+fn spawn_proxy_event_logger(events: futures::channel::mpsc::UnboundedReceiver<ProxyEvent>) {+ std::thread::spawn(move || {+ futures::executor::block_on(async move {+ use futures::StreamExt as _;+ let mut events = events;+ while let Some(event) = events.next().await {+ log_proxy_event(&event);+ }+ });+ });+}++#[cfg(not(target_os = "windows"))]+fn log_proxy_event(event: &ProxyEvent) {+ match event {+ ProxyEvent::Ready { .. } => {}+ ProxyEvent::RequestAttempt {+ host,+ port,+ method,+ outcome,+ } => {+ log::debug!(+ "[sandbox/network] {} {host}:{port} → {outcome:?}",+ method.as_str()+ );+ }+ ProxyEvent::RequestCompleted {+ host,+ port,+ method,+ bytes_to_remote,+ bytes_from_remote,+ duration_ms,+ } => {+ log::debug!(+ "[sandbox/network] completed {} {host}:{port} sent={bytes_to_remote} recv={bytes_from_remote} duration={duration_ms}ms",+ method.as_str(),+ );+ }+ }+}++#[cfg(target_os = "linux")]+fn map_linux_status(status: linux_bubblewrap::LauncherStatus) -> SandboxError {+ match status {+ linux_bubblewrap::LauncherStatus::BwrapNotFound => SandboxError::BwrapNotFound,+ linux_bubblewrap::LauncherStatus::SetuidRejected => SandboxError::BwrapSetuidRejected,+ linux_bubblewrap::LauncherStatus::SandboxProbeFailed => SandboxError::SandboxProbeFailed,+ }+}++#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]+fn map_anyhow_error(error: anyhow::Error) -> SandboxError {+ #[cfg(target_os = "windows")]+ if let Some(error) = error.downcast_ref::<windows_wsl::WslSandboxUnavailable>() {+ return SandboxError::WslUnavailable(error.to_string());+ }++ SandboxError::Other(format!("{error:#}"))+}++#[cfg(all(test, not(target_os = "windows")))]+mod tests {+ use super::*;++ #[test]+ fn fs_merge_unrestricted_dominates_else_unions_paths() {+ let a = SandboxFsPolicy::Restricted {+ writable_paths: vec![PathBuf::from("/a"), PathBuf::from("/b")],+ };+ let b = SandboxFsPolicy::Restricted {+ writable_paths: vec![PathBuf::from("/b"), PathBuf::from("/c")],+ };+ assert_eq!(+ a.clone().merge(b),+ SandboxFsPolicy::Restricted {+ writable_paths: vec![+ PathBuf::from("/a"),+ PathBuf::from("/b"),+ PathBuf::from("/c")+ ],+ }+ );+ assert_eq!(+ a.merge(SandboxFsPolicy::Unrestricted),+ SandboxFsPolicy::Unrestricted+ );+ assert_eq!(+ SandboxFsPolicy::Unrestricted.merge(SandboxFsPolicy::Restricted {+ writable_paths: vec![PathBuf::from("/a")],+ }),+ SandboxFsPolicy::Unrestricted+ );+ }++ #[test]+ fn net_merge_unrestricted_dominates_blocked_is_identity_else_unions() {+ let hosts = |list: &[&str]| SandboxNetPolicy::Restricted {+ allowed_domains: list.iter().map(|s| s.to_string()).collect(),+ };+ assert_eq!(+ hosts(&["a.com", "b.com"]).merge(hosts(&["b.com", "c.com"])),+ hosts(&["a.com", "b.com", "c.com"])+ );+ assert_eq!(+ SandboxNetPolicy::Blocked.merge(hosts(&["a.com"])),+ hosts(&["a.com"])+ );+ assert_eq!(+ hosts(&["a.com"]).merge(SandboxNetPolicy::Blocked),+ hosts(&["a.com"])+ );+ assert_eq!(+ SandboxNetPolicy::Blocked.merge(SandboxNetPolicy::Blocked),+ SandboxNetPolicy::Blocked+ );+ assert_eq!(+ hosts(&["a.com"]).merge(SandboxNetPolicy::Unrestricted),+ SandboxNetPolicy::Unrestricted+ );+ }++ #[test]+ fn upstream_proxy_from_env_uses_precedence_and_no_proxy() {+ let mut env = HashMap::new();+ env.insert("HTTPS_PROXY".to_string(), " ".to_string());+ env.insert("https_proxy".to_string(), "http://lower:1111".to_string());+ env.insert("ALL_PROXY".to_string(), "http://all:2222".to_string());+ env.insert("HTTP_PROXY".to_string(), "http://http:3333".to_string());+ env.insert("NO_PROXY".to_string(), "".to_string());+ env.insert("no_proxy".to_string(), "internal.example".to_string());++ let upstream = upstream_proxy_from_env(&env).expect("should configure an upstream");+ assert_eq!(upstream.host, "lower");+ assert_eq!(upstream.port, 1111);+ assert!(upstream.bypasses("internal.example", 443));+ assert!(!upstream.bypasses("zed.dev", 443));+ }++ #[test]+ fn apply_proxy_env_points_vars_at_proxy_and_blanks_no_proxy() {+ let mut env = HashMap::new();+ env.insert("HTTPS_PROXY".to_string(), "http://corp:3128".to_string());+ env.insert("NO_PROXY".to_string(), "internal.example".to_string());+ env.insert("PATH".to_string(), "/usr/bin".to_string());++ apply_proxy_env(&mut env, 54321);++ for key in [+ "HTTPS_PROXY",+ "https_proxy",+ "HTTP_PROXY",+ "http_proxy",+ "ALL_PROXY",+ "all_proxy",+ ] {+ assert_eq!(+ env.get(key).map(String::as_str),+ Some("http://127.0.0.1:54321")+ );+ }+ for key in ["NO_PROXY", "no_proxy"] {+ assert_eq!(env.get(key).map(String::as_str), Some(""));+ }+ assert_eq!(env.get("PATH").map(String::as_str), Some("/usr/bin"));+ }+}+/// Canonicalize `path`, resolving symlinks, even when its final component/// doesn't exist yet.///@@ -84,7 +959,11 @@ pub fn run_sandbox_launcher_if_invoked() {/// existing parent and re-appending the final component keeps the child/// consistent with its parent. If neither the path nor its parent can be/// canonicalized, the path is returned unchanged.-#[cfg(any(target_os = "linux", target_os = "macos"))]+//+// Only the macOS Seatbelt layer uses this (Linux skips not-yet-existing `.git`+// dirs rather than emitting a rule for them), so it's gated to macOS to avoid a+// dead-code warning elsewhere.+#[cfg(target_os = "macos")]pub(crate) fn canonicalize_allowing_missing_leaf(path: &std::path::Path) -> std::path::PathBuf {if let Ok(canonical) = path.canonicalize() {return canonical;@@ -97,8 +976,8 @@ pub(crate) fn canonicalize_allowing_missing_leaf(path: &std::path::Path) -> std:path.to_path_buf()}-#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]-mod tests {+#[cfg(all(test, target_os = "macos"))]+mod macos_tests {use super::canonicalize_allowing_missing_leaf;#[test]diff --git a/crates/sandbox/src/windows_wsl.rs b/crates/sandbox/src/windows_wsl.rsindex 50beab807a6..e1254d40adb 100644--- a/crates/sandbox/src/windows_wsl.rs+++ b/crates/sandbox/src/windows_wsl.rs@@ -32,7 +32,16 @@ use smol::process::{Command, Stdio};use anyhow::{Context as _, Result, bail, ensure};-use crate::{SandboxPermissions, WSL_SANDBOX_UNAVAILABLE_PREFIX};+use crate::WSL_SANDBOX_UNAVAILABLE_PREFIX;++/// Per-command relaxations of the WSL/Bubblewrap sandbox. Windows can only+/// toggle network access wholesale (no loopback-proxy confinement yet), so this+/// is a plain bool rather than the richer cross-platform [`crate::SandboxNetPolicy`].+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub(crate) struct SandboxPermissions {+ pub(crate) allow_network: bool,+ pub(crate) allow_fs_write: bool,+}/// Exit code the environment probe script uses to signal that `bwrap` is not/// installed, distinguishing that from WSL itself failing to start a shell.@@ -68,6 +77,7 @@ impl WslSandboxUnavailable {}/// The reason, without the leading [`WSL_SANDBOX_UNAVAILABLE_PREFIX`].+ #[cfg(test)]pub fn message(&self) -> &str {&self.0}diff --git a/crates/sandbox/src/wsl_sandbox_test_helper.rs b/crates/sandbox/src/wsl_sandbox_test_helper.rsindex 5fa13cb2280..b4fab4cbcd2 100644--- a/crates/sandbox/src/wsl_sandbox_test_helper.rs+++ b/crates/sandbox/src/wsl_sandbox_test_helper.rs@@ -4,8 +4,8 @@//! Where the Linux helper is the sandboxed process itself (it re-execs under//! the launcher), here the sandboxed process is a *Linux* program inside WSL//! while this helper runs on Windows. So instead of a status channel and a-//! launcher, the helper drives the real [`sandbox::windows_wsl::wrap_invocation`],-//! spawns the `wsl.exe` command line it produces, and inspects exit codes and+//! launcher, the helper drives the real [`sandbox::Sandbox`] (`new` + `wrap`),+//! spawns the command line it produces, and inspects exit codes and//! host-side filesystem effects to confirm every grant the sandbox makes and//! every restriction it imposes actually holds — including the Windows-specific//! one: that a sandboxed process cannot escape via WSL interop by exec'ing a@@ -47,8 +47,28 @@ mod imp {use std::process::{Command, Output};use anyhow::{Context as _, Result, bail, ensure};- use sandbox::SandboxPermissions;- use sandbox::windows_wsl;+ use sandbox::{+ CommandAndArgs, GitSandboxPolicy, Sandbox, SandboxError, SandboxFsPolicy, SandboxNetPolicy,+ SandboxPolicy,+ };++ /// Network access for a helper run, translated into a `SandboxNetPolicy` in+ /// `drive_sandbox`. Only the all-or-nothing cases the helper exercises are+ /// represented.+ #[derive(Clone, Copy, Default)]+ enum NetworkAccess {+ #[default]+ None,+ All,+ }++ /// The per-run permission knobs the helper varies, translated into a+ /// `SandboxPolicy` in `drive_sandbox`.+ #[derive(Clone, Copy, Default)]+ struct SandboxPermissions {+ network: NetworkAccess,+ allow_fs_write: bool,+ }/// Tag prefixed to every result line, matching `bwrap_test_helper` so both/// helpers' output reads the same.@@ -144,11 +164,11 @@ mod imp {let default = SandboxPermissions::default();let fs_write_all = SandboxPermissions {- allow_network: false,+ network: NetworkAccess::None,allow_fs_write: true,};let network_allowed = SandboxPermissions {- allow_network: true,+ network: NetworkAccess::All,allow_fs_write: false,};@@ -488,31 +508,42 @@ mod imp {permissions: SandboxPermissions,env: &HashMap<String, String>,) -> Result<Outcome> {- let wrapped = smol::block_on(windows_wsl::wrap_invocation(- program.to_string(),- args.iter().map(|arg| arg.to_string()).collect(),- writable_paths.to_vec(),- permissions,- None,- env.clone(),- ));+ let policy = SandboxPolicy {+ fs: if permissions.allow_fs_write {+ SandboxFsPolicy::Unrestricted+ } else {+ SandboxFsPolicy::Restricted {+ writable_paths: writable_paths.to_vec(),+ }+ },+ network: match permissions.network {+ NetworkAccess::None => SandboxNetPolicy::Blocked,+ NetworkAccess::All => SandboxNetPolicy::Unrestricted,+ },+ git: GitSandboxPolicy::default(),+ };+ let command = CommandAndArgs {+ program: program.to_string(),+ args: args.iter().map(|arg| arg.to_string()).collect(),+ env: env.clone(),+ cwd: None,+ };+ let prepared =+ Sandbox::new(policy).and_then(|mut sandbox| smol::block_on(sandbox.wrap(&command)));- let (wsl_exe, wsl_args) = match wrapped {- Ok(wrapped) => wrapped,+ let prepared = match prepared {+ Ok(prepared) => prepared,Err(error) => {- let message = format!("{error:#}");- return Ok(- if message.contains(sandbox::WSL_SANDBOX_UNAVAILABLE_PREFIX) {- Outcome::Unavailable(message)- } else {- Outcome::BadRequest(message)- },- );+ let message = error.to_string();+ return Ok(match error {+ SandboxError::WslUnavailable(_) => Outcome::Unavailable(message),+ _ => Outcome::BadRequest(message),+ });}};- let output = Command::new(&wsl_exe)- .args(&wsl_args)+ let output = Command::new(&prepared.program)+ .args(&prepared.args).creation_flags(CREATE_NO_WINDOW).output().context("failed to spawn the wrapped wsl.exe sandbox command")?;diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rsindex 6af0fa1b06b..b23f0774ad4 100644--- a/crates/zed/src/main.rs+++ b/crates/zed/src/main.rs@@ -202,11 +202,10 @@ 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.+ // If this process was re-executed as a Linux sandbox helper, run that mode+ // 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)]diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rsindex 668b1fc514c..ee9b0ec2d55 100644--- a/crates/zed/src/visual_test_runner.rs+++ b/crates/zed/src/visual_test_runner.rs@@ -2739,6 +2739,7 @@ fn run_multi_workspace_sidebar_visual_tests(ui_scroll_position: None,draft_prompt: None,sandboxed_terminal_temp_dir: None,+ sandbox_grants: Default::default(),},path_list,cx,diff --git a/nix/tests/sandboxing/default.nix b/nix/tests/sandboxing/default.nixindex f97336d317b..22eaf10357b 100644--- a/nix/tests/sandboxing/default.nix+++ b/nix/tests/sandboxing/default.nix@@ -1,30 +1,45 @@# 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:+# What actually changes the sandbox's behavior is the *host configuration* —+# whether a usable `bwrap` exists and whether the kernel lets us create user+# namespaces. We can only set those at boot, which is exactly what a VM gives+# us. So we run one machine per host configuration:#-# 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.+# working - `bwrap` present, unprivileged user namespaces available;+# the sandbox must be enforced.+# no-bwrap - no `bwrap` on PATH; `Sandbox::can_create` must report+# `BwrapNotFound` and the consumer must fail closed.+# setuid-bwrap - the only `bwrap` is setuid-root; `can_create` must report+# `BwrapSetuidRejected` (we refuse to run setuid bwrap).+# userns-disabled - `bwrap` present but unprivileged user namespaces are+# disabled via sysctl; `can_create` must report+# `SandboxProbeFailed`.#-# 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.+# The behavior to assert is declared *here* as a list of `checks`, serialized to+# JSON and handed to the `bwrap_test_helper` binary, which builds the described+# sandbox policy via the sandbox crate's public API, performs the operation, and+# asserts the outcome. Each check is one of:+#+# { read = "/path"; succeeds = true; } # read a host file+# { write = "/path"; succeeds = false; } # write a host file+# { network = "echo1"; succeeds = true; } # connect to an echo server+# { canCreate = false; error = "bwrap_not_found"; } # Sandbox::can_create+#+# plus optional policy fields applied to that check (defaults shown):+#+# fs = "restricted"; # or "unrestricted"+# writablePaths = [ ]; # writable subtrees when fs = "restricted"+# networkAccess = "blocked"; # or "unrestricted" / "restricted"+# allowedDomains = [ ]; # allowed hosts when networkAccess = "restricted"+#+# Two echo servers (`echo1`, `echo2`) on separate nodes give the network checks+# real peers, so a restricted-network policy that allowlists `echo1` can be+# shown to reach `echo1` while `echo2` is blocked.## Build one scenario:-# nix build .#checks.x86_64-linux.sandbox-userns-enabled+# nix build .#checks.x86_64-linux.sandbox-working# Interactive:-# nix run .#checks.x86_64-linux.sandbox-userns-enabled.driverInteractive+# nix run .#checks.x86_64-linux.sandbox-working.driverInteractive{pkgs,inputs,@@ -34,113 +49,256 @@ letbwrap-test-helper = import ./helper.nix { inherit pkgs inputs; };+ # Both echo nodes listen on the same port; the helper appends it to a bare+ # hostname (`echo1` -> `echo1:7000`).echoPort = 7000;+ # A node running a raw TCP echo server (socat EXEC:cat). The helper round-trips+ # a byte through it, directly or via the sandbox's HTTP CONNECT proxy.+ mkEchoNode = {+ 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";+ };+ };+ };++ # Quiet boot + a couple of cores; shared by every machine-under-test.+ baseMachine = {+ boot.consoleLogLevel = lib.mkForce 3; # be quiet pls :)+ services.journald.extraConfig = lib.mkAfter "MaxLevelConsole=notice";+ environment.systemPackages = [ bwrap-test-helper ];+ virtualisation = {+ memorySize = 1024;+ cores = 2;+ };+ };++ # Per-scenario host configuration. Each entry layers onto `baseMachine`.+ machineConfigs = {+ # Plain, working host: bwrap on PATH, user namespaces available.+ working =+ { ... }:+ lib.mkMerge [+ baseMachine+ { environment.systemPackages = [ pkgs.bubblewrap ]; }+ ];++ # No bwrap anywhere on PATH.+ no-bwrap = { ... }: baseMachine;++ # The only bwrap is a setuid-root wrapper. We deliberately do NOT also put a+ # plain `pkgs.bubblewrap` on PATH: `locate_bwrap` returns the first `bwrap`+ # it finds on PATH, and we want that to be the setuid one so the helper sees+ # `BwrapSetuidRejected`.+ setuid-bwrap =+ { ... }:+ lib.mkMerge [+ baseMachine+ {+ security.wrappers.bwrap = {+ source = "${pkgs.bubblewrap}/bin/bwrap";+ owner = "root";+ group = "root";+ setuid = true;+ };+ }+ ];++ # bwrap present, but unprivileged user namespaces disabled at boot. Capping+ # the count at 0 makes `bwrap --unshare-user` fail, exactly like a hardened+ # host, so the probe reports `SandboxProbeFailed`.+ userns-disabled =+ { ... }:+ lib.mkMerge [+ baseMachine+ {+ environment.systemPackages = [ pkgs.bubblewrap ];+ boot.kernel.sysctl."user.max_user_namespaces" = 0;+ }+ ];+ };++ # Build a VM test for `machine` that runs `checks` through the helper.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,+ machine,+ checks,}:let- # The sandbox is only actually enforced when bwrap is present *and* user- # namespaces are available.- enforced = installBwrap && !usernsDisabled;+ checksFile = pkgs.writeText "${name}-checks.json" (builtins.toJSON checks);inpkgs.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;- };- };+ echo1 = { ... }: mkEchoNode;+ echo2 = { ... }: mkEchoNode;+ machine = machine;};testScript = ''start_all()- echo.wait_for_unit("echo-server.service")- echo.wait_for_open_port(${toString echoPort})+ echo1.wait_for_unit("echo-server.service")+ echo1.wait_for_open_port(${toString echoPort})+ echo2.wait_for_unit("echo-server.service")+ echo2.wait_for_open_port(${toString echoPort})machine.wait_for_unit("multi-user.target")- machine.wait_until_succeeds("getent hosts echo", timeout=30)+ machine.wait_until_succeeds("getent hosts echo1", timeout=30)+ machine.wait_until_succeeds("getent hosts echo2", 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")+ # The helper logs each check tagged `[sandbox_test]:`. `succeed` fails the+ # whole test on a non-zero exit; we print its output so the per-check+ # results show up in the build log.+ print(machine.succeed(+ "ZED_SANDBOX_CHECKS=${checksFile} "+ "ZED_TEST_ECHO_PORT=${toString echoPort} "+ "bwrap_test_helper 2>&1"+ ))'';};+in{- sandbox-userns-enabled = mkTest {- name = "sandbox-userns-enabled";- };+ sandbox-working = mkTest {+ name = "sandbox-working";+ machine = machineConfigs.working;+ # Each check is written out in full (no shared fragments) so the policy and+ # expected outcome for every case are obvious at a glance.+ checks = [+ # Reads of host files are always allowed, regardless of the write policy.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "blocked";+ read = "/sandbox-test/readable/host.txt";+ succeeds = true;+ }- sandbox-userns-disabled = mkTest {- name = "sandbox-userns-disabled";- usernsDisabled = true;- expectedDegradeStatus = "probe_failed";+ # Write inside the granted subtree: allowed.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "blocked";+ write = "/sandbox-test/writable/ok.txt";+ succeeds = true;+ }++ # Write outside the granted subtree: denied.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "blocked";+ write = "/sandbox-test/forbidden/no.txt";+ succeeds = false;+ }++ # A writable path that doesn't exist yet must be bound at its exact+ # location (created up front), never widened to an existing ancestor. If it+ # widened to `/sandbox-test`, this write to a read-only file under that+ # ancestor would succeed — the scope-widening sandbox escape this guards+ # against. It must be denied.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/not-yet-created/deep" ];+ networkAccess = "blocked";+ write = "/sandbox-test/readable/host.txt";+ succeeds = false;+ }++ # ...and the not-yet-existing path itself is created and writable.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/not-yet-created/deep" ];+ networkAccess = "blocked";+ write = "/sandbox-test/not-yet-created/deep/ok.txt";+ succeeds = true;+ }++ # The fs escape hatch lets a command write anywhere.+ {+ fs = "unrestricted";+ networkAccess = "blocked";+ write = "/sandbox-test/forbidden/anywhere.txt";+ succeeds = true;+ }++ # Blocked network: the echo server is unreachable.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "blocked";+ network = "echo1";+ succeeds = false;+ }++ # Unrestricted network: both echo servers are reachable.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "unrestricted";+ network = "echo1";+ succeeds = true;+ }+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "unrestricted";+ network = "echo2";+ succeeds = true;+ }++ # Restricted network: only the allowlisted host is reachable.+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "restricted";+ allowedDomains = [ "echo1" ];+ network = "echo1";+ succeeds = true;+ }+ {+ fs = "restricted";+ writablePaths = [ "/sandbox-test/writable" ];+ networkAccess = "restricted";+ allowedDomains = [ "echo1" ];+ network = "echo2";+ succeeds = false;+ }++ # On a working host the sandbox can be created.+ {+ fs = "restricted";+ networkAccess = "blocked";+ canCreate = true;+ }+ ];};sandbox-no-bwrap = mkTest {name = "sandbox-no-bwrap";- installBwrap = false;- expectedDegradeStatus = "bwrap_not_found";+ machine = machineConfigs.no-bwrap;+ checks = [ { canCreate = false; error = "bwrap_not_found"; } ];+ };++ sandbox-setuid-bwrap = mkTest {+ name = "sandbox-setuid-bwrap";+ machine = machineConfigs.setuid-bwrap;+ checks = [ { canCreate = false; error = "setuid_rejected"; } ];+ };++ sandbox-userns-disabled = mkTest {+ name = "sandbox-userns-disabled";+ machine = machineConfigs.userns-disabled;+ checks = [ { canCreate = false; error = "probe_failed"; } ];};}diff --git a/tooling/xtask/src/tasks/sandbox_tests.rs b/tooling/xtask/src/tasks/sandbox_tests.rsindex c885d97e8e0..bf68ca27b43 100644--- a/tooling/xtask/src/tasks/sandbox_tests.rs+++ b/tooling/xtask/src/tasks/sandbox_tests.rs@@ -7,14 +7,16 @@ 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.+/// Each test boots a real kernel under QEMU to exercise bwrap behavior across+/// host configurations: a working host (the sandbox must be enforced and the+/// full fs x network policy matrix must hold), and degraded hosts (no bwrap,+/// setuid-only bwrap, user namespaces disabled) where `Sandbox::can_create`+/// must report the specific failure and the consumer must fail closed. 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+ /// Names of specific tests to run (e.g. `sandbox-working`). Defaults/// to all.tests: Vec<String>,