eclipse-core 0.13.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
//! 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, 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>,
    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(),
            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(),
            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.mode == ShellIsolate::Fs && self.bwrap.is_none()
    }

    /// 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();
        }
        let skipped = self.skipped_hides();
        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> {
        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 self.mode == ShellIsolate::Fs && self.bwrap.is_none() {
            return Err(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(),
            ));
        }
        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());
                    }
                }
                // 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.
                for dir in self.hides_in_effect() {
                    a.push("--tmpfs".into());
                    a.push(dir.as_os_str().to_owned());
                }
            }
            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 are actually applied: a hide containing something the run is allowed to
    /// write is dropped, because emptying it would delete the workspace the command was given —
    /// a setting that silently broke every run would be worse than the gap it closes.
    fn hides_in_effect(&self) -> Vec<&PathBuf> {
        let writes = self.writable_paths();
        self.hide
            .iter()
            .filter(|h| h.is_dir() && !writes.iter().any(|w| w.starts_with(h)))
            .collect()
    }

    /// The hides a profile asked for that cannot be applied, 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> {
        self.hide
            .iter()
            .filter(|h| h.is_dir() && !self.hides_in_effect().contains(h))
            .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
    }
}

/// `~` 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 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()));
    }

    #[test]
    fn hide_list_is_expanded_and_only_applied_to_existing_directories() {
        let mut c = cfg(ShellIsolate::Fs);
        c.shell_isolate_hide = vec![
            PathBuf::from("~/.eclipse-never-exists"),
            PathBuf::from("/tmp"),
        ];
        let sb = Sandbox::new(&c, Path::new("/w"), None);
        if let Some(home) = std::env::var_os("HOME") {
            assert_eq!(
                sb.hide[0],
                PathBuf::from(home).join(".eclipse-never-exists")
            );
        }
        if sb.bwrap.is_none() {
            return;
        }
        let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
        let a = strings(&plan.args);
        // `/tmp` exists and is hidden; the imaginary home path is not bound at all, because a
        // `--tmpfs` over a path that does not exist would fail the whole run.
        assert!(a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == "/tmp"));
        assert!(!a.iter().any(|w| w.contains(".eclipse-never-exists")));
    }

    #[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}");
    }
}