1use std::ffi::{OsStr, OsString};
28use std::path::{Path, PathBuf};
29
30use crate::config::{ShellIsolate, ToolsConfig};
31use crate::tools::ToolError;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Plan {
37 pub program: OsString,
38 pub args: Vec<OsString>,
39}
40
41#[derive(Debug, Clone)]
44pub struct Sandbox {
45 mode: ShellIsolate,
46 workspace: PathBuf,
47 scripts_dir: Option<PathBuf>,
48 writable: Vec<PathBuf>,
50 hide: Vec<PathBuf>,
52 network: bool,
53 bwrap: Option<PathBuf>,
56}
57
58impl Sandbox {
59 pub fn new(cfg: &ToolsConfig, workspace: &Path, scripts_dir: Option<&Path>) -> Self {
60 let mode = cfg.shell_isolate;
61 Self {
62 mode,
63 workspace: workspace.to_path_buf(),
64 scripts_dir: scripts_dir.map(Path::to_path_buf),
65 writable: cfg
66 .shell_isolate_writable
67 .iter()
68 .map(|p| expand(p))
69 .collect(),
70 hide: cfg.shell_isolate_hide.iter().map(|p| expand(p)).collect(),
71 network: cfg.shell_isolate_network,
72 bwrap: need_bwrap(mode).then(find_bwrap).flatten(),
73 }
74 }
75
76 pub fn off() -> Self {
79 Self {
80 mode: ShellIsolate::Off,
81 workspace: PathBuf::new(),
82 scripts_dir: None,
83 writable: Vec::new(),
84 hide: Vec::new(),
85 network: true,
86 bwrap: None,
87 }
88 }
89
90 #[cfg(test)]
93 pub fn without_bwrap(mode: ShellIsolate) -> Self {
94 let mut sb = Self::off();
95 sb.mode = mode;
96 sb
97 }
98
99 pub fn mode(&self) -> ShellIsolate {
100 self.mode
101 }
102
103 pub fn is_on(&self) -> bool {
105 self.mode != ShellIsolate::Off
106 }
107
108 pub fn refuses(&self) -> bool {
111 self.mode == ShellIsolate::Fs && self.bwrap.is_none()
112 }
113
114 pub fn degraded(&self) -> bool {
118 self.mode == ShellIsolate::Process && self.bwrap.is_none()
119 }
120
121 pub fn status(&self) -> String {
123 if !self.is_on() {
124 return "off — a command runs as you, with your files, your network and your daemons"
125 .to_string();
126 }
127 let skipped = self.skipped_hides();
128 let note = if skipped.is_empty() {
129 String::new()
130 } else {
131 format!(
132 "; not hiding {}: it contains a path the run must write",
133 skipped
134 .iter()
135 .map(|p| p.display().to_string())
136 .collect::<Vec<_>>()
137 .join(", ")
138 )
139 };
140 match (&self.bwrap, self.mode) {
141 (Some(path), _) => format!("{} — bubblewrap at {}{note}", self.mode, path.display()),
142 (None, ShellIsolate::Process) => format!(
143 "process — bubblewrap is NOT on PATH, so commands run uncontained and say so: \
144 install bubblewrap to contain them{note}"
145 ),
146 (None, _) => format!(
147 "{} — bubblewrap is NOT on PATH, so `shell` will refuse to run: install \
148 bubblewrap, or set [tools] shell_isolate = \"off\"{note}",
149 self.mode
150 ),
151 }
152 }
153
154 pub fn plan(&self, program: &OsStr, args: &[OsString], cwd: &Path) -> Result<Plan, ToolError> {
159 if !self.is_on() {
160 return Ok(Plan {
161 program: program.to_owned(),
162 args: args.to_vec(),
163 });
164 }
165 if self.mode == ShellIsolate::Fs && self.bwrap.is_none() {
170 return Err(ToolError::Failed(
171 "[tools] shell_isolate = \"fs\" makes the filesystem read-only, and that needs \
172 bubblewrap, which is not on PATH, so the command was not run. Install it \
173 (Debian/Ubuntu: `sudo apt install bubblewrap`, Fedora: `sudo dnf install \
174 bubblewrap`, Arch: `sudo pacman -S bubblewrap`), or use shell_isolate = \
175 \"process\" for a namespace without the filesystem scoping. Running uncontained \
176 instead is not something this profile asked for."
177 .to_string(),
178 ));
179 }
180 let Some(bwrap) = &self.bwrap else {
181 return Ok(Plan {
183 program: program.to_owned(),
184 args: args.to_vec(),
185 });
186 };
187
188 let mut a: Vec<OsString> = Vec::with_capacity(32);
189 a.push("--die-with-parent".into());
190 a.push("--unshare-pid".into());
191 match self.mode {
192 ShellIsolate::Process => {
194 a.push("--dev-bind".into());
195 a.push("/".into());
196 a.push("/".into());
197 a.push("--proc".into());
198 a.push("/proc".into());
199 }
200 ShellIsolate::Fs => {
201 a.push("--ro-bind".into());
202 a.push("/".into());
203 a.push("/".into());
204 a.push("--proc".into());
205 a.push("/proc".into());
206 a.push("--dev".into());
207 a.push("/dev".into());
208 a.push("--tmpfs".into());
209 a.push("/tmp".into());
210 if !self.network {
211 a.push("--unshare-net".into());
212 }
213 for dir in self.writable_paths() {
214 if dir.is_dir() {
215 a.push("--bind".into());
216 a.push(dir.as_os_str().to_owned());
217 a.push(dir.as_os_str().to_owned());
218 }
219 }
220 for dir in self.hides_in_effect() {
224 a.push("--tmpfs".into());
225 a.push(dir.as_os_str().to_owned());
226 }
227 }
228 ShellIsolate::Off => unreachable!("handled above"),
229 }
230 a.push("--chdir".into());
231 a.push(cwd.as_os_str().to_owned());
232 a.push("--".into());
233 a.push(program.to_owned());
234 a.extend(args.iter().cloned());
235 Ok(Plan {
236 program: bwrap.as_os_str().to_owned(),
237 args: a,
238 })
239 }
240
241 fn hides_in_effect(&self) -> Vec<&PathBuf> {
245 let writes = self.writable_paths();
246 self.hide
247 .iter()
248 .filter(|h| h.is_dir() && !writes.iter().any(|w| w.starts_with(h)))
249 .collect()
250 }
251
252 pub fn skipped_hides(&self) -> Vec<&PathBuf> {
255 self.hide
256 .iter()
257 .filter(|h| h.is_dir() && !self.hides_in_effect().contains(h))
258 .collect()
259 }
260
261 fn writable_paths(&self) -> Vec<PathBuf> {
264 let mut out = vec![self.workspace.clone()];
265 for path in self.scripts_dir.iter().chain(self.writable.iter()) {
266 if !out.contains(path) {
267 out.push(path.clone());
268 }
269 }
270 out
271 }
272}
273
274fn expand(path: &Path) -> PathBuf {
276 let Some(home) = std::env::var_os("HOME") else {
277 return path.to_path_buf();
278 };
279 match path.strip_prefix("~") {
280 Ok(rest) => PathBuf::from(home).join(rest),
281 Err(_) => path.to_path_buf(),
282 }
283}
284
285fn need_bwrap(mode: ShellIsolate) -> bool {
286 mode != ShellIsolate::Off
287}
288
289fn find_bwrap() -> Option<PathBuf> {
291 let path = std::env::var_os("PATH")?;
292 std::env::split_paths(&path)
293 .map(|dir| dir.join("bwrap"))
294 .find(|candidate| {
295 std::fs::metadata(candidate).is_ok_and(|m| {
296 m.is_file() && {
297 #[cfg(unix)]
298 {
299 use std::os::unix::fs::PermissionsExt;
300 m.permissions().mode() & 0o111 != 0
301 }
302 #[cfg(not(unix))]
303 {
304 true
305 }
306 }
307 })
308 })
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 fn cfg(mode: ShellIsolate) -> ToolsConfig {
316 ToolsConfig {
317 shell_isolate: mode,
318 ..ToolsConfig::default()
319 }
320 }
321
322 fn strings(args: &[OsString]) -> Vec<String> {
323 args.iter()
324 .map(|a| a.to_string_lossy().into_owned())
325 .collect()
326 }
327
328 #[test]
329 fn off_is_the_command_itself_and_nothing_else() {
330 let sb = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
331 assert!(!sb.is_on());
332 let plan = sb
333 .plan(
334 OsStr::new("sh"),
335 &["-c".into(), "echo hi".into()],
336 Path::new("/w"),
337 )
338 .unwrap();
339 assert_eq!(plan.program, OsString::from("sh"));
340 assert_eq!(strings(&plan.args), vec!["-c", "echo hi"]);
341 }
342
343 #[test]
344 fn fs_refuses_without_bubblewrap_and_process_degrades_out_loud() {
345 let fs = Sandbox::without_bwrap(ShellIsolate::Fs);
347 let err = fs
348 .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
349 .unwrap_err()
350 .to_string();
351 assert!(err.contains("read-only"), "{err}");
352 assert!(err.contains("not run"), "{err}");
353 assert!(err.contains("bubblewrap"), "{err}");
354 assert!(!fs.degraded());
355
356 let process = Sandbox::without_bwrap(ShellIsolate::Process);
358 let plan = process
359 .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
360 .unwrap();
361 assert_eq!(plan.program, OsString::from("sh"));
362 assert!(process.degraded());
363 assert!(
364 process.status().contains("uncontained"),
365 "{}",
366 process.status()
367 );
368 }
369
370 #[test]
371 fn process_mode_scopes_the_pid_namespace_and_leaves_the_filesystem_alone() {
372 let sb = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
373 if sb.bwrap.is_none() {
374 return;
375 }
376 let plan = sb
377 .plan(
378 OsStr::new("sh"),
379 &["-c".into(), "echo hi".into()],
380 Path::new("/w"),
381 )
382 .unwrap();
383 assert!(plan.program.to_string_lossy().ends_with("bwrap"));
384 let a = strings(&plan.args);
385 assert!(a.starts_with(&["--die-with-parent".into(), "--unshare-pid".into()]));
386 assert!(a.contains(&"--dev-bind".to_string()));
387 assert!(
388 !a.contains(&"--ro-bind".to_string()),
389 "process mode must not scope files"
390 );
391 assert!(!a.contains(&"--unshare-net".to_string()));
392 assert_eq!(
393 &a[a.len() - 6..],
394 &["--chdir", "/w", "--", "sh", "-c", "echo hi"]
395 );
396 }
397
398 #[test]
399 fn fs_mode_is_read_only_with_the_workspace_bound_back() {
400 let sb = Sandbox::new(
401 &cfg(ShellIsolate::Fs),
402 Path::new("/w"),
403 Some(Path::new("/s")),
404 );
405 if sb.bwrap.is_none() {
406 return;
407 }
408 let plan = sb
409 .plan(OsStr::new("sh"), &["-c".into()], Path::new("/w"))
410 .unwrap();
411 let a = strings(&plan.args);
412 assert!(a.contains(&"--ro-bind".to_string()));
413 assert!(a.contains(&"/tmp".to_string()));
414 let binds: Vec<&String> = a
416 .windows(3)
417 .filter(|w| {
418 w[0] == "--bind" && {
419 let p = Path::new(&w[1]);
420 p.is_dir()
421 }
422 })
423 .map(|w| &w[1])
424 .collect();
425 assert!(binds.iter().any(|p| *p == "/w") || !Path::new("/w").is_dir());
426 assert!(a.contains(&"--unshare-pid".to_string()));
427 }
428
429 #[test]
430 fn fs_mode_can_drop_the_network() {
431 let mut c = cfg(ShellIsolate::Fs);
432 c.shell_isolate_network = false;
433 let sb = Sandbox::new(&c, Path::new("/w"), None);
434 if sb.bwrap.is_none() {
435 return;
436 }
437 let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
438 assert!(strings(&plan.args).contains(&"--unshare-net".to_string()));
439 }
440
441 #[test]
442 fn hide_list_is_expanded_and_only_applied_to_existing_directories() {
443 let mut c = cfg(ShellIsolate::Fs);
444 c.shell_isolate_hide = vec![
445 PathBuf::from("~/.eclipse-never-exists"),
446 PathBuf::from("/tmp"),
447 ];
448 let sb = Sandbox::new(&c, Path::new("/w"), None);
449 if let Some(home) = std::env::var_os("HOME") {
450 assert_eq!(
451 sb.hide[0],
452 PathBuf::from(home).join(".eclipse-never-exists")
453 );
454 }
455 if sb.bwrap.is_none() {
456 return;
457 }
458 let plan = sb.plan(OsStr::new("sh"), &[], Path::new("/w")).unwrap();
459 let a = strings(&plan.args);
460 assert!(a.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == "/tmp"));
463 assert!(!a.iter().any(|w| w.contains(".eclipse-never-exists")));
464 }
465
466 #[test]
467 fn status_says_which_mechanism_and_whether_it_is_there() {
468 let off = Sandbox::new(&cfg(ShellIsolate::Off), Path::new("/w"), None);
469 assert!(off.status().starts_with("off"));
470 let on = Sandbox::new(&cfg(ShellIsolate::Process), Path::new("/w"), None);
471 let text = on.status();
472 assert!(text.starts_with("process"));
473 assert!(text.contains("bubblewrap"), "{text}");
474 }
475}