返回 CodeWhale
bwrap.rs
根目录 / crates / sandbox / src / bwrap.rs
1 //! Bubblewrap (bwrap) passthrough for Linux sandbox (#2184).
2 //!
3 //! Bubblewrap is a setuid-less container runtime used by Flatpak and other
4 //! projects. It creates a new mount namespace with configurable bind mounts,
5 //! providing filesystem isolation without requiring root privileges.
6 //!
7 //! # How it works
8 //!
9 //! When `/usr/bin/bwrap` actually works — it is executable AND it can create
10 //! its namespaces on this host — sandboxed exec_shell commands are routed
11 //! through it by default. `prefer_bwrap = false` in the config opts out and
12 //! leaves Linux commands unwrapped; the posture then reports policy-only.
13 //! The bwrap invocation looks like:
14 //!
15 //! ```text
16 //! bwrap \
17 //! --unshare-all \
18 //! --ro-bind / / \
19 //! --dev /dev \
20 //! --proc /proc \
21 //! --tmpfs /tmp \
22 //! --bind <writable-root> <writable-root> \
23 //! --chdir <cwd> \
24 //! -- <program> <args>
25 //! ```
26 //!
27 //! This creates a read-only view of the entire filesystem with write access
28 //! limited to the policy-derived writable roots. Policies that allow network
29 //! access add `--share-net` after `--unshare-all`. A private `/dev` and
30 //! `/proc` plus a tmpfs `/tmp` keep standard toolchain expectations working
31 //! (#5410); user-configured extra roots and device nodes append after them.
32 //! The read deny-list masks go last; exceptions inside a masked directory
33 //! (`SandboxManager::set_denied_read_exceptions`) are bound again after them.
34 //!
35 //! The extension host (`extension_host::supervisor`) launches through this
36 //! builder whenever bubblewrap works, without the `prefer_bwrap` opt-in; it
37 //! probes the finished command first and reports the host as unsandboxed,
38 //! with bwrap's own error, when it does not run.
39 //!
40 //! # Important
41 //!
42 //! We do NOT vendor bwrap. The user must install it themselves:
43 //!
44 //! - Ubuntu/Debian: `apt install bubblewrap`
45 //! - Fedora: `dnf install bubblewrap`
46 //! - Arch: `pacman -S bubblewrap`
47 //!
48 //! If bwrap is missing, Codewhale reports no Linux OS sandbox and runs the
49 //! command without an OS wrapper (that is the documented no-launcher
50 //! fallback). If bwrap is installed but cannot run (e.g. user namespaces are
51 //! restricted, as on Ubuntu 24.04 with
52 //! `kernel.apparmor_restrict_unprivileged_userns`), a workspace-write posture
53 //! refuses the command instead of running it unwrapped: the launcher failed,
54 //! it was not missing. Read-only keeps its existing engine-side enforcement
55 //! rule. Neither path is ever labeled sandboxed.
56
57 #[cfg(target_os = "linux")]
58 use super::policy::{
59 DEFAULT_DENY_GLOBS, SandboxOverlay, SandboxPolicy, WritableRoot, expand_deny_globs_in_workspace,
60 };
61 #[cfg(target_os = "linux")]
62 use std::collections::BTreeSet;
63 #[cfg(target_os = "linux")]
64 use std::path::{Path, PathBuf};
65
66 /// Crate-visible wrapper over [`existing_directory`] so the sandbox module's
67 /// `BwrapMountExtensions::resolve` applies the same canonicalize + is_dir
68 /// rule to user-configured read-only roots (#5410).
69 #[cfg(target_os = "linux")]
70 pub(crate) fn existing_directory_shim(path: &Path) -> Option<PathBuf> {
71 existing_directory(path)
72 }
73
74 /// Canonical path to the bubblewrap binary.
75 #[cfg(target_os = "linux")]
76 pub const BWRAP_PATH: &str = "/usr/bin/bwrap";
77
78 pub(super) fn spawn<T: Send + 'static>(
79 launch: impl FnOnce() -> T + Send + 'static,
80 ) -> std::io::Result<T> {
81 use std::sync::{LazyLock, mpsc};
82 type Launch = Box<dyn FnOnce() + Send>;
83 static SPAWNER: LazyLock<std::io::Result<mpsc::Sender<Launch>>> = LazyLock::new(|| {
84 let (sender, receiver) = mpsc::channel::<Launch>();
85 std::thread::Builder::new()
86 .name("codewhale-sandbox-spawner".into())
87 .spawn(move || {
88 for launch in receiver {
89 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(launch));
90 }
91 })?;
92 Ok(sender)
93 });
94 let spawner = SPAWNER
95 .as_ref()
96 .map_err(|error| std::io::Error::new(error.kind(), error.to_string()))?;
97 let (sender, receiver) = mpsc::sync_channel(1);
98 spawner
99 .send(Box::new(move || {
100 let _ = sender.send(launch());
101 }))
102 .map_err(|_| std::io::Error::other("sandbox spawner stopped"))?;
103 receiver
104 .recv()
105 .map_err(|_| std::io::Error::other("sandbox spawn did not return"))
106 }
107
108 /// How long the availability probe may take. A working bwrap runs a wrapped
109 /// `/bin/true` in well under a second, even on a loaded host.
110 #[cfg(target_os = "linux")]
111 const PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(10);
112
113 /// How the configured bubblewrap launcher resolved on this host.
114 ///
115 /// `Failed` is deliberately distinct from `NotInstalled`. A host without a
116 /// launcher keeps the documented policy-only fallback, while a launcher that
117 /// is installed but cannot start a confined child is a broken dependency:
118 /// postures that promise filesystem/network enforcement must refuse rather
119 /// than silently run the command on the host.
120 #[derive(Clone, Debug, PartialEq, Eq)]
121 #[cfg(target_os = "linux")]
122 enum ProbeOutcome {
123 /// The installed launcher ran the wrapped probe successfully.
124 Available,
125 /// `/usr/bin/bwrap` is not installed on this host.
126 NotInstalled,
127 /// `/usr/bin/bwrap` is installed but cannot start a confined child here.
128 /// The payload names what the probe observed.
129 Failed(String),
130 }
131
132 /// The cached probe outcome for this process.
133 #[cfg(target_os = "linux")]
134 fn outcome() -> &'static ProbeOutcome {
135 static VERDICT: std::sync::OnceLock<ProbeOutcome> = std::sync::OnceLock::new();
136 VERDICT.get_or_init(|| probe_at(std::path::Path::new(BWRAP_PATH)))
137 }
138
139 /// Why an installed launcher cannot start a confined child here, if that is
140 /// the case.
141 ///
142 /// `None` means there is no failure to report: the launcher works, or it is
143 /// not installed at all, so the documented no-launcher fallback applies. A
144 /// caller that requires the sandbox must not treat the two as the same
145 /// question.
146 #[cfg(target_os = "linux")]
147 pub(crate) fn probe_failure() -> Option<&'static str> {
148 match outcome() {
149 ProbeOutcome::Failed(reason) => Some(reason.as_str()),
150 ProbeOutcome::Available | ProbeOutcome::NotInstalled => None,
151 }
152 }
153
154 /// Whether bwrap is executable AND can actually confine a child here.
155 ///
156 /// The exec bit alone lies on hosts where user namespaces are restricted:
157 /// bwrap starts but cannot create the sandbox, so every wrapped command
158 /// would fail instead of running unsandboxed. The check therefore runs a
159 /// real wrapped `/bin/true` once, built by [`build_bwrap_command`] itself so
160 /// the probe covers the same argument shape the real path uses, and caches
161 /// the verdict for the process.
162 #[cfg(target_os = "linux")]
163 pub fn is_available() -> bool {
164 matches!(outcome(), ProbeOutcome::Available)
165 }
166
167 /// Probe one launcher path. Split out from [`outcome`] so the three verdicts
168 /// can be exercised without writing to `/usr/bin`.
169 #[cfg(target_os = "linux")]
170 fn probe_at(launcher: &std::path::Path) -> ProbeOutcome {
171 use std::io::Read as _;
172 use std::os::unix::fs::PermissionsExt as _;
173 use wait_timeout::ChildExt as _;
174
175 match std::fs::metadata(launcher) {
176 Ok(metadata) => {
177 if !metadata.is_file() || metadata.permissions().mode() & 0o111 == 0 {
178 return ProbeOutcome::Failed(format!(
179 "{} is not an executable file",
180 launcher.display()
181 ));
182 }
183 }
184 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
185 return ProbeOutcome::NotInstalled;
186 }
187 Err(error) => {
188 return ProbeOutcome::Failed(format!(
189 "{} cannot be inspected: {error}",
190 launcher.display()
191 ));
192 }
193 }
194
195 let mut command = build_bwrap_command(
196 std::path::Path::new("/"),
197 "/bin/true",
198 &[],
199 &[],
200 false,
201 &crate::BwrapMountExtensions::default(),
202 &[],
203 &[],
204 );
205 if let Some(program) = command.first_mut() {
206 *program = launcher.to_string_lossy().into_owned();
207 }
208 let Some((program, args)) = command.split_first() else {
209 return ProbeOutcome::Failed(format!(
210 "{} produced an empty launcher command",
211 launcher.display()
212 ));
213 };
214 let mut child = match std::process::Command::new(program)
215 .args(args)
216 .env_clear()
217 .stdin(std::process::Stdio::null())
218 .stdout(std::process::Stdio::null())
219 .stderr(std::process::Stdio::piped())
220 .spawn()
221 {
222 Ok(child) => child,
223 Err(error) => {
224 return ProbeOutcome::Failed(format!(
225 "{} could not start: {error}",
226 launcher.display()
227 ));
228 }
229 };
230 let status = match child.wait_timeout(PROBE_DEADLINE) {
231 Ok(Some(status)) => status,
232 _ => {
233 let _ = child.kill();
234 let _ = child.wait();
235 return ProbeOutcome::Failed(format!(
236 "{} did not finish its probe within {}s",
237 launcher.display(),
238 PROBE_DEADLINE.as_secs()
239 ));
240 }
241 };
242 if status.success() {
243 return ProbeOutcome::Available;
244 }
245 let mut stderr = String::new();
246 if let Some(mut pipe) = child.stderr.take() {
247 let _ = pipe.read_to_string(&mut stderr);
248 }
249 let reason = super::bwrap_setup_failure(&stderr)
250 .or_else(|| stderr.lines().map(str::trim).find(|line| !line.is_empty()))
251 .map_or_else(|| format!("exit status {status}"), str::to_string);
252 ProbeOutcome::Failed(format!(
253 "{} could not create a sandbox here: {}",
254 launcher.display(),
255 reason.chars().take(400).collect::<String>()
256 ))
257 }
258
259 #[cfg(target_os = "linux")]
260 #[derive(Clone, Debug, PartialEq, Eq)]
261 pub struct LaunchIdentity {
262 pub uid: u32,
263 pub gids: Vec<u32>,
264 }
265
266 #[cfg(target_os = "linux")]
267 impl LaunchIdentity {
268 fn can_search(&self, dir: &Path) -> bool {
269 use std::os::unix::fs::MetadataExt;
270 let Ok(metadata) = std::fs::metadata(dir) else {
271 return false;
272 };
273 if self.uid == 0 {
274 return true;
275 }
276 let mode = metadata.mode();
277 if metadata.uid() == self.uid {
278 mode & 0o100 != 0
279 } else if self.gids.contains(&metadata.gid()) {
280 mode & 0o010 != 0
281 } else {
282 mode & 0o001 != 0
283 }
284 }
285
286 pub(crate) fn reaches(&self, path: &Path) -> bool {
287 path.ancestors().skip(1).all(|dir| self.can_search(dir))
288 }
289
290 pub(crate) fn mask_target(&self, path: &Path) -> PathBuf {
291 let mut ancestors: Vec<&Path> = path.ancestors().skip(1).collect();
292 ancestors.reverse();
293 ancestors
294 .into_iter()
295 .find(|dir| *dir != Path::new("/") && !self.can_search(dir))
296 .map_or_else(|| path.to_path_buf(), Path::to_path_buf)
297 }
298
299 fn parse(output: &str) -> Option<Self> {
300 let mut lines = output.lines();
301 let uid = lines.next()?.trim().parse().ok()?;
302 let gids = lines
303 .next()?
304 .split_whitespace()
305 .map(str::parse)
306 .collect::<Result<Vec<u32>, _>>()
307 .ok()?;
308 Some(Self { uid, gids })
309 }
310 }
311
312 #[cfg(target_os = "linux")]
313 fn run_probe(argv: &[String]) -> Result<String, String> {
314 use std::io::Read as _;
315 use wait_timeout::ChildExt as _;
316 let (program, args) = argv
317 .split_first()
318 .ok_or_else(|| "empty probe command".to_string())?;
319 let mut child = std::process::Command::new(program)
320 .args(args)
321 .env_clear()
322 .env("PATH", "/usr/bin:/bin")
323 .stdin(std::process::Stdio::null())
324 .stdout(std::process::Stdio::piped())
325 .stderr(std::process::Stdio::piped())
326 .spawn()
327 .map_err(|error| format!("{program} could not start: {error}"))?;
328 let status = match child.wait_timeout(PROBE_DEADLINE) {
329 Ok(Some(status)) => status,
330 _ => {
331 let _ = child.kill();
332 let _ = child.wait();
333 return Err(format!(
334 "{program} did not finish within {}s",
335 PROBE_DEADLINE.as_secs()
336 ));
337 }
338 };
339 let mut stdout = String::new();
340 let mut stderr = String::new();
341 if let Some(mut pipe) = child.stdout.take() {
342 let _ = pipe.read_to_string(&mut stdout);
343 }
344 if let Some(mut pipe) = child.stderr.take() {
345 let _ = pipe.read_to_string(&mut stderr);
346 }
347 if status.success() {
348 return Ok(stdout);
349 }
350 let reason = super::bwrap_setup_failure(&stderr)
351 .or_else(|| stderr.lines().map(str::trim).find(|line| !line.is_empty()))
352 .map_or_else(|| format!("{program} exited with {status}"), str::to_string);
353 Err(reason.chars().take(400).collect())
354 }
355
356 #[cfg(target_os = "linux")]
357 pub fn probe_launcher(
358 launcher: &[String],
359 denied_read_subpaths: &[PathBuf],
360 ) -> Result<LaunchIdentity, String> {
361 use std::collections::HashMap;
362 use std::sync::{LazyLock, Mutex};
363 type Key = (Vec<String>, Vec<PathBuf>);
364 static READY: LazyLock<Mutex<HashMap<Key, LaunchIdentity>>> =
365 LazyLock::new(|| Mutex::new(HashMap::new()));
366 let key = (launcher.to_vec(), denied_read_subpaths.to_vec());
367 if let Some(identity) = READY
368 .lock()
369 .unwrap_or_else(std::sync::PoisonError::into_inner)
370 .get(&key)
371 {
372 return Ok(identity.clone());
373 }
374 if !is_executable(Path::new(BWRAP_PATH)) {
375 return Err(format!("{BWRAP_PATH} is not installed"));
376 }
377 let mut id_command = launcher.to_vec();
378 id_command.extend(["/bin/sh", "-c", "id -u && id -G"].map(str::to_string));
379 let identity = LaunchIdentity::parse(&run_probe(&id_command)?)
380 .ok_or_else(|| "the launcher did not report its user and groups".to_string())?;
381 let mut bwrap_command = launcher.to_vec();
382 bwrap_command.extend(build_bwrap_command_with_read_paths(
383 Path::new("/"),
384 "/bin/true",
385 &[],
386 &[],
387 false,
388 &crate::BwrapMountExtensions::default(),
389 denied_read_subpaths,
390 &[],
391 None,
392 Some(&identity),
393 ));
394 run_probe(&bwrap_command)?;
395 READY
396 .lock()
397 .unwrap_or_else(std::sync::PoisonError::into_inner)
398 .insert(key, identity.clone());
399 Ok(identity)
400 }
401
402 #[cfg(target_os = "linux")]
403 pub(crate) fn is_executable(path: &std::path::Path) -> bool {
404 use std::os::unix::fs::PermissionsExt;
405
406 std::fs::metadata(path)
407 .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
408 }
409
410 #[cfg(not(target_os = "linux"))]
411 pub fn is_available() -> bool {
412 false
413 }
414
415 /// Build a bwrap command that wraps the given program and arguments.
416 ///
417 /// The returned command vector is suitable for use as `ExecEnv.command` —
418 /// it replaces the normal program+args with a bwrap invocation that sets
419 /// up a read-only root filesystem with write access only to the specified
420 /// policy roots.
421 ///
422 /// # Arguments
423 ///
424 /// - `cwd` — working directory and sandbox chdir target
425 /// - `program` — the program to run inside the container
426 /// - `args` — arguments to pass to the program
427 /// - `writable_roots` — policy-derived directories to remount read-write
428 /// - `network_access` — whether to retain the caller's network namespace
429 /// - `extensions` — user-configured extra read-only roots and writable
430 /// device nodes (#5410); skipped when they do not exist on the host
431 ///
432 /// # Returns
433 ///
434 /// A `Vec<String>` representing the full bwrap invocation.
435 #[cfg(target_os = "linux")]
436 #[expect(clippy::too_many_arguments)]
437 pub fn build_bwrap_command(
438 cwd: &std::path::Path,
439 program: &str,
440 args: &[String],
441 writable_roots: &[WritableRoot],
442 network_access: bool,
443 extensions: &crate::BwrapMountExtensions,
444 denied_read_subpaths: &[std::path::PathBuf],
445 denied_read_exceptions: &[std::path::PathBuf],
446 ) -> Vec<String> {
447 build_bwrap_command_with_read_paths(
448 cwd,
449 program,
450 args,
451 writable_roots,
452 network_access,
453 extensions,
454 denied_read_subpaths,
455 denied_read_exceptions,
456 None,
457 None,
458 )
459 }
460
461 #[cfg(target_os = "linux")]
462 #[expect(clippy::too_many_arguments)]
463 pub(crate) fn build_bwrap_command_with_read_paths(
464 cwd: &std::path::Path,
465 program: &str,
466 args: &[String],
467 writable_roots: &[WritableRoot],
468 network_access: bool,
469 extensions: &crate::BwrapMountExtensions,
470 denied_read_subpaths: &[std::path::PathBuf],
471 denied_read_exceptions: &[std::path::PathBuf],
472 readable_paths: Option<&[PathBuf]>,
473 launch_identity: Option<&LaunchIdentity>,
474 ) -> Vec<String> {
475 let reachable = |path: &PathBuf| launch_identity.is_none_or(|identity| identity.reaches(path));
476 let caller_policy = if writable_roots.is_empty() {
477 SandboxPolicy::ReadOnly { network_access }
478 } else {
479 SandboxPolicy::WorkspaceWrite {
480 writable_roots: vec![],
481 network_access,
482 exclude_tmpdir: false,
483 exclude_slash_tmp: false,
484 }
485 };
486 let overlay = SandboxOverlay::load_from_workspace(cwd).ok().flatten();
487 let resolved_overlay = overlay
488 .as_ref()
489 .map(|raw| caller_policy.apply_workspace_overlay(raw, cwd));
490 let effective_network_access = match &resolved_overlay {
491 Some(resolved) => network_access && resolved.policy.has_network_access(),
492 None => network_access,
493 };
494 let (mut writable_mounts, mut read_only_mounts) = safe_mounts(writable_roots);
495 let (mut extra_read_only, mut device_mounts) = extensions.resolve();
496 let mut effective_denied: Vec<PathBuf> = denied_read_subpaths.to_vec();
497 let default_globs: Vec<String> = DEFAULT_DENY_GLOBS
498 .iter()
499 .map(|glob| (*glob).to_string())
500 .collect();
501 let deny_globs: &[String] = match &resolved_overlay {
502 Some(resolved) => &resolved.deny_globs,
503 None => &default_globs,
504 };
505 for denied in expand_deny_globs_in_workspace(deny_globs, cwd) {
506 if (launch_identity.is_none() || reachable(&denied)) && !effective_denied.contains(&denied)
507 {
508 effective_denied.push(denied);
509 }
510 }
511 if let Some(resolved) = &resolved_overlay {
512 if !writable_roots.is_empty()
513 && let SandboxPolicy::WorkspaceWrite {
514 writable_roots: overlay_rw,
515 ..
516 } = &resolved.policy
517 {
518 for root in overlay_rw {
519 if let Some(canonical) = safe_existing_directory(root)
520 && !writable_mounts.contains(&canonical)
521 {
522 writable_mounts.push(canonical);
523 }
524 }
525 }
526 if matches!(resolved.policy, SandboxPolicy::ReadOnly { .. }) {
527 writable_mounts.clear();
528 read_only_mounts.clear();
529 }
530 for ro_path in &resolved.read_only_paths {
531 if ro_path.exists() {
532 let canonical = super::policy::canonical_or_self(ro_path);
533 if canonical != Path::new("/") && !extra_read_only.contains(&canonical) {
534 extra_read_only.push(canonical);
535 }
536 }
537 }
538 }
539 writable_mounts.retain(reachable);
540 read_only_mounts.retain(reachable);
541 extra_read_only.retain(reachable);
542 device_mounts.retain(reachable);
543 let readable_paths: Option<Vec<PathBuf>> = readable_paths.map(|paths| {
544 paths
545 .iter()
546 .filter(|path| reachable(path))
547 .cloned()
548 .collect()
549 });
550 let mut cmd: Vec<String> =
551 Vec::with_capacity(10 + args.len() + 3 * (writable_mounts.len() + read_only_mounts.len()));
552
553 cmd.push(BWRAP_PATH.to_string());
554
555 // Isolate every supported namespace by default. `--share-net` selectively
556 // retains only the network namespace when the resolved policy allows it.
557 cmd.push("--unshare-all".to_string());
558 if effective_network_access {
559 cmd.push("--share-net".to_string());
560 }
561 // Tie the sandbox to the outer bwrap process: if it is killed (the TUI's
562 // parent-death cleanup, a group kill), bwrap's PID-namespace init dies
563 // too and takes every process in the sandbox with it (#6654).
564 cmd.push("--die-with-parent".to_string());
565
566 let mut synthetic_roots: Vec<PathBuf> = if readable_paths.is_some() {
567 vec![PathBuf::from("/dev"), PathBuf::from("/")]
568 } else {
569 Vec::new()
570 };
571
572 if readable_paths.is_none() {
573 cmd.push("--ro-bind".to_string());
574 cmd.push("/".to_string());
575 cmd.push("/".to_string());
576 }
577
578 // Standard container essentials (#5410): a private `/dev` (so device
579 // nodes exist fresh and writable — `>/dev/null` under the read-only
580 // root bind is EROFS without this), `/proc`, and a writable isolated
581 // `/tmp` for toolchain scratch space.
582 cmd.push("--dev".to_string());
583 cmd.push("/dev".to_string());
584 cmd.push("--proc".to_string());
585 cmd.push("/proc".to_string());
586 cmd.push("--tmpfs".to_string());
587 cmd.push("/tmp".to_string());
588
589 if let Some(paths) = &readable_paths {
590 for path in paths {
591 synthetic_roots.retain(|root| !root.starts_with(path));
592 cmd.push("--ro-bind".to_string());
593 cmd.push(path.to_string_lossy().into_owned());
594 cmd.push(path.to_string_lossy().into_owned());
595 }
596 }
597
598 // User-configured writable device nodes (#5410), e.g. a host `/dev/null`
599 // when the caller needs the host's, not the fresh private one.
600 for device in device_mounts {
601 synthetic_roots.retain(|root| !root.starts_with(&device));
602 let device = device.to_string_lossy().into_owned();
603 cmd.push("--dev-bind".to_string());
604 cmd.push(device.clone());
605 cmd.push(device);
606 }
607
608 let mut policy_mounts: Vec<(&Path, bool)> = writable_mounts
609 .iter()
610 .map(|root| (root.as_path(), false))
611 .chain(read_only_mounts.iter().map(|root| (root.as_path(), true)))
612 .collect();
613 policy_mounts.sort_unstable();
614 for (root, is_read_only) in policy_mounts {
615 synthetic_roots.retain(|synthetic| !synthetic.starts_with(root));
616 let flag = if is_read_only { "--ro-bind" } else { "--bind" };
617 let root = root.to_string_lossy().into_owned();
618 cmd.push(flag.to_string());
619 cmd.push(root.clone());
620 cmd.push(root);
621 }
622
623 // User-configured extra read-only roots (#5410) apply last so they can
624 // narrow (re-mount read-only over) any earlier writable bind if the
625 // user explicitly lists a path the policy made writable.
626 for root in extra_read_only {
627 synthetic_roots.retain(|synthetic| !synthetic.starts_with(&root));
628 let root = root.to_string_lossy().into_owned();
629 cmd.push("--ro-bind".to_string());
630 cmd.push(root.clone());
631 cmd.push(root);
632 }
633
634 // Opt-in read deny-list (S1, #5568), applied after every bind so nothing
635 // re-exposes a denied path: an existing directory is masked with an empty
636 // tmpfs, an existing file with a bind of /dev/null. Non-existent paths
637 // are skipped — there is nothing to deny.
638 let mut lifted_masks: Vec<PathBuf> = Vec::new();
639 for denied in &effective_denied {
640 let resolved = std::fs::canonicalize(denied).ok();
641 let lifted = launch_identity.and_then(|identity| {
642 let resolved = resolved.as_ref()?;
643 let target = identity.mask_target(resolved);
644 (target != *resolved).then_some(target)
645 });
646 match lifted {
647 Some(target) if lifted_masks.contains(&target) => {}
648 Some(target) => {
649 synthetic_roots.retain(|synthetic| !synthetic.starts_with(&target));
650 cmd.push("--tmpfs".to_string());
651 cmd.push(target.to_string_lossy().into_owned());
652 lifted_masks.push(target);
653 }
654 None => {
655 if let Some(resolved) = resolved.as_ref() {
656 synthetic_roots.retain(|synthetic| !synthetic.starts_with(resolved));
657 }
658 cmd.extend(super::bwrap_mask_args(denied));
659 }
660 }
661 }
662
663 // Exceptions inside a masked directory (the extension host's own files
664 // and plugin code under a Codewhale home it denies whole) are bound again
665 // after the masks, then any denied path inside them is masked again.
666 cmd.extend(super::bwrap_exception_args(
667 &effective_denied,
668 denied_read_exceptions,
669 &writable_mounts,
670 ));
671
672 for synthetic in synthetic_roots {
673 cmd.push("--remount-ro".to_string());
674 cmd.push(synthetic.to_string_lossy().into_owned());
675 }
676
677 // Change to the working directory inside the container.
678 let cwd_str = cwd.to_string_lossy().to_string();
679 cmd.push("--chdir".to_string());
680 cmd.push(cwd_str);
681
682 // Separator between bwrap args and the command to run.
683 cmd.push("--".to_string());
684
685 // The actual program and its arguments.
686 cmd.push(program.to_string());
687 cmd.extend(args.iter().cloned());
688
689 cmd
690 }
691
692 #[cfg(target_os = "linux")]
693 fn safe_mounts(writable_roots: &[WritableRoot]) -> (Vec<PathBuf>, Vec<PathBuf>) {
694 let mut writable = BTreeSet::new();
695 let mut read_only = BTreeSet::new();
696
697 for root in writable_roots {
698 let Some(canonical_root) = safe_existing_directory(&root.root) else {
699 continue;
700 };
701 writable.insert(canonical_root.clone());
702
703 for exception in &root.read_only_subpaths {
704 let Some(canonical_exception) = exception.canonicalize().ok() else {
705 continue;
706 };
707 if canonical_exception.starts_with(&canonical_root) {
708 read_only.insert(canonical_exception);
709 }
710 }
711 }
712
713 (
714 writable.into_iter().collect(),
715 read_only.into_iter().collect(),
716 )
717 }
718
719 #[cfg(target_os = "linux")]
720 fn safe_existing_directory(path: &Path) -> Option<PathBuf> {
721 let canonical = existing_directory(path)?;
722 (canonical != Path::new("/")).then_some(canonical)
723 }
724
725 #[cfg(target_os = "linux")]
726 fn existing_directory(path: &Path) -> Option<PathBuf> {
727 let canonical = path.canonicalize().ok()?;
728 canonical.is_dir().then_some(canonical)
729 }
730
731 #[cfg(target_os = "linux")]
732 fn stderr_matches_erofs(stderr: &str, localized_erofs: Option<&str>) -> bool {
733 stderr.contains("Read-only file system")
734 || localized_erofs.is_some_and(|msg| !msg.is_empty() && stderr.contains(msg))
735 }
736
737 #[cfg(target_os = "linux")]
738 pub(crate) fn is_erofs_stderr(stderr: &str) -> bool {
739 let localized = super::localized_errno_message(libc::EROFS);
740 stderr_matches_erofs(stderr, localized.as_deref())
741 }
742
743 #[cfg(target_os = "linux")]
744 fn detect_denial_with_localized(
745 exit_code: i32,
746 stderr: &str,
747 localized_erofs: Option<&str>,
748 ) -> bool {
749 exit_code != 0
750 && (super::bwrap_setup_failure(stderr).is_some()
751 || stderr_matches_erofs(stderr, localized_erofs))
752 }
753
754 /// Detect a failure attributable to the bubblewrap boundary.
755 #[cfg(target_os = "linux")]
756 pub fn detect_denial(exit_code: i32, stderr: &str) -> bool {
757 let localized = super::localized_errno_message(libc::EROFS);
758 detect_denial_with_localized(exit_code, stderr, localized.as_deref())
759 }
760
761 #[cfg(not(target_os = "linux"))]
762 pub fn detect_denial(_exit_code: i32, _stderr: &str) -> bool {
763 false
764 }
765
766 #[cfg(test)]
767 mod tests {
768 use super::*;
769
770 #[test]
771 fn test_is_available_does_not_panic() {
772 let _ = is_available();
773 }
774
775 #[test]
776 #[cfg(target_os = "linux")]
777 fn test_build_bwrap_command_structure() {
778 let dir = tempfile::tempdir().expect("tempdir");
779 let cwd = dir.path();
780 let cmd = build_bwrap_command(
781 cwd,
782 "sh",
783 &["-c".to_string(), "echo hi".to_string()],
784 &[WritableRoot::new(cwd.to_path_buf())],
785 false,
786 &crate::BwrapMountExtensions::default(),
787 &[],
788 &[],
789 );
790
791 // Should start with bwrap
792 assert_eq!(cmd[0], "/usr/bin/bwrap");
793
794 // Should have ro-bind for root
795 assert!(cmd.contains(&"--ro-bind".to_string()));
796
797 // Standard container essentials (#5410): private /dev, /proc, tmpfs /tmp.
798 assert!(cmd.contains(&"--dev".to_string()));
799 assert!(cmd.contains(&"--proc".to_string()));
800 assert!(cmd.contains(&"--tmpfs".to_string()));
801
802 // Should have --chdir
803 assert!(cmd.contains(&"--chdir".to_string()));
804
805 // Network stays isolated unless the policy explicitly allows it.
806 assert!(cmd.contains(&"--unshare-all".to_string()));
807 assert!(!cmd.contains(&"--share-net".to_string()));
808
809 // The sandbox dies with the outer bwrap process (#6654).
810 assert!(cmd.contains(&"--die-with-parent".to_string()));
811
812 // Should end with the command
813 assert_eq!(cmd[cmd.len() - 1], "echo hi");
814 assert_eq!(cmd[cmd.len() - 2], "-c");
815 assert_eq!(cmd[cmd.len() - 3], "sh");
816 }
817
818 #[test]
819 #[cfg(target_os = "linux")]
820 fn read_only_command_does_not_remount_the_working_directory_writable() {
821 let dir = tempfile::tempdir().expect("tempdir");
822 let cwd = dir.path();
823 let cmd = build_bwrap_command(
824 cwd,
825 "true",
826 &[],
827 &[],
828 false,
829 &crate::BwrapMountExtensions::default(),
830 &[],
831 &[],
832 );
833
834 assert!(!cmd.iter().any(|arg| arg == "--bind"));
835 assert!(!cmd.iter().any(|arg| arg == "--share-net"));
836 assert!(
837 cmd.windows(2)
838 .any(|args| args[0] == "--chdir" && args[1] == cwd.to_string_lossy())
839 );
840 }
841
842 #[test]
843 #[cfg(target_os = "linux")]
844 fn workspace_write_mounts_every_safe_root_and_protects_read_only_descendants() {
845 let dir = tempfile::tempdir().expect("tempdir");
846 let workspace = dir.path().join("workspace");
847 let extra = dir.path().join("extra");
848 let protected = workspace.join(".codewhale");
849 std::fs::create_dir_all(&protected).expect("protected directory");
850 std::fs::create_dir_all(&extra).expect("extra directory");
851
852 let roots = vec![
853 WritableRoot::with_exceptions(workspace.clone(), vec![protected.clone()]),
854 WritableRoot::new(extra.clone()),
855 WritableRoot::new(dir.path().join("missing")),
856 WritableRoot::new(PathBuf::from("/")),
857 ];
858 let cmd = build_bwrap_command(
859 &workspace,
860 "true",
861 &[],
862 &roots,
863 true,
864 &crate::BwrapMountExtensions::default(),
865 &[],
866 &[],
867 );
868
869 for root in [&workspace, &extra] {
870 let canonical = root.canonicalize().expect("canonical root");
871 assert!(has_mount(&cmd, "--bind", &canonical));
872 }
873 assert!(has_mount(
874 &cmd,
875 "--ro-bind",
876 &protected.canonicalize().expect("canonical protected path")
877 ));
878 assert!(!has_mount(&cmd, "--bind", Path::new("/")));
879 assert!(!cmd.iter().any(|arg| arg.ends_with("/missing")));
880
881 let unshare = cmd
882 .iter()
883 .position(|arg| arg == "--unshare-all")
884 .expect("unshare all");
885 let share = cmd
886 .iter()
887 .position(|arg| arg == "--share-net")
888 .expect("share net");
889 assert!(share > unshare);
890 }
891
892 #[test]
893 #[cfg(target_os = "linux")]
894 fn extensions_add_ro_roots_and_device_nodes_and_skip_invalid_entries() {
895 let dir = tempfile::tempdir().expect("tempdir");
896 let cwd = dir.path();
897 let extra_ro = dir.path().join("vendor-libs");
898 std::fs::create_dir_all(&extra_ro).expect("extra ro dir");
899
900 let extensions = crate::BwrapMountExtensions {
901 read_only_roots: vec![
902 extra_ro.clone(),
903 dir.path().join("missing-ro"), // silently skipped
904 ],
905 device_roots: vec![
906 // A real char device on every Linux host: /dev/null.
907 PathBuf::from("/dev/null"),
908 // Not a device: skipped even though it exists.
909 extra_ro.clone(),
910 // Missing: skipped.
911 PathBuf::from("/dev/does-not-exist"),
912 ],
913 };
914 let cmd = build_bwrap_command(cwd, "true", &[], &[], false, &extensions, &[], &[]);
915
916 assert!(has_mount(
917 &cmd,
918 "--ro-bind",
919 &extra_ro.canonicalize().expect("canonical extra"),
920 ));
921 assert!(has_mount(
922 &cmd,
923 "--dev-bind",
924 &PathBuf::from("/dev/null")
925 .canonicalize()
926 .expect("canonical null")
927 ));
928 // The non-device directory must never appear as a dev-bind — the key
929 // is not a writable-root escape hatch.
930 assert!(!cmd.iter().any(|arg| arg.ends_with("/missing-ro")));
931 let dev_binds_of_extra = cmd
932 .windows(3)
933 .any(|args| args[0] == "--dev-bind" && args[1].as_str() == extra_ro.to_string_lossy());
934 assert!(!dev_binds_of_extra, "directories must not be dev-bound");
935 }
936
937 #[test]
938 #[cfg(target_os = "linux")]
939 fn extension_ro_roots_apply_after_writable_binds_so_they_can_narrow() {
940 let dir = tempfile::tempdir().expect("tempdir");
941 let workspace = dir.path().join("workspace");
942 let narrowed = workspace.join("vendor-libs");
943 std::fs::create_dir_all(&narrowed).expect("dirs");
944
945 let roots = vec![WritableRoot::new(workspace.clone())];
946 let extensions = crate::BwrapMountExtensions {
947 read_only_roots: vec![narrowed.clone()],
948 device_roots: vec![],
949 };
950 let cmd = build_bwrap_command(
951 &workspace,
952 "true",
953 &[],
954 &roots,
955 false,
956 &extensions,
957 &[],
958 &[],
959 );
960
961 let writable_pos = cmd
962 .windows(3)
963 .position(|args| {
964 args[0] == "--bind"
965 && args[1].as_str() == workspace.canonicalize().unwrap().to_string_lossy()
966 })
967 .expect("workspace writable bind");
968 let narrow_pos = cmd
969 .windows(3)
970 .position(|args| {
971 args[0] == "--ro-bind"
972 && args[1].as_str() == narrowed.canonicalize().unwrap().to_string_lossy()
973 })
974 .expect("narrowed ro bind");
975 assert!(
976 narrow_pos > writable_pos,
977 "extra ro roots must apply after writable binds so they can narrow them"
978 );
979 }
980
981 /// The extension host's form of the deny-list: its Codewhale home masked
982 /// whole, then its own files bound again read-only and its data dir
983 /// writable again, all after the mask; a missing exception is skipped.
984 #[test]
985 #[cfg(target_os = "linux")]
986 fn a_home_denied_whole_keeps_its_exceptions_after_the_mask() {
987 let dir = tempfile::tempdir().expect("tempdir");
988 std::fs::create_dir_all(dir.path().join("home/extension-host/data")).expect("data dir");
989 std::fs::create_dir_all(dir.path().join("home/secrets")).expect("secrets dir");
990 let home = dir
991 .path()
992 .join("home")
993 .canonicalize()
994 .expect("canonical home");
995 let bundle = home.join("extension-host");
996 let data = bundle.join("data");
997 let cmd = build_bwrap_command(
998 &data,
999 "true",
1000 &[],
1001 &[WritableRoot::new(data.clone())],
1002 false,
1003 &crate::BwrapMountExtensions::default(),
1004 std::slice::from_ref(&home),
1005 &[bundle.clone(), home.join("plugins")],
1006 );
1007 let at = |flag: &str, path: &Path| -> Vec<usize> {
1008 cmd.windows(3)
1009 .enumerate()
1010 .filter(|(_, args)| args[0] == flag && args[1] == path.to_string_lossy())
1011 .map(|(index, _)| index)
1012 .collect()
1013 };
1014 let mask = at("--tmpfs", &home);
1015 let exception = at("--ro-bind", &bundle);
1016 let data_binds = at("--bind", &data);
1017 assert_eq!(mask.len(), 1, "{cmd:?}");
1018 assert_eq!(exception.len(), 1, "{cmd:?}");
1019 assert!(mask[0] < exception[0], "{cmd:?}");
1020 assert!(data_binds.last() > Some(&exception[0]), "{cmd:?}");
1021 assert!(!cmd.iter().any(|arg| arg.ends_with("/plugins")), "{cmd:?}");
1022 }
1023
1024 #[test]
1025 #[cfg(target_os = "linux")]
1026 fn a_deny_path_the_launcher_user_cannot_reach_is_masked_at_its_highest_closed_ancestor() {
1027 use std::os::unix::fs::PermissionsExt;
1028 let dir = tempfile::tempdir_in("/tmp").expect("tempdir");
1029 let root = dir.path().canonicalize().expect("canonical tempdir");
1030 std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755)).unwrap();
1031 let closed = root.join("engine-home");
1032 let secret = closed.join(".codewhale/secrets");
1033 std::fs::create_dir_all(&secret).expect("secret dir");
1034 std::fs::create_dir_all(closed.join("work")).expect("closed work dir");
1035 std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o700)).unwrap();
1036 let open = root.join("workspace");
1037 let open_secret = open.join(".env");
1038 std::fs::create_dir_all(&open).expect("workspace");
1039 std::fs::write(&open_secret, b"x").expect("open secret");
1040 let stranger = LaunchIdentity {
1041 uid: u32::MAX - 7,
1042 gids: vec![u32::MAX - 7],
1043 };
1044 assert_eq!(stranger.mask_target(&secret), closed);
1045 assert_eq!(stranger.mask_target(&open_secret), open_secret);
1046 assert!(stranger.reaches(&open));
1047 assert!(!stranger.reaches(&closed.join("work")));
1048
1049 let cmd = build_bwrap_command_with_read_paths(
1050 &open,
1051 "true",
1052 &[],
1053 &[
1054 WritableRoot::new(open.clone()),
1055 WritableRoot::new(closed.join("work")),
1056 ],
1057 false,
1058 &crate::BwrapMountExtensions::default(),
1059 &[
1060 secret.clone(),
1061 closed.join(".ssh-missing"),
1062 open_secret.clone(),
1063 ],
1064 &[],
1065 None,
1066 Some(&stranger),
1067 );
1068 let masks: Vec<&[String]> = cmd
1069 .windows(2)
1070 .filter(|args| args[0] == "--tmpfs" && args[1] != "/tmp")
1071 .collect();
1072 assert_eq!(masks.len(), 1, "{cmd:?}");
1073 assert_eq!(masks[0][1], closed.to_string_lossy());
1074 assert!(!cmd.iter().any(|arg| arg.ends_with("/secrets")), "{cmd:?}");
1075 assert!(has_mount(&cmd, "--bind", &open));
1076 assert!(!cmd.iter().any(|arg| arg.ends_with("/work")), "{cmd:?}");
1077 assert!(
1078 cmd.windows(3).any(|args| args[0] == "--ro-bind"
1079 && args[1] == "/dev/null"
1080 && args[2] == open_secret.to_string_lossy()),
1081 "{cmd:?}"
1082 );
1083 assert!(cmd.iter().any(|arg| arg == "--die-with-parent"));
1084 std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o755)).unwrap();
1085 }
1086
1087 #[test]
1088 #[cfg(target_os = "linux")]
1089 fn launch_identity_parses_id_output() {
1090 assert_eq!(
1091 LaunchIdentity::parse("1001\n1001 27 100\n"),
1092 Some(LaunchIdentity {
1093 uid: 1001,
1094 gids: vec![1001, 27, 100],
1095 })
1096 );
1097 assert_eq!(
1098 LaunchIdentity::parse("sudo: a password is required\n"),
1099 None
1100 );
1101 }
1102
1103 #[cfg(target_os = "linux")]
1104 fn has_mount(command: &[String], flag: &str, path: &Path) -> bool {
1105 let path = path.to_string_lossy();
1106 command.windows(3).any(|args| {
1107 args[0] == flag
1108 && args[1].as_str() == path.as_ref()
1109 && args[2].as_str() == path.as_ref()
1110 })
1111 }
1112
1113 #[test]
1114 #[cfg(target_os = "linux")]
1115 fn executable_probe_requires_a_regular_executable_file() {
1116 use std::os::unix::fs::PermissionsExt;
1117
1118 let dir = tempfile::tempdir().expect("tempdir");
1119 let path = dir.path().join("bwrap");
1120 std::fs::write(&path, b"fixture").expect("write fixture");
1121 assert!(!is_executable(&path));
1122
1123 let mut permissions = std::fs::metadata(&path).expect("metadata").permissions();
1124 permissions.set_mode(0o755);
1125 std::fs::set_permissions(&path, permissions).expect("set executable bit");
1126 assert!(is_executable(&path));
1127 assert!(!is_executable(dir.path()));
1128 }
1129
1130 #[test]
1131 #[cfg(target_os = "linux")]
1132 fn probe_separates_a_missing_launcher_from_a_broken_one() {
1133 use std::os::unix::fs::PermissionsExt;
1134
1135 let dir = tempfile::tempdir().expect("tempdir");
1136 assert_eq!(
1137 probe_at(&dir.path().join("missing")),
1138 ProbeOutcome::NotInstalled
1139 );
1140
1141 // Installed but not executable is a fault, not an opt-out.
1142 let not_executable = dir.path().join("bwrap");
1143 std::fs::write(&not_executable, b"fixture").expect("write fixture");
1144 let mut permissions = std::fs::metadata(&not_executable)
1145 .expect("metadata")
1146 .permissions();
1147 permissions.set_mode(0o644);
1148 std::fs::set_permissions(&not_executable, permissions).expect("set permissions");
1149 assert!(matches!(probe_at(&not_executable), ProbeOutcome::Failed(_)));
1150
1151 // Installed and executable, but it cannot create a sandbox: the
1152 // probe must report a failure with the launcher's own diagnostic.
1153 let broken = dir.path().join("broken-bwrap");
1154 std::fs::write(
1155 &broken,
1156 b"#!/bin/sh\necho 'bwrap: setting up uid map: Permission denied' >&2\nexit 1\n",
1157 )
1158 .expect("write fixture");
1159 let mut permissions = std::fs::metadata(&broken).expect("metadata").permissions();
1160 permissions.set_mode(0o755);
1161 std::fs::set_permissions(&broken, permissions).expect("set permissions");
1162 match probe_at(&broken) {
1163 ProbeOutcome::Failed(reason) => {
1164 assert!(reason.contains("Permission denied"), "{reason}");
1165 }
1166 other => panic!("expected a failed probe, got {other:?}"),
1167 }
1168
1169 // A launcher that runs the wrapped probe successfully is available.
1170 let working = dir.path().join("working-bwrap");
1171 std::fs::write(&working, b"#!/bin/sh\nexit 0\n").expect("write fixture");
1172 let mut permissions = std::fs::metadata(&working).expect("metadata").permissions();
1173 permissions.set_mode(0o755);
1174 std::fs::set_permissions(&working, permissions).expect("set permissions");
1175 assert_eq!(probe_at(&working), ProbeOutcome::Available);
1176 }
1177
1178 #[test]
1179 fn denial_detection_requires_a_failed_sandbox_signal() {
1180 assert!(!detect_denial(0, "bwrap: ignored on success"));
1181 #[cfg(target_os = "linux")]
1182 {
1183 assert!(detect_denial(1, "bwrap: Creating new namespace failed"));
1184 assert!(detect_denial(1, "Read-only file system"));
1185 assert!(!detect_denial(1, "child output mentions bwrap: casually"));
1186 assert!(!detect_denial(1, "Permission denied"));
1187 assert!(!detect_denial(1, "Operation not permitted"));
1188 assert!(!detect_denial(1, "ordinary command failure"));
1189 }
1190 }
1191
1192 #[test]
1193 #[cfg(target_os = "linux")]
1194 fn denial_detection_matches_localized_erofs_without_bwrap_prefix() {
1195 let localized = "Только для чтения файловая система";
1196 assert!(detect_denial_with_localized(
1197 1,
1198 &format!("touch: cannot touch '/etc/x': {localized}"),
1199 Some(localized),
1200 ));
1201 assert!(!detect_denial_with_localized(0, localized, Some(localized),));
1202 assert!(!detect_denial_with_localized(
1203 1,
1204 "ordinary command failure",
1205 Some(localized),
1206 ));
1207 assert!(super::super::localized_errno_message(libc::EROFS).is_some());
1208 }
1209
1210 #[test]
1211 #[cfg(target_os = "linux")]
1212 fn read_restricted_sandbox_seals_synthetic_root_and_dev_before_chdir() {
1213 let dir = tempfile::tempdir().expect("tempdir");
1214 let granted = dir.path().join("granted");
1215 std::fs::create_dir_all(&granted).expect("granted dir");
1216 let cmd = build_bwrap_command_with_read_paths(
1217 &granted,
1218 "true",
1219 &[],
1220 &[],
1221 false,
1222 &crate::BwrapMountExtensions::default(),
1223 &[],
1224 &[],
1225 Some(std::slice::from_ref(&granted)),
1226 None,
1227 );
1228 let chdir_pos = cmd.iter().position(|arg| arg == "--chdir").expect("chdir");
1229 let remount_dev = cmd
1230 .windows(2)
1231 .position(|args| args[0] == "--remount-ro" && args[1] == "/dev")
1232 .expect("remount-ro /dev");
1233 let remount_root = cmd
1234 .windows(2)
1235 .position(|args| args[0] == "--remount-ro" && args[1] == "/")
1236 .expect("remount-ro /");
1237 assert!(remount_dev < chdir_pos, "{cmd:?}");
1238 assert!(remount_root < chdir_pos, "{cmd:?}");
1239
1240 let unrestricted = build_bwrap_command(
1241 &granted,
1242 "true",
1243 &[],
1244 &[],
1245 false,
1246 &crate::BwrapMountExtensions::default(),
1247 &[],
1248 &[],
1249 );
1250 assert!(!unrestricted.iter().any(|arg| arg == "--remount-ro"));
1251 }
1252
1253 #[test]
1254 #[cfg(target_os = "linux")]
1255 fn writable_symlink_aliases_and_nested_reopens_emit_parents_before_children() {
1256 let dir = tempfile::tempdir().expect("tempdir");
1257 let real = dir.path().join("real");
1258 let ro = real.join("protected");
1259 let reopened = ro.join("reopened");
1260 let secret = real.join("secret");
1261 std::fs::create_dir_all(&reopened).expect("reopened dir");
1262 std::fs::write(&secret, b"secret").expect("secret");
1263 let aliases = dir.path().join("nested/deep/aliases");
1264 std::fs::create_dir_all(&aliases).expect("aliases dir");
1265 let outer_alias = aliases.join("outer");
1266 let inner_alias = dir.path().join("inner");
1267 std::os::unix::fs::symlink(&real, &outer_alias).expect("outer symlink");
1268 std::os::unix::fs::symlink(&reopened, &inner_alias).expect("inner symlink");
1269
1270 let cmd = build_bwrap_command(
1271 &real,
1272 "true",
1273 &[],
1274 &[
1275 WritableRoot::with_exceptions(
1276 outer_alias.clone(),
1277 vec![outer_alias.join("protected")],
1278 ),
1279 WritableRoot::new(inner_alias),
1280 ],
1281 false,
1282 &crate::BwrapMountExtensions::default(),
1283 &[outer_alias.join("secret")],
1284 &[],
1285 );
1286
1287 let canonical_real = real.canonicalize().expect("real");
1288 let canonical_ro = ro.canonicalize().expect("ro");
1289 let canonical_reopened = reopened.canonicalize().expect("reopened");
1290 let canonical_secret = secret.canonicalize().expect("secret");
1291
1292 let pos_of = |flag: &str, target: &Path| {
1293 cmd.windows(3)
1294 .position(|args| args[0] == flag && args[2] == target.to_string_lossy())
1295 .unwrap_or_else(|| panic!("missing {flag} {} in {cmd:?}", target.display()))
1296 };
1297 let real_pos = pos_of("--bind", &canonical_real);
1298 let ro_pos = pos_of("--ro-bind", &canonical_ro);
1299 let reopened_pos = pos_of("--bind", &canonical_reopened);
1300 let secret_pos = pos_of("--ro-bind", &canonical_secret);
1301 assert!(real_pos < ro_pos, "{cmd:?}");
1302 assert!(ro_pos < reopened_pos, "{cmd:?}");
1303 assert!(reopened_pos < secret_pos, "{cmd:?}");
1304 }
1305
1306 #[test]
1307 #[cfg(target_os = "linux")]
1308 fn bwrap_enforces_workspace_overlay_network_ro_and_deny_globs() {
1309 let dir = tempfile::tempdir().expect("tempdir");
1310 let root = dir.path().canonicalize().expect("canonical");
1311 std::fs::create_dir_all(root.join(".codewhale")).expect("mkdir .codewhale");
1312 std::fs::create_dir_all(root.join("docs")).expect("mkdir docs");
1313 std::fs::create_dir_all(root.join("secrets")).expect("mkdir secrets");
1314 std::fs::write(root.join(".env"), "SECRET=1").expect("write .env");
1315 std::fs::write(root.join("secrets/prod.key"), "KEY").expect("write key");
1316 std::fs::write(
1317 root.join(".codewhale/sandbox.toml"),
1318 "extends = \"strict\"\nrestrict_network = true\nread_only = [\"docs\"]\ndeny = [\"secrets/*.key\"]\n",
1319 )
1320 .expect("write sandbox.toml");
1321
1322 let cmd = build_bwrap_command(
1323 &root,
1324 "true",
1325 &[],
1326 &[WritableRoot::new(root.clone())],
1327 true,
1328 &crate::BwrapMountExtensions::default(),
1329 &[],
1330 &[],
1331 );
1332
1333 assert!(cmd.contains(&"--unshare-all".to_string()));
1334 assert!(!cmd.contains(&"--share-net".to_string()));
1335 assert!(has_mount(&cmd, "--ro-bind", &root.join("docs")));
1336 assert!(cmd.windows(3).any(|args| {
1337 args[0] == "--ro-bind"
1338 && args[1] == "/dev/null"
1339 && args[2] == root.join(".env").to_string_lossy()
1340 }));
1341 assert!(cmd.windows(3).any(|args| {
1342 args[0] == "--ro-bind"
1343 && args[1] == "/dev/null"
1344 && args[2] == root.join("secrets/prod.key").to_string_lossy()
1345 }));
1346 }
1347
1348 #[test]
1349 #[cfg(target_os = "linux")]
1350 fn bwrap_applies_default_deny_globs_without_overlay_and_blocks_hostile_widening() {
1351 let dir = tempfile::tempdir().expect("tempdir");
1352 let root = dir.path().canonicalize().expect("canonical");
1353 std::fs::write(root.join(".env"), "SECRET=1").expect("write .env");
1354 std::fs::write(root.join(".env.local"), "LOCAL=1").expect("write .env.local");
1355
1356 let no_overlay = build_bwrap_command(
1357 &root,
1358 "true",
1359 &[],
1360 &[WritableRoot::new(root.clone())],
1361 false,
1362 &crate::BwrapMountExtensions::default(),
1363 &[],
1364 &[],
1365 );
1366 assert!(no_overlay.windows(3).any(|args| {
1367 args[0] == "--ro-bind"
1368 && args[1] == "/dev/null"
1369 && args[2] == root.join(".env").to_string_lossy()
1370 }));
1371 assert!(no_overlay.windows(3).any(|args| {
1372 args[0] == "--ro-bind"
1373 && args[1] == "/dev/null"
1374 && args[2] == root.join(".env.local").to_string_lossy()
1375 }));
1376
1377 std::fs::create_dir_all(root.join(".codewhale")).expect("mkdir .codewhale");
1378 std::fs::write(
1379 root.join(".codewhale/sandbox.toml"),
1380 "extends = \"off\"\nrestrict_network = false\nread_write = [\"/\", \"~\", \"../escape\"]\n",
1381 )
1382 .expect("write hostile overlay");
1383
1384 let ro_cmd = build_bwrap_command(
1385 &root,
1386 "true",
1387 &[],
1388 &[],
1389 false,
1390 &crate::BwrapMountExtensions::default(),
1391 &[],
1392 &[],
1393 );
1394 assert!(!ro_cmd.contains(&"--share-net".to_string()));
1395 assert!(!ro_cmd.iter().any(|arg| arg == "--bind"));
1396 assert!(ro_cmd.windows(3).any(|args| {
1397 args[0] == "--ro-bind"
1398 && args[1] == "/dev/null"
1399 && args[2] == root.join(".env").to_string_lossy()
1400 }));
1401 }
1402 }
1403
1403 lines RUST