mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
sandbox: Linux domain filtering and some more cleanup (#59790)
--- Release Notes: - N/A or Added/Fixed/Improved ... --------- Co-authored-by: MartinYe1234 <martin@zed.dev> Co-authored-by: Richard Feldman <oss@rtfeldman.com>
This commit is contained in:
committed by
GitHub
parent
df6c440fe8
commit
c49a29f461
Generated
+5
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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*
|
||||
@@ -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>
|
||||
|
After Width: | Height: | Size: 540 B |
@@ -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` on
|
||||
|
||||
+134
-583
@@ -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;
|
||||
sandbox::Sandbox::can_create(&self.to_policy(), cwd).map_err(LinuxWslSandboxError::from)
|
||||
}
|
||||
|
||||
let writable: Vec<&std::path::Path> = self
|
||||
.writable_paths
|
||||
.iter()
|
||||
.chain(self.extra_write_paths.iter())
|
||||
.map(|path| path.as_path())
|
||||
.collect();
|
||||
let protected: Vec<&std::path::Path> = self
|
||||
.protected_paths
|
||||
.iter()
|
||||
.map(|path| path.as_path())
|
||||
.collect();
|
||||
let allowed_unix_sockets: Vec<&std::path::Path> = self
|
||||
.allowed_unix_socket_paths
|
||||
.iter()
|
||||
.map(|path| path.as_path())
|
||||
.collect();
|
||||
let allow_network = !matches!(self.network, SandboxNetworkAccess::None);
|
||||
let permissions = sandbox::SandboxPermissions {
|
||||
allow_network,
|
||||
allow_fs_write: self.allow_fs_write,
|
||||
};
|
||||
sandbox::linux_bubblewrap::check_can_create_sandbox(
|
||||
&writable,
|
||||
&protected,
|
||||
&allowed_unix_sockets,
|
||||
permissions,
|
||||
cwd,
|
||||
)
|
||||
.map_err(|status| match status {
|
||||
LauncherStatus::BwrapNotFound => LinuxWslSandboxError::BwrapNotFound,
|
||||
LauncherStatus::SetuidRejected => LinuxWslSandboxError::SetuidRejected,
|
||||
LauncherStatus::SandboxProbeFailed => LinuxWslSandboxError::SandboxProbeFailed,
|
||||
// `Success` never appears in the `Err` arm; map defensively.
|
||||
LauncherStatus::Success => {
|
||||
LinuxWslSandboxError::Other(status.describe().to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = cwd;
|
||||
Ok(())
|
||||
}
|
||||
/// Translate this request into the cross-platform [`sandbox::SandboxPolicy`].
|
||||
fn to_policy(&self) -> sandbox::SandboxPolicy {
|
||||
let fs = if self.allow_fs_write {
|
||||
sandbox::SandboxFsPolicy::Unrestricted
|
||||
} else {
|
||||
sandbox::SandboxFsPolicy::Restricted {
|
||||
writable_paths: self
|
||||
.writable_paths
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(self.extra_write_paths.iter().cloned())
|
||||
.collect(),
|
||||
}
|
||||
};
|
||||
let network = match &self.network {
|
||||
SandboxNetworkAccess::None => sandbox::SandboxNetPolicy::Blocked,
|
||||
SandboxNetworkAccess::All => sandbox::SandboxNetPolicy::Unrestricted,
|
||||
SandboxNetworkAccess::Restricted(allowlist) => sandbox::SandboxNetPolicy::Restricted {
|
||||
allowed_domains: allowlist
|
||||
.patterns()
|
||||
.iter()
|
||||
.map(|pattern| pattern.to_string())
|
||||
.collect(),
|
||||
},
|
||||
};
|
||||
let git_dirs = self.git_dirs.clone();
|
||||
let git = if self.allow_git_access {
|
||||
sandbox::GitSandboxPolicy::Allowed { git_dirs }
|
||||
} else {
|
||||
sandbox::GitSandboxPolicy::Denied { git_dirs }
|
||||
};
|
||||
sandbox::SandboxPolicy { fs, network, git }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,439 +190,67 @@ impl SandboxWrap {
|
||||
/// grow their own failure cases later without a migration.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SandboxNotAppliedReason {
|
||||
/// The user allowed unsandboxed execution for the rest of this thread after
|
||||
/// an earlier sandbox failure. There is always a preceding tool call whose
|
||||
/// reason is [`SandboxNotAppliedReason::ErrorLinuxWsl`].
|
||||
/// The user disabled the sandbox for the rest of this thread, so the command
|
||||
/// ran without one. This happens either when the user approved a
|
||||
/// model-requested `unsandboxed: true` escape "for this thread", or when
|
||||
/// they chose to run unsandboxed for the thread after a sandbox-creation
|
||||
/// failure (in which case a preceding tool call's reason is
|
||||
/// [`SandboxNotAppliedReason::ErrorLinuxWsl`]).
|
||||
DisabledForThisThread,
|
||||
/// The Linux/WSL (Bubblewrap) sandbox could not be created for this command.
|
||||
ErrorLinuxWsl(LinuxWslSandboxError),
|
||||
}
|
||||
|
||||
/// Opaque RAII handle the sandbox implementation hands back to keep its
|
||||
/// per-command resources (e.g. an on-disk Seatbelt config file) alive for
|
||||
/// the duration of the spawned command. `Terminal` holds it in a field
|
||||
/// whose only job is to drop with the entity.
|
||||
pub type SandboxConfigHandle = Box<dyn std::any::Any + Send>;
|
||||
/// The live sandbox kept alive for its per-command resources (the network proxy
|
||||
/// and, on macOS, the Seatbelt policy file) until the terminal exits.
|
||||
type SandboxConfigHandle = sandbox::Sandbox;
|
||||
|
||||
/// The outbound-network policy resolved for a sandboxed command.
|
||||
pub(crate) enum NetworkPolicy {
|
||||
/// The command requested no outbound network.
|
||||
Denied,
|
||||
/// Egress is confined to the in-process proxy on this loopback port.
|
||||
Proxied(u16),
|
||||
/// The command explicitly requested, and the user approved, unrestricted
|
||||
/// outbound network access.
|
||||
Unrestricted,
|
||||
}
|
||||
|
||||
/// Apply a [`SandboxWrap`] to a `(program, args)` pair, substituting the
|
||||
/// platform's sandboxed invocation in place of the original. The returned
|
||||
/// `SandboxConfigHandle` (when `Some`) must be kept alive for the duration
|
||||
/// of the spawned command — dropping it deletes any on-disk config the
|
||||
/// launcher reads at startup.
|
||||
///
|
||||
/// `network_policy` is the decision resolved by [`setup_network_proxy`].
|
||||
/// Unrestricted network access must be requested explicitly via
|
||||
/// [`SandboxNetworkAccess::All`].
|
||||
///
|
||||
/// There is a dedicated code path per platform:
|
||||
/// * macOS wraps the command with `sandbox-exec` and a Seatbelt config file
|
||||
/// (returned as the handle).
|
||||
/// * Linux re-execs this binary as a launcher that locates `bwrap` and `exec`s
|
||||
/// it for filesystem and network isolation (see
|
||||
/// [`sandbox::linux_bubblewrap`]); no handle is needed. The launcher reports
|
||||
/// back over a status channel whether it could enforce the sandbox, and when
|
||||
/// it can't (no usable `bwrap`, user namespaces disabled, …) it runs the
|
||||
/// command unsandboxed and the parent logs a warning rather than failing.
|
||||
/// * Windows routes the command through WSL and runs it under Bubblewrap
|
||||
/// there, but that path is async (it performs `wsl.exe` round-trips), so it
|
||||
/// lives in [`apply_windows_wsl_sandbox_wrap`] rather than this synchronous
|
||||
/// function.
|
||||
/// * All other platforms pass the command through unchanged — we have no
|
||||
/// sandbox integration there, so the command runs with the agent's ambient
|
||||
/// permissions.
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
pub(crate) fn apply_sandbox_wrap(
|
||||
program: String,
|
||||
args: Vec<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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
+116
-14
@@ -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,
|
||||
|
||||
@@ -168,6 +168,7 @@ mod tests {
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
sandbox_grants: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<NetworkReques
|
||||
Ok(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,6 +3259,177 @@ mod tests {
|
||||
assert_eq!(environment2.terminal_creation_count(), 0);
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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 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}"
|
||||
);
|
||||
}
|
||||
|
||||
/// 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}"
|
||||
);
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// 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()
|
||||
@@ -3444,87 +3438,6 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_all_access_and_network() {
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(NetworkRequest::AnyHost, true, &[])),
|
||||
"Allow arbitrary network access and unrestricted filesystem writes?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(NetworkRequest::AnyHost, false, &[])),
|
||||
"Allow arbitrary network access?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(NetworkRequest::None, true, &[])),
|
||||
"Allow unrestricted filesystem writes?"
|
||||
);
|
||||
|
||||
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?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_specific_hosts() {
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(host_request(&["github.com"]), false, &[])),
|
||||
"Allow network access to github.com?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(
|
||||
host_request(&["github.com", "*.npmjs.org"]),
|
||||
false,
|
||||
&[]
|
||||
)),
|
||||
"Allow network access to github.com and *.npmjs.org?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(
|
||||
host_request(&["github.com", "npmjs.org", "pypi.org"]),
|
||||
false,
|
||||
&[]
|
||||
)),
|
||||
"Allow network access to github.com, npmjs.org, and pypi.org?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_per_path_writes() {
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(
|
||||
NetworkRequest::None,
|
||||
false,
|
||||
&["/tmp/build"]
|
||||
)),
|
||||
"Allow write access to /tmp/build?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(
|
||||
host_request(&["github.com"]),
|
||||
false,
|
||||
&["/tmp/build"]
|
||||
)),
|
||||
"Allow network access to github.com and write access to /tmp/build?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_access_takes_precedence_over_paths_in_title() {
|
||||
// When all-access is requested, the specific paths are redundant and
|
||||
// should not be listed.
|
||||
assert_eq!(
|
||||
sandbox_approval_title(&sandbox_request(
|
||||
NetworkRequest::None,
|
||||
true,
|
||||
&["/tmp/build"]
|
||||
)),
|
||||
"Allow unrestricted filesystem writes?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_network_request_validates_and_classifies() {
|
||||
// No fields -> None.
|
||||
@@ -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:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ release_channel.workspace = true
|
||||
remote.workspace = true
|
||||
remote_connection.workspace = true
|
||||
rope.workspace = true
|
||||
sandbox.workspace = true
|
||||
schemars.workspace = true
|
||||
search.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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(|| {
|
||||
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"
|
||||
}
|
||||
)
|
||||
};
|
||||
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();
|
||||
|
||||
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),
|
||||
)
|
||||
.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;
|
||||
}
|
||||
|
||||
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(
|
||||
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),
|
||||
)
|
||||
|
||||
@@ -1852,6 +1852,7 @@ mod tests {
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
sandbox_grants: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = true
|
||||
base64.workspace = true
|
||||
|
||||
+175
-30
@@ -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<A
|
||||
break;
|
||||
}
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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()]);
|
||||
|
||||
@@ -184,6 +184,7 @@ pub enum IconName {
|
||||
LoadCircle,
|
||||
LocationEdit,
|
||||
LockOutlined,
|
||||
LockOutlinedOff,
|
||||
MagnifyingGlass,
|
||||
Maximize,
|
||||
MaximizeAlt,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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 = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
smol.workspace = true
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")?;
|
||||
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}")
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
/// 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()))?;
|
||||
|
||||
/// Drive the sandbox launcher the same way Zed's terminal integration does:
|
||||
/// bind a status channel, build the launcher invocation, spawn it, and collect
|
||||
/// both the reported status and the command's exit result.
|
||||
fn drive_launcher(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
writable_dirs: &[&Path],
|
||||
cwd: Option<&Path>,
|
||||
permissions: SandboxPermissions,
|
||||
) -> Result<LaunchResult> {
|
||||
let launcher = std::env::current_exe().context("failed to resolve current executable")?;
|
||||
let launcher = launcher
|
||||
.to_str()
|
||||
.context("current executable path is not valid UTF-8")?;
|
||||
|
||||
let channel = StatusChannel::bind().context("failed to bind status channel")?;
|
||||
let (launcher_program, launcher_args) = wrap_invocation(
|
||||
launcher,
|
||||
Some(channel.name()),
|
||||
permissions,
|
||||
writable_dirs,
|
||||
&[],
|
||||
&[],
|
||||
cwd,
|
||||
program,
|
||||
args,
|
||||
);
|
||||
|
||||
let mut child = Command::new(&launcher_program)
|
||||
.args(&launcher_args)
|
||||
.spawn()
|
||||
.context("failed to spawn sandbox launcher")?;
|
||||
|
||||
// The launcher connects and reports before it execs, so read the status
|
||||
// while the command runs, then wait for the command to finish.
|
||||
let status = channel.recv(Duration::from_secs(30));
|
||||
let exit = child.wait().context("failed to wait for launcher")?;
|
||||
|
||||
Ok(LaunchResult {
|
||||
status,
|
||||
command_succeeded: exit.success(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Run `sh -c <script>` inside the sandbox and report whether it succeeded.
|
||||
fn run_in_sandbox(
|
||||
script: &str,
|
||||
writable_dirs: &[&Path],
|
||||
permissions: SandboxPermissions,
|
||||
) -> Result<LaunchResult> {
|
||||
drive_launcher(
|
||||
let mut sandbox = Sandbox::new(policy.clone()).map_err(sandbox_err)?;
|
||||
run_command(
|
||||
&mut sandbox,
|
||||
"sh",
|
||||
&["-c".to_string(), script.to_string()],
|
||||
writable_dirs,
|
||||
None,
|
||||
permissions,
|
||||
&["-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",
|
||||
&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,
|
||||
/// 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 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(());
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+937
-58
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")?;
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 @@ let
|
||||
|
||||
bwrap-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);
|
||||
in
|
||||
pkgs.testers.nixosTest {
|
||||
inherit name;
|
||||
|
||||
nodes = {
|
||||
# TCP echo server, so the network checks have a real peer to (fail to)
|
||||
# reach from inside the sandbox.
|
||||
echo =
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
networking.firewall.allowedTCPPorts = [ echoPort ];
|
||||
systemd.services.echo-server = {
|
||||
description = "TCP echo server";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${pkgs.socat}/bin/socat -d TCP-LISTEN:${toString echoPort},reuseaddr,fork EXEC:cat";
|
||||
DynamicUser = true;
|
||||
Restart = "on-failure";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
# The machine under test.
|
||||
machine =
|
||||
{ ... }:
|
||||
{
|
||||
boot.consoleLogLevel = lib.mkForce 3; # be quiet pls :)
|
||||
services.journald.extraConfig = lib.mkAfter "MaxLevelConsole=notice";
|
||||
|
||||
# Disable unprivileged user namespaces for the degradation scenario.
|
||||
# Capping the count at 0 makes `bwrap --unshare-user` fail, which is
|
||||
# exactly what a hardened host looks like.
|
||||
boot.kernel.sysctl = lib.mkIf usernsDisabled {
|
||||
"user.max_user_namespaces" = 0;
|
||||
};
|
||||
|
||||
# `bwrap` itself (the helper locates it on PATH) plus the helper.
|
||||
# The no-bwrap scenario deliberately omits bubblewrap.
|
||||
environment.systemPackages = [
|
||||
bwrap-test-helper
|
||||
]
|
||||
++ lib.optionals installBwrap [ pkgs.bubblewrap ];
|
||||
|
||||
# The helper reads its expectations from the environment; setting
|
||||
# them here means `machine.execute` picks them up via /etc/profile.
|
||||
environment.variables = {
|
||||
ZED_TEST_SANDBOX_ENFORCED = if enforced then "1" else "0";
|
||||
ZED_TEST_ECHO_ADDR = "echo:${toString echoPort}";
|
||||
}
|
||||
// lib.optionalAttrs (expectedDegradeStatus != null) {
|
||||
ZED_TEST_EXPECTED_DEGRADE_STATUS = expectedDegradeStatus;
|
||||
};
|
||||
|
||||
virtualisation = {
|
||||
memorySize = 1024;
|
||||
cores = 2;
|
||||
};
|
||||
};
|
||||
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"; } ];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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>,
|
||||
|
||||
|
||||
Reference in New Issue
Block a user