| 1 | //! macOS Seatbelt (sandbox-exec) profile generation. |
| 2 | //! |
| 3 | //! Seatbelt is Apple's mandatory access control framework that uses the |
| 4 | //! Scheme-based policy language to define what system resources a process |
| 5 | //! can access. This module generates sandbox profiles dynamically based |
| 6 | //! on the configured `SandboxPolicy`. |
| 7 | //! |
| 8 | //! # How it works |
| 9 | //! |
| 10 | //! 1. We generate a Seatbelt policy string in the SBPL format |
| 11 | //! 2. We invoke `/usr/bin/sandbox-exec -p <policy>` to run the command |
| 12 | //! 3. The kernel enforces the policy, blocking unauthorized operations |
| 13 | //! |
| 14 | //! # References |
| 15 | //! |
| 16 | //! - Apple's sandbox(7) man page |
| 17 | //! - <https://reverse.put.as/wp-content/uploads/2011/09/Apple-Sandbox-Guide-v1.0.pdf> |
| 18 | |
| 19 | // Note: cfg(target_os = "macos") is already applied at the module level in mod.rs |
| 20 | |
| 21 | use super::policy::{ |
| 22 | DEFAULT_DENY_GLOBS, ResolvedSandboxOverlay, SandboxOverlay, SandboxPolicy, glob_to_sbpl_regex, |
| 23 | }; |
| 24 | use std::path::{Path, PathBuf}; |
| 25 | use std::process::Command; |
| 26 | use std::sync::OnceLock; |
| 27 | |
| 28 | /// Path to the sandbox-exec binary on macOS. |
| 29 | pub const SANDBOX_EXEC_PATH: &str = "/usr/bin/sandbox-exec"; |
| 30 | |
| 31 | /// Base seatbelt policy that provides minimal process functionality. |
| 32 | /// |
| 33 | /// This policy: |
| 34 | /// - Denies everything by default |
| 35 | /// - Allows process execution and forking |
| 36 | /// - Allows signals within the same sandbox |
| 37 | /// - Allows reading user preferences (needed by many tools) |
| 38 | /// - Allows basic process introspection |
| 39 | /// - Allows writing to /dev/null |
| 40 | /// - Allows reading sysctl values |
| 41 | /// - Allows POSIX semaphores and pseudo-TTY operations |
| 42 | const SEATBELT_BASE_POLICY: &str = r#" |
| 43 | (version 1) |
| 44 | (deny default) |
| 45 | |
| 46 | ; Core process operations |
| 47 | (allow process-exec) |
| 48 | (allow process-fork) |
| 49 | (allow signal (target same-sandbox)) |
| 50 | (allow process-info* (target same-sandbox)) |
| 51 | |
| 52 | ; User preferences (needed by many CLI tools) |
| 53 | (allow user-preference-read) |
| 54 | |
| 55 | ; Consume only filesystem access tokens already granted by macOS |
| 56 | (allow file-read* (extension "com.apple.app-sandbox.read")) |
| 57 | (allow file-read* (extension "com.apple.app-sandbox.read-write")) |
| 58 | |
| 59 | ; Basic I/O to /dev/null |
| 60 | (allow file-write-data |
| 61 | (require-all |
| 62 | (path "/dev/null") |
| 63 | (vnode-type CHARACTER-DEVICE))) |
| 64 | |
| 65 | ; System information |
| 66 | (allow sysctl-read) |
| 67 | |
| 68 | ; IPC primitives |
| 69 | (allow ipc-posix-sem) |
| 70 | (allow ipc-posix-shm-read*) |
| 71 | (allow ipc-posix-shm-write-create) |
| 72 | (allow ipc-posix-shm-write-data) |
| 73 | (allow ipc-posix-shm-write-unlink) |
| 74 | |
| 75 | ; Terminal support (essential for shell commands) |
| 76 | (allow pseudo-tty) |
| 77 | (allow file-read* file-write* file-ioctl (literal "/dev/ptmx")) |
| 78 | (allow file-read* file-write* file-ioctl (literal "/dev/tty")) |
| 79 | (allow file-read* file-write* file-ioctl (regex #"^/dev/ttys[0-9]+$")) |
| 80 | |
| 81 | ; macOS-specific device access |
| 82 | (allow file-read* (literal "/dev/urandom")) |
| 83 | (allow file-read* (literal "/dev/random")) |
| 84 | (allow file-ioctl (literal "/dev/dtracehelper")) |
| 85 | |
| 86 | ; Mach IPC (needed by many system services) |
| 87 | (allow mach-lookup) |
| 88 | "#; |
| 89 | |
| 90 | /// Network access policy additions. |
| 91 | const SEATBELT_NETWORK_POLICY: &str = r" |
| 92 | ; Network access |
| 93 | (allow network-outbound) |
| 94 | (allow network-inbound) |
| 95 | (allow system-socket) |
| 96 | (allow network-bind) |
| 97 | "; |
| 98 | |
| 99 | const SEATBELT_READ_ONLY_NETWORK_POLICY: &str = r#" |
| 100 | ; Outbound IPv4 network and the system DNS resolver; no loopback, IPv6 or other local sockets |
| 101 | (allow network-outbound (remote ip)) |
| 102 | (allow network-outbound (remote unix-socket (path-literal "/private/var/run/mDNSResponder"))) |
| 103 | (allow system-socket) |
| 104 | (deny network-outbound (remote ip "localhost:*")) |
| 105 | (deny network-outbound (remote tcp6 "*:*")) |
| 106 | (deny network-outbound (remote udp6 "*:*")) |
| 107 | "#; |
| 108 | |
| 109 | /// AppleEvents/LaunchServices allowances for the trusted (full-disk-write) |
| 110 | /// tier only (#4828). |
| 111 | /// |
| 112 | /// `open`, `osascript`, and `launchctl` send AppleEvents and drive |
| 113 | /// LaunchServices; under `(deny default)` those calls die with exit -54. |
| 114 | /// The base policy already allows `mach-lookup` broadly, so the missing |
| 115 | /// operations are `appleevent-send` and the LaunchServices `lsopen` |
| 116 | /// operation. The launchservicesd/appleevents mach names are listed |
| 117 | /// explicitly so a future narrowing of the blanket `mach-lookup` rule |
| 118 | /// cannot silently break this tier. |
| 119 | /// |
| 120 | /// Restrictive tiers (workspace-write, read-only) intentionally stay locked |
| 121 | /// down: AppleEvents automation can instruct other apps to act outside the |
| 122 | /// sandbox, which would defeat the write restrictions. |
| 123 | const SEATBELT_TRUSTED_AUTOMATION_POLICY: &str = r#" |
| 124 | ; AppleEvents + LaunchServices (trusted full-access tier only) |
| 125 | (allow appleevent-send) |
| 126 | (allow lsopen) |
| 127 | (allow mach-lookup |
| 128 | (global-name "com.apple.coreservices.launchservicesd") |
| 129 | (global-name "com.apple.coreservices.appleevents")) |
| 130 | "#; |
| 131 | |
| 132 | /// Check if sandbox-exec is available and permitted on this system. |
| 133 | pub fn is_available() -> bool { |
| 134 | static SEATBELT_AVAILABLE: OnceLock<bool> = OnceLock::new(); |
| 135 | |
| 136 | *SEATBELT_AVAILABLE.get_or_init(|| { |
| 137 | if !Path::new(SANDBOX_EXEC_PATH).exists() { |
| 138 | return false; |
| 139 | } |
| 140 | |
| 141 | let output = Command::new(SANDBOX_EXEC_PATH) |
| 142 | .args(["-p", "(version 1)(allow default)", "--", "/usr/bin/true"]) |
| 143 | .output(); |
| 144 | |
| 145 | match output { |
| 146 | Ok(result) => result.status.success(), |
| 147 | Err(_) => false, |
| 148 | } |
| 149 | }) |
| 150 | } |
| 151 | |
| 152 | /// Create the command-line arguments for sandbox-exec. |
| 153 | /// |
| 154 | /// Returns a Vec of arguments that should be prepended to the command. |
| 155 | /// The format is: `sandbox-exec -p <policy> -D KEY=VALUE ... -- <original command>` |
| 156 | pub fn create_seatbelt_args( |
| 157 | command: Vec<String>, |
| 158 | policy: &SandboxPolicy, |
| 159 | sandbox_cwd: &Path, |
| 160 | denied_read_subpaths: &[std::path::PathBuf], |
| 161 | scratch: Option<&Path>, |
| 162 | ) -> Vec<String> { |
| 163 | let overlay = SandboxOverlay::load_from_workspace(sandbox_cwd) |
| 164 | .ok() |
| 165 | .flatten() |
| 166 | .map(|raw| policy.apply_workspace_overlay(&raw, sandbox_cwd)); |
| 167 | create_seatbelt_args_with_overlay( |
| 168 | command, |
| 169 | policy, |
| 170 | sandbox_cwd, |
| 171 | denied_read_subpaths, |
| 172 | scratch, |
| 173 | overlay.as_ref(), |
| 174 | ) |
| 175 | } |
| 176 | |
| 177 | pub fn create_seatbelt_args_with_overlay( |
| 178 | command: Vec<String>, |
| 179 | policy: &SandboxPolicy, |
| 180 | sandbox_cwd: &Path, |
| 181 | denied_read_subpaths: &[std::path::PathBuf], |
| 182 | scratch: Option<&Path>, |
| 183 | overlay: Option<&ResolvedSandboxOverlay>, |
| 184 | ) -> Vec<String> { |
| 185 | let effective_policy = overlay.map_or(policy, |resolved| &resolved.policy); |
| 186 | let read_only_paths: &[PathBuf] = overlay.map_or(&[], |resolved| &resolved.read_only_paths); |
| 187 | let default_globs: Vec<String> = if effective_policy.should_sandbox() { |
| 188 | DEFAULT_DENY_GLOBS |
| 189 | .iter() |
| 190 | .map(|glob| (*glob).to_string()) |
| 191 | .collect() |
| 192 | } else { |
| 193 | Vec::new() |
| 194 | }; |
| 195 | let deny_globs: &[String] = overlay.map_or(&default_globs, |resolved| &resolved.deny_globs); |
| 196 | let full_policy = generate_policy_with_scratch_and_overlay( |
| 197 | effective_policy, |
| 198 | sandbox_cwd, |
| 199 | denied_read_subpaths, |
| 200 | read_only_paths, |
| 201 | deny_globs, |
| 202 | scratch.is_some(), |
| 203 | ); |
| 204 | let mut params = generate_params(effective_policy, sandbox_cwd); |
| 205 | if let Some(scratch) = scratch { |
| 206 | params.push(("PRIVATE_TMPDIR".to_string(), scratch.to_path_buf())); |
| 207 | } |
| 208 | |
| 209 | let mut args = vec!["-p".to_string(), full_policy]; |
| 210 | |
| 211 | // Add parameter definitions for variable substitution |
| 212 | for (key, value) in params { |
| 213 | args.push(format!("-D{}={}", key, value.to_string_lossy())); |
| 214 | } |
| 215 | |
| 216 | // Separator between sandbox-exec args and the actual command |
| 217 | args.push("--".to_string()); |
| 218 | args.extend(command); |
| 219 | |
| 220 | args |
| 221 | } |
| 222 | |
| 223 | pub(crate) fn create_restricted_seatbelt_args( |
| 224 | command: Vec<String>, |
| 225 | sandbox_cwd: &Path, |
| 226 | readable_paths: &[PathBuf], |
| 227 | denied_read_subpaths: &[PathBuf], |
| 228 | ) -> Vec<String> { |
| 229 | let mut profile = String::from( |
| 230 | "(version 1)\n(deny default)\n(allow process-exec)\n(allow process-fork)\n(allow signal (target same-sandbox))\n(allow process-info* (target same-sandbox))\n(allow sysctl-read)\n(allow file-read* (literal \"/\"))\n(allow file-write-data (literal \"/dev/null\"))\n(allow file-ioctl (literal \"/dev/dtracehelper\"))\n", |
| 231 | ); |
| 232 | let escape = |path: &Path| { |
| 233 | path.to_string_lossy() |
| 234 | .replace('\\', "\\\\") |
| 235 | .replace('"', "\\\"") |
| 236 | }; |
| 237 | let mut ancestors = std::collections::BTreeSet::new(); |
| 238 | for path in readable_paths { |
| 239 | let predicate = if path.is_dir() { "subpath" } else { "literal" }; |
| 240 | profile.push_str(&format!( |
| 241 | "(allow file-read* ({predicate} \"{}\"))\n", |
| 242 | escape(path) |
| 243 | )); |
| 244 | ancestors.extend(path.ancestors().skip(1).map(Path::to_path_buf)); |
| 245 | } |
| 246 | for path in ancestors { |
| 247 | profile.push_str(&format!( |
| 248 | "(allow file-read* (literal \"{}\"))\n", |
| 249 | escape(&path) |
| 250 | )); |
| 251 | } |
| 252 | if let Ok(data) = sandbox_cwd.canonicalize() { |
| 253 | profile.push_str(&format!( |
| 254 | "(allow file-write* (subpath \"{}\"))\n", |
| 255 | escape(&data) |
| 256 | )); |
| 257 | } |
| 258 | for path in denied_read_subpaths { |
| 259 | profile.push_str(&format!( |
| 260 | "\n(deny file-read* (subpath \"{}\"))", |
| 261 | escape(path) |
| 262 | )); |
| 263 | } |
| 264 | let mut args = vec!["-p".to_string(), profile, "--".to_string()]; |
| 265 | args.extend(command); |
| 266 | args |
| 267 | } |
| 268 | |
| 269 | #[cfg(test)] |
| 270 | fn generate_policy( |
| 271 | policy: &SandboxPolicy, |
| 272 | cwd: &Path, |
| 273 | denied_read_subpaths: &[std::path::PathBuf], |
| 274 | ) -> String { |
| 275 | generate_policy_with_scratch_and_overlay(policy, cwd, denied_read_subpaths, &[], &[], false) |
| 276 | } |
| 277 | |
| 278 | fn generate_policy_with_scratch_and_overlay( |
| 279 | policy: &SandboxPolicy, |
| 280 | cwd: &Path, |
| 281 | denied_read_subpaths: &[std::path::PathBuf], |
| 282 | read_only_paths: &[PathBuf], |
| 283 | deny_globs: &[String], |
| 284 | has_scratch: bool, |
| 285 | ) -> String { |
| 286 | let mut full_policy = SEATBELT_BASE_POLICY.to_string(); |
| 287 | |
| 288 | // Base read grant. Emitted unconditionally, including when a deny-list is |
| 289 | // in force: SBPL is last-match-wins, so the `(deny file-read* …)` rules |
| 290 | // appended at the end of this profile override it for exactly the denied |
| 291 | // subpaths and nothing else. Dropping the broad allow instead would make |
| 292 | // every posture unable to read `/usr/bin`, and nothing would run. |
| 293 | full_policy.push_str("\n; Full filesystem read access\n(allow file-read*)"); |
| 294 | |
| 295 | // Add write access policy |
| 296 | let file_write_policy = generate_write_policy(policy, cwd); |
| 297 | if !file_write_policy.is_empty() { |
| 298 | full_policy.push_str("\n\n; Write access policy\n"); |
| 299 | full_policy.push_str(&file_write_policy); |
| 300 | } |
| 301 | if has_scratch { |
| 302 | full_policy.push_str( |
| 303 | "\n\n; Private per-command TMPDIR, removed after the command\n(allow file-write* (subpath (param \"PRIVATE_TMPDIR\")))\n(deny file-write-unlink (literal (param \"PRIVATE_TMPDIR\")))\n", |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | // Add network policy if enabled |
| 308 | if policy.has_network_access() { |
| 309 | full_policy.push('\n'); |
| 310 | if matches!(policy, SandboxPolicy::ReadOnly { .. }) { |
| 311 | full_policy.push_str(SEATBELT_READ_ONLY_NETWORK_POLICY); |
| 312 | for port in loopback_proxy_ports() { |
| 313 | full_policy.push_str(&format!( |
| 314 | "(allow network-outbound (remote ip \"localhost:{port}\"))\n" |
| 315 | )); |
| 316 | } |
| 317 | } else { |
| 318 | full_policy.push_str(SEATBELT_NETWORK_POLICY); |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | // Trusted tier (#4828): full-disk-write policies also get AppleEvents + |
| 323 | // LaunchServices so `open`/`osascript`/`launchctl` work when a |
| 324 | // full-access policy is still routed through seatbelt (e.g. a forced |
| 325 | // sandbox); in the normal flow danger-full-access bypasses the wrap |
| 326 | // entirely via `should_sandbox()`. |
| 327 | if policy.has_full_disk_write_access() { |
| 328 | full_policy.push('\n'); |
| 329 | full_policy.push_str(SEATBELT_TRUSTED_AUTOMATION_POLICY); |
| 330 | } |
| 331 | |
| 332 | // Darwin user cache: read always; write only when the policy allows any |
| 333 | // write (same gate as cargo/npm). ReadOnly must not get a cache escape. |
| 334 | full_policy.push_str("\n\n; Darwin user cache directory\n"); |
| 335 | full_policy.push_str(r#"(allow file-read* (subpath (param "DARWIN_USER_CACHE_DIR")))"#); |
| 336 | if !matches!(policy, SandboxPolicy::ReadOnly { .. }) { |
| 337 | full_policy.push('\n'); |
| 338 | full_policy.push_str(r#"(allow file-write* (subpath (param "DARWIN_USER_CACHE_DIR")))"#); |
| 339 | } |
| 340 | |
| 341 | // Add common macOS directories that tools often need |
| 342 | full_policy.push_str("\n\n; Common macOS directories\n"); |
| 343 | full_policy.push_str(r#"(allow file-read* (subpath "/usr/lib"))"#); |
| 344 | full_policy.push('\n'); |
| 345 | full_policy.push_str(r#"(allow file-read* (subpath "/usr/share"))"#); |
| 346 | full_policy.push('\n'); |
| 347 | full_policy.push_str(r#"(allow file-read* (subpath "/System/Library"))"#); |
| 348 | full_policy.push('\n'); |
| 349 | full_policy.push_str(r#"(allow file-read* (subpath "/Library/Preferences"))"#); |
| 350 | full_policy.push('\n'); |
| 351 | full_policy.push_str(r#"(allow file-read* (subpath "/private/var/db"))"#); |
| 352 | |
| 353 | // Cargo home (#558): cargo build/test/publish reach into ~/.cargo/registry |
| 354 | // and ~/.cargo/git for crate metadata, downloaded tarballs, and unpacked |
| 355 | // sources. Sandboxed workspace-write was previously rejecting these, |
| 356 | // making `cargo publish` unrunnable from inside the TUI's shell tool. |
| 357 | // Read access is always allowed; write access is granted whenever the |
| 358 | // policy allows any write at all (the registry caches need to be |
| 359 | // mutable for `cargo build` to populate them on a cache miss). Skipped |
| 360 | // entirely when neither `CARGO_HOME` nor `HOME` is set — without one of |
| 361 | // those we have no path to plumb into the policy params. |
| 362 | if resolve_cargo_home().is_some() { |
| 363 | full_policy.push_str("\n\n; Cargo home (~/.cargo) — registry/index/git caches\n"); |
| 364 | full_policy.push_str(r#"(allow file-read* (subpath (param "CARGO_HOME")))"#); |
| 365 | if !matches!(policy, SandboxPolicy::ReadOnly { .. }) { |
| 366 | full_policy.push('\n'); |
| 367 | full_policy.push_str(r#"(allow file-write* (subpath (param "CARGO_HOME_REGISTRY")))"#); |
| 368 | full_policy.push('\n'); |
| 369 | full_policy.push_str(r#"(allow file-write* (subpath (param "CARGO_HOME_GIT")))"#); |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | // npm cache (#1267): npx-based MCP servers write to ~/.npm when downloading |
| 374 | // packages on first run. Without write access the npx subprocess fails |
| 375 | // immediately with "Stdio transport closed", making all stdio MCP servers |
| 376 | // broken on macOS under the default workspace-write policy. |
| 377 | // Read access is always allowed; write access mirrors the cargo pattern — |
| 378 | // granted for all policies that allow any write, skipped for ReadOnly. |
| 379 | // Skipped entirely when neither `NPM_CONFIG_CACHE` nor `HOME` is set. |
| 380 | if resolve_npm_cache_dir().is_some() { |
| 381 | full_policy.push_str("\n\n; npm cache (~/.npm) — npx package downloads\n"); |
| 382 | full_policy.push_str(r#"(allow file-read* (subpath (param "NPM_CACHE_DIR")))"#); |
| 383 | if !matches!(policy, SandboxPolicy::ReadOnly { .. }) { |
| 384 | full_policy.push('\n'); |
| 385 | full_policy.push_str(r#"(allow file-write* (subpath (param "NPM_CACHE_DIR")))"#); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // Opt-in read deny-list (S1, #5568). Appended LAST deliberately: SBPL is |
| 390 | // last-match-wins, so these rules override every broad read allowance |
| 391 | // above — including the full-disk `(allow file-read*)` — for the listed |
| 392 | // subpaths. Metadata reads are denied too so the paths do not enumerate. |
| 393 | // A read deny does not stop connect(2) to a socket under the path, so with |
| 394 | // network on, unix-socket connects under each path are denied as well. |
| 395 | if !denied_read_subpaths.is_empty() { |
| 396 | full_policy.push_str("\n\n; Opt-in read deny-list (user-configured)\n"); |
| 397 | for path in denied_read_subpaths { |
| 398 | let escaped = path |
| 399 | .to_string_lossy() |
| 400 | .replace('\\', "\\\\") |
| 401 | .replace('"', "\\\""); |
| 402 | full_policy.push_str(&format!("(deny file-read* (subpath \"{escaped}\"))\n")); |
| 403 | if policy.has_network_access() { |
| 404 | full_policy.push_str(&format!( |
| 405 | "(deny network-outbound (remote unix-socket (subpath \"{escaped}\")))\n" |
| 406 | )); |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | if !read_only_paths.is_empty() { |
| 412 | full_policy.push_str("\n\n; Overlay read-only subpaths\n"); |
| 413 | for path in read_only_paths { |
| 414 | let resolved = super::policy::canonical_or_self(path); |
| 415 | let raw = resolved.to_string_lossy(); |
| 416 | if raw.chars().any(|ch| ch.is_control()) { |
| 417 | continue; |
| 418 | } |
| 419 | let escaped = raw.replace('\\', "\\\\").replace('"', "\\\""); |
| 420 | full_policy.push_str(&format!("(deny file-write* (subpath \"{escaped}\"))\n")); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | if !deny_globs.is_empty() { |
| 425 | full_policy.push_str("\n\n; Kernel-enforced deny globs\n"); |
| 426 | for pattern in deny_globs { |
| 427 | if let Some(regex) = glob_to_sbpl_regex(pattern, cwd) { |
| 428 | let escaped = regex.replace('"', "\\\""); |
| 429 | full_policy.push_str(&format!( |
| 430 | "(deny file-read* file-write* (regex #\"{escaped}\"))\n" |
| 431 | )); |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | full_policy |
| 437 | } |
| 438 | |
| 439 | /// Resolve the user's cargo home — `CARGO_HOME` if set, else `$HOME/.cargo`. |
| 440 | /// Returns `None` only on hosts where neither env var is set (essentially |
| 441 | /// never on a real macOS user account; can happen in CI containers without |
| 442 | /// `HOME` exported). |
| 443 | fn resolve_cargo_home() -> Option<PathBuf> { |
| 444 | if let Ok(explicit) = std::env::var("CARGO_HOME") |
| 445 | && !explicit.trim().is_empty() |
| 446 | { |
| 447 | return Some(PathBuf::from(explicit)); |
| 448 | } |
| 449 | let home = std::env::var("HOME").ok()?; |
| 450 | Some(PathBuf::from(home).join(".cargo")) |
| 451 | } |
| 452 | |
| 453 | /// Resolve the npm cache directory — `NPM_CONFIG_CACHE` if set, else `$HOME/.npm`. |
| 454 | /// Returns `None` only on hosts where neither env var is set. |
| 455 | fn resolve_npm_cache_dir() -> Option<PathBuf> { |
| 456 | if let Ok(explicit) = std::env::var("NPM_CONFIG_CACHE") |
| 457 | && !explicit.trim().is_empty() |
| 458 | { |
| 459 | return Some(PathBuf::from(explicit)); |
| 460 | } |
| 461 | let home = std::env::var("HOME").ok()?; |
| 462 | Some(PathBuf::from(home).join(".npm")) |
| 463 | } |
| 464 | |
| 465 | fn loopback_proxy_ports() -> Vec<u16> { |
| 466 | let mut ports: Vec<u16> = [ |
| 467 | "HTTP_PROXY", |
| 468 | "HTTPS_PROXY", |
| 469 | "ALL_PROXY", |
| 470 | "http_proxy", |
| 471 | "https_proxy", |
| 472 | "all_proxy", |
| 473 | ] |
| 474 | .into_iter() |
| 475 | .filter_map(|key| std::env::var(key).ok()) |
| 476 | .filter_map(|value| { |
| 477 | let value = value.trim(); |
| 478 | let url = if value.contains("://") { |
| 479 | url::Url::parse(value) |
| 480 | } else { |
| 481 | url::Url::parse(&format!("http://{value}")) |
| 482 | } |
| 483 | .ok()?; |
| 484 | let host = url.host_str()?; |
| 485 | if host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "[::1]" { |
| 486 | url.port_or_known_default() |
| 487 | } else { |
| 488 | None |
| 489 | } |
| 490 | }) |
| 491 | .collect(); |
| 492 | ports.sort_unstable(); |
| 493 | ports.dedup(); |
| 494 | ports |
| 495 | } |
| 496 | |
| 497 | /// Generate the write access portion of the Seatbelt policy. |
| 498 | fn generate_write_policy(policy: &SandboxPolicy, cwd: &Path) -> String { |
| 499 | // Full disk write access |
| 500 | if policy.has_full_disk_write_access() { |
| 501 | return r#"(allow file-write* (regex #"^/"))"#.to_string(); |
| 502 | } |
| 503 | |
| 504 | // Read-only - no write policy needed |
| 505 | if matches!(policy, SandboxPolicy::ReadOnly { .. }) { |
| 506 | return String::new(); |
| 507 | } |
| 508 | |
| 509 | // Workspace write - enumerate allowed paths |
| 510 | let writable_roots = policy.get_writable_roots(cwd); |
| 511 | if writable_roots.is_empty() { |
| 512 | return String::new(); |
| 513 | } |
| 514 | |
| 515 | let mut policies = Vec::new(); |
| 516 | |
| 517 | for (index, root) in writable_roots.iter().enumerate() { |
| 518 | let root_param = format!("WRITABLE_ROOT_{index}"); |
| 519 | |
| 520 | let mut root_parts = vec![format!("(subpath (param \"{root_param}\"))")]; |
| 521 | for (subpath_index, _) in root.read_only_subpaths.iter().enumerate() { |
| 522 | let ro_param = format!("WRITABLE_ROOT_{index}_RO_{subpath_index}"); |
| 523 | root_parts.push(format!("(require-not (subpath (param \"{ro_param}\")))")); |
| 524 | } |
| 525 | |
| 526 | let root_policy = if root_parts.len() == 1 { |
| 527 | root_parts[0].clone() |
| 528 | } else { |
| 529 | format!("(require-all {})", root_parts.join(" ")) |
| 530 | }; |
| 531 | policies.push(root_policy); |
| 532 | |
| 533 | // File Provider paths can require an inherited macOS extension even |
| 534 | // when their logical path is already an approved root. Keep Codewhale's |
| 535 | // root and protected-subpath restrictions authoritative by requiring |
| 536 | // the extension and every root predicate in the same conjunction. |
| 537 | let mut extension_parts = |
| 538 | vec![r#"(extension "com.apple.app-sandbox.read-write")"#.to_string()]; |
| 539 | extension_parts.extend(root_parts); |
| 540 | policies.push(format!("(require-all {})", extension_parts.join(" "))); |
| 541 | } |
| 542 | |
| 543 | if policies.is_empty() { |
| 544 | return String::new(); |
| 545 | } |
| 546 | |
| 547 | // Combine all write policies with allow |
| 548 | format!("(allow file-write*\n {})", policies.join("\n ")) |
| 549 | } |
| 550 | |
| 551 | /// Generate parameter definitions for variable substitution in the policy. |
| 552 | /// |
| 553 | /// sandbox-exec allows -DKEY=VALUE to substitute `(param "KEY")` in the policy. |
| 554 | fn generate_params(policy: &SandboxPolicy, cwd: &Path) -> Vec<(String, PathBuf)> { |
| 555 | let mut params = Vec::new(); |
| 556 | |
| 557 | // Add writable root parameters |
| 558 | let writable_roots = policy.get_writable_roots(cwd); |
| 559 | |
| 560 | for (index, root) in writable_roots.iter().enumerate() { |
| 561 | let canonical = root |
| 562 | .root |
| 563 | .canonicalize() |
| 564 | .unwrap_or_else(|_| root.root.clone()); |
| 565 | params.push((format!("WRITABLE_ROOT_{index}"), canonical)); |
| 566 | |
| 567 | // Add parameters for read-only subpaths |
| 568 | for (subpath_index, subpath) in root.read_only_subpaths.iter().enumerate() { |
| 569 | let canonical_subpath = subpath.canonicalize().unwrap_or_else(|_| { |
| 570 | match ( |
| 571 | subpath.parent().map(Path::canonicalize), |
| 572 | subpath.file_name(), |
| 573 | ) { |
| 574 | (Some(Ok(parent)), Some(name)) => parent.join(name), |
| 575 | _ => subpath.clone(), |
| 576 | } |
| 577 | }); |
| 578 | params.push(( |
| 579 | format!("WRITABLE_ROOT_{index}_RO_{subpath_index}"), |
| 580 | canonical_subpath, |
| 581 | )); |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | // Add Darwin user cache directory |
| 586 | if let Some(cache_dir) = get_darwin_user_cache_dir() { |
| 587 | params.push(("DARWIN_USER_CACHE_DIR".to_string(), cache_dir)); |
| 588 | } else { |
| 589 | // Fallback to a reasonable default |
| 590 | if let Ok(home) = std::env::var("HOME") { |
| 591 | params.push(( |
| 592 | "DARWIN_USER_CACHE_DIR".to_string(), |
| 593 | PathBuf::from(format!("{home}/Library/Caches")), |
| 594 | )); |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | // Cargo home (#558): paired with the policy lines emitted by |
| 599 | // `generate_policy` when `resolve_cargo_home()` succeeds. Both helpers |
| 600 | // use the same fallback chain so the policy text and the -DKEY=VALUE |
| 601 | // params stay in sync — emit one without the other and sandbox-exec |
| 602 | // refuses to load the profile. |
| 603 | if let Some(home) = resolve_cargo_home() { |
| 604 | let canonical_home = home.canonicalize().unwrap_or_else(|_| home.clone()); |
| 605 | params.push(( |
| 606 | "CARGO_HOME_REGISTRY".to_string(), |
| 607 | canonical_home.join("registry"), |
| 608 | )); |
| 609 | params.push(("CARGO_HOME_GIT".to_string(), canonical_home.join("git"))); |
| 610 | params.push(("CARGO_HOME".to_string(), canonical_home)); |
| 611 | } |
| 612 | |
| 613 | // npm cache (#1267): paired with the policy lines emitted by |
| 614 | // `generate_policy` when `resolve_npm_cache_dir()` succeeds. Both helpers |
| 615 | // use the same fallback chain so the policy text and the -DKEY=VALUE |
| 616 | // params stay in sync. |
| 617 | if let Some(npm_cache) = resolve_npm_cache_dir() { |
| 618 | let canonical = npm_cache |
| 619 | .canonicalize() |
| 620 | .unwrap_or_else(|_| npm_cache.clone()); |
| 621 | params.push(("NPM_CACHE_DIR".to_string(), canonical)); |
| 622 | } |
| 623 | |
| 624 | params |
| 625 | } |
| 626 | |
| 627 | fn get_darwin_confstr_dir(name: libc::c_int) -> Option<PathBuf> { |
| 628 | let mut buf = vec![0i8; (libc::PATH_MAX as usize) + 1]; |
| 629 | |
| 630 | // Safety: `buf` is a writable buffer sized to PATH_MAX + 1 for confstr. |
| 631 | let len = unsafe { libc::confstr(name, buf.as_mut_ptr(), buf.len()) }; |
| 632 | |
| 633 | if len == 0 { |
| 634 | return None; |
| 635 | } |
| 636 | |
| 637 | // Safety: confstr guarantees a NUL-terminated string in `buf` when len > 0. |
| 638 | let cstr = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) }; |
| 639 | let path_str = cstr.to_str().ok()?; |
| 640 | let path = PathBuf::from(path_str); |
| 641 | |
| 642 | path.canonicalize().ok().or(Some(path)) |
| 643 | } |
| 644 | |
| 645 | /// Get the Darwin user cache directory using confstr. |
| 646 | /// |
| 647 | /// This returns the per-user cache directory that macOS assigns, |
| 648 | /// typically something like /var/folders/xx/xxx.../C/ |
| 649 | fn get_darwin_user_cache_dir() -> Option<PathBuf> { |
| 650 | get_darwin_confstr_dir(libc::_CS_DARWIN_USER_CACHE_DIR) |
| 651 | } |
| 652 | |
| 653 | pub(crate) fn darwin_user_temp_dir() -> Option<PathBuf> { |
| 654 | get_darwin_confstr_dir(libc::_CS_DARWIN_USER_TEMP_DIR) |
| 655 | } |
| 656 | |
| 657 | fn detect_denial_with_localized( |
| 658 | exit_code: i32, |
| 659 | stderr: &str, |
| 660 | localized_eperm: Option<&str>, |
| 661 | ) -> bool { |
| 662 | if exit_code == 0 { |
| 663 | return false; |
| 664 | } |
| 665 | |
| 666 | // Common sandbox denial messages |
| 667 | let denial_patterns = [ |
| 668 | "Operation not permitted", |
| 669 | "sandbox-exec", |
| 670 | "deny(", |
| 671 | "Sandbox: ", |
| 672 | ]; |
| 673 | |
| 674 | denial_patterns.iter().any(|p| stderr.contains(p)) |
| 675 | || localized_eperm.is_some_and(|msg| !msg.is_empty() && stderr.contains(msg)) |
| 676 | } |
| 677 | |
| 678 | /// Detect sandbox denial from command output. |
| 679 | /// |
| 680 | /// Returns true if the output suggests the sandbox blocked an operation. |
| 681 | pub fn detect_denial(exit_code: i32, stderr: &str) -> bool { |
| 682 | let localized = super::localized_errno_message(libc::EPERM); |
| 683 | detect_denial_with_localized(exit_code, stderr, localized.as_deref()) |
| 684 | } |
| 685 | |
| 686 | #[cfg(test)] |
| 687 | mod tests; |
| 688 | |
| 689 | #[cfg(test)] |
| 690 | mod existing_tests { |
| 691 | use super::*; |
| 692 | |
| 693 | // Tests that mutate HOME/CARGO_HOME use codewhale_runtime::test_support::lock_test_env() |
| 694 | // so they don't race with sibling tests in this crate that read those vars. |
| 695 | #[test] |
| 696 | fn test_generate_policy_with_network() { |
| 697 | let policy = SandboxPolicy::workspace_with_network(); |
| 698 | let cwd = Path::new("/tmp/test"); |
| 699 | let result = generate_policy(&policy, cwd, &[]); |
| 700 | |
| 701 | assert!(result.contains("network-outbound")); |
| 702 | assert!(result.contains("network-inbound")); |
| 703 | } |
| 704 | |
| 705 | #[test] |
| 706 | fn test_generate_params() { |
| 707 | let policy = SandboxPolicy::default(); |
| 708 | let cwd = Path::new("/tmp/test"); |
| 709 | let params = generate_params(&policy, cwd); |
| 710 | |
| 711 | // Should have at least the cache dir param |
| 712 | assert!(params.iter().any(|(k, _)| k == "DARWIN_USER_CACHE_DIR")); |
| 713 | } |
| 714 | |
| 715 | #[test] |
| 716 | fn test_darwin_user_cache_write_skipped_for_read_only() { |
| 717 | let cwd = Path::new("/tmp/test"); |
| 718 | |
| 719 | let default_text = generate_policy(&SandboxPolicy::default(), cwd, &[]); |
| 720 | assert!( |
| 721 | default_text |
| 722 | .contains(r#"(allow file-read* (subpath (param "DARWIN_USER_CACHE_DIR")))"#), |
| 723 | "default policy should allow reading the Darwin user cache" |
| 724 | ); |
| 725 | assert!( |
| 726 | default_text |
| 727 | .contains(r#"(allow file-write* (subpath (param "DARWIN_USER_CACHE_DIR")))"#), |
| 728 | "default policy should allow writing the Darwin user cache" |
| 729 | ); |
| 730 | |
| 731 | let read_only_text = generate_policy(&SandboxPolicy::read_only(), cwd, &[]); |
| 732 | assert!( |
| 733 | read_only_text |
| 734 | .contains(r#"(allow file-read* (subpath (param "DARWIN_USER_CACHE_DIR")))"#), |
| 735 | "read-only mode should still allow reading the Darwin user cache" |
| 736 | ); |
| 737 | assert!( |
| 738 | !read_only_text |
| 739 | .contains(r#"(allow file-write* (subpath (param "DARWIN_USER_CACHE_DIR")))"#), |
| 740 | "read-only mode must NOT grant write access to the Darwin user cache" |
| 741 | ); |
| 742 | assert!( |
| 743 | !read_only_text.contains( |
| 744 | r#"(allow file-read* file-write* (subpath (param "DARWIN_USER_CACHE_DIR")))"# |
| 745 | ), |
| 746 | "read-only mode must not combine Darwin cache write into the read rule" |
| 747 | ); |
| 748 | } |
| 749 | |
| 750 | /// #558: cargo publish reaches into ~/.cargo/registry; the seatbelt has |
| 751 | /// to allow read+write inside it. Both the policy text and the param |
| 752 | /// table must be in sync — emitting one without the other makes |
| 753 | /// sandbox-exec refuse to load the profile. |
| 754 | #[test] |
| 755 | fn test_cargo_home_paths_emitted_in_policy_and_params_when_home_set() { |
| 756 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 757 | |
| 758 | // SAFETY: HOME / CARGO_HOME are process-global. lock_test_env |
| 759 | // serializes tests that mutate them, and we always restore the |
| 760 | // prior value before returning. |
| 761 | let saved_home = std::env::var_os("HOME"); |
| 762 | let saved_cargo = std::env::var_os("CARGO_HOME"); |
| 763 | unsafe { |
| 764 | std::env::set_var("HOME", "/tmp/seatbelt-cargo-test"); |
| 765 | std::env::remove_var("CARGO_HOME"); |
| 766 | } |
| 767 | |
| 768 | let policy = SandboxPolicy::default(); |
| 769 | let cwd = Path::new("/tmp/test"); |
| 770 | |
| 771 | let policy_text = generate_policy(&policy, cwd, &[]); |
| 772 | assert!(policy_text.contains(r#"(allow file-read* (subpath (param "CARGO_HOME")))"#)); |
| 773 | assert!(policy_text.contains("CARGO_HOME_REGISTRY")); |
| 774 | assert!(policy_text.contains("CARGO_HOME_GIT")); |
| 775 | |
| 776 | let params = generate_params(&policy, cwd); |
| 777 | assert!(params.iter().any(|(k, _)| k == "CARGO_HOME")); |
| 778 | assert!(params.iter().any(|(k, _)| k == "CARGO_HOME_REGISTRY")); |
| 779 | assert!(params.iter().any(|(k, _)| k == "CARGO_HOME_GIT")); |
| 780 | |
| 781 | // Read-only policy should still emit CARGO_HOME read rule but skip writes. |
| 782 | let read_only_text = generate_policy(&SandboxPolicy::read_only(), cwd, &[]); |
| 783 | assert!( |
| 784 | read_only_text.contains(r#"(allow file-read* (subpath (param "CARGO_HOME")))"#), |
| 785 | "read-only mode should still allow reading the cargo registry: {read_only_text}" |
| 786 | ); |
| 787 | assert!( |
| 788 | !read_only_text |
| 789 | .contains(r#"(allow file-write* (subpath (param "CARGO_HOME_REGISTRY")))"#), |
| 790 | "read-only mode must NOT grant write access to the cargo registry" |
| 791 | ); |
| 792 | |
| 793 | // Restore. |
| 794 | // SAFETY: restoring the prior value the test stashed at entry. |
| 795 | unsafe { |
| 796 | match saved_home { |
| 797 | Some(v) => std::env::set_var("HOME", v), |
| 798 | None => std::env::remove_var("HOME"), |
| 799 | } |
| 800 | match saved_cargo { |
| 801 | Some(v) => std::env::set_var("CARGO_HOME", v), |
| 802 | None => std::env::remove_var("CARGO_HOME"), |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | /// #558: if neither `CARGO_HOME` nor `HOME` is set, the cargo lines and |
| 808 | /// their params must both be omitted — emitting one without the other |
| 809 | /// would crash sandbox-exec on profile load. |
| 810 | #[test] |
| 811 | fn test_cargo_home_skipped_when_no_env() { |
| 812 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 813 | |
| 814 | let saved_home = std::env::var_os("HOME"); |
| 815 | let saved_cargo = std::env::var_os("CARGO_HOME"); |
| 816 | // SAFETY: HOME/CARGO_HOME are process-global; lock_test_env serializes |
| 817 | // mutations here and we restore the prior values before returning. |
| 818 | unsafe { |
| 819 | std::env::remove_var("HOME"); |
| 820 | std::env::remove_var("CARGO_HOME"); |
| 821 | } |
| 822 | |
| 823 | let policy = SandboxPolicy::default(); |
| 824 | let cwd = Path::new("/tmp/test"); |
| 825 | let policy_text = generate_policy(&policy, cwd, &[]); |
| 826 | let params = generate_params(&policy, cwd); |
| 827 | |
| 828 | assert!(!policy_text.contains("CARGO_HOME")); |
| 829 | assert!(!params.iter().any(|(k, _)| k.starts_with("CARGO_HOME"))); |
| 830 | |
| 831 | // Restore. |
| 832 | // SAFETY: restoring the prior values the test stashed at entry. |
| 833 | unsafe { |
| 834 | match saved_home { |
| 835 | Some(v) => std::env::set_var("HOME", v), |
| 836 | None => std::env::remove_var("HOME"), |
| 837 | } |
| 838 | match saved_cargo { |
| 839 | Some(v) => std::env::set_var("CARGO_HOME", v), |
| 840 | None => std::env::remove_var("CARGO_HOME"), |
| 841 | } |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | /// #1267: npx MCP servers write to ~/.npm on first run; the seatbelt must |
| 846 | /// allow writes to the npm cache directory. Both the policy text and the |
| 847 | /// param table must be in sync — emitting one without the other makes |
| 848 | /// sandbox-exec refuse to load the profile. |
| 849 | #[test] |
| 850 | fn test_npm_cache_paths_emitted_in_policy_and_params_when_home_set() { |
| 851 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 852 | |
| 853 | let saved_home = std::env::var_os("HOME"); |
| 854 | let saved_npm = std::env::var_os("NPM_CONFIG_CACHE"); |
| 855 | // SAFETY: HOME/NPM_CONFIG_CACHE are process-global; lock_test_env |
| 856 | // serializes mutations here, and we always restore the prior value. |
| 857 | unsafe { |
| 858 | std::env::set_var("HOME", "/tmp/seatbelt-npm-test"); |
| 859 | std::env::remove_var("NPM_CONFIG_CACHE"); |
| 860 | } |
| 861 | |
| 862 | let policy = SandboxPolicy::default(); |
| 863 | let cwd = Path::new("/tmp/test"); |
| 864 | |
| 865 | let policy_text = generate_policy(&policy, cwd, &[]); |
| 866 | assert!( |
| 867 | policy_text.contains(r#"(allow file-read* (subpath (param "NPM_CACHE_DIR")))"#), |
| 868 | "npm cache read rule missing from policy" |
| 869 | ); |
| 870 | assert!( |
| 871 | policy_text.contains(r#"(allow file-write* (subpath (param "NPM_CACHE_DIR")))"#), |
| 872 | "npm cache write rule missing from default policy" |
| 873 | ); |
| 874 | |
| 875 | let params = generate_params(&policy, cwd); |
| 876 | assert!( |
| 877 | params.iter().any(|(k, _)| k == "NPM_CACHE_DIR"), |
| 878 | "NPM_CACHE_DIR param missing" |
| 879 | ); |
| 880 | |
| 881 | // ReadOnly policy: read access allowed, write access must be absent. |
| 882 | let read_only_text = generate_policy(&SandboxPolicy::read_only(), cwd, &[]); |
| 883 | assert!( |
| 884 | read_only_text.contains(r#"(allow file-read* (subpath (param "NPM_CACHE_DIR")))"#), |
| 885 | "read-only mode should allow reading the npm cache" |
| 886 | ); |
| 887 | assert!( |
| 888 | !read_only_text.contains(r#"(allow file-write* (subpath (param "NPM_CACHE_DIR")))"#), |
| 889 | "read-only mode must NOT grant write access to the npm cache" |
| 890 | ); |
| 891 | |
| 892 | // Restore. |
| 893 | // SAFETY: restoring the prior values the test stashed at entry. |
| 894 | unsafe { |
| 895 | match saved_home { |
| 896 | Some(v) => std::env::set_var("HOME", v), |
| 897 | None => std::env::remove_var("HOME"), |
| 898 | } |
| 899 | match saved_npm { |
| 900 | Some(v) => std::env::set_var("NPM_CONFIG_CACHE", v), |
| 901 | None => std::env::remove_var("NPM_CONFIG_CACHE"), |
| 902 | } |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | /// #1267: if neither `NPM_CONFIG_CACHE` nor `HOME` is set, the npm lines |
| 907 | /// and their param must both be omitted. |
| 908 | #[test] |
| 909 | fn test_npm_cache_skipped_when_no_env() { |
| 910 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 911 | |
| 912 | let saved_home = std::env::var_os("HOME"); |
| 913 | let saved_npm = std::env::var_os("NPM_CONFIG_CACHE"); |
| 914 | // SAFETY: HOME/NPM_CONFIG_CACHE are process-global; lock_test_env |
| 915 | // serializes mutations here and we restore the prior values before returning. |
| 916 | unsafe { |
| 917 | std::env::remove_var("HOME"); |
| 918 | std::env::remove_var("NPM_CONFIG_CACHE"); |
| 919 | } |
| 920 | |
| 921 | let policy = SandboxPolicy::default(); |
| 922 | let cwd = Path::new("/tmp/test"); |
| 923 | let policy_text = generate_policy(&policy, cwd, &[]); |
| 924 | let params = generate_params(&policy, cwd); |
| 925 | |
| 926 | assert!(!policy_text.contains("NPM_CACHE_DIR")); |
| 927 | assert!(!params.iter().any(|(k, _)| k == "NPM_CACHE_DIR")); |
| 928 | |
| 929 | // Restore. |
| 930 | // SAFETY: restoring the prior values the test stashed at entry. |
| 931 | unsafe { |
| 932 | match saved_home { |
| 933 | Some(v) => std::env::set_var("HOME", v), |
| 934 | None => std::env::remove_var("HOME"), |
| 935 | } |
| 936 | match saved_npm { |
| 937 | Some(v) => std::env::set_var("NPM_CONFIG_CACHE", v), |
| 938 | None => std::env::remove_var("NPM_CONFIG_CACHE"), |
| 939 | } |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | #[test] |
| 944 | fn test_generate_policy_allows_dev_tty() { |
| 945 | let policy = SandboxPolicy::default(); |
| 946 | let cwd = Path::new("/tmp/test"); |
| 947 | let policy_text = generate_policy(&policy, cwd, &[]); |
| 948 | |
| 949 | assert!( |
| 950 | policy_text |
| 951 | .contains(r#"(allow file-read* file-write* file-ioctl (literal "/dev/tty"))"#), |
| 952 | "TTY-mode shells need /dev/tty access for sshpass/sudo prompts" |
| 953 | ); |
| 954 | } |
| 955 | |
| 956 | #[test] |
| 957 | fn seatbelt_profile_grants_network_only_when_the_policy_does() { |
| 958 | // The OS layer and the application-level policy must agree. The |
| 959 | // seatbelt base profile is `(deny default)` with no network rules, so |
| 960 | // absence of SEATBELT_NETWORK_POLICY is a real denial, not a gap. |
| 961 | let cwd = Path::new("/tmp/test"); |
| 962 | |
| 963 | let restricted = SandboxPolicy::WorkspaceWrite { |
| 964 | writable_roots: vec![cwd.to_path_buf()], |
| 965 | network_access: false, |
| 966 | exclude_tmpdir: false, |
| 967 | exclude_slash_tmp: false, |
| 968 | }; |
| 969 | let text = generate_policy(&restricted, cwd, &[]); |
| 970 | assert!( |
| 971 | !text.contains("network-outbound"), |
| 972 | "a network-restricted policy must not emit outbound rules:\n{text}" |
| 973 | ); |
| 974 | assert!(!text.contains("network-inbound")); |
| 975 | assert!(!text.contains("network-bind")); |
| 976 | |
| 977 | let allowed = SandboxPolicy::WorkspaceWrite { |
| 978 | writable_roots: vec![cwd.to_path_buf()], |
| 979 | network_access: true, |
| 980 | exclude_tmpdir: false, |
| 981 | exclude_slash_tmp: false, |
| 982 | }; |
| 983 | let text = generate_policy(&allowed, cwd, &[]); |
| 984 | assert!( |
| 985 | text.contains("network-outbound"), |
| 986 | "an explicitly granted policy must emit outbound rules:\n{text}" |
| 987 | ); |
| 988 | |
| 989 | // Default construction is restricted, so the shipped default profile |
| 990 | // carries no network rules. |
| 991 | assert!(!generate_policy(&SandboxPolicy::default(), cwd, &[]).contains("network-outbound")); |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn test_create_seatbelt_args() { |
| 996 | let policy = SandboxPolicy::default(); |
| 997 | let cwd = Path::new("/tmp/test"); |
| 998 | let command = vec!["echo".to_string(), "hello".to_string()]; |
| 999 | |
| 1000 | let args = create_seatbelt_args(command, &policy, cwd, &[], None); |
| 1001 | |
| 1002 | // Should start with -p and the policy |
| 1003 | assert_eq!(args[0], "-p"); |
| 1004 | assert!(args[1].contains("(version 1)")); |
| 1005 | |
| 1006 | // Should contain the separator |
| 1007 | assert!(args.contains(&"--".to_string())); |
| 1008 | |
| 1009 | // Should end with the original command |
| 1010 | assert!(args.contains(&"echo".to_string())); |
| 1011 | assert!(args.contains(&"hello".to_string())); |
| 1012 | } |
| 1013 | |
| 1014 | /// #4828: `open`/`osascript`/`launchctl` die with exit -54 under |
| 1015 | /// `(deny default)` because AppleEvent sends and the LaunchServices |
| 1016 | /// `lsopen` operation are blocked. Only the trusted (full-disk-write) |
| 1017 | /// tier gains those allowances; the restrictive tiers must stay locked |
| 1018 | /// down since AppleEvents automation can drive other apps to act |
| 1019 | /// outside the sandbox. |
| 1020 | #[test] |
| 1021 | fn test_apple_events_allowed_only_in_trusted_tier() { |
| 1022 | let cwd = Path::new("/tmp/test"); |
| 1023 | |
| 1024 | let trusted = generate_policy(&SandboxPolicy::DangerFullAccess, cwd, &[]); |
| 1025 | assert!( |
| 1026 | trusted.contains("(allow appleevent-send)"), |
| 1027 | "trusted tier must allow AppleEvent sends: {trusted}" |
| 1028 | ); |
| 1029 | assert!( |
| 1030 | trusted.contains("(allow lsopen)"), |
| 1031 | "trusted tier must allow LaunchServices lsopen: {trusted}" |
| 1032 | ); |
| 1033 | assert!( |
| 1034 | trusted.contains(r#"(global-name "com.apple.coreservices.launchservicesd")"#), |
| 1035 | "trusted tier must pin the launchservicesd mach name: {trusted}" |
| 1036 | ); |
| 1037 | assert!( |
| 1038 | trusted.contains(r#"(global-name "com.apple.coreservices.appleevents")"#), |
| 1039 | "trusted tier must pin the appleevents mach name: {trusted}" |
| 1040 | ); |
| 1041 | |
| 1042 | for (name, restrictive) in [ |
| 1043 | ( |
| 1044 | "workspace-write", |
| 1045 | generate_policy(&SandboxPolicy::default(), cwd, &[]), |
| 1046 | ), |
| 1047 | ( |
| 1048 | "workspace-write+network", |
| 1049 | generate_policy(&SandboxPolicy::workspace_with_network(), cwd, &[]), |
| 1050 | ), |
| 1051 | ( |
| 1052 | "read-only", |
| 1053 | generate_policy(&SandboxPolicy::read_only(), cwd, &[]), |
| 1054 | ), |
| 1055 | ] { |
| 1056 | assert!( |
| 1057 | !restrictive.contains("appleevent-send"), |
| 1058 | "{name} tier must NOT allow AppleEvent sends: {restrictive}" |
| 1059 | ); |
| 1060 | assert!( |
| 1061 | !restrictive.contains("lsopen"), |
| 1062 | "{name} tier must NOT allow LaunchServices lsopen: {restrictive}" |
| 1063 | ); |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | /// #4828: the trusted-tier policy (with the AppleEvents/LaunchServices |
| 1068 | /// additions) must still be a valid SBPL profile that sandbox-exec |
| 1069 | /// accepts. |
| 1070 | #[test] |
| 1071 | fn test_trusted_tier_policy_parses_under_sandbox_exec() { |
| 1072 | // generate_policy/generate_params both read HOME/CARGO_HOME; take the |
| 1073 | // env lock so sibling tests mutating those vars can't desync the |
| 1074 | // policy text from its -DKEY=VALUE params mid-call. |
| 1075 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 1076 | |
| 1077 | assert!( |
| 1078 | is_available(), |
| 1079 | "UNRUN: macOS sandbox-exec is unavailable; generated policy was not parsed" |
| 1080 | ); |
| 1081 | |
| 1082 | let cwd = std::env::temp_dir(); |
| 1083 | let args = create_seatbelt_args( |
| 1084 | vec!["/usr/bin/true".to_string()], |
| 1085 | &SandboxPolicy::DangerFullAccess, |
| 1086 | &cwd, |
| 1087 | &[], |
| 1088 | None, |
| 1089 | ); |
| 1090 | let output = Command::new(SANDBOX_EXEC_PATH) |
| 1091 | .args(args) |
| 1092 | .current_dir(&cwd) |
| 1093 | .output() |
| 1094 | .expect("run sandbox-exec with trusted-tier policy"); |
| 1095 | assert!( |
| 1096 | output.status.success(), |
| 1097 | "sandbox-exec rejected the trusted-tier policy: {}", |
| 1098 | String::from_utf8_lossy(&output.stderr) |
| 1099 | ); |
| 1100 | } |
| 1101 | |
| 1102 | #[test] |
| 1103 | fn test_detect_denial() { |
| 1104 | assert!(detect_denial(1, "Operation not permitted")); |
| 1105 | assert!(detect_denial(1, "Sandbox: ls denied file-write*")); |
| 1106 | assert!(!detect_denial(0, "Operation not permitted")); |
| 1107 | assert!(!detect_denial(1, "File not found")); |
| 1108 | } |
| 1109 | |
| 1110 | #[test] |
| 1111 | fn test_detect_denial_matches_localized_eperm() { |
| 1112 | let localized = "Операция запрещена"; |
| 1113 | assert!(detect_denial_with_localized( |
| 1114 | 1, |
| 1115 | &format!("rm: /protected: {localized}"), |
| 1116 | Some(localized), |
| 1117 | )); |
| 1118 | assert!(!detect_denial_with_localized(0, localized, Some(localized),)); |
| 1119 | assert!(!detect_denial_with_localized( |
| 1120 | 1, |
| 1121 | "File not found", |
| 1122 | Some(localized), |
| 1123 | )); |
| 1124 | assert!(super::super::localized_errno_message(libc::EPERM).is_some()); |
| 1125 | } |
| 1126 | |
| 1127 | #[test] |
| 1128 | fn seatbelt_enforces_workspace_overlay_and_deny_globs_in_kernel() { |
| 1129 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 1130 | assert!(is_available(), "macOS sandbox-exec must be available"); |
| 1131 | |
| 1132 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1133 | let root = dir.path().canonicalize().expect("canonical"); |
| 1134 | std::fs::create_dir_all(root.join(".codewhale")).expect("mkdir .codewhale"); |
| 1135 | std::fs::create_dir_all(root.join("docs")).expect("mkdir docs"); |
| 1136 | std::fs::create_dir_all(root.join("secrets")).expect("mkdir secrets"); |
| 1137 | std::fs::write(root.join(".env"), "SECRET=1").expect("write .env"); |
| 1138 | std::fs::write(root.join("secrets/prod.key"), "PRIVATE").expect("write key"); |
| 1139 | std::fs::write(root.join("secrets/public.txt"), "PUBLIC").expect("write public"); |
| 1140 | std::fs::write( |
| 1141 | root.join(".codewhale/sandbox.toml"), |
| 1142 | "extends = \"strict\"\nrestrict_network = true\nread_only = [\"docs\"]\ndeny = [\"secrets/*.key\"]\n", |
| 1143 | ) |
| 1144 | .expect("write sandbox.toml"); |
| 1145 | |
| 1146 | let run = |script: &str| { |
| 1147 | let args = create_seatbelt_args( |
| 1148 | vec!["/bin/sh".to_string(), "-c".to_string(), script.to_string()], |
| 1149 | &SandboxPolicy::default(), |
| 1150 | &root, |
| 1151 | &[], |
| 1152 | None, |
| 1153 | ); |
| 1154 | Command::new(SANDBOX_EXEC_PATH) |
| 1155 | .args(args) |
| 1156 | .current_dir(&root) |
| 1157 | .output() |
| 1158 | .expect("run sandbox-exec") |
| 1159 | }; |
| 1160 | |
| 1161 | assert!( |
| 1162 | !run("cat .env").status.success(), |
| 1163 | ".env must be kernel-denied" |
| 1164 | ); |
| 1165 | assert!( |
| 1166 | !run("cat secrets/prod.key").status.success(), |
| 1167 | "secrets/*.key must be kernel-denied" |
| 1168 | ); |
| 1169 | assert!( |
| 1170 | run("cat secrets/public.txt").status.success(), |
| 1171 | "non-matching file must remain readable" |
| 1172 | ); |
| 1173 | assert!( |
| 1174 | !run("echo blocked > docs/out.txt").status.success(), |
| 1175 | "overlay read_only path must block writes" |
| 1176 | ); |
| 1177 | assert!( |
| 1178 | run("echo ok > allowed.txt").status.success(), |
| 1179 | "ordinary workspace write must succeed" |
| 1180 | ); |
| 1181 | } |
| 1182 | |
| 1183 | #[test] |
| 1184 | fn seatbelt_hostile_overlay_cannot_weaken_read_only_or_workspace() { |
| 1185 | let _guard = codewhale_runtime::test_support::lock_test_env(); |
| 1186 | assert!(is_available(), "macOS sandbox-exec must be available"); |
| 1187 | |
| 1188 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1189 | let root = dir.path().canonicalize().expect("canonical"); |
| 1190 | std::fs::create_dir_all(root.join(".codewhale")).expect("mkdir .codewhale"); |
| 1191 | std::fs::write(root.join(".env"), "SECRET=1").expect("write .env"); |
| 1192 | std::fs::write( |
| 1193 | root.join(".codewhale/sandbox.toml"), |
| 1194 | "extends = \"off\"\nrestrict_network = false\nread_write = [\"/\", \"..\"]\n", |
| 1195 | ) |
| 1196 | .expect("write hostile sandbox.toml"); |
| 1197 | |
| 1198 | let ro_args = create_seatbelt_args( |
| 1199 | vec![ |
| 1200 | "/bin/sh".to_string(), |
| 1201 | "-c".to_string(), |
| 1202 | "echo nope > out.txt".to_string(), |
| 1203 | ], |
| 1204 | &SandboxPolicy::read_only(), |
| 1205 | &root, |
| 1206 | &[], |
| 1207 | None, |
| 1208 | ); |
| 1209 | assert!(!ro_args[1].contains("network-outbound")); |
| 1210 | let ro_out = Command::new(SANDBOX_EXEC_PATH) |
| 1211 | .args(ro_args) |
| 1212 | .current_dir(&root) |
| 1213 | .output() |
| 1214 | .expect("run sandbox-exec"); |
| 1215 | assert!(!ro_out.status.success(), "read-only must stay read-only"); |
| 1216 | |
| 1217 | let ws_args = create_seatbelt_args( |
| 1218 | vec![ |
| 1219 | "/bin/sh".to_string(), |
| 1220 | "-c".to_string(), |
| 1221 | "cat .env".to_string(), |
| 1222 | ], |
| 1223 | &SandboxPolicy::default(), |
| 1224 | &root, |
| 1225 | &[], |
| 1226 | None, |
| 1227 | ); |
| 1228 | assert!(!ws_args[1].contains("network-outbound")); |
| 1229 | let ws_out = Command::new(SANDBOX_EXEC_PATH) |
| 1230 | .args(ws_args) |
| 1231 | .current_dir(&root) |
| 1232 | .output() |
| 1233 | .expect("run sandbox-exec"); |
| 1234 | assert!(!ws_out.status.success(), ".env must remain kernel-denied"); |
| 1235 | } |
| 1236 | } |
| 1237 |