Skip to main content

eclipse_core/
sandbox.rs

1//! What a `shell` command can reach once it runs.
2//!
3//! Approvals and `shell_allowlist` answer *whether* a command runs. This answers a different
4//! question: once it does, what can it touch — the machine's files, its network, and the daemons
5//! it leaves behind. M8 called that gap the biggest one left, and the honest answer used to be
6//! "it is your machine, you asked for it".
7//!
8//! The mechanism is bubblewrap (`bwrap`): one binary, no daemon, no setuid bit, no configuration
9//! file, packaged by every mainstream distribution because Flatpak is built on it. It is never
10//! bundled with eclipse. It is looked for once, on `PATH`, and a mode that needs it **refuses**
11//! when it is missing rather than running without it — a security promise that degrades silently
12//! is worse than one that was never made.
13//!
14//! - `process` — a private PID namespace, filesystem untouched. Nothing the command starts
15//!   outlives the call: when the run ends, PID 1 of that namespace dies and the kernel takes the
16//!   rest with it. That closes the hole the cancellation work could not reach (a daemon that
17//!   double-forks and is reparented to init) without a cgroup, and it costs one `clone`.
18//! - `fs` — the same namespace plus a read-only filesystem: `/` read-only, a fresh `/tmp`, the
19//!   workspace and the scripts directory writable, `shell_isolate_hide` paths replaced by an
20//!   empty directory (a file — `.netrc`, `.git-credentials`, a `.env` — bound over with
21//!   `/dev/null`, because a file cannot be emptied), and the network optional. A build that
22//!   writes outside the workspace
23//!   (cargo into `~/.cargo`, pip into `~/.cache`) needs that path in `shell_isolate_writable`;
24//!   that is a real cost, and the reason this mode is not the default.
25//!
26//! Both modes are the same argv with different mount flags, so the argument list is built in one
27//! place and can be asserted in a test without bubblewrap installed.
28
29use std::ffi::{OsStr, OsString};
30use std::path::{Path, PathBuf};
31
32use crate::config::{ShellIsolate, ToolsConfig};
33use crate::tools::ToolError;
34
35/// The program and arguments a run should actually invoke: the intended command, wrapped in
36/// bubblewrap when isolation is on.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Plan {
39    pub program: OsString,
40    pub args: Vec<OsString>,
41}
42
43/// Clonable because two places run under the same policy without being able to share one
44/// value: the agent's tool registry and the interface's `!command`.
45#[derive(Debug, Clone)]
46pub struct Sandbox {
47    mode: ShellIsolate,
48    workspace: PathBuf,
49    scripts_dir: Option<PathBuf>,
50    /// Extra paths bound read-write in `fs` mode, with `~` already expanded.
51    writable: Vec<PathBuf>,
52    /// Paths replaced by an empty directory in `fs` mode, with `~` already expanded.
53    hide: Vec<PathBuf>,
54    /// The hides the build suggests (`default_hidden_paths`), expanded the same way, so a
55    /// suggestion this machine does not have can be told from a path a person wrote and misspelled
56    /// (#552).
57    suggested_hides: Vec<PathBuf>,
58    network: bool,
59    /// Where `bwrap` was found, if it was. `None` in a mode that needs it is a refusal, not a
60    /// fallback.
61    bwrap: Option<PathBuf>,
62}
63
64impl Sandbox {
65    pub fn new(cfg: &ToolsConfig, workspace: &Path, scripts_dir: Option<&Path>) -> Self {
66        let mode = cfg.shell_isolate;
67        Self {
68            mode,
69            workspace: workspace.to_path_buf(),
70            scripts_dir: scripts_dir.map(Path::to_path_buf),
71            writable: cfg
72                .shell_isolate_writable
73                .iter()
74                .map(|p| expand(p))
75                .collect(),
76            hide: cfg.shell_isolate_hide.iter().map(|p| expand(p)).collect(),
77            suggested_hides: crate::config::default_hidden_paths()
78                .iter()
79                .map(|p| expand(p))
80                .collect(),
81            network: cfg.shell_isolate_network,
82            bwrap: need_bwrap(mode).then(find_bwrap).flatten(),
83        }
84    }
85
86    /// A sandbox that does nothing. Tests of the process-group kill (and anything else that
87    /// wants the plain child) use this, so the two mechanisms stay separately testable.
88    pub fn off() -> Self {
89        Self {
90            mode: ShellIsolate::Off,
91            workspace: PathBuf::new(),
92            scripts_dir: None,
93            writable: Vec::new(),
94            hide: Vec::new(),
95            suggested_hides: Vec::new(),
96            network: true,
97            bwrap: None,
98        }
99    }
100
101    /// A sandbox in `mode` that has not found a `bwrap`, so the refusal can be tested on a
102    /// machine where bubblewrap is installed.
103    #[cfg(test)]
104    pub fn without_bwrap(mode: ShellIsolate) -> Self {
105        let mut sb = Self::off();
106        sb.mode = mode;
107        sb
108    }
109
110    pub fn mode(&self) -> ShellIsolate {
111        self.mode
112    }
113
114    /// Whether a command runs inside a namespace at all.
115    pub fn is_on(&self) -> bool {
116        self.mode != ShellIsolate::Off
117    }
118
119    /// Whether a mode that promised containment will refuse instead of running at all. True only
120    /// for `fs` without bubblewrap; `process` degrades instead.
121    pub fn refuses(&self) -> bool {
122        self.refusal().is_some()
123    }
124
125    /// The refusal a mode owes when it cannot be honoured, as the error the tool returns, or
126    /// `None` when a command may run. One place, because three tools now ask it: `shell`,
127    /// `script` and `execute_code` all start a process and all answer to the same policy (#550).
128    pub fn refusal(&self) -> Option<ToolError> {
129        (self.mode == ShellIsolate::Fs && self.bwrap.is_none()).then(|| {
130            ToolError::Failed(
131                "[tools] shell_isolate = \"fs\" makes the filesystem read-only, and that needs \
132                 bubblewrap, which is not on PATH, so the command was not run. Install it \
133                 (Debian/Ubuntu: `sudo apt install bubblewrap`, Fedora: `sudo dnf install \
134                 bubblewrap`, Arch: `sudo pacman -S bubblewrap`), or use shell_isolate = \
135                 \"process\" for a namespace without the filesystem scoping. Running uncontained \
136                 instead is not something this profile asked for."
137                    .to_string(),
138            )
139        })
140    }
141
142    /// Whether isolation was asked for and could not be given: the run happens anyway, and the
143    /// result says so. Only `process` degrades; `fs` refuses in [`Sandbox::plan`], because a
144    /// read-only promise is not one to keep halfway.
145    pub fn degraded(&self) -> bool {
146        self.mode == ShellIsolate::Process && self.bwrap.is_none()
147    }
148
149    /// What `config check` and the docs print: the mode, and whether the mechanism is there.
150    pub fn status(&self) -> String {
151        if !self.is_on() {
152            return "off — a command runs as you, with your files, your network and your daemons"
153                .to_string();
154        }
155        // Only the hide that lost to the workspace is worth a sentence here: it is the one where
156        // the entry is right and the run still sees the file. A path that is not there is a typo,
157        // and `config check` names it as the warning it is rather than padding out a status line.
158        let skipped = self
159            .skipped_hides()
160            .into_iter()
161            .filter(|(_, why)| *why == HideSkip::ContainsWritable)
162            .map(|(path, _)| path)
163            .collect::<Vec<_>>();
164        let note = if skipped.is_empty() {
165            String::new()
166        } else {
167            format!(
168                "; not hiding {}: it contains a path the run must write",
169                skipped
170                    .iter()
171                    .map(|p| p.display().to_string())
172                    .collect::<Vec<_>>()
173                    .join(", ")
174            )
175        };
176        match (&self.bwrap, self.mode) {
177            (Some(path), _) => format!("{} — bubblewrap at {}{note}", self.mode, path.display()),
178            (None, ShellIsolate::Process) => format!(
179                "process — bubblewrap is NOT on PATH, so commands run uncontained and say so: \
180                 install bubblewrap to contain them{note}"
181            ),
182            (None, _) => format!(
183                "{} — bubblewrap is NOT on PATH, so `shell` will refuse to run: install \
184                 bubblewrap, or set [tools] shell_isolate = \"off\"{note}",
185                self.mode
186            ),
187        }
188    }
189
190    /// The program and arguments to run instead of `program` itself.
191    ///
192    /// `cwd` is passed to bubblewrap rather than left to the caller so the directory is resolved
193    /// inside the namespace, which is the only place it is guaranteed to mean the same thing.
194    pub fn plan(&self, program: &OsStr, args: &[OsString], cwd: &Path) -> Result<Plan, ToolError> {
195        self.plan_with(program, args, cwd, &[])
196    }
197
198    /// [`Sandbox::plan`] with extra directories bound read-write at their own path under `fs`.
199    ///
200    /// The tool bridge is why this exists: its socket is created after the sandbox is built, so a
201    /// contained child can only reach it if the run binds the socket's directory (#550). Under
202    /// `process` the whole filesystem is already there, and under `off` nothing is wrapped.
203    pub fn plan_with(
204        &self,
205        program: &OsStr,
206        args: &[OsString],
207        cwd: &Path,
208        extra_rw: &[PathBuf],
209    ) -> Result<Plan, ToolError> {
210        if !self.is_on() {
211            return Ok(Plan {
212                program: program.to_owned(),
213                args: args.to_vec(),
214            });
215        }
216        // `fs` promises that the machine is read-only, and a promise like that is worth a
217        // refusal: running the command anyway would be the one outcome the mode exists to
218        // prevent. `process` promises only what it can — the run still happens, and
219        // `degraded()` makes the caller say so in the result rather than in a comment.
220        if let Some(why) = self.refusal() {
221            return Err(why);
222        }
223        let Some(bwrap) = &self.bwrap else {
224            // `process` without the package: run it plainly. The caller appends the note.
225            return Ok(Plan {
226                program: program.to_owned(),
227                args: args.to_vec(),
228            });
229        };
230
231        let mut a: Vec<OsString> = Vec::with_capacity(32);
232        a.push("--die-with-parent".into());
233        a.push("--unshare-pid".into());
234        match self.mode {
235            // The filesystem is left exactly as it is; only the process tree is scoped.
236            ShellIsolate::Process => {
237                a.push("--dev-bind".into());
238                a.push("/".into());
239                a.push("/".into());
240                a.push("--proc".into());
241                a.push("/proc".into());
242            }
243            ShellIsolate::Fs => {
244                a.push("--ro-bind".into());
245                a.push("/".into());
246                a.push("/".into());
247                a.push("--proc".into());
248                a.push("/proc".into());
249                a.push("--dev".into());
250                a.push("/dev".into());
251                a.push("--tmpfs".into());
252                a.push("/tmp".into());
253                if !self.network {
254                    a.push("--unshare-net".into());
255                }
256                for dir in self.writable_paths() {
257                    if dir.is_dir() {
258                        a.push("--bind".into());
259                        a.push(dir.as_os_str().to_owned());
260                        a.push(dir.as_os_str().to_owned());
261                    }
262                }
263                // Paths the caller created after the sandbox was built — the tool bridge's socket
264                // directory, in practice. The child is told the path by environment variable, so
265                // the mount has to be at the same path it was told (#550).
266                for dir in extra_rw.iter().filter(|d| d.is_dir()) {
267                    a.push("--bind".into());
268                    a.push(dir.as_os_str().to_owned());
269                    a.push(dir.as_os_str().to_owned());
270                }
271                // Bound first, emptied after: mounts stack, so a bind of a parent would cover a
272                // tmpfs put over its child. The hide list wins even inside the workspace, which
273                // is exactly the case a careless `shell_isolate_hide` produces.
274                //
275                // A directory is emptied; a file cannot be, so the device that reads as nothing
276                // is bound over it. `~/.netrc`, `~/.git-credentials`, `~/.npmrc` and a `.env` are
277                // files — they are precisely what this key exists for, and the `--tmpfs`-only
278                // version hid none of them and said nothing (#552).
279                for (_, resolved) in self.applied_hides() {
280                    if resolved.is_dir() {
281                        a.push("--tmpfs".into());
282                    } else {
283                        a.push("--ro-bind".into());
284                        a.push("/dev/null".into());
285                    }
286                    a.push(resolved.into_os_string());
287                }
288            }
289            ShellIsolate::Off => unreachable!("handled above"),
290        }
291        a.push("--chdir".into());
292        a.push(cwd.as_os_str().to_owned());
293        a.push("--".into());
294        a.push(program.to_owned());
295        a.extend(args.iter().cloned());
296        Ok(Plan {
297            program: bwrap.as_os_str().to_owned(),
298            args: a,
299        })
300    }
301
302    /// The hides that will be mounted, each with where it resolved to.
303    ///
304    /// Resolved, because the comparison is between paths that come from three places — a profile
305    /// (`~/.netrc`), a canonicalised workspace, and the filesystem — and a lexical `starts_with`
306    /// between those answers the wrong question the moment `/home/me` is a symlink: hiding
307    /// `/home/me` "would" leave a canonical `/data/me/work` untouched, so the tmpfs went over the
308    /// workspace itself and every run lost it (#552).
309    ///
310    /// A path that is not there resolves to nothing and is reported by [`Self::skipped_hides`]:
311    /// there is nothing to hide, and silence is how someone ends up believing their `.env` was
312    /// withheld when in fact it was a typo.
313    fn applied_hides(&self) -> Vec<(PathBuf, PathBuf)> {
314        let writes: Vec<PathBuf> = self
315            .writable_paths()
316            .iter()
317            .map(|w| std::fs::canonicalize(w).unwrap_or_else(|_| w.clone()))
318            .collect();
319        self.hide
320            .iter()
321            .filter_map(|declared| {
322                let resolved = std::fs::canonicalize(declared).ok()?;
323                // A hide containing something the run may write is dropped: emptying it would
324                // delete the workspace the command was given, and a setting that silently broke
325                // every run would be worse than the gap it closes.
326                if writes.iter().any(|w| w.starts_with(&resolved)) {
327                    return None;
328                }
329                Some((declared.clone(), resolved))
330            })
331            .collect()
332    }
333
334    /// Whether `path` is one of the hides the build suggests rather than one a person wrote.
335    pub fn is_suggested_hide(&self, path: &Path) -> bool {
336        self.suggested_hides.iter().any(|s| s == path)
337    }
338
339    /// The hides a profile asked for that will not be applied, and why — for `config check` and
340    /// the docs to name, rather than leave someone believing a path is hidden when it is not.
341    pub fn skipped_hides(&self) -> Vec<(&PathBuf, HideSkip)> {
342        let applied: Vec<PathBuf> = self
343            .applied_hides()
344            .into_iter()
345            .map(|(declared, _)| declared)
346            .collect();
347        self.hide
348            .iter()
349            .filter(|h| !applied.contains(h))
350            .map(|h| match std::fs::canonicalize(h) {
351                Err(_) => (h, HideSkip::Missing),
352                Ok(_) => (h, HideSkip::ContainsWritable),
353            })
354            .collect()
355    }
356
357    /// Everything `fs` mode leaves writable, in the order it is bound. The workspace is first so
358    /// it wins if an extra path is a parent of it.
359    fn writable_paths(&self) -> Vec<PathBuf> {
360        let mut out = vec![self.workspace.clone()];
361        for path in self.scripts_dir.iter().chain(self.writable.iter()) {
362            if !out.contains(path) {
363                out.push(path.clone());
364            }
365        }
366        out
367    }
368}
369
370/// Why a `shell_isolate_hide` entry is not hiding anything.
371///
372/// Two reasons, because they are fixed differently: a path that does not exist is a typo to
373/// correct, and a path that contains something writable is a choice to make — the run keeps its
374/// workspace, and the file the entry names stays visible.
375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376pub enum HideSkip {
377    /// Nothing is at that path.
378    Missing,
379    /// The path contains something the run is allowed to write, so emptying it would take the
380    /// workspace with it.
381    ContainsWritable,
382}
383
384impl HideSkip {
385    pub fn why(self) -> &'static str {
386        match self {
387            Self::Missing => "no such path",
388            Self::ContainsWritable => "contains something the run may write",
389        }
390    }
391}
392
393/// `~` and `~/x` mean the home directory; anything else is taken as written.
394fn expand(path: &Path) -> PathBuf {
395    let Some(home) = std::env::var_os("HOME") else {
396        return path.to_path_buf();
397    };
398    match path.strip_prefix("~") {
399        Ok(rest) => PathBuf::from(home).join(rest),
400        Err(_) => path.to_path_buf(),
401    }
402}
403
404fn need_bwrap(mode: ShellIsolate) -> bool {
405    mode != ShellIsolate::Off
406}
407
408/// `bwrap` from `PATH`, executable and not a directory.
409fn find_bwrap() -> Option<PathBuf> {
410    let path = std::env::var_os("PATH")?;
411    std::env::split_paths(&path)
412        .map(|dir| dir.join("bwrap"))
413        .find(|candidate| {
414            std::fs::metadata(candidate).is_ok_and(|m| {
415                m.is_file() && {
416                    #[cfg(unix)]
417                    {
418                        use std::os::unix::fs::PermissionsExt;
419                        m.permissions().mode() & 0o111 != 0
420                    }
421                    #[cfg(not(unix))]
422                    {
423                        true
424                    }
425                }
426            })
427        })
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    fn cfg(mode: ShellIsolate) -> ToolsConfig {
435        ToolsConfig {
436            shell_isolate: mode,
437            ..ToolsConfig::default()
438        }
439    }
440
441    fn strings(args: &[OsString]) -> Vec<String> {
442        args.iter()
443            .map(|a| a.to_string_lossy().into_owned())
444            .collect()
445    }
446
447    #[test]
448    fn off_is_the_command_itself_and_nothing_else() {
449        let sb = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
450        assert!(!sb.is_on());
451        let plan = sb
452            .plan(
453                OsStr::new("sh"),
454                &["-c".into(), "echo hi".into()],
455                Path::new("/w"),
456            )
457            .unwrap();
458        assert_eq!(plan.program, OsString::from("sh"));
459        assert_eq!(strings(&plan.args), vec!["-c", "echo hi"]);
460    }
461
462    #[test]
463    fn fs_refuses_without_bubblewrap_and_process_degrades_out_loud() {
464        // `fs` promised a read-only machine, so it refuses rather than run uncontained.
465        let fs = Sandbox::without_bwrap(ShellIsolate::Fs);
466        let err = fs
467            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
468            .unwrap_err()
469            .to_string();
470        assert!(err.contains("read-only"), "{err}");
471        assert!(err.contains("not run"), "{err}");
472        assert!(err.contains("bubblewrap"), "{err}");
473        assert!(!fs.degraded());
474
475        // `process` promised only a namespace, so it runs plainly and says what it could not do.
476        let process = Sandbox::without_bwrap(ShellIsolate::Process);
477        let plan = process
478            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
479            .unwrap();
480        assert_eq!(plan.program, OsString::from("sh"));
481        assert!(process.degraded());
482        assert!(
483            process.status().contains("uncontained"),
484            "{}",
485            process.status()
486        );
487    }
488
489    #[test]
490    fn process_mode_scopes_the_pid_namespace_and_leaves_the_filesystem_alone() {
491        let sb = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
492        if sb.bwrap.is_none() {
493            return;
494        }
495        let plan = sb
496            .plan(
497                OsStr::new("sh"),
498                &["-c".into(), "echo hi".into()],
499                Path::new("/w"),
500            )
501            .unwrap();
502        assert!(plan.program.to_string_lossy().ends_with("bwrap"));
503        let a = strings(&plan.args);
504        assert!(a.starts_with(&["--die-with-parent".into(), "--unshare-pid".into()]));
505        assert!(a.contains(&"--dev-bind".to_string()));
506        assert!(
507            !a.contains(&"--ro-bind".to_string()),
508            "process mode must not scope files"
509        );
510        assert!(!a.contains(&"--unshare-net".to_string()));
511        assert_eq!(
512            &a[a.len() - 6..],
513            &["--chdir", "/w", "--", "sh", "-c", "echo hi"]
514        );
515    }
516
517    #[test]
518    fn fs_mode_is_read_only_with_the_workspace_bound_back() {
519        let sb = Sandbox::new(
520            &cfg(ShellIsolate::Fs),
521            Path::new("/w"),
522            Some(Path::new("/s")),
523        );
524        if sb.bwrap.is_none() {
525            return;
526        }
527        let plan = sb
528            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
529            .unwrap();
530        let a = strings(&plan.args);
531        assert!(a.contains(&"--ro-bind".to_string()));
532        assert!(a.contains(&"/tmp".to_string()));
533        // The workspace and the scripts directory are the two writes that always survive.
534        let binds: Vec<&String> = a
535            .windows(3)
536            .filter(|w| {
537                w[0] == "--bind" && {
538                    let p = Path::new(&w[1]);
539                    p.is_dir()
540                }
541            })
542            .map(|w| &w[1])
543            .collect();
544        assert!(binds.iter().any(|p| *p == "/w") || !Path::new("/w").is_dir());
545        assert!(a.contains(&"--unshare-pid".to_string()));
546    }
547
548    #[test]
549    fn a_path_the_caller_added_is_bound_read_write_in_fs_mode() {
550        // The tool bridge creates its socket after the sandbox does, so the run has to be able to
551        // bind that directory: without it the child is told a path that does not exist where it
552        // runs, and `eclipse tool` inside a script has no bridge to call (#550).
553        let extra = tempfile::tempdir().unwrap();
554        let sb = Sandbox::new(&cfg(ShellIsolate::Fs), Path::new("/w"), None);
555        if sb.bwrap.is_none() {
556            return;
557        }
558        let plan = sb
559            .plan_with(
560                OsStr::new("sh"),
561                &[],
562                extra.path(),
563                &[extra.path().to_path_buf()],
564            )
565            .unwrap();
566        let a = strings(&plan.args);
567        assert!(
568            a.windows(3).any(|w| {
569                w[0] == "--bind"
570                    && Path::new(&w[1]) == extra.path()
571                    && Path::new(&w[2]) == extra.path()
572            }),
573            "the extra directory is bound at its own path: {a:?}"
574        );
575    }
576
577    #[test]
578    fn fs_mode_can_drop_the_network() {
579        let mut c = cfg(ShellIsolate::Fs);
580        c.shell_isolate_network = false;
581        let sb = Sandbox::new(&c, Path::new("/w"), None);
582        if sb.bwrap.is_none() {
583            return;
584        }
585        let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
586        assert!(strings(&plan.args).contains(&"--unshare-net".to_string()));
587    }
588
589    fn hidden(mode: ShellIsolate, workspace: &Path, hide: Vec<PathBuf>) -> Sandbox {
590        let mut c = cfg(mode);
591        c.shell_isolate_hide = hide;
592        Sandbox::new(&c, workspace, None)
593    }
594
595    #[test]
596    fn a_hide_is_expanded_and_applied_whether_it_is_a_file_or_a_directory() {
597        let home = tempfile::tempdir().unwrap();
598        let workspace = home.path().join("work");
599        std::fs::create_dir_all(&workspace).unwrap();
600        let netrc = home.path().join(".netrc");
601        std::fs::write(&netrc, "machine example login me password hunter2\n").unwrap();
602        let ssh = home.path().join(".ssh");
603        std::fs::create_dir(&ssh).unwrap();
604
605        let sb = hidden(
606            ShellIsolate::Fs,
607            &workspace,
608            vec![
609                netrc.clone(),
610                ssh.clone(),
611                PathBuf::from("~/.eclipse-never-exists"),
612            ],
613        );
614        assert_eq!(
615            sb.hide[2],
616            PathBuf::from(std::env::var_os("HOME").unwrap_or_default())
617                .join(".eclipse-never-exists"),
618            "`~` is home"
619        );
620        let applied = sb.applied_hides();
621        let resolved: Vec<PathBuf> = applied.iter().map(|(_, r)| r.clone()).collect();
622        assert_eq!(
623            resolved,
624            vec![
625                std::fs::canonicalize(&netrc).unwrap(),
626                std::fs::canonicalize(&ssh).unwrap()
627            ],
628            "a file is not dropped for not being a directory (#552)"
629        );
630
631        if sb.bwrap.is_none() {
632            return;
633        }
634        let plan = sb.plan(OsStr::new("sh"), &[], &workspace).unwrap();
635        let a = strings(&plan.args);
636        let netrc_at = std::fs::canonicalize(&netrc).unwrap().display().to_string();
637        let ssh_at = std::fs::canonicalize(&ssh).unwrap().display().to_string();
638        // A directory is emptied; a file cannot be, so the device that reads as nothing goes over
639        // it — which is what `~/.netrc`, `~/.git-credentials` and a `.env` need.
640        assert!(
641            a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == ssh_at),
642            "{a:?}"
643        );
644        assert!(
645            a.windows(3)
646                .any(|w| w[0] == "--ro-bind" && w[1] == "/dev/null" && w[2] == netrc_at),
647            "{a:?}"
648        );
649        assert!(
650            !a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == netrc_at),
651            "a file cannot be tmpfs'd: {a:?}"
652        );
653        // A path that is not there is not bound at all: a mount over nothing fails the whole run.
654        assert!(
655            !a.iter().any(|w| w.contains(".eclipse-never-exists")),
656            "{a:?}"
657        );
658    }
659
660    #[test]
661    fn a_hide_that_does_not_exist_is_reported_rather_than_dropped_silently() {
662        let home = tempfile::tempdir().unwrap();
663        let workspace = home.path().join("work");
664        std::fs::create_dir_all(&workspace).unwrap();
665        let typo = home.path().join(".netrcc");
666        let sb = hidden(ShellIsolate::Fs, &workspace, vec![typo.clone()]);
667        assert!(sb.applied_hides().is_empty());
668        let skipped = sb.skipped_hides();
669        assert_eq!(skipped.len(), 1);
670        assert_eq!(skipped[0].0, &typo);
671        assert_eq!(skipped[0].1, HideSkip::Missing);
672        assert!(
673            !sb.status().contains(".netrcc"),
674            "a typo is `config check`'s finding, not a sentence in the status line: {}",
675            sb.status()
676        );
677    }
678
679    #[test]
680    fn a_hide_that_reaches_the_workspace_through_a_symlink_is_skipped() {
681        // The profile names a parent by a symlink; the workspace the run is given is canonical.
682        // Lexically the two do not overlap, so the `--tmpfs` used to land on the workspace itself
683        // and every run lost it (#552).
684        let real = tempfile::tempdir().unwrap();
685        let workspace = real.path().join("work");
686        std::fs::create_dir_all(&workspace).unwrap();
687        std::fs::write(workspace.join("keep.txt"), "keep me\n").unwrap();
688        let link = real.path().join("home-by-another-name");
689        std::os::unix::fs::symlink(real.path(), &link).unwrap();
690
691        let sb = hidden(ShellIsolate::Fs, &workspace, vec![link]);
692        assert!(
693            sb.applied_hides().is_empty(),
694            "the workspace is inside it once both are resolved"
695        );
696        let skipped = sb.skipped_hides();
697        assert_eq!(skipped.len(), 1);
698        assert_eq!(skipped[0].1, HideSkip::ContainsWritable);
699    }
700
701    #[test]
702    fn status_says_which_mechanism_and_whether_it_is_there() {
703        let off = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
704        assert!(off.status().starts_with("off"));
705        let on = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
706        let text = on.status();
707        assert!(text.starts_with("process"));
708        assert!(text.contains("bubblewrap"), "{text}");
709    }
710}