Skip to main content

host/
sandboxed.rs

1//! Isolation for the host's operations, from the `sandbox` crate.
2//!
3//! [`Host::sandboxed`] turns it on: shell commands (blocking bash and shell jobs) run under the session's
4//! [`sandbox::Launcher`]. Writes (runtime.py's `write`/`edit`, through `files.before_write`) are also contained:
5//! outside the sandbox's writable paths they are blocked, as the shell's would be. There are no approvals: every
6//! operation the sandbox contains is allowed.
7
8use crate::{Guard, Host};
9use sandbox::Settings;
10use sandbox::launcher::{Launcher, Mechanism, Policy, SANDBOX_PATH};
11use sandbox::settings::Mode;
12use serde_json::{Value, json};
13use std::path::Path;
14use std::sync::Arc;
15
16/// The write containment check in front of another guard (Loki, file hooks), which still runs after it.
17pub struct SandboxGuard {
18    pub inner: Box<dyn Guard>,
19    pub launcher: Arc<Launcher>,
20}
21
22impl Guard for SandboxGuard {
23    fn before_shell(&self, lane: &str, command: &str) -> Option<String> {
24        self.inner.before_shell(lane, command)
25    }
26
27    fn before_write(&self, lane: &str, path: &str, content: &str) -> Value {
28        if self.launcher.mode != Mode::Off {
29            let target = self.launcher.policy.cwd.join(path);
30            if !self.launcher.policy.may_write(&target) {
31                return json!({ "blocked": true, "reason": outside_message(&self.launcher.policy) });
32            }
33        }
34        self.inner.before_write(lane, path, content)
35    }
36
37    fn guard_stats(&self) -> Vec<Value> {
38        self.inner.guard_stats()
39    }
40
41    fn begin_turn(&self) {
42        self.inner.begin_turn();
43    }
44
45    fn cell_started(&self, lane: &str) {
46        self.inner.cell_started(lane);
47    }
48
49    fn cell_ended(&self, lane: &str) {
50        self.inner.cell_ended(lane);
51    }
52
53    fn take_pending(&self, lane: &str) -> Option<String> {
54        self.inner.take_pending(lane)
55    }
56}
57
58/// The environment a sandbox policy is built from: the host's base environment (the session's, see
59/// [`Host::with_base_env`]); a host without one gets an empty environment plus `PATH` = [`SANDBOX_PATH`] and `HOME` =
60/// the sandbox's `home`, never this process's environment (its PATH, credentials or `DOCKER_HOST` would otherwise
61/// reach the sandbox and its launcher).
62fn sandbox_host_env(base: Option<&[(String, String)]>, home: &Path) -> Vec<(String, String)> {
63    match base {
64        Some(env) => env.to_vec(),
65        None => vec![
66            ("PATH".to_string(), SANDBOX_PATH.to_string()),
67            ("HOME".to_string(), home.display().to_string()),
68        ],
69    }
70}
71
72fn outside_message(policy: &Policy) -> String {
73    let roots: Vec<String> = policy.writable.iter().map(|p| p.display().to_string()).collect();
74    format!(
75        "it is outside the sandbox's writable paths ({}); add the path to sandbox.writable to allow it",
76        roots.join(", ")
77    )
78}
79
80impl Host {
81    /// Run this host's shell commands isolated and contain its writes by `settings` (`sandbox.*`). `home` is the
82    /// user's home, `tmp` the session temp dir seen as /tmp inside (None: a private /tmp per command).
83    pub fn sandboxed(self, settings: &Value, home: &Path, tmp: Option<&Path>) -> Self {
84        self.sandboxed_under(settings, home, tmp, None)
85    }
86
87    /// [`Host::sandboxed`] under `mechanism` instead of the strongest one that works here (tests run every backend
88    /// this way; None runs unisolated, as `auto` does when nothing works).
89    pub fn sandboxed_with_mechanism(
90        self,
91        settings: &Value,
92        home: &Path,
93        tmp: Option<&Path>,
94        mechanism: Option<Mechanism>,
95    ) -> Self {
96        self.sandboxed_under(settings, home, tmp, Some(mechanism))
97    }
98
99    fn sandboxed_under(
100        mut self,
101        settings: &Value,
102        home: &Path,
103        tmp: Option<&Path>,
104        mechanism: Option<Option<Mechanism>>,
105    ) -> Self {
106        let sandbox_settings = Settings::from_settings(settings);
107        let host_env = sandbox_host_env(self.base_env.as_deref().map(Vec::as_slice), home);
108        let policy = Policy::new(
109            &sandbox_settings,
110            &self.cwd,
111            home,
112            &[self.jobs_dir.clone(), self.spill_dir.clone()],
113            tmp,
114            &host_env,
115        );
116        let launcher = Launcher::new(sandbox_settings.mode, policy);
117        let launcher = Arc::new(match mechanism {
118            Some(mechanism) => launcher.with_mechanism(mechanism),
119            None => launcher,
120        });
121        let inner = std::mem::replace(&mut self.guard, Box::new(crate::AllowAll));
122        self.guard = Box::new(SandboxGuard {
123            inner,
124            launcher: launcher.clone(),
125        });
126        self.launcher = Some(launcher);
127        self
128    }
129
130    /// The launcher of a sandboxed host (for `doctor` and status lines).
131    pub fn launcher(&self) -> Option<&Arc<Launcher>> {
132        self.launcher.as_ref()
133    }
134}