1use std::ffi::{OsStr, OsString};
30use std::path::{Path, PathBuf};
31
32use crate::config::{ShellIsolate, ToolsConfig};
33use crate::tools::ToolError;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Plan {
39 pub program: OsString,
40 pub args: Vec<OsString>,
41}
42
43#[derive(Debug, Clone)]
46pub struct Sandbox {
47 mode: ShellIsolate,
48 workspace: PathBuf,
49 scripts_dir: Option<PathBuf>,
50 writable: Vec<PathBuf>,
52 hide: Vec<PathBuf>,
54 suggested_hides: Vec<PathBuf>,
58 network: bool,
59 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 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 #[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 pub fn is_on(&self) -> bool {
116 self.mode != ShellIsolate::Off
117 }
118
119 pub fn refuses(&self) -> bool {
122 self.refusal().is_some()
123 }
124
125 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 pub fn degraded(&self) -> bool {
146 self.mode == ShellIsolate::Process && self.bwrap.is_none()
147 }
148
149 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 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 pub fn plan(&self, program: &OsStr, args: &[OsString], cwd: &Path) -> Result<Plan, ToolError> {
195 self.plan_with(program, args, cwd, &[])
196 }
197
198 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 if let Some(why) = self.refusal() {
221 return Err(why);
222 }
223 let Some(bwrap) = &self.bwrap else {
224 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 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 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 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 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 if writes.iter().any(|w| w.starts_with(&resolved)) {
327 return None;
328 }
329 Some((declared.clone(), resolved))
330 })
331 .collect()
332 }
333
334 pub fn is_suggested_hide(&self, path: &Path) -> bool {
336 self.suggested_hides.iter().any(|s| s == path)
337 }
338
339 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376pub enum HideSkip {
377 Missing,
379 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
393fn 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
408fn 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 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 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 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 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 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 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 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}