eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! What a `shell` command can reach once it runs.
//!
//! Approvals and `shell_allowlist` answer *whether* a command runs. This answers a different
//! question: once it does, what can it touch — the machine's files, its network, and the daemons
//! it leaves behind. M8 called that gap the biggest one left, and the honest answer used to be
//! "it is your machine, you asked for it".
//!
//! The mechanism is bubblewrap (`bwrap`): one binary, no daemon, no setuid bit, no configuration
//! file, packaged by every mainstream distribution because Flatpak is built on it. It is never
//! bundled with eclipse. It is looked for once, on `PATH`, and a mode that needs it **refuses**
//! when it is missing rather than running without it — a security promise that degrades silently
//! is worse than one that was never made.
//!
//! - `process` — a private PID namespace, filesystem untouched. Nothing the command starts
//!   outlives the call: when the run ends, PID 1 of that namespace dies and the kernel takes the
//!   rest with it. That closes the hole the cancellation work could not reach (a daemon that
//!   double-forks and is reparented to init) without a cgroup, and it costs one `clone`.
//! - `fs` — the same namespace plus a read-only filesystem: `/` read-only, a fresh `/tmp`, the
//!   workspace and the scripts directory writable, `shell_isolate_hide` paths replaced by an
//!   empty directory (a file — `.netrc`, `.git-credentials`, a `.env` — bound over with
//!   `/dev/null`, because a file cannot be emptied), and the network optional. A build that
//!   writes outside the workspace
//!   (cargo into `~/.cargo`, pip into `~/.cache`) needs that path in `shell_isolate_writable`;
//!   that is a real cost, and the reason this mode is not the default.
//!
//! Both modes are the same argv with different mount flags, so the argument list is built in one
//! place and can be asserted in a test without bubblewrap installed.

use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

use crate::config::{ShellIsolate, ToolsConfig};
use crate::tools::ToolError;

/// The program and arguments a run should actually invoke: the intended command, wrapped in
/// bubblewrap when isolation is on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
    pub program: OsString,
    pub args: Vec<OsString>,
}

/// Clonable because two places run under the same policy without being able to share one
/// value: the agent's tool registry and the interface's `!command`.
#[derive(Debug, Clone)]
pub struct Sandbox {
    mode: ShellIsolate,
    workspace: PathBuf,
    scripts_dir: Option<PathBuf>,
    /// Extra paths bound read-write in `fs` mode, with `~` already expanded.
    writable: Vec<PathBuf>,
    /// Paths replaced by an empty directory in `fs` mode, with `~` already expanded.
    hide: Vec<PathBuf>,
    /// The hides the build suggests (`default_hidden_paths`), expanded the same way, so a
    /// suggestion this machine does not have can be told from a path a person wrote and misspelled
    /// (#552).
    suggested_hides: Vec<PathBuf>,
    network: bool,
    /// Where `bwrap` was found, if it was. `None` in a mode that needs it is a refusal, not a
    /// fallback.
    bwrap: Option<PathBuf>,
}

impl Sandbox {
    pub fn new(cfg: &ToolsConfig, workspace: &Path, scripts_dir: Option<&Path>) -> Self {
        let mode = cfg.shell_isolate;
        Self {
            mode,
            workspace: workspace.to_path_buf(),
            scripts_dir: scripts_dir.map(Path::to_path_buf),
            writable: cfg
                .shell_isolate_writable
                .iter()
                .map(|p| expand(p))
                .collect(),
            hide: cfg.shell_isolate_hide.iter().map(|p| expand(p)).collect(),
            suggested_hides: crate::config::default_hidden_paths()
                .iter()
                .map(|p| expand(p))
                .collect(),
            network: cfg.shell_isolate_network,
            bwrap: need_bwrap(mode).then(find_bwrap).flatten(),
        }
    }

    /// A sandbox that does nothing. Tests of the process-group kill (and anything else that
    /// wants the plain child) use this, so the two mechanisms stay separately testable.
    pub fn off() -> Self {
        Self {
            mode: ShellIsolate::Off,
            workspace: PathBuf::new(),
            scripts_dir: None,
            writable: Vec::new(),
            hide: Vec::new(),
            suggested_hides: Vec::new(),
            network: true,
            bwrap: None,
        }
    }

    /// A sandbox in `mode` that has not found a `bwrap`, so the refusal can be tested on a
    /// machine where bubblewrap is installed.
    #[cfg(test)]
    pub fn without_bwrap(mode: ShellIsolate) -> Self {
        let mut sb = Self::off();
        sb.mode = mode;
        sb
    }

    pub fn mode(&self) -> ShellIsolate {
        self.mode
    }

    /// Whether a command runs inside a namespace at all.
    pub fn is_on(&self) -> bool {
        self.mode != ShellIsolate::Off
    }

    /// Whether a mode that promised containment will refuse instead of running at all. True only
    /// for `fs` without bubblewrap; `process` degrades instead.
    pub fn refuses(&self) -> bool {
        self.refusal().is_some()
    }

    /// The refusal a mode owes when it cannot be honoured, as the error the tool returns, or
    /// `None` when a command may run. One place, because three tools now ask it: `shell`,
    /// `script` and `execute_code` all start a process and all answer to the same policy (#550).
    pub fn refusal(&self) -> Option<ToolError> {
        (self.mode == ShellIsolate::Fs && self.bwrap.is_none()).then(|| {
            ToolError::Failed(
                "[tools] shell_isolate = \"fs\" makes the filesystem read-only, and that needs \
                 bubblewrap, which is not on PATH, so the command was not run. Install it \
                 (Debian/Ubuntu: `sudo apt install bubblewrap`, Fedora: `sudo dnf install \
                 bubblewrap`, Arch: `sudo pacman -S bubblewrap`), or use shell_isolate = \
                 \"process\" for a namespace without the filesystem scoping. Running uncontained \
                 instead is not something this profile asked for."
                    .to_string(),
            )
        })
    }

    /// Whether isolation was asked for and could not be given: the run happens anyway, and the
    /// result says so. Only `process` degrades; `fs` refuses in [`Sandbox::plan`], because a
    /// read-only promise is not one to keep halfway.
    pub fn degraded(&self) -> bool {
        self.mode == ShellIsolate::Process && self.bwrap.is_none()
    }

    /// What `config check` and the docs print: the mode, and whether the mechanism is there.
    pub fn status(&self) -> String {
        if !self.is_on() {
            return "off — a command runs as you, with your files, your network and your daemons"
                .to_string();
        }
        // Only the hide that lost to the workspace is worth a sentence here: it is the one where
        // the entry is right and the run still sees the file. A path that is not there is a typo,
        // and `config check` names it as the warning it is rather than padding out a status line.
        let skipped = self
            .skipped_hides()
            .into_iter()
            .filter(|(_, why)| *why == HideSkip::ContainsWritable)
            .map(|(path, _)| path)
            .collect::<Vec<_>>();
        let note = if skipped.is_empty() {
            String::new()
        } else {
            format!(
                "; not hiding {}: it contains a path the run must write",
                skipped
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };
        match (&self.bwrap, self.mode) {
            (Some(path), _) => format!("{} — bubblewrap at {}{note}", self.mode, path.display()),
            (None, ShellIsolate::Process) => format!(
                "process — bubblewrap is NOT on PATH, so commands run uncontained and say so: \
                 install bubblewrap to contain them{note}"
            ),
            (None, _) => format!(
                "{} — bubblewrap is NOT on PATH, so `shell` will refuse to run: install \
                 bubblewrap, or set [tools] shell_isolate = \"off\"{note}",
                self.mode
            ),
        }
    }

    /// The program and arguments to run instead of `program` itself.
    ///
    /// `cwd` is passed to bubblewrap rather than left to the caller so the directory is resolved
    /// inside the namespace, which is the only place it is guaranteed to mean the same thing.
    pub fn plan(&self, program: &OsStr, args: &[OsString], cwd: &Path) -> Result<Plan, ToolError> {
        self.plan_with(program, args, cwd, &[])
    }

    /// [`Sandbox::plan`] with extra directories bound read-write at their own path under `fs`.
    ///
    /// The tool bridge is why this exists: its socket is created after the sandbox is built, so a
    /// contained child can only reach it if the run binds the socket's directory (#550). Under
    /// `process` the whole filesystem is already there, and under `off` nothing is wrapped.
    pub fn plan_with(
        &self,
        program: &OsStr,
        args: &[OsString],
        cwd: &Path,
        extra_rw: &[PathBuf],
    ) -> Result<Plan, ToolError> {
        if !self.is_on() {
            return Ok(Plan {
                program: program.to_owned(),
                args: args.to_vec(),
            });
        }
        // `fs` promises that the machine is read-only, and a promise like that is worth a
        // refusal: running the command anyway would be the one outcome the mode exists to
        // prevent. `process` promises only what it can — the run still happens, and
        // `degraded()` makes the caller say so in the result rather than in a comment.
        if let Some(why) = self.refusal() {
            return Err(why);
        }
        let Some(bwrap) = &self.bwrap else {
            // `process` without the package: run it plainly. The caller appends the note.
            return Ok(Plan {
                program: program.to_owned(),
                args: args.to_vec(),
            });
        };

        let mut a: Vec<OsString> = Vec::with_capacity(32);
        a.push("--die-with-parent".into());
        a.push("--unshare-pid".into());
        match self.mode {
            // The filesystem is left exactly as it is; only the process tree is scoped.
            ShellIsolate::Process => {
                a.push("--dev-bind".into());
                a.push("/".into());
                a.push("/".into());
                a.push("--proc".into());
                a.push("/proc".into());
            }
            ShellIsolate::Fs => {
                a.push("--ro-bind".into());
                a.push("/".into());
                a.push("/".into());
                a.push("--proc".into());
                a.push("/proc".into());
                a.push("--dev".into());
                a.push("/dev".into());
                a.push("--tmpfs".into());
                a.push("/tmp".into());
                if !self.network {
                    a.push("--unshare-net".into());
                }
                for dir in self.writable_paths() {
                    if dir.is_dir() {
                        a.push("--bind".into());
                        a.push(dir.as_os_str().to_owned());
                        a.push(dir.as_os_str().to_owned());
                    }
                }
                // Paths the caller created after the sandbox was built — the tool bridge's socket
                // directory, in practice. The child is told the path by environment variable, so
                // the mount has to be at the same path it was told (#550).
                for dir in extra_rw.iter().filter(|d| d.is_dir()) {
                    a.push("--bind".into());
                    a.push(dir.as_os_str().to_owned());
                    a.push(dir.as_os_str().to_owned());
                }
                // Bound first, emptied after: mounts stack, so a bind of a parent would cover a
                // tmpfs put over its child. The hide list wins even inside the workspace, which
                // is exactly the case a careless `shell_isolate_hide` produces.
                //
                // A directory is emptied; a file cannot be, so the device that reads as nothing
                // is bound over it. `~/.netrc`, `~/.git-credentials`, `~/.npmrc` and a `.env` are
                // files — they are precisely what this key exists for, and the `--tmpfs`-only
                // version hid none of them and said nothing (#552).
                for (_, resolved) in self.applied_hides() {
                    if resolved.is_dir() {
                        a.push("--tmpfs".into());
                    } else {
                        a.push("--ro-bind".into());
                        a.push("/dev/null".into());
                    }
                    a.push(resolved.into_os_string());
                }
            }
            ShellIsolate::Off => unreachable!("handled above"),
        }
        a.push("--chdir".into());
        a.push(cwd.as_os_str().to_owned());
        a.push("--".into());
        a.push(program.to_owned());
        a.extend(args.iter().cloned());
        Ok(Plan {
            program: bwrap.as_os_str().to_owned(),
            args: a,
        })
    }

    /// The hides that will be mounted, each with where it resolved to.
    ///
    /// Resolved, because the comparison is between paths that come from three places — a profile
    /// (`~/.netrc`), a canonicalised workspace, and the filesystem — and a lexical `starts_with`
    /// between those answers the wrong question the moment `/home/me` is a symlink: hiding
    /// `/home/me` "would" leave a canonical `/data/me/work` untouched, so the tmpfs went over the
    /// workspace itself and every run lost it (#552).
    ///
    /// A path that is not there resolves to nothing and is reported by [`Self::skipped_hides`]:
    /// there is nothing to hide, and silence is how someone ends up believing their `.env` was
    /// withheld when in fact it was a typo.
    fn applied_hides(&self) -> Vec<(PathBuf, PathBuf)> {
        let writes: Vec<PathBuf> = self
            .writable_paths()
            .iter()
            .map(|w| std::fs::canonicalize(w).unwrap_or_else(|_| w.clone()))
            .collect();
        self.hide
            .iter()
            .filter_map(|declared| {
                let resolved = std::fs::canonicalize(declared).ok()?;
                // A hide containing something the run may write is dropped: emptying it would
                // delete the workspace the command was given, and a setting that silently broke
                // every run would be worse than the gap it closes.
                if writes.iter().any(|w| w.starts_with(&resolved)) {
                    return None;
                }
                Some((declared.clone(), resolved))
            })
            .collect()
    }

    /// Whether `path` is one of the hides the build suggests rather than one a person wrote.
    pub fn is_suggested_hide(&self, path: &Path) -> bool {
        self.suggested_hides.iter().any(|s| s == path)
    }

    /// The hides a profile asked for that will not be applied, and why — for `config check` and
    /// the docs to name, rather than leave someone believing a path is hidden when it is not.
    pub fn skipped_hides(&self) -> Vec<(&PathBuf, HideSkip)> {
        let applied: Vec<PathBuf> = self
            .applied_hides()
            .into_iter()
            .map(|(declared, _)| declared)
            .collect();
        self.hide
            .iter()
            .filter(|h| !applied.contains(h))
            .map(|h| match std::fs::canonicalize(h) {
                Err(_) => (h, HideSkip::Missing),
                Ok(_) => (h, HideSkip::ContainsWritable),
            })
            .collect()
    }

    /// Everything `fs` mode leaves writable, in the order it is bound. The workspace is first so
    /// it wins if an extra path is a parent of it.
    fn writable_paths(&self) -> Vec<PathBuf> {
        let mut out = vec![self.workspace.clone()];
        for path in self.scripts_dir.iter().chain(self.writable.iter()) {
            if !out.contains(path) {
                out.push(path.clone());
            }
        }
        out
    }
}

/// Why a `shell_isolate_hide` entry is not hiding anything.
///
/// Two reasons, because they are fixed differently: a path that does not exist is a typo to
/// correct, and a path that contains something writable is a choice to make — the run keeps its
/// workspace, and the file the entry names stays visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HideSkip {
    /// Nothing is at that path.
    Missing,
    /// The path contains something the run is allowed to write, so emptying it would take the
    /// workspace with it.
    ContainsWritable,
}

impl HideSkip {
    pub fn why(self) -> &'static str {
        match self {
            Self::Missing => "no such path",
            Self::ContainsWritable => "contains something the run may write",
        }
    }
}

/// `~` and `~/x` mean the home directory; anything else is taken as written.
fn expand(path: &Path) -> PathBuf {
    let Some(home) = std::env::var_os("HOME") else {
        return path.to_path_buf();
    };
    match path.strip_prefix("~") {
        Ok(rest) => PathBuf::from(home).join(rest),
        Err(_) => path.to_path_buf(),
    }
}

fn need_bwrap(mode: ShellIsolate) -> bool {
    mode != ShellIsolate::Off
}

/// `bwrap` from `PATH`, executable and not a directory.
fn find_bwrap() -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|dir| dir.join("bwrap"))
        .find(|candidate| {
            std::fs::metadata(candidate).is_ok_and(|m| {
                m.is_file() && {
                    #[cfg(unix)]
                    {
                        use std::os::unix::fs::PermissionsExt;
                        m.permissions().mode() & 0o111 != 0
                    }
                    #[cfg(not(unix))]
                    {
                        true
                    }
                }
            })
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg(mode: ShellIsolate) -> ToolsConfig {
        ToolsConfig {
            shell_isolate: mode,
            ..ToolsConfig::default()
        }
    }

    fn strings(args: &[OsString]) -> Vec<String> {
        args.iter()
            .map(|a| a.to_string_lossy().into_owned())
            .collect()
    }

    #[test]
    fn off_is_the_command_itself_and_nothing_else() {
        let sb = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
        assert!(!sb.is_on());
        let plan = sb
            .plan(
                OsStr::new("sh"),
                &["-c".into(), "echo hi".into()],
                Path::new("/w"),
            )
            .unwrap();
        assert_eq!(plan.program, OsString::from("sh"));
        assert_eq!(strings(&plan.args), vec!["-c", "echo hi"]);
    }

    #[test]
    fn fs_refuses_without_bubblewrap_and_process_degrades_out_loud() {
        // `fs` promised a read-only machine, so it refuses rather than run uncontained.
        let fs = Sandbox::without_bwrap(ShellIsolate::Fs);
        let err = fs
            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("read-only"), "{err}");
        assert!(err.contains("not run"), "{err}");
        assert!(err.contains("bubblewrap"), "{err}");
        assert!(!fs.degraded());

        // `process` promised only a namespace, so it runs plainly and says what it could not do.
        let process = Sandbox::without_bwrap(ShellIsolate::Process);
        let plan = process
            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
            .unwrap();
        assert_eq!(plan.program, OsString::from("sh"));
        assert!(process.degraded());
        assert!(
            process.status().contains("uncontained"),
            "{}",
            process.status()
        );
    }

    #[test]
    fn process_mode_scopes_the_pid_namespace_and_leaves_the_filesystem_alone() {
        let sb = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
        if sb.bwrap.is_none() {
            return;
        }
        let plan = sb
            .plan(
                OsStr::new("sh"),
                &["-c".into(), "echo hi".into()],
                Path::new("/w"),
            )
            .unwrap();
        assert!(plan.program.to_string_lossy().ends_with("bwrap"));
        let a = strings(&plan.args);
        assert!(a.starts_with(&["--die-with-parent".into(), "--unshare-pid".into()]));
        assert!(a.contains(&"--dev-bind".to_string()));
        assert!(
            !a.contains(&"--ro-bind".to_string()),
            "process mode must not scope files"
        );
        assert!(!a.contains(&"--unshare-net".to_string()));
        assert_eq!(
            &a[a.len() - 6..],
            &["--chdir", "/w", "--", "sh", "-c", "echo hi"]
        );
    }

    #[test]
    fn fs_mode_is_read_only_with_the_workspace_bound_back() {
        let sb = Sandbox::new(
            &cfg(ShellIsolate::Fs),
            Path::new("/w"),
            Some(Path::new("/s")),
        );
        if sb.bwrap.is_none() {
            return;
        }
        let plan = sb
            .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
            .unwrap();
        let a = strings(&plan.args);
        assert!(a.contains(&"--ro-bind".to_string()));
        assert!(a.contains(&"/tmp".to_string()));
        // The workspace and the scripts directory are the two writes that always survive.
        let binds: Vec<&String> = a
            .windows(3)
            .filter(|w| {
                w[0] == "--bind" && {
                    let p = Path::new(&w[1]);
                    p.is_dir()
                }
            })
            .map(|w| &w[1])
            .collect();
        assert!(binds.iter().any(|p| *p == "/w") || !Path::new("/w").is_dir());
        assert!(a.contains(&"--unshare-pid".to_string()));
    }

    #[test]
    fn a_path_the_caller_added_is_bound_read_write_in_fs_mode() {
        // The tool bridge creates its socket after the sandbox does, so the run has to be able to
        // bind that directory: without it the child is told a path that does not exist where it
        // runs, and `eclipse tool` inside a script has no bridge to call (#550).
        let extra = tempfile::tempdir().unwrap();
        let sb = Sandbox::new(&cfg(ShellIsolate::Fs), Path::new("/w"), None);
        if sb.bwrap.is_none() {
            return;
        }
        let plan = sb
            .plan_with(
                OsStr::new("sh"),
                &[],
                extra.path(),
                &[extra.path().to_path_buf()],
            )
            .unwrap();
        let a = strings(&plan.args);
        assert!(
            a.windows(3).any(|w| {
                w[0] == "--bind"
                    && Path::new(&w[1]) == extra.path()
                    && Path::new(&w[2]) == extra.path()
            }),
            "the extra directory is bound at its own path: {a:?}"
        );
    }

    #[test]
    fn fs_mode_can_drop_the_network() {
        let mut c = cfg(ShellIsolate::Fs);
        c.shell_isolate_network = false;
        let sb = Sandbox::new(&c, Path::new("/w"), None);
        if sb.bwrap.is_none() {
            return;
        }
        let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
        assert!(strings(&plan.args).contains(&"--unshare-net".to_string()));
    }

    fn hidden(mode: ShellIsolate, workspace: &Path, hide: Vec<PathBuf>) -> Sandbox {
        let mut c = cfg(mode);
        c.shell_isolate_hide = hide;
        Sandbox::new(&c, workspace, None)
    }

    #[test]
    fn a_hide_is_expanded_and_applied_whether_it_is_a_file_or_a_directory() {
        let home = tempfile::tempdir().unwrap();
        let workspace = home.path().join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let netrc = home.path().join(".netrc");
        std::fs::write(&netrc, "machine example login me password hunter2\n").unwrap();
        let ssh = home.path().join(".ssh");
        std::fs::create_dir(&ssh).unwrap();

        let sb = hidden(
            ShellIsolate::Fs,
            &workspace,
            vec![
                netrc.clone(),
                ssh.clone(),
                PathBuf::from("~/.eclipse-never-exists"),
            ],
        );
        assert_eq!(
            sb.hide[2],
            PathBuf::from(std::env::var_os("HOME").unwrap_or_default())
                .join(".eclipse-never-exists"),
            "`~` is home"
        );
        let applied = sb.applied_hides();
        let resolved: Vec<PathBuf> = applied.iter().map(|(_, r)| r.clone()).collect();
        assert_eq!(
            resolved,
            vec![
                std::fs::canonicalize(&netrc).unwrap(),
                std::fs::canonicalize(&ssh).unwrap()
            ],
            "a file is not dropped for not being a directory (#552)"
        );

        if sb.bwrap.is_none() {
            return;
        }
        let plan = sb.plan(OsStr::new("sh"), &[], &workspace).unwrap();
        let a = strings(&plan.args);
        let netrc_at = std::fs::canonicalize(&netrc).unwrap().display().to_string();
        let ssh_at = std::fs::canonicalize(&ssh).unwrap().display().to_string();
        // A directory is emptied; a file cannot be, so the device that reads as nothing goes over
        // it — which is what `~/.netrc`, `~/.git-credentials` and a `.env` need.
        assert!(
            a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == ssh_at),
            "{a:?}"
        );
        assert!(
            a.windows(3)
                .any(|w| w[0] == "--ro-bind" && w[1] == "/dev/null" && w[2] == netrc_at),
            "{a:?}"
        );
        assert!(
            !a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == netrc_at),
            "a file cannot be tmpfs'd: {a:?}"
        );
        // A path that is not there is not bound at all: a mount over nothing fails the whole run.
        assert!(
            !a.iter().any(|w| w.contains(".eclipse-never-exists")),
            "{a:?}"
        );
    }

    #[test]
    fn a_hide_that_does_not_exist_is_reported_rather_than_dropped_silently() {
        let home = tempfile::tempdir().unwrap();
        let workspace = home.path().join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let typo = home.path().join(".netrcc");
        let sb = hidden(ShellIsolate::Fs, &workspace, vec![typo.clone()]);
        assert!(sb.applied_hides().is_empty());
        let skipped = sb.skipped_hides();
        assert_eq!(skipped.len(), 1);
        assert_eq!(skipped[0].0, &typo);
        assert_eq!(skipped[0].1, HideSkip::Missing);
        assert!(
            !sb.status().contains(".netrcc"),
            "a typo is `config check`'s finding, not a sentence in the status line: {}",
            sb.status()
        );
    }

    #[test]
    fn a_hide_that_reaches_the_workspace_through_a_symlink_is_skipped() {
        // The profile names a parent by a symlink; the workspace the run is given is canonical.
        // Lexically the two do not overlap, so the `--tmpfs` used to land on the workspace itself
        // and every run lost it (#552).
        let real = tempfile::tempdir().unwrap();
        let workspace = real.path().join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        std::fs::write(workspace.join("keep.txt"), "keep me\n").unwrap();
        let link = real.path().join("home-by-another-name");
        std::os::unix::fs::symlink(real.path(), &link).unwrap();

        let sb = hidden(ShellIsolate::Fs, &workspace, vec![link]);
        assert!(
            sb.applied_hides().is_empty(),
            "the workspace is inside it once both are resolved"
        );
        let skipped = sb.skipped_hides();
        assert_eq!(skipped.len(), 1);
        assert_eq!(skipped[0].1, HideSkip::ContainsWritable);
    }

    #[test]
    fn status_says_which_mechanism_and_whether_it_is_there() {
        let off = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
        assert!(off.status().starts_with("off"));
        let on = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
        let text = on.status();
        assert!(text.starts_with("process"));
        assert!(text.contains("bubblewrap"), "{text}");
    }
}