| 1 | //! Sandbox module for secure command execution. |
| 2 | //! |
| 3 | //! This module provides sandboxing capabilities for shell commands executed by |
| 4 | //! CodeWhale. Sandboxing restricts what system resources a command can access, |
| 5 | //! preventing accidental or malicious damage to the system. |
| 6 | //! |
| 7 | //! # Platform Support |
| 8 | //! |
| 9 | //! - **macOS**: Uses Seatbelt (`sandbox-exec`) when the runtime probe succeeds |
| 10 | //! - **Linux**: Uses bubblewrap by default whenever `/usr/bin/bwrap` is |
| 11 | //! installed and a probe shows it can create its namespaces; `prefer_bwrap |
| 12 | //! = false` opts out. A workspace-write posture refuses to run when an |
| 13 | //! installed launcher fails that probe, instead of running the command |
| 14 | //! unwrapped; read-only keeps its existing engine-side enforcement rule. |
| 15 | //! The extension host uses bubblewrap on the same |
| 16 | //! condition, probed per launch |
| 17 | //! (`extension_host::supervisor::plan_launch`). |
| 18 | //! - **OpenHarmony**: No local Linux sandbox is advertised. Bubblewrap |
| 19 | //! and Linux `prctl` hardening are gated out under `target_env = |
| 20 | //! "ohos"`. |
| 21 | //! - **Windows**: No OS sandbox is advertised yet. The planned first helper |
| 22 | //! contract is process-tree containment only via a Windows Job Object; it |
| 23 | //! must not claim filesystem, network, registry, or AppContainer isolation. |
| 24 | //! |
| 25 | //! # Usage |
| 26 | //! |
| 27 | //! ```rust,ignore |
| 28 | //! use codewhale_sandbox::{SandboxManager, CommandSpec, SandboxPolicy}; |
| 29 | //! |
| 30 | //! let manager = SandboxManager::new(); |
| 31 | //! let spec = CommandSpec::shell("ls -la", PathBuf::from("."), Duration::from_secs(30)) |
| 32 | //! .with_policy(SandboxPolicy::default()); |
| 33 | //! |
| 34 | //! let exec_env = manager.prepare(&spec); |
| 35 | //! // exec_env.command now contains the sandboxed command |
| 36 | //! ``` |
| 37 | |
| 38 | pub mod backend; |
| 39 | pub mod opensandbox; |
| 40 | pub mod policy; |
| 41 | pub mod process_hardening; |
| 42 | pub mod read_guard; |
| 43 | pub mod shell_dispatcher; |
| 44 | |
| 45 | #[cfg(target_os = "macos")] |
| 46 | pub mod seatbelt; |
| 47 | |
| 48 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 49 | pub mod bwrap; |
| 50 | |
| 51 | #[cfg(target_os = "windows")] |
| 52 | pub mod windows; |
| 53 | |
| 54 | use std::collections::HashMap; |
| 55 | use std::path::PathBuf; |
| 56 | use std::time::Duration; |
| 57 | |
| 58 | pub use policy::SandboxPolicy; |
| 59 | |
| 60 | /// Public OS-sandbox capability labels consumed by the website facts |
| 61 | /// generator. Keep this list limited to wrappers that the command execution |
| 62 | /// path can actually select and apply. |
| 63 | // EXTERNAL CONTRACT — zero Rust references by design: the website's docs |
| 64 | // drift gate parses this const out of the source text (web/lib/facts-drift.ts |
| 65 | // and web/scripts/facts-lib.mjs match the literal declaration). Deleting or |
| 66 | // renaming it silently breaks that gate. |
| 67 | pub const PUBLIC_SANDBOX_BACKENDS: &[&str] = &[ |
| 68 | "seatbelt (macOS, when available)", |
| 69 | "bubblewrap (Linux, default when installed and working)", |
| 70 | ]; |
| 71 | |
| 72 | /// Specification for a command to be executed, potentially within a sandbox. |
| 73 | /// |
| 74 | /// This struct captures all the information needed to execute a command: |
| 75 | /// the program and arguments, working directory, environment variables, |
| 76 | /// timeout, and sandbox policy. |
| 77 | #[derive(Debug, Clone)] |
| 78 | pub struct CommandSpec { |
| 79 | /// The program to execute (e.g., "sh", "python", "cargo"). |
| 80 | pub program: String, |
| 81 | |
| 82 | /// Arguments to pass to the program. |
| 83 | pub args: Vec<String>, |
| 84 | |
| 85 | /// Working directory for the command. |
| 86 | pub cwd: PathBuf, |
| 87 | |
| 88 | /// Additional environment variables to set. |
| 89 | pub env: HashMap<String, String>, |
| 90 | |
| 91 | /// Maximum execution time before the command is killed. |
| 92 | pub timeout: Duration, |
| 93 | |
| 94 | /// Sandbox policy controlling resource access. |
| 95 | pub sandbox_policy: SandboxPolicy, |
| 96 | |
| 97 | /// Optional justification for why this command needs to run. |
| 98 | /// Used for logging and audit purposes. |
| 99 | pub justification: Option<String>, |
| 100 | |
| 101 | /// The shell command exactly as requested, before the dispatcher adds |
| 102 | /// shell-specific wrapping (encoding prefixes, exit-code capture, temp |
| 103 | /// `-File` scripts). Authoritative for display; `None` for specs built |
| 104 | /// directly from a program + args. |
| 105 | pub requested_command: Option<String>, |
| 106 | |
| 107 | pub private_tmp: bool, |
| 108 | } |
| 109 | |
| 110 | impl CommandSpec { |
| 111 | /// Create a `CommandSpec` for running a shell command via the platform shell. |
| 112 | pub fn shell(command: &str, cwd: PathBuf, timeout: Duration) -> Self { |
| 113 | let dispatcher = crate::shell_dispatcher::global_dispatcher(); |
| 114 | |
| 115 | #[cfg(windows)] |
| 116 | let (program, args) = { |
| 117 | // Force UTF-8 output. cmd.exe uses chcp; PowerShell sets the |
| 118 | // console output encoding directly. See issue #982. Key on the |
| 119 | // PowerShell family so a custom PowerShell path keeps the same |
| 120 | // output contract as the two detected variants (#6745). |
| 121 | let kind = dispatcher.kind(); |
| 122 | let cmd = if kind.is_powershell() { |
| 123 | format!("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; {command}") |
| 124 | } else if matches!(kind, crate::shell_dispatcher::ShellKind::Cmd) { |
| 125 | format!("chcp 65001 >NUL & {command}") |
| 126 | } else { |
| 127 | command.to_string() |
| 128 | }; |
| 129 | dispatcher.build_command_parts(&cmd) |
| 130 | }; |
| 131 | #[cfg(not(windows))] |
| 132 | let (program, args) = dispatcher.build_command_parts(command); |
| 133 | |
| 134 | let env = { |
| 135 | #[cfg(windows)] |
| 136 | { |
| 137 | windows_shell_default_env() |
| 138 | } |
| 139 | #[cfg(not(windows))] |
| 140 | { |
| 141 | HashMap::new() |
| 142 | } |
| 143 | }; |
| 144 | |
| 145 | Self { |
| 146 | program, |
| 147 | args, |
| 148 | cwd, |
| 149 | env, |
| 150 | timeout, |
| 151 | sandbox_policy: SandboxPolicy::default(), |
| 152 | justification: None, |
| 153 | requested_command: Some(command.to_string()), |
| 154 | private_tmp: false, |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// Create a `CommandSpec` for running a program directly. |
| 159 | pub fn program(program: &str, args: Vec<String>, cwd: PathBuf, timeout: Duration) -> Self { |
| 160 | Self { |
| 161 | program: program.to_string(), |
| 162 | args, |
| 163 | cwd, |
| 164 | env: HashMap::new(), |
| 165 | timeout, |
| 166 | sandbox_policy: SandboxPolicy::default(), |
| 167 | justification: None, |
| 168 | requested_command: None, |
| 169 | private_tmp: false, |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// Set the sandbox policy for this command. |
| 174 | pub fn with_policy(mut self, policy: SandboxPolicy) -> Self { |
| 175 | self.sandbox_policy = policy; |
| 176 | self |
| 177 | } |
| 178 | |
| 179 | pub fn with_private_tmp(mut self) -> Self { |
| 180 | self.private_tmp = true; |
| 181 | self |
| 182 | } |
| 183 | |
| 184 | /// Add environment variables without discarding shell defaults. |
| 185 | pub fn with_env(mut self, env: HashMap<String, String>) -> Self { |
| 186 | for (key, value) in env { |
| 187 | self = self.with_env_var(&key, &value); |
| 188 | } |
| 189 | self |
| 190 | } |
| 191 | |
| 192 | /// Add a single environment variable. |
| 193 | pub fn with_env_var(mut self, key: &str, value: &str) -> Self { |
| 194 | #[cfg(windows)] |
| 195 | self.env |
| 196 | .retain(|existing, _| !existing.eq_ignore_ascii_case(key)); |
| 197 | self.env.insert(key.to_string(), value.to_string()); |
| 198 | self |
| 199 | } |
| 200 | |
| 201 | /// Set a justification for this command (for logging/audit). |
| 202 | #[cfg(test)] |
| 203 | pub fn with_justification(mut self, justification: &str) -> Self { |
| 204 | self.justification = Some(justification.to_string()); |
| 205 | self |
| 206 | } |
| 207 | |
| 208 | /// Get the original command as a single string (for display). |
| 209 | pub fn display_command(&self) -> String { |
| 210 | if let Some(requested) = &self.requested_command { |
| 211 | return requested.clone(); |
| 212 | } |
| 213 | if self.args.len() == 2 |
| 214 | && self.args[0] == "-c" |
| 215 | && matches!( |
| 216 | self.program.as_str(), |
| 217 | "sh" | "bash" | "/bin/sh" | "/bin/bash" | "/usr/bin/sh" | "/usr/bin/bash" |
| 218 | ) |
| 219 | { |
| 220 | // For shell commands, show the actual command |
| 221 | self.args[1].clone() |
| 222 | } else if self.args.len() == 2 |
| 223 | && self.args[0] == "-c" |
| 224 | && !self.program.eq_ignore_ascii_case("cmd") |
| 225 | && !self.program.eq_ignore_ascii_case("pwsh") |
| 226 | && !self.program.eq_ignore_ascii_case("pwsh.exe") |
| 227 | && !self.program.eq_ignore_ascii_case("powershell") |
| 228 | && !self.program.eq_ignore_ascii_case("powershell.exe") |
| 229 | { |
| 230 | self.args[1].clone() |
| 231 | } else if self.program.eq_ignore_ascii_case("cmd") |
| 232 | && self.args.len() == 2 |
| 233 | && self.args[0].eq_ignore_ascii_case("/C") |
| 234 | { |
| 235 | // Strip the `chcp 65001 >NUL & ` prefix we add on Windows for |
| 236 | // UTF-8 output (issue #982). |
| 237 | let raw = &self.args[1]; |
| 238 | raw.strip_prefix("chcp 65001 >NUL & ") |
| 239 | .unwrap_or(raw) |
| 240 | .to_string() |
| 241 | } else if { |
| 242 | let program = self.program.to_ascii_lowercase(); |
| 243 | program == "pwsh" |
| 244 | || program == "pwsh.exe" |
| 245 | || program == "powershell" |
| 246 | || program == "powershell.exe" |
| 247 | } && self.args.len() >= 3 |
| 248 | && self.args[0].eq_ignore_ascii_case("-NoProfile") |
| 249 | && self.args[1].eq_ignore_ascii_case("-Command") |
| 250 | { |
| 251 | // Strip the PowerShell encoding prefix. |
| 252 | let raw = &self.args[2]; |
| 253 | raw.strip_prefix("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ") |
| 254 | .unwrap_or(raw) |
| 255 | .to_string() |
| 256 | } else { |
| 257 | // For other commands, join program and args |
| 258 | let mut parts = vec![self.program.clone()]; |
| 259 | parts.extend(self.args.clone()); |
| 260 | parts.join(" ") |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | #[cfg(any(test, windows))] |
| 266 | fn windows_shell_default_env() -> HashMap<String, String> { |
| 267 | HashMap::from([("PYTHONIOENCODING".to_string(), "utf-8".to_string())]) |
| 268 | } |
| 269 | |
| 270 | /// The type of sandbox being used for execution. |
| 271 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 272 | pub enum SandboxType { |
| 273 | /// No sandboxing - command runs with full permissions. |
| 274 | #[default] |
| 275 | None, |
| 276 | |
| 277 | /// macOS Seatbelt (sandbox-exec) sandboxing. |
| 278 | #[cfg(target_os = "macos")] |
| 279 | MacosSeatbelt, |
| 280 | |
| 281 | /// Linux bubblewrap namespace sandboxing. |
| 282 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 283 | LinuxBubblewrap, |
| 284 | |
| 285 | /// Windows process-containment helper. |
| 286 | /// |
| 287 | /// Not advertised until a helper enforces Job Object cleanup. This does |
| 288 | /// not imply filesystem, network, registry, or AppContainer isolation. |
| 289 | #[cfg(target_os = "windows")] |
| 290 | Windows, |
| 291 | } |
| 292 | |
| 293 | impl std::fmt::Display for SandboxType { |
| 294 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 295 | match self { |
| 296 | SandboxType::None => write!(f, "none"), |
| 297 | #[cfg(target_os = "macos")] |
| 298 | SandboxType::MacosSeatbelt => write!(f, "macos-seatbelt"), |
| 299 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 300 | SandboxType::LinuxBubblewrap => write!(f, "linux-bwrap"), |
| 301 | #[cfg(target_os = "windows")] |
| 302 | SandboxType::Windows => write!(f, "windows-sandbox"), |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | /// The execution environment after sandbox transformation. |
| 308 | /// |
| 309 | /// This contains the actual command to run (which may include sandbox wrapper |
| 310 | /// commands) and all necessary environment configuration. |
| 311 | #[derive(Debug)] |
| 312 | pub struct ExecEnv { |
| 313 | /// The full command to execute (may include sandbox wrapper). |
| 314 | pub command: Vec<String>, |
| 315 | |
| 316 | /// Working directory for execution. |
| 317 | pub cwd: PathBuf, |
| 318 | |
| 319 | /// Environment variables to set. |
| 320 | pub env: HashMap<String, String>, |
| 321 | |
| 322 | /// Timeout for the command. |
| 323 | pub timeout: Duration, |
| 324 | |
| 325 | /// The type of sandbox being used. |
| 326 | pub sandbox_type: SandboxType, |
| 327 | |
| 328 | /// The original policy (for reference). |
| 329 | pub policy: SandboxPolicy, |
| 330 | |
| 331 | pub scratch: Option<ScratchDir>, |
| 332 | } |
| 333 | |
| 334 | #[derive(Debug)] |
| 335 | pub struct ScratchDir(Option<tempfile::TempDir>); |
| 336 | |
| 337 | impl ScratchDir { |
| 338 | pub fn path(&self) -> &std::path::Path { |
| 339 | self.0 |
| 340 | .as_ref() |
| 341 | .map_or_else(|| std::path::Path::new(""), tempfile::TempDir::path) |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | impl Drop for ScratchDir { |
| 346 | fn drop(&mut self) { |
| 347 | let Some(dir) = self.0.take() else { |
| 348 | return; |
| 349 | }; |
| 350 | let path = dir.path().to_path_buf(); |
| 351 | if dir.close().is_err() { |
| 352 | cleanup_scratch_tree(&path); |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | #[cfg(unix)] |
| 358 | fn clear_immutable_flags(path: &std::path::Path) { |
| 359 | #[cfg(target_os = "macos")] |
| 360 | { |
| 361 | use std::os::unix::ffi::OsStrExt; |
| 362 | if let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) { |
| 363 | unsafe { |
| 364 | let mut stat: libc::stat = std::mem::zeroed(); |
| 365 | if libc::lstat(c_path.as_ptr(), &mut stat) == 0 { |
| 366 | let cleared = stat.st_flags & !(libc::UF_IMMUTABLE | libc::UF_APPEND); |
| 367 | if cleared != stat.st_flags { |
| 368 | let _ = libc::lchflags(c_path.as_ptr(), cleared); |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | #[cfg(not(target_os = "macos"))] |
| 375 | let _ = path; |
| 376 | } |
| 377 | |
| 378 | #[cfg(unix)] |
| 379 | fn normalize_scratch_tree(path: &std::path::Path) { |
| 380 | use std::os::unix::fs::PermissionsExt; |
| 381 | clear_immutable_flags(path); |
| 382 | let Ok(meta) = std::fs::symlink_metadata(path) else { |
| 383 | return; |
| 384 | }; |
| 385 | if !meta.file_type().is_dir() { |
| 386 | return; |
| 387 | } |
| 388 | let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); |
| 389 | let Ok(entries) = std::fs::read_dir(path) else { |
| 390 | return; |
| 391 | }; |
| 392 | for entry in entries.flatten() { |
| 393 | let entry_path = entry.path(); |
| 394 | let Ok(file_type) = entry.file_type() else { |
| 395 | continue; |
| 396 | }; |
| 397 | if file_type.is_dir() { |
| 398 | normalize_scratch_tree(&entry_path); |
| 399 | } else if !file_type.is_symlink() { |
| 400 | clear_immutable_flags(&entry_path); |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | fn cleanup_scratch_tree(path: &std::path::Path) { |
| 406 | #[cfg(unix)] |
| 407 | { |
| 408 | let Ok(meta) = std::fs::symlink_metadata(path) else { |
| 409 | return; |
| 410 | }; |
| 411 | if !meta.file_type().is_dir() { |
| 412 | clear_immutable_flags(path); |
| 413 | let _ = std::fs::remove_file(path); |
| 414 | return; |
| 415 | } |
| 416 | normalize_scratch_tree(path); |
| 417 | } |
| 418 | let _ = std::fs::remove_dir_all(path); |
| 419 | } |
| 420 | |
| 421 | #[cfg(target_os = "macos")] |
| 422 | fn read_only_scratch(spec: &CommandSpec) -> Option<(ScratchDir, std::path::PathBuf)> { |
| 423 | if !spec.private_tmp || !matches!(spec.sandbox_policy, SandboxPolicy::ReadOnly { .. }) { |
| 424 | return None; |
| 425 | } |
| 426 | let canonical_cwd = spec.cwd.canonicalize().unwrap_or_else(|_| spec.cwd.clone()); |
| 427 | let outside_cwd = |path: &std::path::Path| { |
| 428 | canonical_cwd == std::path::Path::new("/") || !path.starts_with(&canonical_cwd) |
| 429 | }; |
| 430 | for parent in [ |
| 431 | seatbelt::darwin_user_temp_dir(), |
| 432 | Some(std::path::PathBuf::from("/private/tmp")), |
| 433 | ] |
| 434 | .into_iter() |
| 435 | .flatten() |
| 436 | { |
| 437 | if !outside_cwd(&parent) { |
| 438 | continue; |
| 439 | } |
| 440 | match tempfile::Builder::new() |
| 441 | .prefix("codewhale-ro-") |
| 442 | .tempdir_in(&parent) |
| 443 | { |
| 444 | Ok(dir) => { |
| 445 | let canonical = dir |
| 446 | .path() |
| 447 | .canonicalize() |
| 448 | .unwrap_or_else(|_| dir.path().to_path_buf()); |
| 449 | if outside_cwd(&canonical) { |
| 450 | return Some((ScratchDir(Some(dir)), canonical)); |
| 451 | } |
| 452 | } |
| 453 | Err(error) => { |
| 454 | tracing::warn!("read-only command runs without a private TMPDIR: {error}"); |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | None |
| 459 | } |
| 460 | |
| 461 | #[cfg(any( |
| 462 | target_os = "macos", |
| 463 | all(target_os = "linux", not(target_env = "ohos")) |
| 464 | ))] |
| 465 | fn insert_private_tmp_env(env: &mut HashMap<String, String>, dir: &std::path::Path) { |
| 466 | let dir = dir.to_string_lossy().into_owned(); |
| 467 | env.insert("TMPPREFIX".to_string(), format!("{dir}/zsh")); |
| 468 | for key in ["TMPDIR", "TMP", "TEMP"] { |
| 469 | env.insert(key.to_string(), dir.clone()); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | #[derive(Debug, Clone, Copy)] |
| 474 | pub struct SandboxResourceLimits { |
| 475 | pub address_space_bytes: u64, |
| 476 | pub file_size_bytes: u64, |
| 477 | pub open_files: u64, |
| 478 | pub processes: u64, |
| 479 | pub cpu_seconds: u64, |
| 480 | } |
| 481 | |
| 482 | impl ExecEnv { |
| 483 | /// Get the program to execute (first element of command). |
| 484 | pub fn program(&self) -> &str { |
| 485 | self.command |
| 486 | .first() |
| 487 | .map_or("sh", std::string::String::as_str) |
| 488 | } |
| 489 | |
| 490 | /// Get the arguments (all elements after the first). |
| 491 | pub fn args(&self) -> &[String] { |
| 492 | if self.command.len() > 1 { |
| 493 | &self.command[1..] |
| 494 | } else { |
| 495 | &[] |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | pub fn spawn_background( |
| 500 | &self, |
| 501 | mut command: std::process::Command, |
| 502 | ) -> std::io::Result<std::process::Child> { |
| 503 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 504 | if self.sandbox_type == SandboxType::LinuxBubblewrap { |
| 505 | return bwrap::spawn(move || command.spawn())?; |
| 506 | } |
| 507 | command.spawn() |
| 508 | } |
| 509 | |
| 510 | pub fn spawn_background_limited( |
| 511 | &self, |
| 512 | command: std::process::Command, |
| 513 | limits: SandboxResourceLimits, |
| 514 | ) -> std::io::Result<std::process::Child> { |
| 515 | #[cfg(unix)] |
| 516 | let mut command = command; |
| 517 | #[cfg(unix)] |
| 518 | { |
| 519 | use std::os::unix::process::CommandExt; |
| 520 | unsafe { |
| 521 | command.pre_exec(move || { |
| 522 | for (resource, value) in [ |
| 523 | (libc::RLIMIT_AS, limits.address_space_bytes), |
| 524 | (libc::RLIMIT_FSIZE, limits.file_size_bytes), |
| 525 | (libc::RLIMIT_NOFILE, limits.open_files), |
| 526 | (libc::RLIMIT_NPROC, limits.processes), |
| 527 | (libc::RLIMIT_CPU, limits.cpu_seconds), |
| 528 | ] { |
| 529 | let limit = libc::rlimit { |
| 530 | rlim_cur: value as libc::rlim_t, |
| 531 | rlim_max: value as libc::rlim_t, |
| 532 | }; |
| 533 | if libc::setrlimit(resource, &raw const limit) != 0 { |
| 534 | return Err(std::io::Error::last_os_error()); |
| 535 | } |
| 536 | } |
| 537 | Ok(()) |
| 538 | }); |
| 539 | } |
| 540 | } |
| 541 | #[cfg(not(unix))] |
| 542 | let _ = limits; |
| 543 | self.spawn_background(command) |
| 544 | } |
| 545 | |
| 546 | #[cfg(not(target_env = "ohos"))] |
| 547 | pub fn spawn_pty( |
| 548 | &self, |
| 549 | slave: Box<dyn portable_pty::SlavePty + Send>, |
| 550 | cwd: &std::path::Path, |
| 551 | ) -> anyhow::Result<Box<dyn portable_pty::Child + Send + Sync>> { |
| 552 | let mut command = portable_pty::CommandBuilder::new(self.program()); |
| 553 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 554 | if self.sandbox_type == SandboxType::LinuxBubblewrap { |
| 555 | let (bwrap_index, separator) = bwrap_target_split(&self.command) |
| 556 | .ok_or_else(|| anyhow::anyhow!("sandboxed PTY command is missing its target"))?; |
| 557 | anyhow::ensure!( |
| 558 | bwrap_index < separator, |
| 559 | "sandboxed PTY requires the configured bubblewrap wrapper" |
| 560 | ); |
| 561 | let setsid = ["/usr/bin/setsid", "/bin/setsid"] |
| 562 | .into_iter() |
| 563 | .find(|path| bwrap::is_executable(std::path::Path::new(path))) |
| 564 | .ok_or_else(|| { |
| 565 | anyhow::anyhow!("sandboxed PTY requires util-linux setsid; install util-linux") |
| 566 | })?; |
| 567 | command.args(&self.command[1..=separator]); |
| 568 | command.args([setsid, "--ctty", "--wait", "--"]); |
| 569 | command.args(&self.command[separator + 1..]); |
| 570 | command.set_controlling_tty(false); |
| 571 | } else { |
| 572 | command.args(self.args()); |
| 573 | } |
| 574 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 575 | command.args(self.args()); |
| 576 | command.cwd(cwd); |
| 577 | codewhale_runtime::child_env::apply_to_pty_command( |
| 578 | &mut command, |
| 579 | codewhale_runtime::child_env::string_map_env(&self.env), |
| 580 | ); |
| 581 | let launch = move || slave.spawn_command(command); |
| 582 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 583 | if self.sandbox_type == SandboxType::LinuxBubblewrap { |
| 584 | return bwrap::spawn(launch)?; |
| 585 | } |
| 586 | launch() |
| 587 | } |
| 588 | |
| 589 | /// Check if this execution is sandboxed. |
| 590 | pub fn is_sandboxed(&self) -> bool { |
| 591 | !matches!(self.sandbox_type, SandboxType::None) |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | /// Detect what sandbox technology is available on the current platform. |
| 596 | #[cfg(test)] |
| 597 | pub fn get_platform_sandbox() -> Option<SandboxType> { |
| 598 | get_platform_sandbox_with_bwrap_preference(false) |
| 599 | } |
| 600 | |
| 601 | /// Detect the sandbox wrapper the configured command path can actually use. |
| 602 | /// |
| 603 | /// Linux bubblewrap is on by default via `Config::prefers_bwrap` (an |
| 604 | /// explicit `prefer_bwrap = false` opts out) and only selected when a real |
| 605 | /// wrapped probe run proves it works on this host. Source-only sandbox |
| 606 | /// prototypes do not make commands sandboxed unless the child launch path |
| 607 | /// applies them. |
| 608 | pub fn get_platform_sandbox_with_bwrap_preference(prefer_bwrap: bool) -> Option<SandboxType> { |
| 609 | #[cfg(target_os = "macos")] |
| 610 | { |
| 611 | if seatbelt::is_available() { |
| 612 | return Some(SandboxType::MacosSeatbelt); |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 617 | { |
| 618 | if prefer_bwrap && bwrap::is_available() { |
| 619 | return Some(SandboxType::LinuxBubblewrap); |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 624 | let _ = prefer_bwrap; |
| 625 | |
| 626 | #[cfg(target_os = "windows")] |
| 627 | { |
| 628 | if windows::is_available() { |
| 629 | return Some(SandboxType::Windows); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | None |
| 634 | } |
| 635 | |
| 636 | /// Check if sandboxing is available on this platform. |
| 637 | #[cfg(test)] |
| 638 | pub fn is_sandbox_available() -> bool { |
| 639 | get_platform_sandbox().is_some() |
| 640 | } |
| 641 | |
| 642 | /// Why the configured Linux launcher is installed but cannot start a confined |
| 643 | /// child, if that is the case. |
| 644 | /// |
| 645 | /// `None` covers both "the launcher works" and "no launcher is installed": |
| 646 | /// the documented no-launcher fallback is not a failure to report. Platforms |
| 647 | /// without bubblewrap leave the selection path unchanged. |
| 648 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 649 | fn installed_launcher_failure() -> Option<&'static str> { |
| 650 | bwrap::probe_failure() |
| 651 | } |
| 652 | |
| 653 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 654 | fn installed_launcher_failure() -> Option<&'static str> { |
| 655 | None |
| 656 | } |
| 657 | |
| 658 | #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))] |
| 659 | fn bwrap_target_split(command: &[String]) -> Option<(usize, usize)> { |
| 660 | let bwrap_index = command.iter().position(|arg| arg == "/usr/bin/bwrap")?; |
| 661 | let separator = command[bwrap_index + 1..] |
| 662 | .iter() |
| 663 | .position(|arg| arg == "--") |
| 664 | .map(|offset| bwrap_index + 1 + offset) |
| 665 | .filter(|index| index + 1 < command.len())?; |
| 666 | Some((bwrap_index, separator)) |
| 667 | } |
| 668 | |
| 669 | pub fn bwrap_setup_failure(stderr: &str) -> Option<&str> { |
| 670 | stderr |
| 671 | .lines() |
| 672 | .map(str::trim_start) |
| 673 | .find(|line| line.starts_with("bwrap:")) |
| 674 | } |
| 675 | |
| 676 | /// Resolve `strerror(errno)` for the active environment `LC_MESSAGES` locale |
| 677 | /// without mutating the process-global locale or child environment. |
| 678 | #[cfg(any( |
| 679 | target_os = "macos", |
| 680 | all(target_os = "linux", not(target_env = "ohos")) |
| 681 | ))] |
| 682 | pub(crate) fn localized_errno_message(errno: libc::c_int) -> Option<String> { |
| 683 | // SAFETY: `newlocale`, `uselocale`, `strerror_r`, and `freelocale` operate |
| 684 | // only on the calling thread's locale and a stack-owned NUL-terminated buffer. |
| 685 | unsafe { |
| 686 | let loc = libc::newlocale(libc::LC_MESSAGES_MASK, c"".as_ptr(), std::ptr::null_mut()); |
| 687 | if loc.is_null() { |
| 688 | return None; |
| 689 | } |
| 690 | let prev = libc::uselocale(loc); |
| 691 | let mut buf = [0 as libc::c_char; 256]; |
| 692 | let rc = libc::strerror_r(errno, buf.as_mut_ptr(), buf.len()); |
| 693 | if !prev.is_null() { |
| 694 | libc::uselocale(prev); |
| 695 | } |
| 696 | libc::freelocale(loc); |
| 697 | if rc != 0 { |
| 698 | return None; |
| 699 | } |
| 700 | buf[buf.len() - 1] = 0; |
| 701 | let msg = std::ffi::CStr::from_ptr(buf.as_ptr()).to_str().ok()?; |
| 702 | (!msg.is_empty()).then(|| msg.to_string()) |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | /// Manager for sandbox operations. |
| 707 | /// |
| 708 | /// User-configured bwrap bind-mount extensions (#5410). |
| 709 | /// |
| 710 | /// The default `--ro-bind / /` already exposes the host filesystem |
| 711 | /// read-only, so extra read-only roots are rarely needed; they exist for |
| 712 | /// setups where a policy or a future default narrows the root bind. Device |
| 713 | /// roots cover host device nodes that must stay writable (e.g. `/dev/null` |
| 714 | /// for redirection) — under a read-only root bind `open(O_WRONLY)` on such |
| 715 | /// nodes fails with `EROFS`, which is the original #5410 report. |
| 716 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 717 | pub struct BwrapMountExtensions { |
| 718 | /// Extra host paths to bind read-only inside the sandbox. Non-existent |
| 719 | /// or non-directory paths are skipped silently (same rule as writable |
| 720 | /// roots — a sandbox must never fail to start because config went |
| 721 | /// stale). |
| 722 | pub read_only_roots: Vec<PathBuf>, |
| 723 | /// Host device-node paths to bind read-write (e.g. `/dev/null`). |
| 724 | /// Non-existent paths are skipped; paths that exist but are not |
| 725 | /// character/block devices are skipped too — this key must never become |
| 726 | /// a general writable-root escape hatch. |
| 727 | pub device_roots: Vec<PathBuf>, |
| 728 | } |
| 729 | |
| 730 | impl BwrapMountExtensions { |
| 731 | /// Resolve configured paths against the live filesystem, returning |
| 732 | /// `(read_only_mounts, device_mounts)` as canonical paths that exist and |
| 733 | /// satisfy each key's constraints. The bwrap module only exists on |
| 734 | /// Linux, so the resolution inlines the same two checks its |
| 735 | /// `existing_directory` performs (canonicalize + is_dir) — the type is |
| 736 | /// carried on every platform because `SandboxManager` is. |
| 737 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 738 | fn resolve(&self) -> (Vec<PathBuf>, Vec<PathBuf>) { |
| 739 | let read_only = self |
| 740 | .read_only_roots |
| 741 | .iter() |
| 742 | .filter_map(|path| bwrap::existing_directory_shim(path)) |
| 743 | .filter(|path| path != std::path::Path::new("/")) |
| 744 | .collect(); |
| 745 | let devices = self |
| 746 | .device_roots |
| 747 | .iter() |
| 748 | .filter_map(|path| { |
| 749 | let canonical = path.canonicalize().ok()?; |
| 750 | let meta = std::fs::metadata(&canonical).ok()?; |
| 751 | use std::os::unix::fs::FileTypeExt; |
| 752 | let file_type = meta.file_type(); |
| 753 | (file_type.is_char_device() || file_type.is_block_device()).then_some(canonical) |
| 754 | }) |
| 755 | .collect(); |
| 756 | (read_only, devices) |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | /// Expand a leading `~` or `~/` to the user's home directory. Paths without |
| 761 | /// the prefix (and any path when no home directory is resolvable) pass |
| 762 | /// through unchanged. |
| 763 | fn expand_home_prefix(path: PathBuf) -> PathBuf { |
| 764 | let Some(text) = path.to_str() else { |
| 765 | return path; |
| 766 | }; |
| 767 | if text == "~" { |
| 768 | return dirs::home_dir().unwrap_or(path); |
| 769 | } |
| 770 | if let Some(rest) = text.strip_prefix("~/") |
| 771 | && let Some(home) = dirs::home_dir() |
| 772 | { |
| 773 | return home.join(rest); |
| 774 | } |
| 775 | path |
| 776 | } |
| 777 | |
| 778 | /// The bubblewrap arguments that hide `path` from a sandboxed command, aimed |
| 779 | /// at its resolved location because bubblewrap cannot mount through a |
| 780 | /// symlink: an empty tmpfs over an existing directory, `/dev/null` bound over |
| 781 | /// an existing file, nothing for a path that does not exist (there is nothing |
| 782 | /// to deny). Blocking. Platform-neutral so it is exercised on every host; only |
| 783 | /// the Linux bwrap builder emits it. |
| 784 | #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))] |
| 785 | fn bwrap_mask_args(path: &std::path::Path) -> Vec<String> { |
| 786 | let Ok(resolved) = std::fs::canonicalize(path) else { |
| 787 | return Vec::new(); |
| 788 | }; |
| 789 | let spelled = resolved.to_string_lossy().into_owned(); |
| 790 | if resolved.is_dir() { |
| 791 | vec!["--tmpfs".to_string(), spelled] |
| 792 | } else { |
| 793 | vec!["--ro-bind".to_string(), "/dev/null".to_string(), spelled] |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | /// Arguments appended after the read deny-list masks so `exceptions` inside |
| 798 | /// a masked directory stay visible. Only a denied directory that holds an |
| 799 | /// existing exception opens up again: each such exception is bound read-only |
| 800 | /// again, then each (canonical) writable root strictly inside such a |
| 801 | /// directory is bound writable again, then every denied path strictly inside |
| 802 | /// what was bound again is masked again, so an exception never re-exposes a |
| 803 | /// denied path. Any other denied directory stays masked over whatever lies |
| 804 | /// inside it, writable roots included. Empty, without touching the |
| 805 | /// filesystem, when there are no exceptions (every caller but the extension |
| 806 | /// host). Blocking (resolves paths). |
| 807 | /// |
| 808 | /// This is how the extension host denies a Codewhale home whole — including |
| 809 | /// entries created after it started, which a per-entry mask cannot cover — |
| 810 | /// while its bundle, data dir and plugin code stay reachable. |
| 811 | /// |
| 812 | /// Known limits: an exception or writable root that does not exist when the |
| 813 | /// command starts stays hidden for its lifetime; a protected descendant |
| 814 | /// (`.codewhale` inside a writable root) or an extra read-only root inside a |
| 815 | /// masked directory is not re-applied. Only the extension host sets |
| 816 | /// exceptions, and its data dir has neither. |
| 817 | #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))] |
| 818 | fn bwrap_exception_args( |
| 819 | denied: &[PathBuf], |
| 820 | exceptions: &[PathBuf], |
| 821 | writable_roots: &[PathBuf], |
| 822 | ) -> Vec<String> { |
| 823 | if exceptions.is_empty() { |
| 824 | return Vec::new(); |
| 825 | } |
| 826 | let canonical = |path: &PathBuf| std::fs::canonicalize(path).ok(); |
| 827 | let strictly_inside = |path: &std::path::Path, roots: &[PathBuf]| { |
| 828 | roots |
| 829 | .iter() |
| 830 | .any(|root| path != root.as_path() && path.starts_with(root)) |
| 831 | }; |
| 832 | let exceptions: Vec<PathBuf> = exceptions.iter().filter_map(canonical).collect(); |
| 833 | let opened: Vec<PathBuf> = denied |
| 834 | .iter() |
| 835 | .filter(|path| path.is_dir()) |
| 836 | .filter_map(canonical) |
| 837 | .filter(|dir| { |
| 838 | exceptions |
| 839 | .iter() |
| 840 | .any(|exception| strictly_inside(exception, std::slice::from_ref(dir))) |
| 841 | }) |
| 842 | .collect(); |
| 843 | let mut rebound: Vec<PathBuf> = Vec::new(); |
| 844 | let mut args = Vec::new(); |
| 845 | let mut candidates: Vec<(&PathBuf, bool)> = exceptions |
| 846 | .iter() |
| 847 | .map(|path| (path, true)) |
| 848 | .chain(writable_roots.iter().map(|path| (path, false))) |
| 849 | .collect(); |
| 850 | candidates.sort_unstable(); |
| 851 | for (path, is_read_only) in candidates { |
| 852 | let flag = if is_read_only { "--ro-bind" } else { "--bind" }; |
| 853 | if strictly_inside(path, &opened) && !rebound.contains(path) { |
| 854 | let spelled = path.to_string_lossy().into_owned(); |
| 855 | args.extend([flag.to_string(), spelled.clone(), spelled]); |
| 856 | rebound.push(path.clone()); |
| 857 | } |
| 858 | } |
| 859 | for path in denied { |
| 860 | if canonical(path).is_some_and(|resolved| strictly_inside(&resolved, &rebound)) { |
| 861 | args.extend(bwrap_mask_args(path)); |
| 862 | } |
| 863 | } |
| 864 | args |
| 865 | } |
| 866 | |
| 867 | /// The `SandboxManager` is responsible for: |
| 868 | /// - Detecting available sandbox technologies |
| 869 | /// - Transforming `CommandSpecs` into sandboxed `ExecEnvs` |
| 870 | /// - Detecting sandbox denials from command output |
| 871 | #[derive(Debug, Default)] |
| 872 | pub struct SandboxManager { |
| 873 | /// Cached sandbox availability check. |
| 874 | sandbox_available: Option<bool>, |
| 875 | |
| 876 | /// Force a specific sandbox type (for testing). |
| 877 | forced_sandbox: Option<SandboxType>, |
| 878 | |
| 879 | /// When true and bwrap is executable on Linux, route commands through |
| 880 | /// bubblewrap (#2184). |
| 881 | prefer_bwrap: bool, |
| 882 | |
| 883 | /// User-configured bwrap bind-mount extensions (#5410): extra |
| 884 | /// read-only roots and writable device nodes. |
| 885 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 886 | bwrap_extensions: BwrapMountExtensions, |
| 887 | |
| 888 | /// Opt-in read deny-list (S1, #5568): paths sandboxed commands must not |
| 889 | /// be able to read even though the sandbox otherwise grants full-disk |
| 890 | /// read (Seatbelt appends last-match-wins deny rules; bubblewrap masks |
| 891 | /// each path). Empty by default — today's behavior unchanged. |
| 892 | #[cfg(any( |
| 893 | test, |
| 894 | target_os = "macos", |
| 895 | all(target_os = "linux", not(target_env = "ohos")) |
| 896 | ))] |
| 897 | denied_read_subpaths: Vec<PathBuf>, |
| 898 | |
| 899 | /// Paths inside a denied directory that stay visible (bubblewrap only, |
| 900 | /// `bwrap_exception_args`; Seatbelt ignores this list). Empty by |
| 901 | /// default. |
| 902 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 903 | denied_read_exceptions: Vec<PathBuf>, |
| 904 | #[cfg(any( |
| 905 | target_os = "macos", |
| 906 | all(target_os = "linux", not(target_env = "ohos")) |
| 907 | ))] |
| 908 | readable_paths: Option<Vec<PathBuf>>, |
| 909 | |
| 910 | tool_launcher: Option<Vec<String>>, |
| 911 | } |
| 912 | |
| 913 | impl SandboxManager { |
| 914 | /// Create a new `SandboxManager`. |
| 915 | pub fn new() -> Self { |
| 916 | Self::default() |
| 917 | } |
| 918 | |
| 919 | /// Create a new `SandboxManager` with bwrap preference (#2184). |
| 920 | /// |
| 921 | /// When `prefer_bwrap` is true and `/usr/bin/bwrap` is executable on Linux, |
| 922 | /// exec_shell commands will be routed through bubblewrap. |
| 923 | pub fn with_bwrap_preference(prefer_bwrap: bool) -> Self { |
| 924 | Self { |
| 925 | prefer_bwrap, |
| 926 | ..Self::default() |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | /// Set the bwrap preference (#2184). |
| 931 | pub fn set_prefer_bwrap(&mut self, prefer: bool) { |
| 932 | self.prefer_bwrap = prefer; |
| 933 | self.sandbox_available = None; |
| 934 | } |
| 935 | |
| 936 | /// Set user-configured bwrap mount extensions (#5410): extra read-only |
| 937 | /// roots and writable device nodes such as `/dev/null`. |
| 938 | pub fn set_bwrap_extensions(&mut self, extensions: BwrapMountExtensions) { |
| 939 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 940 | { |
| 941 | self.bwrap_extensions = extensions; |
| 942 | } |
| 943 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 944 | let _ = extensions; |
| 945 | } |
| 946 | |
| 947 | /// Set the opt-in read deny-list (S1, #5568). A leading `~` in a path |
| 948 | /// expands to the user's home directory here, and each existing path is |
| 949 | /// ALSO recorded in canonicalized form when that differs: macOS Seatbelt |
| 950 | /// matches the kernel-resolved path, so a rule written against |
| 951 | /// `/var/...` alone never fires for the real `/private/var/...` file — |
| 952 | /// the deny must name both spellings to actually deny. |
| 953 | pub fn set_denied_read_subpaths(&mut self, paths: Vec<PathBuf>) { |
| 954 | let mut resolved: Vec<PathBuf> = Vec::with_capacity(paths.len()); |
| 955 | for path in paths.into_iter().map(expand_home_prefix) { |
| 956 | if let Ok(canonical) = std::fs::canonicalize(&path) |
| 957 | && canonical != path |
| 958 | && !resolved.contains(&canonical) |
| 959 | { |
| 960 | resolved.push(canonical); |
| 961 | } |
| 962 | if !resolved.contains(&path) { |
| 963 | resolved.push(path); |
| 964 | } |
| 965 | } |
| 966 | #[cfg(any( |
| 967 | test, |
| 968 | target_os = "macos", |
| 969 | all(target_os = "linux", not(target_env = "ohos")) |
| 970 | ))] |
| 971 | { |
| 972 | self.denied_read_subpaths = resolved; |
| 973 | } |
| 974 | #[cfg(not(any( |
| 975 | test, |
| 976 | target_os = "macos", |
| 977 | all(target_os = "linux", not(target_env = "ohos")) |
| 978 | )))] |
| 979 | let _ = resolved; |
| 980 | } |
| 981 | |
| 982 | /// Set the paths inside a denied directory that stay visible under |
| 983 | /// bubblewrap (`bwrap_exception_args`). The extension host uses it to |
| 984 | /// deny a Codewhale home whole while keeping its own files and plugin |
| 985 | /// code readable. |
| 986 | pub fn set_denied_read_exceptions(&mut self, paths: Vec<PathBuf>) { |
| 987 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 988 | { |
| 989 | self.denied_read_exceptions = paths; |
| 990 | } |
| 991 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 992 | let _ = paths; |
| 993 | } |
| 994 | |
| 995 | pub fn set_readable_paths(&mut self, paths: Vec<PathBuf>) { |
| 996 | #[cfg(any( |
| 997 | target_os = "macos", |
| 998 | all(target_os = "linux", not(target_env = "ohos")) |
| 999 | ))] |
| 1000 | { |
| 1001 | self.readable_paths = Some(paths); |
| 1002 | } |
| 1003 | #[cfg(not(any( |
| 1004 | target_os = "macos", |
| 1005 | all(target_os = "linux", not(target_env = "ohos")) |
| 1006 | )))] |
| 1007 | let _ = paths; |
| 1008 | } |
| 1009 | |
| 1010 | /// Run every prepared command through `launcher`, an argv prefix that |
| 1011 | /// changes the user commands run as (for example |
| 1012 | /// `sudo -n -u <user> -- <exec-wrapper>`). It stands in front of |
| 1013 | /// bubblewrap, because every unprivileged confinement sets |
| 1014 | /// no-new-privileges and a setuid launcher inside it cannot switch user. |
| 1015 | /// Only the managed configuration layer can set it (`Config::tool_launcher`). |
| 1016 | /// |
| 1017 | /// With a launcher, a command always runs under bubblewrap or not at all: |
| 1018 | /// a policy that would leave it unwrapped (`danger-full-access`, an |
| 1019 | /// external sandbox), `prefer_bwrap = false`, a failed probe through the |
| 1020 | /// launcher, or a non-Linux host refuses the command. Masks and binds are |
| 1021 | /// computed for the launcher's user on every command: a path whose |
| 1022 | /// ancestors that user cannot search is masked at the highest such |
| 1023 | /// ancestor, or dropped when it is a bind. Each command gets a private |
| 1024 | /// `/tmp` instead of the host's. |
| 1025 | /// |
| 1026 | /// Known limitations: it covers only commands prepared here (shell |
| 1027 | /// commands, PTY sessions and workspace runners). In-process file tools, |
| 1028 | /// MCP servers, hooks, LSP servers and the extension host still run as the |
| 1029 | /// Engine's own user. Deny-list exceptions are not applied, so a denied |
| 1030 | /// directory stays masked whole. Search rights are read from mode bits and |
| 1031 | /// group membership; ACLs are not consulted. Processes still run after the |
| 1032 | /// Engine itself dies, until bubblewrap's parent exits. |
| 1033 | pub fn set_tool_launcher(&mut self, launcher: Option<Vec<String>>) { |
| 1034 | self.tool_launcher = launcher.filter(|argv| !argv.is_empty()); |
| 1035 | self.sandbox_available = None; |
| 1036 | } |
| 1037 | |
| 1038 | pub fn tool_launcher_active(&self) -> bool { |
| 1039 | self.tool_launcher.is_some() |
| 1040 | } |
| 1041 | |
| 1042 | /// Test-only view of the resolved deny-list (post home-expansion and |
| 1043 | /// canonicalization). |
| 1044 | #[cfg(test)] |
| 1045 | pub fn denied_read_subpaths_for_test(&self) -> &[PathBuf] { |
| 1046 | &self.denied_read_subpaths |
| 1047 | } |
| 1048 | |
| 1049 | /// Check if sandboxing is available. |
| 1050 | pub fn is_available(&mut self) -> bool { |
| 1051 | if let Some(available) = self.sandbox_available { |
| 1052 | return available; |
| 1053 | } |
| 1054 | |
| 1055 | let available = self.configured_sandbox().is_some(); |
| 1056 | self.sandbox_available = Some(available); |
| 1057 | available |
| 1058 | } |
| 1059 | |
| 1060 | /// Return the wrapper this manager is configured and able to apply. |
| 1061 | pub fn configured_sandbox(&self) -> Option<SandboxType> { |
| 1062 | if self.tool_launcher.is_some() { |
| 1063 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1064 | return self |
| 1065 | .launcher_identity() |
| 1066 | .ok() |
| 1067 | .map(|_| SandboxType::LinuxBubblewrap); |
| 1068 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 1069 | return None; |
| 1070 | } |
| 1071 | get_platform_sandbox_with_bwrap_preference(self.prefer_bwrap) |
| 1072 | } |
| 1073 | |
| 1074 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1075 | fn launcher_identity(&self) -> Result<bwrap::LaunchIdentity, String> { |
| 1076 | let launcher = self |
| 1077 | .tool_launcher |
| 1078 | .as_deref() |
| 1079 | .ok_or_else(|| "no tool launcher is configured".to_string())?; |
| 1080 | if !self.prefer_bwrap { |
| 1081 | return Err( |
| 1082 | "tool_launcher needs bubblewrap, and prefer_bwrap = false turns it off".to_string(), |
| 1083 | ); |
| 1084 | } |
| 1085 | bwrap::probe_launcher(launcher, &self.denied_read_subpaths) |
| 1086 | } |
| 1087 | |
| 1088 | /// Select the appropriate sandbox type for the given policy. |
| 1089 | pub fn select_sandbox(&self, policy: &SandboxPolicy) -> SandboxType { |
| 1090 | // If the policy doesn't want sandboxing, return None |
| 1091 | if !policy.should_sandbox() { |
| 1092 | return SandboxType::None; |
| 1093 | } |
| 1094 | |
| 1095 | // Check for forced sandbox (testing) |
| 1096 | if let Some(forced) = self.forced_sandbox { |
| 1097 | return forced; |
| 1098 | } |
| 1099 | |
| 1100 | self.configured_sandbox().unwrap_or(SandboxType::None) |
| 1101 | } |
| 1102 | |
| 1103 | /// Transform a `CommandSpec` into a sandboxed `ExecEnv`. |
| 1104 | /// |
| 1105 | /// This is the main entry point for sandboxing. It takes a command |
| 1106 | /// specification and returns the actual command to run, which may |
| 1107 | /// include sandbox wrapper commands. |
| 1108 | pub fn prepare(&self, spec: &CommandSpec) -> ExecEnv { |
| 1109 | self.prepare_with_probe_failure(spec, installed_launcher_failure()) |
| 1110 | } |
| 1111 | |
| 1112 | /// Like [`Self::prepare`], but a command that must not run (a tool |
| 1113 | /// launcher whose sandbox cannot be applied, or an installed sandbox that |
| 1114 | /// fails its own probe) is an error naming why. |
| 1115 | pub fn try_prepare(&self, spec: &CommandSpec) -> Result<ExecEnv, String> { |
| 1116 | self.try_prepare_with_probe_failure(spec, installed_launcher_failure()) |
| 1117 | } |
| 1118 | |
| 1119 | fn prepare_with_probe_failure( |
| 1120 | &self, |
| 1121 | spec: &CommandSpec, |
| 1122 | probe_failure: Option<&str>, |
| 1123 | ) -> ExecEnv { |
| 1124 | self.try_prepare_with_probe_failure(spec, probe_failure) |
| 1125 | .unwrap_or_else(|reason| Self::prepare_refusal(spec, &reason)) |
| 1126 | } |
| 1127 | |
| 1128 | fn try_prepare_with_probe_failure( |
| 1129 | &self, |
| 1130 | spec: &CommandSpec, |
| 1131 | probe_failure: Option<&str>, |
| 1132 | ) -> Result<ExecEnv, String> { |
| 1133 | if self.tool_launcher.is_some() { |
| 1134 | return self.prepare_launched(spec); |
| 1135 | } |
| 1136 | if let Some(reason) = self.sandbox_probe_failure(&spec.sandbox_policy, probe_failure) { |
| 1137 | return Err(reason); |
| 1138 | } |
| 1139 | let sandbox_type = self.select_sandbox(&spec.sandbox_policy); |
| 1140 | |
| 1141 | Ok(match sandbox_type { |
| 1142 | SandboxType::None => Self::prepare_unsandboxed(spec), |
| 1143 | |
| 1144 | #[cfg(target_os = "macos")] |
| 1145 | SandboxType::MacosSeatbelt => self.prepare_seatbelt(spec), |
| 1146 | |
| 1147 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1148 | SandboxType::LinuxBubblewrap => self.prepare_bwrap(spec, None), |
| 1149 | |
| 1150 | #[cfg(target_os = "windows")] |
| 1151 | SandboxType::Windows => Self::prepare_windows(spec), |
| 1152 | }) |
| 1153 | } |
| 1154 | |
| 1155 | /// Refuse a posture that promises an OS sandbox when the configured |
| 1156 | /// launcher is installed but fails its own probe. |
| 1157 | /// |
| 1158 | /// A launcher that is not installed, a platform without one, a disabled |
| 1159 | /// sandbox and the documented `prefer_bwrap = false` opt-out all keep the |
| 1160 | /// policy-only fallback. This covers only the fault case: the boundary the |
| 1161 | /// posture names is configured, but the launcher that must apply it cannot |
| 1162 | /// start, so the command is refused instead of being run on the host. |
| 1163 | fn sandbox_probe_failure( |
| 1164 | &self, |
| 1165 | policy: &SandboxPolicy, |
| 1166 | probe_failure: Option<&str>, |
| 1167 | ) -> Option<String> { |
| 1168 | // Read-only keeps its existing engine-side rule: arbitrary commands require native |
| 1169 | // enforcement, while the separately hardened allowlisted argv may run without it. This |
| 1170 | // gate is for workspace-write, whose boundary exists only in the bubblewrap wrapper. |
| 1171 | if !matches!(policy, SandboxPolicy::WorkspaceWrite { .. }) |
| 1172 | || !self.prefer_bwrap |
| 1173 | || self.tool_launcher.is_some() |
| 1174 | || self.forced_sandbox.is_some() |
| 1175 | { |
| 1176 | return None; |
| 1177 | } |
| 1178 | let reason = probe_failure?; |
| 1179 | Some(format!( |
| 1180 | "the {} policy needs an OS sandbox, and the installed bubblewrap cannot start one on this host, so nothing was run: {reason}. Install or repair bubblewrap, or set prefer_bwrap = false to opt out explicitly", |
| 1181 | policy.config_value() |
| 1182 | )) |
| 1183 | } |
| 1184 | |
| 1185 | fn prepare_launched(&self, spec: &CommandSpec) -> Result<ExecEnv, String> { |
| 1186 | if !spec.sandbox_policy.should_sandbox() { |
| 1187 | return Err(format!( |
| 1188 | "this host runs tool commands as another user, and only inside the sandbox; the {} policy would run this command without it, so nothing was run", |
| 1189 | spec.sandbox_policy.posture_label() |
| 1190 | )); |
| 1191 | } |
| 1192 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1193 | { |
| 1194 | let identity = self.launcher_identity().map_err(|error| { |
| 1195 | format!( |
| 1196 | "this host runs tool commands as another user, and the sandbox cannot start through its launcher, so nothing was run: {error}" |
| 1197 | ) |
| 1198 | })?; |
| 1199 | let mut env = self.prepare_bwrap(spec, Some(&identity)); |
| 1200 | let mut command = self.tool_launcher.clone().unwrap_or_default(); |
| 1201 | command.append(&mut env.command); |
| 1202 | env.command = command; |
| 1203 | Ok(env) |
| 1204 | } |
| 1205 | #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))] |
| 1206 | { |
| 1207 | Err("tool_launcher works only on Linux, so nothing was run".to_string()) |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | fn prepare_refusal(spec: &CommandSpec, reason: &str) -> ExecEnv { |
| 1212 | ExecEnv { |
| 1213 | command: vec![ |
| 1214 | "/bin/sh".to_string(), |
| 1215 | "-c".to_string(), |
| 1216 | "printf 'codewhale: %s\\n' \"$1\" >&2; exit 126".to_string(), |
| 1217 | "codewhale-refusal".to_string(), |
| 1218 | reason.to_string(), |
| 1219 | ], |
| 1220 | cwd: spec.cwd.clone(), |
| 1221 | env: HashMap::new(), |
| 1222 | timeout: spec.timeout, |
| 1223 | sandbox_type: SandboxType::None, |
| 1224 | policy: spec.sandbox_policy.clone(), |
| 1225 | scratch: None, |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | /// Prepare an unsandboxed execution environment. |
| 1230 | fn prepare_unsandboxed(spec: &CommandSpec) -> ExecEnv { |
| 1231 | let mut command = vec![spec.program.clone()]; |
| 1232 | command.extend(spec.args.clone()); |
| 1233 | |
| 1234 | ExecEnv { |
| 1235 | command, |
| 1236 | cwd: spec.cwd.clone(), |
| 1237 | env: spec.env.clone(), |
| 1238 | timeout: spec.timeout, |
| 1239 | sandbox_type: SandboxType::None, |
| 1240 | policy: spec.sandbox_policy.clone(), |
| 1241 | scratch: None, |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | /// Prepare a Seatbelt-sandboxed execution environment (macOS). |
| 1246 | #[cfg(target_os = "macos")] |
| 1247 | fn prepare_seatbelt(&self, spec: &CommandSpec) -> ExecEnv { |
| 1248 | // Build the original command |
| 1249 | let mut original_command = vec![spec.program.clone()]; |
| 1250 | original_command.extend(spec.args.clone()); |
| 1251 | |
| 1252 | let (scratch, scratch_path) = if self.readable_paths.is_none() { |
| 1253 | match read_only_scratch(spec) { |
| 1254 | Some((dir, path)) => (Some(dir), Some(path)), |
| 1255 | None => (None, None), |
| 1256 | } |
| 1257 | } else { |
| 1258 | (None, None) |
| 1259 | }; |
| 1260 | |
| 1261 | // Generate sandbox-exec arguments |
| 1262 | let seatbelt_args = if let Some(paths) = &self.readable_paths { |
| 1263 | seatbelt::create_restricted_seatbelt_args( |
| 1264 | original_command, |
| 1265 | &spec.cwd, |
| 1266 | paths, |
| 1267 | &self.denied_read_subpaths, |
| 1268 | ) |
| 1269 | } else { |
| 1270 | seatbelt::create_seatbelt_args( |
| 1271 | original_command, |
| 1272 | &spec.sandbox_policy, |
| 1273 | &spec.cwd, |
| 1274 | &self.denied_read_subpaths, |
| 1275 | scratch_path.as_deref(), |
| 1276 | ) |
| 1277 | }; |
| 1278 | |
| 1279 | // Prepend sandbox-exec to the command |
| 1280 | let mut command = vec![seatbelt::SANDBOX_EXEC_PATH.to_string()]; |
| 1281 | command.extend(seatbelt_args); |
| 1282 | |
| 1283 | // Add sandbox indicator to environment |
| 1284 | let mut env = spec.env.clone(); |
| 1285 | env.insert("CODEWHALE_SANDBOX".to_string(), "seatbelt".to_string()); |
| 1286 | env.insert("DEEPSEEK_SANDBOX".to_string(), "seatbelt".to_string()); |
| 1287 | if let Some(path) = &scratch_path { |
| 1288 | insert_private_tmp_env(&mut env, path); |
| 1289 | } |
| 1290 | |
| 1291 | ExecEnv { |
| 1292 | command, |
| 1293 | cwd: spec.cwd.clone(), |
| 1294 | env, |
| 1295 | timeout: spec.timeout, |
| 1296 | sandbox_type: SandboxType::MacosSeatbelt, |
| 1297 | policy: spec.sandbox_policy.clone(), |
| 1298 | scratch, |
| 1299 | } |
| 1300 | } |
| 1301 | |
| 1302 | /// Prepare a bubblewrap-sandboxed execution environment (Linux). |
| 1303 | /// |
| 1304 | /// Carries the standard container trio `--dev /dev`, `--proc /proc`, |
| 1305 | /// `--tmpfs /tmp` (#5410): without a private `/dev`, host device nodes |
| 1306 | /// inherited through the read-only root bind reject `open(O_WRONLY)` |
| 1307 | /// with `EROFS` — `foo >/dev/null` was the original report — and |
| 1308 | /// without `/proc`, toolchains that read process tables misbehave. |
| 1309 | /// `/tmp` starts as a private tmpfs; a `workspace-write` policy binds the |
| 1310 | /// host `/tmp` and `TMPDIR` over it unless it excludes them, except under |
| 1311 | /// a tool launcher, where `/tmp` stays private. User-configured |
| 1312 | /// extensions (extra read-only roots, writable device nodes) apply after |
| 1313 | /// the defaults. |
| 1314 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1315 | fn prepare_bwrap( |
| 1316 | &self, |
| 1317 | spec: &CommandSpec, |
| 1318 | launch_identity: Option<&bwrap::LaunchIdentity>, |
| 1319 | ) -> ExecEnv { |
| 1320 | let writable_roots = if self.readable_paths.is_some() { |
| 1321 | vec![policy::WritableRoot::new(spec.cwd.clone())] |
| 1322 | } else { |
| 1323 | if matches!(spec.sandbox_policy, SandboxPolicy::WorkspaceWrite { .. }) { |
| 1324 | let _ = std::fs::create_dir(spec.cwd.join(".codewhale")); |
| 1325 | } |
| 1326 | match (&spec.sandbox_policy, launch_identity) { |
| 1327 | ( |
| 1328 | SandboxPolicy::WorkspaceWrite { |
| 1329 | writable_roots, |
| 1330 | network_access, |
| 1331 | .. |
| 1332 | }, |
| 1333 | Some(_), |
| 1334 | ) => SandboxPolicy::WorkspaceWrite { |
| 1335 | writable_roots: writable_roots.clone(), |
| 1336 | network_access: *network_access, |
| 1337 | exclude_tmpdir: true, |
| 1338 | exclude_slash_tmp: true, |
| 1339 | } |
| 1340 | .get_writable_roots(&spec.cwd), |
| 1341 | _ => spec.sandbox_policy.get_writable_roots(&spec.cwd), |
| 1342 | } |
| 1343 | }; |
| 1344 | let denied_read_exceptions: &[PathBuf] = if launch_identity.is_some() { |
| 1345 | &[] |
| 1346 | } else { |
| 1347 | &self.denied_read_exceptions |
| 1348 | }; |
| 1349 | let command = bwrap::build_bwrap_command_with_read_paths( |
| 1350 | &spec.cwd, |
| 1351 | &spec.program, |
| 1352 | &spec.args, |
| 1353 | &writable_roots, |
| 1354 | spec.sandbox_policy.has_network_access(), |
| 1355 | &self.bwrap_extensions, |
| 1356 | &self.denied_read_subpaths, |
| 1357 | denied_read_exceptions, |
| 1358 | self.readable_paths.as_deref(), |
| 1359 | launch_identity, |
| 1360 | ); |
| 1361 | |
| 1362 | let mut env = spec.env.clone(); |
| 1363 | env.insert("CODEWHALE_SANDBOX".to_string(), "bwrap".to_string()); |
| 1364 | env.insert("DEEPSEEK_SANDBOX".to_string(), "bwrap".to_string()); |
| 1365 | if matches!(spec.sandbox_policy, SandboxPolicy::ReadOnly { .. }) { |
| 1366 | insert_private_tmp_env(&mut env, std::path::Path::new("/tmp")); |
| 1367 | } |
| 1368 | |
| 1369 | ExecEnv { |
| 1370 | command, |
| 1371 | cwd: spec.cwd.clone(), |
| 1372 | env, |
| 1373 | timeout: spec.timeout, |
| 1374 | sandbox_type: SandboxType::LinuxBubblewrap, |
| 1375 | policy: spec.sandbox_policy.clone(), |
| 1376 | scratch: None, |
| 1377 | } |
| 1378 | } |
| 1379 | |
| 1380 | /// Prepare a Windows helper execution environment. |
| 1381 | /// |
| 1382 | /// Windows support is currently not advertised by `get_platform_sandbox`. |
| 1383 | /// This branch only exists for forced tests and future helper wiring. |
| 1384 | /// The first supported helper contract is process-tree containment only; |
| 1385 | /// it must not be presented as filesystem or network isolation. |
| 1386 | #[cfg(target_os = "windows")] |
| 1387 | fn prepare_windows(spec: &CommandSpec) -> ExecEnv { |
| 1388 | let mut command = vec![spec.program.clone()]; |
| 1389 | command.extend(spec.args.clone()); |
| 1390 | |
| 1391 | let mut env = spec.env.clone(); |
| 1392 | let kind = windows::select_best_kind(&spec.sandbox_policy, &spec.cwd); |
| 1393 | env.insert("CODEWHALE_SANDBOX".to_string(), format!("windows:{kind}")); |
| 1394 | env.insert("DEEPSEEK_SANDBOX".to_string(), format!("windows:{kind}")); |
| 1395 | if !spec.sandbox_policy.has_network_access() { |
| 1396 | env.insert( |
| 1397 | "CODEWHALE_SANDBOX_BLOCK_NETWORK".to_string(), |
| 1398 | "1".to_string(), |
| 1399 | ); |
| 1400 | env.insert( |
| 1401 | "DEEPSEEK_SANDBOX_BLOCK_NETWORK".to_string(), |
| 1402 | "1".to_string(), |
| 1403 | ); |
| 1404 | } |
| 1405 | |
| 1406 | ExecEnv { |
| 1407 | command, |
| 1408 | cwd: spec.cwd.clone(), |
| 1409 | env, |
| 1410 | timeout: spec.timeout, |
| 1411 | sandbox_type: SandboxType::Windows, |
| 1412 | policy: spec.sandbox_policy.clone(), |
| 1413 | scratch: None, |
| 1414 | } |
| 1415 | } |
| 1416 | |
| 1417 | /// Check if a command failure was due to sandbox denial. |
| 1418 | /// |
| 1419 | /// This helps distinguish between legitimate command failures and |
| 1420 | /// sandbox-blocked operations. |
| 1421 | pub fn was_denied(sandbox_type: SandboxType, exit_code: i32, stderr: &str) -> bool { |
| 1422 | #[cfg(not(any( |
| 1423 | target_os = "macos", |
| 1424 | all(target_os = "linux", not(target_env = "ohos")) |
| 1425 | )))] |
| 1426 | let _ = (exit_code, stderr); |
| 1427 | |
| 1428 | match sandbox_type { |
| 1429 | SandboxType::None => false, |
| 1430 | |
| 1431 | #[cfg(target_os = "macos")] |
| 1432 | SandboxType::MacosSeatbelt => seatbelt::detect_denial(exit_code, stderr), |
| 1433 | |
| 1434 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1435 | SandboxType::LinuxBubblewrap => bwrap::detect_denial(exit_code, stderr), |
| 1436 | |
| 1437 | #[cfg(target_os = "windows")] |
| 1438 | SandboxType::Windows => windows::detect_denial(exit_code, stderr), |
| 1439 | } |
| 1440 | } |
| 1441 | |
| 1442 | /// Get a human-readable description of why a command was blocked. |
| 1443 | pub fn denial_message(sandbox_type: SandboxType, stderr: &str) -> String { |
| 1444 | #[cfg(not(any( |
| 1445 | target_os = "macos", |
| 1446 | all(target_os = "linux", not(target_env = "ohos")) |
| 1447 | )))] |
| 1448 | let _ = stderr; |
| 1449 | |
| 1450 | match sandbox_type { |
| 1451 | SandboxType::None => "Command failed (no sandbox)".to_string(), |
| 1452 | |
| 1453 | #[cfg(target_os = "macos")] |
| 1454 | SandboxType::MacosSeatbelt => { |
| 1455 | if stderr.contains("file-write") { |
| 1456 | "Sandbox blocked write access. The command tried to write to a protected location.".to_string() |
| 1457 | } else if stderr.contains("network") { |
| 1458 | "Sandbox blocked network access. Enable network_access in sandbox policy if needed.".to_string() |
| 1459 | } else { |
| 1460 | format!( |
| 1461 | "Sandbox blocked operation: {}", |
| 1462 | stderr.lines().next().unwrap_or("unknown") |
| 1463 | ) |
| 1464 | } |
| 1465 | } |
| 1466 | |
| 1467 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1468 | SandboxType::LinuxBubblewrap => { |
| 1469 | if let Some(error) = bwrap_setup_failure(stderr) { |
| 1470 | format!("Bubblewrap could not create the sandbox: {}", error) |
| 1471 | } else if bwrap::is_erofs_stderr(stderr) { |
| 1472 | "Bubblewrap blocked access outside the writable workspace view.".to_string() |
| 1473 | } else { |
| 1474 | format!( |
| 1475 | "Bubblewrap blocked operation: {}", |
| 1476 | stderr.lines().next().unwrap_or("unknown") |
| 1477 | ) |
| 1478 | } |
| 1479 | } |
| 1480 | |
| 1481 | #[cfg(target_os = "windows")] |
| 1482 | SandboxType::Windows => { |
| 1483 | if stderr.contains("Access is denied") { |
| 1484 | "Windows sandbox blocked access. The command lacked required privileges." |
| 1485 | .to_string() |
| 1486 | } else if stderr.contains("network") { |
| 1487 | "Windows sandbox blocked network access. Enable network_access in policy if needed." |
| 1488 | .to_string() |
| 1489 | } else { |
| 1490 | format!( |
| 1491 | "Windows sandbox blocked operation: {}", |
| 1492 | stderr.lines().next().unwrap_or("unknown") |
| 1493 | ) |
| 1494 | } |
| 1495 | } |
| 1496 | } |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | #[cfg(test)] |
| 1501 | mod tests { |
| 1502 | use super::*; |
| 1503 | |
| 1504 | /// The extension host's deny-list form, platform-neutral so it runs on |
| 1505 | /// every host: an exception and a writable root inside a masked |
| 1506 | /// directory are bound again, a missing exception and the masked |
| 1507 | /// directory itself are not, and a denied path inside an exception is |
| 1508 | /// masked again. |
| 1509 | #[test] |
| 1510 | fn bwrap_exceptions_rebind_inside_masks_and_never_reexpose_a_denied_path() { |
| 1511 | let dir = tempfile::tempdir().unwrap(); |
| 1512 | let root = std::fs::canonicalize(dir.path()).unwrap(); |
| 1513 | let home = root.join("home"); |
| 1514 | std::fs::create_dir_all(home.join("extension-host/data")).unwrap(); |
| 1515 | std::fs::create_dir_all(home.join("extension-host/secret")).unwrap(); |
| 1516 | std::fs::write(home.join("token"), "s3cret").unwrap(); |
| 1517 | std::fs::create_dir_all(root.join("other/writable")).unwrap(); |
| 1518 | let bundle = home.join("extension-host"); |
| 1519 | let data = bundle.join("data"); |
| 1520 | let nested = bundle.join("secret"); |
| 1521 | let token = home.join("token"); |
| 1522 | let spell = |path: &std::path::Path| path.to_string_lossy().into_owned(); |
| 1523 | let (bundle_s, data_s, nested_s, home_s, token_s) = ( |
| 1524 | spell(&bundle), |
| 1525 | spell(&data), |
| 1526 | spell(&nested), |
| 1527 | spell(&home), |
| 1528 | spell(&token), |
| 1529 | ); |
| 1530 | |
| 1531 | // `other` is denied without an exception: the writable root inside |
| 1532 | // it stays masked, as it is for every caller that sets none. |
| 1533 | let args = bwrap_exception_args( |
| 1534 | &[ |
| 1535 | home.clone(), |
| 1536 | token.clone(), |
| 1537 | nested.clone(), |
| 1538 | root.join("other"), |
| 1539 | ], |
| 1540 | &[bundle.clone(), home.join("plugins"), home.clone()], |
| 1541 | &[data.clone(), root.clone(), root.join("other/writable")], |
| 1542 | ); |
| 1543 | assert_eq!( |
| 1544 | args, |
| 1545 | [ |
| 1546 | "--ro-bind", |
| 1547 | bundle_s.as_str(), |
| 1548 | bundle_s.as_str(), |
| 1549 | "--bind", |
| 1550 | data_s.as_str(), |
| 1551 | data_s.as_str(), |
| 1552 | "--tmpfs", |
| 1553 | nested_s.as_str(), |
| 1554 | ] |
| 1555 | ); |
| 1556 | // No exceptions, or none inside a masked directory: nothing to add. |
| 1557 | assert!( |
| 1558 | bwrap_exception_args( |
| 1559 | std::slice::from_ref(&home), |
| 1560 | &[], |
| 1561 | std::slice::from_ref(&data) |
| 1562 | ) |
| 1563 | .is_empty() |
| 1564 | ); |
| 1565 | assert!(bwrap_exception_args(std::slice::from_ref(&token), &[bundle], &[data]).is_empty()); |
| 1566 | |
| 1567 | assert_eq!(bwrap_mask_args(&home), ["--tmpfs", home_s.as_str()]); |
| 1568 | assert_eq!( |
| 1569 | bwrap_mask_args(&token), |
| 1570 | ["--ro-bind", "/dev/null", token_s.as_str()] |
| 1571 | ); |
| 1572 | assert!(bwrap_mask_args(&home.join("missing")).is_empty()); |
| 1573 | } |
| 1574 | |
| 1575 | #[test] |
| 1576 | fn test_command_spec_shell() { |
| 1577 | let spec = CommandSpec::shell("echo hello", PathBuf::from("/tmp"), Duration::from_secs(30)); |
| 1578 | |
| 1579 | // Program and args depend on the detected shell. |
| 1580 | assert!(!spec.program.is_empty(), "program must not be empty"); |
| 1581 | assert!(!spec.args.is_empty(), "args must not be empty"); |
| 1582 | assert_eq!(spec.display_command(), "echo hello"); |
| 1583 | } |
| 1584 | |
| 1585 | #[test] |
| 1586 | fn test_command_spec_shell_custom_posix_path_display() { |
| 1587 | let spec = CommandSpec { |
| 1588 | program: "/bin/zsh".to_string(), |
| 1589 | args: vec!["-c".to_string(), "echo hello".to_string()], |
| 1590 | cwd: PathBuf::from("/tmp"), |
| 1591 | env: HashMap::new(), |
| 1592 | timeout: Duration::from_secs(30), |
| 1593 | sandbox_policy: SandboxPolicy::default(), |
| 1594 | justification: None, |
| 1595 | requested_command: None, |
| 1596 | private_tmp: false, |
| 1597 | }; |
| 1598 | |
| 1599 | assert_eq!(spec.display_command(), "echo hello"); |
| 1600 | } |
| 1601 | |
| 1602 | #[test] |
| 1603 | fn test_command_spec_shell_quoted_arg_not_split() { |
| 1604 | // Regression for #1691: a `-m` message containing spaces must remain a |
| 1605 | // single, unsplit argv entry. The shell command string is passed |
| 1606 | // verbatim as ONE argument (`sh -c <cmd>` / `cmd /C <payload>`); we |
| 1607 | // must never tokenize it ourselves into `feat:` / `complete` / |
| 1608 | // `sub-pages"`. |
| 1609 | let cmd = r#"git commit -m "feat: complete sub-pages""#; |
| 1610 | let spec = CommandSpec::shell(cmd, PathBuf::from("/tmp"), Duration::from_secs(30)); |
| 1611 | |
| 1612 | let dispatcher = crate::shell_dispatcher::global_dispatcher(); |
| 1613 | assert_eq!(spec.program, dispatcher.kind().binary()); |
| 1614 | // The quoted message survives in exactly ONE argv slot, regardless of |
| 1615 | // which shell-specific wrapping (encoding prefix, exit-code capture) |
| 1616 | // the dispatcher added around it. This single-line ASCII command never |
| 1617 | // takes the temp `-File` path, so the payload stays on the argv. |
| 1618 | let carriers: Vec<&String> = spec |
| 1619 | .args |
| 1620 | .iter() |
| 1621 | .filter(|arg| arg.contains(r#""feat: complete sub-pages""#)) |
| 1622 | .collect(); |
| 1623 | assert_eq!(carriers.len(), 1, "args: {:?}", spec.args); |
| 1624 | // And no argv entry is a tokenized fragment of the message. |
| 1625 | assert!( |
| 1626 | !spec |
| 1627 | .args |
| 1628 | .iter() |
| 1629 | .any(|arg| arg == "feat:" || arg == "complete" || arg == "sub-pages\""), |
| 1630 | "args: {:?}", |
| 1631 | spec.args |
| 1632 | ); |
| 1633 | assert_eq!(spec.display_command(), cmd); |
| 1634 | } |
| 1635 | |
| 1636 | #[test] |
| 1637 | fn test_command_spec_program() { |
| 1638 | let spec = CommandSpec::program( |
| 1639 | "cargo", |
| 1640 | vec!["build".to_string(), "--release".to_string()], |
| 1641 | PathBuf::from("/project"), |
| 1642 | Duration::from_secs(300), |
| 1643 | ); |
| 1644 | |
| 1645 | assert_eq!(spec.program, "cargo"); |
| 1646 | assert_eq!(spec.display_command(), "cargo build --release"); |
| 1647 | } |
| 1648 | |
| 1649 | #[test] |
| 1650 | fn test_command_spec_builder() { |
| 1651 | let spec = CommandSpec::shell("test", PathBuf::from("."), Duration::from_secs(10)) |
| 1652 | .with_policy(SandboxPolicy::read_only()) |
| 1653 | .with_env_var("FOO", "bar") |
| 1654 | .with_justification("Testing"); |
| 1655 | |
| 1656 | assert!(matches!( |
| 1657 | spec.sandbox_policy, |
| 1658 | SandboxPolicy::ReadOnly { .. } |
| 1659 | )); |
| 1660 | assert_eq!(spec.env.get("FOO"), Some(&"bar".to_string())); |
| 1661 | assert_eq!(spec.justification, Some("Testing".to_string())); |
| 1662 | |
| 1663 | let spec = spec |
| 1664 | .with_env(HashMap::new()) |
| 1665 | .with_env(HashMap::from([("SECOND".to_string(), "added".to_string())])); |
| 1666 | assert_eq!(spec.env.get("FOO").map(String::as_str), Some("bar")); |
| 1667 | assert_eq!(spec.env.get("SECOND").map(String::as_str), Some("added")); |
| 1668 | let spec = spec.with_env(HashMap::from([("FOO".to_string(), "override".to_string())])); |
| 1669 | assert_eq!(spec.env.get("FOO").map(String::as_str), Some("override")); |
| 1670 | #[cfg(windows)] |
| 1671 | { |
| 1672 | let spec = spec.with_env(HashMap::from([( |
| 1673 | "foo".to_string(), |
| 1674 | "lowercase".to_string(), |
| 1675 | )])); |
| 1676 | assert!(!spec.env.contains_key("FOO")); |
| 1677 | assert_eq!(spec.env.get("foo").map(String::as_str), Some("lowercase")); |
| 1678 | let spec = spec.with_env_var("FOO", "uppercase"); |
| 1679 | assert!(!spec.env.contains_key("foo")); |
| 1680 | assert_eq!(spec.env.get("FOO").map(String::as_str), Some("uppercase")); |
| 1681 | } |
| 1682 | } |
| 1683 | |
| 1684 | #[test] |
| 1685 | fn windows_shell_default_env_forces_python_pipe_stdio_utf8() { |
| 1686 | let env = windows_shell_default_env(); |
| 1687 | |
| 1688 | assert_eq!( |
| 1689 | env.get("PYTHONIOENCODING").map(String::as_str), |
| 1690 | Some("utf-8") |
| 1691 | ); |
| 1692 | } |
| 1693 | |
| 1694 | #[test] |
| 1695 | fn test_sandbox_manager_new() { |
| 1696 | let manager = SandboxManager::new(); |
| 1697 | assert!(manager.sandbox_available.is_none()); |
| 1698 | } |
| 1699 | |
| 1700 | #[test] |
| 1701 | fn test_sandbox_manager_select_sandbox() { |
| 1702 | let manager = SandboxManager::new(); |
| 1703 | |
| 1704 | // DangerFullAccess should never sandbox |
| 1705 | let no_sandbox = manager.select_sandbox(&SandboxPolicy::DangerFullAccess); |
| 1706 | assert_eq!(no_sandbox, SandboxType::None); |
| 1707 | |
| 1708 | // ExternalSandbox should never sandbox |
| 1709 | let external = manager.select_sandbox(&SandboxPolicy::ExternalSandbox { |
| 1710 | network_access: true, |
| 1711 | }); |
| 1712 | assert_eq!(external, SandboxType::None); |
| 1713 | } |
| 1714 | |
| 1715 | #[test] |
| 1716 | fn test_prepare_unsandboxed() { |
| 1717 | let manager = SandboxManager::new(); |
| 1718 | let spec = CommandSpec::shell("echo test", PathBuf::from("/tmp"), Duration::from_secs(30)) |
| 1719 | .with_policy(SandboxPolicy::DangerFullAccess); |
| 1720 | |
| 1721 | let env = manager.prepare(&spec); |
| 1722 | |
| 1723 | assert_eq!(env.sandbox_type, SandboxType::None); |
| 1724 | // Unsandboxed preparation passes the spec through untouched: the |
| 1725 | // command is exactly the spec's program followed by the dispatcher- |
| 1726 | // built args, whatever wrapping the current shell required. |
| 1727 | let mut expected = vec![spec.program.clone()]; |
| 1728 | expected.extend(spec.args.iter().cloned()); |
| 1729 | assert_eq!(env.command, expected); |
| 1730 | assert!(!env.is_sandboxed()); |
| 1731 | } |
| 1732 | |
| 1733 | #[test] |
| 1734 | fn test_exec_env_helpers() { |
| 1735 | let env = ExecEnv { |
| 1736 | command: vec![ |
| 1737 | "sandbox-exec".to_string(), |
| 1738 | "-p".to_string(), |
| 1739 | "policy".to_string(), |
| 1740 | "--".to_string(), |
| 1741 | "echo".to_string(), |
| 1742 | "hello".to_string(), |
| 1743 | ], |
| 1744 | cwd: PathBuf::from("/tmp"), |
| 1745 | env: HashMap::new(), |
| 1746 | timeout: Duration::from_secs(30), |
| 1747 | sandbox_type: SandboxType::None, |
| 1748 | policy: SandboxPolicy::default(), |
| 1749 | scratch: None, |
| 1750 | }; |
| 1751 | |
| 1752 | assert_eq!(env.program(), "sandbox-exec"); |
| 1753 | assert_eq!(env.args().len(), 5); |
| 1754 | } |
| 1755 | |
| 1756 | #[test] |
| 1757 | fn test_sandbox_type_display() { |
| 1758 | assert_eq!(format!("{}", SandboxType::None), "none"); |
| 1759 | |
| 1760 | #[cfg(target_os = "macos")] |
| 1761 | assert_eq!(format!("{}", SandboxType::MacosSeatbelt), "macos-seatbelt"); |
| 1762 | |
| 1763 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1764 | assert_eq!(format!("{}", SandboxType::LinuxBubblewrap), "linux-bwrap"); |
| 1765 | } |
| 1766 | |
| 1767 | // ── Parity tests (#2187) ────────────────────────────────────────────── |
| 1768 | |
| 1769 | #[test] |
| 1770 | fn test_parity_platform_sandbox_detection() { |
| 1771 | let sandbox_type = get_platform_sandbox(); |
| 1772 | let available = is_sandbox_available(); |
| 1773 | if available { |
| 1774 | assert!(sandbox_type.is_some()); |
| 1775 | } |
| 1776 | } |
| 1777 | |
| 1778 | #[test] |
| 1779 | #[cfg(target_os = "macos")] |
| 1780 | fn test_parity_macos_seatbelt_available() { |
| 1781 | // Match real runtime availability (`seatbelt::is_available` via |
| 1782 | // `get_platform_sandbox`), not merely the presence of sandbox-exec or a |
| 1783 | // diagnostics layer that may report seatbelt at another boundary. |
| 1784 | // On hosts where sandbox-exec exists but is denied (e.g. some CI / |
| 1785 | // restricted macOS environments), skip rather than asserting a false |
| 1786 | // positive. |
| 1787 | match get_platform_sandbox() { |
| 1788 | Some(SandboxType::MacosSeatbelt) => {} |
| 1789 | None => { |
| 1790 | eprintln!("skipping: MacosSeatbelt unavailable via get_platform_sandbox()"); |
| 1791 | } |
| 1792 | Some(other) => panic!("unexpected macOS sandbox type: {other:?}"), |
| 1793 | } |
| 1794 | } |
| 1795 | |
| 1796 | #[test] |
| 1797 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1798 | fn linux_default_never_claims_an_unwired_sandbox() { |
| 1799 | assert_eq!(get_platform_sandbox(), None); |
| 1800 | assert_eq!(get_platform_sandbox_with_bwrap_preference(false), None); |
| 1801 | } |
| 1802 | |
| 1803 | #[test] |
| 1804 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1805 | fn linux_bwrap_selection_requires_opt_in_and_executable() { |
| 1806 | let expected = bwrap::is_available().then_some(SandboxType::LinuxBubblewrap); |
| 1807 | assert_eq!(get_platform_sandbox_with_bwrap_preference(true), expected); |
| 1808 | |
| 1809 | let manager = SandboxManager::with_bwrap_preference(true); |
| 1810 | let selected = manager.select_sandbox(&SandboxPolicy::default()); |
| 1811 | assert_eq!(selected, expected.unwrap_or(SandboxType::None)); |
| 1812 | } |
| 1813 | |
| 1814 | #[test] |
| 1815 | fn test_parity_denial_zero_exit_never_denied() { |
| 1816 | assert!(!SandboxManager::was_denied( |
| 1817 | SandboxType::None, |
| 1818 | 0, |
| 1819 | "anything" |
| 1820 | )); |
| 1821 | #[cfg(target_os = "macos")] |
| 1822 | assert!(!SandboxManager::was_denied( |
| 1823 | SandboxType::MacosSeatbelt, |
| 1824 | 0, |
| 1825 | "" |
| 1826 | )); |
| 1827 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1828 | assert!(!SandboxManager::was_denied( |
| 1829 | SandboxType::LinuxBubblewrap, |
| 1830 | 0, |
| 1831 | "" |
| 1832 | )); |
| 1833 | #[cfg(target_os = "windows")] |
| 1834 | assert!(!SandboxManager::was_denied(SandboxType::Windows, 0, "")); |
| 1835 | } |
| 1836 | |
| 1837 | #[test] |
| 1838 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1839 | fn bwrap_denial_is_not_inferred_from_seccomp_text() { |
| 1840 | assert!(!SandboxManager::was_denied( |
| 1841 | SandboxType::LinuxBubblewrap, |
| 1842 | 1, |
| 1843 | "Bad system call" |
| 1844 | )); |
| 1845 | assert!(SandboxManager::was_denied( |
| 1846 | SandboxType::LinuxBubblewrap, |
| 1847 | 1, |
| 1848 | "Read-only file system" |
| 1849 | )); |
| 1850 | } |
| 1851 | |
| 1852 | #[test] |
| 1853 | #[cfg(target_os = "macos")] |
| 1854 | fn test_parity_seatbelt_file_write_detected() { |
| 1855 | // Seatbelt patterns use "Sandbox: <cmd> denied <operation>" format. |
| 1856 | assert!(SandboxManager::was_denied( |
| 1857 | SandboxType::MacosSeatbelt, |
| 1858 | 1, |
| 1859 | "Sandbox: ls denied file-write*" |
| 1860 | )); |
| 1861 | assert!(SandboxManager::was_denied( |
| 1862 | SandboxType::MacosSeatbelt, |
| 1863 | 1, |
| 1864 | "Operation not permitted" |
| 1865 | )); |
| 1866 | } |
| 1867 | |
| 1868 | #[test] |
| 1869 | #[cfg(target_os = "macos")] |
| 1870 | fn sandbox_child_env_exports_codewhale_marker_and_legacy_alias() { |
| 1871 | let manager = SandboxManager { |
| 1872 | forced_sandbox: Some(SandboxType::MacosSeatbelt), |
| 1873 | ..SandboxManager::default() |
| 1874 | }; |
| 1875 | let spec = CommandSpec::shell("true", PathBuf::from("/tmp"), Duration::from_secs(5)); |
| 1876 | let env = manager.prepare(&spec); |
| 1877 | |
| 1878 | assert_eq!( |
| 1879 | env.env.get("CODEWHALE_SANDBOX").map(String::as_str), |
| 1880 | Some("seatbelt") |
| 1881 | ); |
| 1882 | assert_eq!( |
| 1883 | env.env.get("DEEPSEEK_SANDBOX").map(String::as_str), |
| 1884 | Some("seatbelt") |
| 1885 | ); |
| 1886 | } |
| 1887 | |
| 1888 | #[test] |
| 1889 | fn test_parity_manager_default_no_bwrap() { |
| 1890 | let manager = SandboxManager::default(); |
| 1891 | let spec = CommandSpec::shell("true", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 1892 | .with_policy(SandboxPolicy::default()); |
| 1893 | let env = manager.prepare(&spec); |
| 1894 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1895 | { |
| 1896 | let primary_marker = env.env.get("CODEWHALE_SANDBOX"); |
| 1897 | let marker = env.env.get("DEEPSEEK_SANDBOX"); |
| 1898 | assert!(primary_marker.is_none()); |
| 1899 | assert!(marker.is_none()); |
| 1900 | assert_eq!(env.sandbox_type, SandboxType::None); |
| 1901 | } |
| 1902 | let _ = env; |
| 1903 | } |
| 1904 | |
| 1905 | #[test] |
| 1906 | fn test_parity_manager_with_bwrap() { |
| 1907 | let manager = SandboxManager::with_bwrap_preference(true); |
| 1908 | let spec = CommandSpec::shell("true", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 1909 | .with_policy(SandboxPolicy::default()); |
| 1910 | let env = manager.prepare(&spec); |
| 1911 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1912 | { |
| 1913 | if crate::bwrap::is_available() { |
| 1914 | let primary_marker = env.env.get("CODEWHALE_SANDBOX"); |
| 1915 | let marker = env.env.get("DEEPSEEK_SANDBOX"); |
| 1916 | assert_eq!(primary_marker.map(String::as_str), Some("bwrap")); |
| 1917 | assert_eq!(marker.map(String::as_str), Some("bwrap")); |
| 1918 | assert_eq!(env.sandbox_type, SandboxType::LinuxBubblewrap); |
| 1919 | assert_eq!(env.program(), bwrap::BWRAP_PATH); |
| 1920 | } else { |
| 1921 | assert_eq!(env.sandbox_type, SandboxType::None); |
| 1922 | assert!(!env.env.contains_key("CODEWHALE_SANDBOX")); |
| 1923 | assert!(!env.env.contains_key("DEEPSEEK_SANDBOX")); |
| 1924 | } |
| 1925 | } |
| 1926 | let _ = env; |
| 1927 | } |
| 1928 | |
| 1929 | /// Real Linux enforcement proof, not a marker check: the same |
| 1930 | /// outside-workspace write succeeds unsandboxed and fails under |
| 1931 | /// bubblewrap, and a normal workspace write succeeds inside the wrapper. |
| 1932 | /// Skips on hosts where the functional probe says bwrap cannot run. |
| 1933 | #[test] |
| 1934 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 1935 | fn bwrap_workspace_write_blocks_outside_write_allows_inside() { |
| 1936 | if !bwrap::is_available() { |
| 1937 | return; |
| 1938 | } |
| 1939 | let workspace = tempfile::tempdir().expect("workspace tempdir"); |
| 1940 | let home = std::env::var_os("HOME").map(PathBuf::from).unwrap(); |
| 1941 | let outside = tempfile::Builder::new() |
| 1942 | .prefix("cw_bwrap_outside") |
| 1943 | .tempdir_in(&home) |
| 1944 | .expect("outside-workspace tempdir under HOME"); |
| 1945 | let outside_target = outside.path().join("must_not_persist"); |
| 1946 | let inside_target = workspace.path().join("allowed_write"); |
| 1947 | |
| 1948 | let run = |manager: &SandboxManager, command: &str| -> (SandboxType, bool) { |
| 1949 | let spec = CommandSpec::shell( |
| 1950 | command, |
| 1951 | workspace.path().to_path_buf(), |
| 1952 | Duration::from_secs(15), |
| 1953 | ) |
| 1954 | // CI's hermetic HOME lives under /tmp. Exclude temporary roots so |
| 1955 | // the outside fixture is outside this test's writable policy too. |
| 1956 | .with_policy(SandboxPolicy::WorkspaceWrite { |
| 1957 | writable_roots: vec![], |
| 1958 | network_access: false, |
| 1959 | exclude_tmpdir: true, |
| 1960 | exclude_slash_tmp: true, |
| 1961 | }); |
| 1962 | let env = manager.prepare(&spec); |
| 1963 | let (program, args) = env.command.split_first().unwrap(); |
| 1964 | let status = std::process::Command::new(program) |
| 1965 | .args(args) |
| 1966 | .current_dir(&env.cwd) |
| 1967 | .envs(&env.env) |
| 1968 | .status() |
| 1969 | .expect("spawn prepared command"); |
| 1970 | (env.sandbox_type, status.success()) |
| 1971 | }; |
| 1972 | |
| 1973 | // Control: without the wrapper the outside write lands on the host — |
| 1974 | // this proves the command itself is permitted and only the sandbox |
| 1975 | // confines it. |
| 1976 | let unwrapped = SandboxManager::default(); |
| 1977 | let (kind, ok) = run( |
| 1978 | &unwrapped, |
| 1979 | &format!("echo x > {}", outside_target.display()), |
| 1980 | ); |
| 1981 | assert_eq!(kind, SandboxType::None); |
| 1982 | assert!(ok); |
| 1983 | assert!(outside_target.exists()); |
| 1984 | std::fs::remove_file(&outside_target).unwrap(); |
| 1985 | |
| 1986 | let wrapped = SandboxManager::with_bwrap_preference(true); |
| 1987 | let (kind, ok) = run(&wrapped, &format!("echo x > {}", outside_target.display())); |
| 1988 | assert_eq!(kind, SandboxType::LinuxBubblewrap); |
| 1989 | assert!(!ok); |
| 1990 | assert!(!outside_target.exists()); |
| 1991 | |
| 1992 | let (kind, ok) = run(&wrapped, &format!("echo ok > {}", inside_target.display())); |
| 1993 | assert_eq!(kind, SandboxType::LinuxBubblewrap); |
| 1994 | assert!(ok); |
| 1995 | assert_eq!( |
| 1996 | std::fs::read_to_string(&inside_target).unwrap().trim(), |
| 1997 | "ok" |
| 1998 | ); |
| 1999 | } |
| 2000 | |
| 2001 | #[test] |
| 2002 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2003 | fn bwrap_read_only_policy_keeps_the_working_directory_read_only() { |
| 2004 | let manager = SandboxManager { |
| 2005 | forced_sandbox: Some(SandboxType::LinuxBubblewrap), |
| 2006 | ..SandboxManager::default() |
| 2007 | }; |
| 2008 | let spec = CommandSpec::shell("true", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2009 | .with_policy(SandboxPolicy::read_only()); |
| 2010 | let env = manager.prepare(&spec); |
| 2011 | |
| 2012 | assert_eq!(env.sandbox_type, SandboxType::LinuxBubblewrap); |
| 2013 | assert!(!env.command.iter().any(|arg| arg == "--bind")); |
| 2014 | assert!(!env.command.iter().any(|arg| arg == "--share-net")); |
| 2015 | } |
| 2016 | |
| 2017 | #[test] |
| 2018 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2019 | fn bwrap_workspace_policy_maps_additional_roots_and_network_access() { |
| 2020 | let dir = tempfile::tempdir().expect("tempdir"); |
| 2021 | let workspace = dir.path().join("workspace"); |
| 2022 | let extra = dir.path().join("extra"); |
| 2023 | std::fs::create_dir_all(&workspace).expect("workspace"); |
| 2024 | std::fs::create_dir_all(&extra).expect("extra"); |
| 2025 | |
| 2026 | let manager = SandboxManager { |
| 2027 | forced_sandbox: Some(SandboxType::LinuxBubblewrap), |
| 2028 | ..SandboxManager::default() |
| 2029 | }; |
| 2030 | let policy = SandboxPolicy::WorkspaceWrite { |
| 2031 | writable_roots: vec![extra.clone()], |
| 2032 | network_access: true, |
| 2033 | exclude_tmpdir: true, |
| 2034 | exclude_slash_tmp: true, |
| 2035 | }; |
| 2036 | let spec = CommandSpec::shell("true", workspace.clone(), Duration::from_secs(5)) |
| 2037 | .with_policy(policy); |
| 2038 | let env = manager.prepare(&spec); |
| 2039 | |
| 2040 | for root in [workspace, extra] { |
| 2041 | let root = root |
| 2042 | .canonicalize() |
| 2043 | .expect("writable root") |
| 2044 | .to_string_lossy() |
| 2045 | .into_owned(); |
| 2046 | assert!(env.command.windows(3).any(|args| args[0] == "--bind" |
| 2047 | && args[1].as_str() == root.as_str() |
| 2048 | && args[2].as_str() == root.as_str())); |
| 2049 | } |
| 2050 | assert!(env.command.iter().any(|arg| arg == "--share-net")); |
| 2051 | } |
| 2052 | |
| 2053 | #[test] |
| 2054 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2055 | fn full_access_and_external_policies_bypass_forced_bwrap() { |
| 2056 | let manager = SandboxManager { |
| 2057 | forced_sandbox: Some(SandboxType::LinuxBubblewrap), |
| 2058 | ..SandboxManager::default() |
| 2059 | }; |
| 2060 | |
| 2061 | for policy in [ |
| 2062 | SandboxPolicy::DangerFullAccess, |
| 2063 | SandboxPolicy::ExternalSandbox { |
| 2064 | network_access: false, |
| 2065 | }, |
| 2066 | ] { |
| 2067 | let spec = CommandSpec::shell("true", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2068 | .with_policy(policy); |
| 2069 | let env = manager.prepare(&spec); |
| 2070 | assert_eq!(env.sandbox_type, SandboxType::None); |
| 2071 | assert_ne!(env.program(), bwrap::BWRAP_PATH); |
| 2072 | } |
| 2073 | } |
| 2074 | |
| 2075 | #[test] |
| 2076 | fn test_parity_exec_env_for_all_policies() { |
| 2077 | let manager = SandboxManager::new(); |
| 2078 | let policies = [ |
| 2079 | SandboxPolicy::DangerFullAccess, |
| 2080 | SandboxPolicy::read_only(), |
| 2081 | SandboxPolicy::workspace_with_network(), |
| 2082 | SandboxPolicy::default(), |
| 2083 | ]; |
| 2084 | for policy in &policies { |
| 2085 | let spec = CommandSpec::shell("true", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2086 | .with_policy(policy.clone()); |
| 2087 | let env = manager.prepare(&spec); |
| 2088 | assert_eq!(env.policy, *policy); |
| 2089 | } |
| 2090 | } |
| 2091 | |
| 2092 | #[test] |
| 2093 | fn pty_separator_is_found_after_a_launcher_prefix() { |
| 2094 | let command: Vec<String> = [ |
| 2095 | "/usr/bin/sudo", |
| 2096 | "-n", |
| 2097 | "-u", |
| 2098 | "agent", |
| 2099 | "--", |
| 2100 | "/opt/exec", |
| 2101 | "/usr/bin/bwrap", |
| 2102 | "--unshare-all", |
| 2103 | "--die-with-parent", |
| 2104 | "--", |
| 2105 | "/bin/sh", |
| 2106 | "-c", |
| 2107 | "id", |
| 2108 | ] |
| 2109 | .map(str::to_string) |
| 2110 | .to_vec(); |
| 2111 | assert_eq!(bwrap_target_split(&command), Some((6, 9))); |
| 2112 | assert_eq!(bwrap_target_split(&command[..10]), None); |
| 2113 | assert_eq!(bwrap_target_split(&command[6..]), Some((0, 3))); |
| 2114 | } |
| 2115 | |
| 2116 | #[test] |
| 2117 | fn a_launcher_refuses_policies_that_skip_the_sandbox() { |
| 2118 | let mut manager = SandboxManager::with_bwrap_preference(true); |
| 2119 | manager.set_tool_launcher(Some(vec!["/usr/bin/env".to_string()])); |
| 2120 | for policy in [ |
| 2121 | SandboxPolicy::DangerFullAccess, |
| 2122 | SandboxPolicy::ExternalSandbox { |
| 2123 | network_access: true, |
| 2124 | }, |
| 2125 | ] { |
| 2126 | let spec = CommandSpec::shell("id", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2127 | .with_policy(policy); |
| 2128 | let error = manager.try_prepare(&spec).expect_err("refused"); |
| 2129 | assert!(error.contains("nothing was run"), "{error}"); |
| 2130 | } |
| 2131 | } |
| 2132 | |
| 2133 | #[test] |
| 2134 | fn a_launcher_without_bubblewrap_refuses_instead_of_running_unwrapped() { |
| 2135 | let mut manager = SandboxManager::with_bwrap_preference(false); |
| 2136 | manager.set_tool_launcher(Some(vec!["/usr/bin/env".to_string()])); |
| 2137 | let spec = CommandSpec::shell("id", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2138 | .with_policy(SandboxPolicy::default()); |
| 2139 | let error = manager.try_prepare(&spec).expect_err("refused"); |
| 2140 | assert!(error.contains("nothing was run"), "{error}"); |
| 2141 | assert_eq!(manager.configured_sandbox(), None); |
| 2142 | |
| 2143 | let refusal = manager.prepare(&spec); |
| 2144 | assert_eq!(refusal.sandbox_type, SandboxType::None); |
| 2145 | assert!(!refusal.command.iter().any(|arg| arg == "id")); |
| 2146 | #[cfg(unix)] |
| 2147 | { |
| 2148 | let output = std::process::Command::new(refusal.program()) |
| 2149 | .args(refusal.args()) |
| 2150 | .output() |
| 2151 | .expect("refusal runs"); |
| 2152 | assert_eq!(output.status.code(), Some(126)); |
| 2153 | assert!(String::from_utf8_lossy(&output.stderr).contains("nothing was run")); |
| 2154 | } |
| 2155 | |
| 2156 | manager.set_tool_launcher(Some(vec!["/nonexistent/launcher".to_string()])); |
| 2157 | manager.set_prefer_bwrap(true); |
| 2158 | let error = manager |
| 2159 | .try_prepare(&spec) |
| 2160 | .expect_err("broken launcher refused"); |
| 2161 | assert!(error.contains("nothing was run"), "{error}"); |
| 2162 | } |
| 2163 | |
| 2164 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2165 | const PROBE_FAILURE: Option<&str> = Some("bwrap: setting up uid map: Permission denied"); |
| 2166 | |
| 2167 | #[test] |
| 2168 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2169 | fn a_workspace_boundary_is_refused_when_the_installed_sandbox_fails_its_probe() { |
| 2170 | let manager = SandboxManager::with_bwrap_preference(true); |
| 2171 | let spec = CommandSpec::shell( |
| 2172 | "echo ESCAPED > outside.txt", |
| 2173 | PathBuf::from("/tmp"), |
| 2174 | Duration::from_secs(5), |
| 2175 | ) |
| 2176 | .with_policy(SandboxPolicy::default()); |
| 2177 | |
| 2178 | let error = manager |
| 2179 | .try_prepare_with_probe_failure(&spec, PROBE_FAILURE) |
| 2180 | .expect_err("a failed launcher probe must refuse, not run unwrapped"); |
| 2181 | assert!(error.contains("nothing was run"), "{error}"); |
| 2182 | assert!(error.contains("Permission denied"), "{error}"); |
| 2183 | assert!(error.contains("prefer_bwrap = false"), "{error}"); |
| 2184 | |
| 2185 | // The infallible preparation path must not fall back to the raw |
| 2186 | // command either: it hands back a shell that reports the refusal. |
| 2187 | let refusal = manager.prepare_with_probe_failure(&spec, PROBE_FAILURE); |
| 2188 | assert_eq!(refusal.sandbox_type, SandboxType::None); |
| 2189 | assert!( |
| 2190 | refusal.command.iter().any(|arg| arg == "codewhale-refusal"), |
| 2191 | "{:?}", |
| 2192 | refusal.command |
| 2193 | ); |
| 2194 | assert!( |
| 2195 | !refusal |
| 2196 | .command |
| 2197 | .iter() |
| 2198 | .any(|arg| arg.contains("echo ESCAPED")), |
| 2199 | "{:?}", |
| 2200 | refusal.command |
| 2201 | ); |
| 2202 | #[cfg(unix)] |
| 2203 | { |
| 2204 | let output = std::process::Command::new(refusal.program()) |
| 2205 | .args(refusal.args()) |
| 2206 | .output() |
| 2207 | .expect("refusal runs"); |
| 2208 | assert_eq!(output.status.code(), Some(126)); |
| 2209 | assert!( |
| 2210 | String::from_utf8_lossy(&output.stderr).contains("nothing was run"), |
| 2211 | "{}", |
| 2212 | String::from_utf8_lossy(&output.stderr) |
| 2213 | ); |
| 2214 | } |
| 2215 | } |
| 2216 | |
| 2217 | #[test] |
| 2218 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2219 | fn a_read_only_posture_keeps_its_engine_decision_without_the_probe_gate() { |
| 2220 | let manager = SandboxManager::with_bwrap_preference(true); |
| 2221 | let spec = CommandSpec::shell("cat file", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2222 | .with_policy(SandboxPolicy::ReadOnly { |
| 2223 | network_access: false, |
| 2224 | }); |
| 2225 | |
| 2226 | // Arbitrary read-only commands are refused by the engine when native enforcement is |
| 2227 | // required; the separately hardened allowlist may run without it. The workspace-write |
| 2228 | // probe gate must not pre-empt either decision. |
| 2229 | // The selected type depends on whether this host's real bwrap works; the point is that |
| 2230 | // the workspace-write probe gate does not turn the read-only decision into an error. |
| 2231 | manager |
| 2232 | .try_prepare_with_probe_failure(&spec, PROBE_FAILURE) |
| 2233 | .expect("read-only is decided by the engine, not by this gate"); |
| 2234 | } |
| 2235 | |
| 2236 | #[test] |
| 2237 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2238 | fn a_missing_launcher_and_an_explicit_opt_out_keep_the_documented_fallback() { |
| 2239 | let failed = PROBE_FAILURE; |
| 2240 | let spec = CommandSpec::shell("echo ok", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2241 | .with_policy(SandboxPolicy::default()); |
| 2242 | |
| 2243 | // No launcher installed: the documented policy-only fallback. |
| 2244 | let manager = SandboxManager::with_bwrap_preference(true); |
| 2245 | manager |
| 2246 | .try_prepare_with_probe_failure(&spec, None) |
| 2247 | .expect("no launcher is a documented fallback"); |
| 2248 | |
| 2249 | // A posture that does not ask for the sandbox is not gated. |
| 2250 | let disabled = CommandSpec::shell("echo ok", PathBuf::from("/tmp"), Duration::from_secs(5)) |
| 2251 | .with_policy(SandboxPolicy::DangerFullAccess); |
| 2252 | let prepared = manager |
| 2253 | .try_prepare_with_probe_failure(&disabled, failed) |
| 2254 | .expect("danger-full-access never needs the probe"); |
| 2255 | assert_eq!(prepared.sandbox_type, SandboxType::None); |
| 2256 | |
| 2257 | // prefer_bwrap = false is the documented explicit opt-out. |
| 2258 | let opted_out = SandboxManager::with_bwrap_preference(false); |
| 2259 | opted_out |
| 2260 | .try_prepare_with_probe_failure(&spec, failed) |
| 2261 | .expect("prefer_bwrap = false never needs the probe"); |
| 2262 | |
| 2263 | // A forced sandbox type is a test seam, not a probe result. |
| 2264 | let forced = SandboxManager { |
| 2265 | prefer_bwrap: true, |
| 2266 | forced_sandbox: Some(SandboxType::LinuxBubblewrap), |
| 2267 | ..SandboxManager::default() |
| 2268 | }; |
| 2269 | forced |
| 2270 | .try_prepare_with_probe_failure(&spec, failed) |
| 2271 | .expect("a forced sandbox type bypasses the probe gate"); |
| 2272 | } |
| 2273 | |
| 2274 | #[test] |
| 2275 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 2276 | fn a_launcher_prefixes_the_bubblewrap_command_and_runs_it_confined() { |
| 2277 | if !bwrap::is_available() { |
| 2278 | eprintln!("skipped: bubblewrap cannot run on this host"); |
| 2279 | return; |
| 2280 | } |
| 2281 | let workspace = tempfile::tempdir().expect("workspace"); |
| 2282 | let mut manager = SandboxManager::with_bwrap_preference(true); |
| 2283 | manager.set_tool_launcher(Some(vec!["/usr/bin/env".to_string()])); |
| 2284 | assert_eq!( |
| 2285 | manager.configured_sandbox(), |
| 2286 | Some(SandboxType::LinuxBubblewrap) |
| 2287 | ); |
| 2288 | let spec = CommandSpec::program( |
| 2289 | "/bin/sh", |
| 2290 | vec![ |
| 2291 | "-c".to_string(), |
| 2292 | "grep NoNewPrivs /proc/self/status; echo ok > written".to_string(), |
| 2293 | ], |
| 2294 | workspace.path().to_path_buf(), |
| 2295 | Duration::from_secs(15), |
| 2296 | ) |
| 2297 | .with_policy(SandboxPolicy::WorkspaceWrite { |
| 2298 | writable_roots: vec![], |
| 2299 | network_access: true, |
| 2300 | exclude_tmpdir: false, |
| 2301 | exclude_slash_tmp: false, |
| 2302 | }); |
| 2303 | let env = manager.try_prepare(&spec).expect("prepared"); |
| 2304 | assert_eq!(env.sandbox_type, SandboxType::LinuxBubblewrap); |
| 2305 | assert_eq!(env.command[0], "/usr/bin/env"); |
| 2306 | assert_eq!(env.command[1], bwrap::BWRAP_PATH); |
| 2307 | for flag in ["--unshare-all", "--die-with-parent", "--share-net"] { |
| 2308 | assert!(env.command.iter().any(|arg| arg == flag), "{flag}"); |
| 2309 | } |
| 2310 | assert!( |
| 2311 | !env.command |
| 2312 | .windows(3) |
| 2313 | .any(|args| args[0] == "--bind" && args[1] == "/tmp"), |
| 2314 | "{:?}", |
| 2315 | env.command |
| 2316 | ); |
| 2317 | let output = std::process::Command::new(env.program()) |
| 2318 | .args(env.args()) |
| 2319 | .current_dir(&env.cwd) |
| 2320 | .output() |
| 2321 | .expect("run prepared command"); |
| 2322 | assert!(output.status.success(), "{output:?}"); |
| 2323 | assert!(String::from_utf8_lossy(&output.stdout).contains("NoNewPrivs:\t1")); |
| 2324 | assert_eq!( |
| 2325 | std::fs::read_to_string(workspace.path().join("written")) |
| 2326 | .unwrap() |
| 2327 | .trim(), |
| 2328 | "ok" |
| 2329 | ); |
| 2330 | } |
| 2331 | |
| 2332 | #[cfg(unix)] |
| 2333 | #[test] |
| 2334 | fn scratch_dir_cleans_up_readonly_subtrees_on_drop() { |
| 2335 | use std::os::unix::fs::PermissionsExt; |
| 2336 | |
| 2337 | let dir = tempfile::Builder::new() |
| 2338 | .prefix("codewhale-ro-test-") |
| 2339 | .tempdir() |
| 2340 | .expect("tempdir"); |
| 2341 | let path = dir.path().to_path_buf(); |
| 2342 | let nested = path.join("nested"); |
| 2343 | std::fs::create_dir(&nested).expect("nested dir"); |
| 2344 | std::fs::write(nested.join("locked.txt"), "data").expect("write"); |
| 2345 | std::fs::set_permissions(&nested, std::fs::Permissions::from_mode(0o555)) |
| 2346 | .expect("chmod 0555"); |
| 2347 | |
| 2348 | let scratch = ScratchDir(Some(dir)); |
| 2349 | assert_eq!(scratch.path(), path.as_path()); |
| 2350 | drop(scratch); |
| 2351 | assert!(!path.exists(), "{} leaked after drop", path.display()); |
| 2352 | } |
| 2353 | |
| 2354 | #[cfg(target_os = "macos")] |
| 2355 | #[test] |
| 2356 | fn read_only_scratch_ignores_host_tmpdir_inside_workspace() { |
| 2357 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 2358 | let workspace = tempfile::tempdir().expect("workspace"); |
| 2359 | let workspace_tmp = workspace.path().join(".tmp"); |
| 2360 | std::fs::create_dir_all(&workspace_tmp).expect("workspace tmp"); |
| 2361 | let prev_tmpdir = std::env::var_os("TMPDIR"); |
| 2362 | unsafe { std::env::set_var("TMPDIR", &workspace_tmp) }; |
| 2363 | |
| 2364 | let spec = CommandSpec::shell( |
| 2365 | "true", |
| 2366 | workspace.path().to_path_buf(), |
| 2367 | Duration::from_secs(5), |
| 2368 | ) |
| 2369 | .with_policy(SandboxPolicy::read_only()) |
| 2370 | .with_private_tmp(); |
| 2371 | let prepared = read_only_scratch(&spec); |
| 2372 | |
| 2373 | match prev_tmpdir { |
| 2374 | Some(val) => unsafe { std::env::set_var("TMPDIR", val) }, |
| 2375 | None => unsafe { std::env::remove_var("TMPDIR") }, |
| 2376 | } |
| 2377 | |
| 2378 | let (scratch, canonical_path) = prepared.expect("scratch dir"); |
| 2379 | let canonical_ws = workspace |
| 2380 | .path() |
| 2381 | .canonicalize() |
| 2382 | .expect("canonical workspace"); |
| 2383 | assert!( |
| 2384 | !canonical_path.starts_with(&canonical_ws), |
| 2385 | "{} created inside {}", |
| 2386 | canonical_path.display(), |
| 2387 | canonical_ws.display() |
| 2388 | ); |
| 2389 | assert!(canonical_path.exists()); |
| 2390 | drop(scratch); |
| 2391 | assert!(!canonical_path.exists()); |
| 2392 | } |
| 2393 | } |
| 2394 |