Skip to main content

base/
engine_exec.rs

1//! The subprocesses the engine starts on a session's behalf — its own git and
2//! helpers such as `pdftotext` — and the one way it starts them: through that
3//! session's [`ExecProviders`].
4//!
5//! Going through the session's `exec.process` is what puts them where the
6//! session's commands are: on the machine (or remote) the host chose, under
7//! the same `sandbox.env`, in a session of their own with no
8//! controlling terminal, and stopped as a whole group when they time out. In a
9//! session whose commands the OS sandbox confines they are confined too, so
10//! whatever a repository a confined command configured makes git run is held
11//! to the same roots.
12
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16use tokio_util::sync::CancellationToken;
17
18use crate::interface::exec::{
19    capture, Captured, Enforcement, ExecError, ExecProviders, FileSystem, NetworkMode, ProcessSpec,
20    SandboxPolicy,
21};
22use crate::permission::ProjectTrust;
23
24/// Options every git the engine runs itself puts before its subcommand.
25///
26/// They turn off the fsmonitor and hooks a repository names: one a sandboxed
27/// command may have written must not start a program through them, whether
28/// or not the git reading it is confined. Filter drivers cannot be turned off
29/// this way; [`Confinement::Sandboxed`] is what confines them.
30pub const ENGINE_GIT_OPTIONS: &[&str] = &[
31    "-c",
32    "core.fsmonitor=false",
33    "-c",
34    "core.hooksPath=/dev/null",
35];
36
37/// The engine's subprocesses for one session.
38#[derive(Clone)]
39pub struct EngineExec {
40    exec: ExecProviders,
41    confinement: Confinement,
42    trust: ProjectTrust,
43    min_deadline: Duration,
44}
45
46/// Whether the engine's subprocesses run in the session's sandbox.
47#[derive(Debug, Clone, Default)]
48#[allow(clippy::large_enum_variant)]
49pub enum Confinement {
50    /// The session's commands are not confined, so a confined command cannot
51    /// have prepared the repository.
52    #[default]
53    Unconfined,
54    /// Inside `exec.sandbox`, under the session's own `policy` narrowed per
55    /// call: no network, and nothing writable but `tmpdir` and what the call
56    /// names. `tmpdir` becomes the subprocess's `TMPDIR`.
57    Sandboxed {
58        policy: SandboxPolicy,
59        require_enforcement: bool,
60        tmpdir: Option<PathBuf>,
61    },
62}
63
64/// What a git the engine runs may write.
65#[derive(Debug, Clone, Copy)]
66pub enum GitAccess<'a> {
67    ReadOnly,
68    Writes(&'a [PathBuf]),
69}
70
71impl<'a> GitAccess<'a> {
72    fn writable(&self) -> &'a [PathBuf] {
73        match self {
74            Self::ReadOnly => &[],
75            Self::Writes(paths) => paths,
76        }
77    }
78}
79
80/// Whether a git may start, decided before anything does.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum Admission {
83    Run { options: &'static [&'static str] },
84    Refuse(String),
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88enum Program {
89    Git,
90    Helper,
91}
92
93#[derive(Debug, Clone, thiserror::Error)]
94#[non_exhaustive]
95pub enum EngineExecError {
96    /// Not started: the admission refused it, or it has to be sandboxed and
97    /// the sandbox cannot hold it.
98    #[error("not run: {0}")]
99    Refused(String),
100    #[error("timed out after {0:?}")]
101    TimedOut(Duration),
102    #[error(transparent)]
103    Failed(#[from] ExecError),
104}
105
106/// The one decision point for every git the engine starts.
107///
108/// An untrusted project's repository configuration is whoever wrote the
109/// project's: the programs it names (filter drivers, `diff.external`,
110/// `core.sshCommand`) git starts on its own. So a git outside any sandbox
111/// does not run in one.
112pub fn admit_git(
113    trust: ProjectTrust,
114    _access: &GitAccess<'_>,
115    confinement: &Confinement,
116) -> Admission {
117    match (confinement, trust) {
118        (Confinement::Sandboxed { .. }, _)
119        | (Confinement::Unconfined, ProjectTrust::Trusted | ProjectTrust::NoProject) => {
120            Admission::Run {
121                options: ENGINE_GIT_OPTIONS,
122            }
123        }
124        (Confinement::Unconfined, ProjectTrust::Untrusted) => {
125            Admission::Refuse(UNTRUSTED_UNCONFINED.into())
126        }
127    }
128}
129
130const UNTRUSTED_UNCONFINED: &str = "the project is not trusted and the engine's git would run \
131     outside any sandbox, where the programs its repository configuration names would run \
132     unconfined; trust the project (`project.trust`) or let the sandbox hold the session's commands";
133
134/// What a repository's `HEAD` says, read as a file rather than asked of git.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Head {
137    /// The branch checked out; `None` when `HEAD` is detached.
138    pub branch: Option<String>,
139    /// The repository's `.git` is a `gitdir:` link: a worktree or a
140    /// submodule checkout.
141    pub linked: bool,
142}
143
144/// The `HEAD` of the repository `dir` is in: the first `.git` in `dir` or
145/// above it, a directory or a file whose `gitdir:` line names one. `None`
146/// where there is no repository or its `HEAD` cannot be read.
147///
148/// For a snapshot of a repository whose git the engine may not run: nothing
149/// in the repository is executed or interpreted beyond these two files.
150pub async fn read_head(fs: &dyn FileSystem, dir: &Path) -> Option<Head> {
151    for at in dir.ancestors() {
152        let dot_git = at.join(".git");
153        let Ok(meta) = fs.metadata_following_symlinks(&dot_git).await else {
154            continue;
155        };
156        let (git_dir, linked) = if meta.is_dir {
157            (dot_git, false)
158        } else {
159            let link = fs.read_to_string(&dot_git).await.ok()?;
160            let target = link.lines().next()?.strip_prefix("gitdir:")?.trim();
161            (at.join(target), true)
162        };
163        let head = fs.read_to_string(&git_dir.join("HEAD")).await.ok()?;
164        let head = head.trim();
165        let branch = head
166            .strip_prefix("ref:")
167            .map(str::trim)
168            .and_then(|r| r.strip_prefix("refs/heads/"))
169            .map(str::to_string);
170        return Some(Head { branch, linked });
171    }
172    None
173}
174
175impl EngineExec {
176    pub fn new(exec: ExecProviders, confinement: Confinement, trust: ProjectTrust) -> Self {
177        Self {
178            exec,
179            confinement,
180            trust,
181            min_deadline: Duration::ZERO,
182        }
183    }
184
185    /// Every call may take at least `floor`, whatever deadline it asks for.
186    pub fn with_min_deadline(mut self, floor: Duration) -> Self {
187        self.min_deadline = floor;
188        self
189    }
190
191    pub fn exec(&self) -> &ExecProviders {
192        &self.exec
193    }
194
195    pub fn is_sandboxed(&self) -> bool {
196        matches!(self.confinement, Confinement::Sandboxed { .. })
197    }
198
199    /// The session's own temporary directory, when the engine's processes
200    /// are sandboxed and it has been made.
201    pub fn tmpdir(&self) -> Option<&Path> {
202        match &self.confinement {
203            Confinement::Sandboxed { tmpdir, .. } => tmpdir.as_deref(),
204            Confinement::Unconfined => None,
205        }
206    }
207
208    /// `git <options> <args>` in `cwd`, never asking for credentials on a
209    /// terminal. The only way the engine starts git.
210    pub async fn git(
211        &self,
212        cwd: &Path,
213        access: GitAccess<'_>,
214        args: &[&str],
215        deadline: Duration,
216    ) -> Result<Captured, EngineExecError> {
217        let options = match admit_git(self.trust, &access, &self.confinement) {
218            Admission::Run { options } => options,
219            Admission::Refuse(why) => return Err(EngineExecError::Refused(why)),
220        };
221        let mut spec = ProcessSpec::new("git", cwd)
222            .args(options.iter().copied())
223            .args(args.iter().copied());
224        spec.env.extend([
225            ("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
226            ("GIT_ASKPASS".to_string(), String::new()),
227        ]);
228        self.run(spec, access.writable(), Program::Git, deadline)
229            .await
230    }
231
232    /// A helper program, confined as the session's commands are, writing
233    /// nothing but `writable`.
234    pub async fn helper(
235        &self,
236        spec: ProcessSpec,
237        writable: &[PathBuf],
238        deadline: Duration,
239    ) -> Result<Captured, EngineExecError> {
240        self.run(spec, writable, Program::Helper, deadline).await
241    }
242
243    async fn run(
244        &self,
245        spec: ProcessSpec,
246        writable: &[PathBuf],
247        program: Program,
248        deadline: Duration,
249    ) -> Result<Captured, EngineExecError> {
250        let spec = self.confine(spec, writable, program)?;
251        let deadline = deadline.max(self.min_deadline);
252        let captured = tokio::time::timeout(
253            deadline,
254            capture(&*self.exec.process, spec, CancellationToken::new()),
255        )
256        .await
257        .map_err(|_| EngineExecError::TimedOut(deadline))??;
258        Ok(captured)
259    }
260
261    /// `spec` as it has to be started. A sandbox that cannot hold it when
262    /// nothing requires one gives the same unconfined program the session's
263    /// own commands then get.
264    fn confine(
265        &self,
266        spec: ProcessSpec,
267        writable: &[PathBuf],
268        program: Program,
269    ) -> Result<ProcessSpec, EngineExecError> {
270        let Confinement::Sandboxed {
271            policy,
272            require_enforcement,
273            tmpdir,
274        } = &self.confinement
275        else {
276            return Ok(spec);
277        };
278        let mut policy = policy.clone();
279        policy.only_additional_writable = true;
280        policy.network_mode = NetworkMode::DenyAll;
281        policy.additional_writable = tmpdir.iter().chain(writable).cloned().collect();
282        let mut confined = self.exec.sandbox.confine(spec.clone(), &policy);
283        if confined.enforcement == Enforcement::None {
284            let unmet = confined.unmet.join("; ");
285            if *require_enforcement {
286                return Err(EngineExecError::Refused(format!(
287                    "the session's commands are sandboxed and `sandbox.require` \
288                     is on, but {} cannot be sandboxed here ({unmet})",
289                    spec.program
290                )));
291            }
292            if program == Program::Git && self.trust.is_untrusted() {
293                return Err(EngineExecError::Refused(format!(
294                    "{UNTRUSTED_UNCONFINED} ({unmet})"
295                )));
296            }
297            warn_unconfined_once(&unmet);
298            return Ok(spec);
299        }
300        if let Some(tmp) = tmpdir {
301            confined
302                .spec
303                .env
304                .push(("TMPDIR".to_string(), tmp.display().to_string()));
305        }
306        Ok(confined.spec)
307    }
308}
309
310impl std::fmt::Debug for EngineExec {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        f.debug_struct("EngineExec")
313            .field("confinement", &self.confinement)
314            .field("trust", &self.trust)
315            .finish_non_exhaustive()
316    }
317}
318
319fn warn_unconfined_once(unmet: &str) {
320    static WARNED: std::sync::Once = std::sync::Once::new();
321    WARNED.call_once(|| {
322        tracing::warn!(
323            unmet,
324            "the engine's own subprocesses run unsandboxed: the sandbox cannot hold them \
325             on this build or platform"
326        );
327    });
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::interface::exec::in_process::{NoSandbox, ScriptedProcess, ScriptedRun};
334    use crate::interface::exec::{Confined, Sandbox};
335    use std::sync::{Arc, Mutex};
336
337    const DEADLINE: Duration = Duration::from_secs(5);
338
339    fn with_process(process: ScriptedProcess) -> ExecProviders {
340        ExecProviders {
341            process: Arc::new(process),
342            ..ExecProviders::in_process()
343        }
344    }
345
346    fn git_key(args: &str) -> String {
347        format!("git {} {args}", ENGINE_GIT_OPTIONS.join(" "))
348    }
349
350    #[tokio::test]
351    async fn git_runs_through_the_sessions_process_with_the_engines_options() {
352        let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok("clean"));
353        let engine = EngineExec::new(
354            with_process(process.clone()),
355            Confinement::Unconfined,
356            ProjectTrust::Trusted,
357        );
358        let out = engine
359            .git(
360                Path::new("/repo"),
361                GitAccess::ReadOnly,
362                &["status"],
363                DEADLINE,
364            )
365            .await
366            .unwrap();
367        assert_eq!(out.stdout_lossy(), "clean");
368        assert_eq!(process.seen(), [git_key("status")]);
369    }
370
371    /// Records the policy it was asked to confine under, and confines fully
372    /// by prefixing the program.
373    #[derive(Default)]
374    struct RecordingSandbox(Mutex<Vec<SandboxPolicy>>);
375
376    impl Sandbox for RecordingSandbox {
377        fn confine(&self, spec: ProcessSpec, policy: &SandboxPolicy) -> Confined {
378            self.0.lock().unwrap().push(policy.clone());
379            let mut wrapped = ProcessSpec::new("boxed", spec.cwd.clone()).arg(spec.program);
380            wrapped.args.extend(spec.args);
381            wrapped.env = spec.env;
382            Confined {
383                spec: wrapped,
384                mode: crate::interface::exec::SandboxMode::LinuxBwrap,
385                enforcement: Enforcement::Full,
386                unmet: Vec::new(),
387            }
388        }
389    }
390
391    #[tokio::test]
392    async fn a_sandboxed_git_writes_only_what_it_names_and_reaches_no_network() {
393        let sandbox = Arc::new(RecordingSandbox::default());
394        let process = ScriptedProcess::new().with(
395            format!("boxed {}", git_key("worktree prune")),
396            ScriptedRun::ok(""),
397        );
398        let exec = ExecProviders {
399            sandbox: sandbox.clone(),
400            ..with_process(process.clone())
401        };
402        let engine = EngineExec::new(
403            exec,
404            Confinement::Sandboxed {
405                policy: SandboxPolicy {
406                    additional_writable: vec![PathBuf::from("/elsewhere")],
407                    ..Default::default()
408                },
409                require_enforcement: true,
410                tmpdir: Some(PathBuf::from("/tmp/session")),
411            },
412            ProjectTrust::Trusted,
413        );
414        let writable = [PathBuf::from("/repo/.git")];
415        engine
416            .git(
417                Path::new("/repo"),
418                GitAccess::Writes(&writable),
419                &["worktree", "prune"],
420                DEADLINE,
421            )
422            .await
423            .unwrap();
424        let policy = sandbox.0.lock().unwrap()[0].clone();
425        assert!(policy.only_additional_writable);
426        assert_eq!(policy.network_mode, NetworkMode::DenyAll);
427        assert_eq!(
428            policy.additional_writable,
429            [PathBuf::from("/tmp/session"), PathBuf::from("/repo/.git")]
430        );
431    }
432
433    #[tokio::test]
434    async fn a_git_the_sandbox_cannot_hold_is_refused_only_when_one_is_required() {
435        let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok(""));
436        let exec = ExecProviders {
437            sandbox: Arc::new(NoSandbox),
438            ..with_process(process.clone())
439        };
440        let engine = |require_enforcement| {
441            EngineExec::new(
442                exec.clone(),
443                Confinement::Sandboxed {
444                    policy: SandboxPolicy::default(),
445                    require_enforcement,
446                    tmpdir: None,
447                },
448                ProjectTrust::Trusted,
449            )
450        };
451        let refused = engine(true)
452            .git(
453                Path::new("/repo"),
454                GitAccess::ReadOnly,
455                &["status"],
456                DEADLINE,
457            )
458            .await
459            .unwrap_err();
460        assert!(
461            matches!(refused, EngineExecError::Refused(_)),
462            "{refused:?}"
463        );
464        assert!(process.seen().is_empty(), "git ran anyway");
465
466        engine(false)
467            .git(
468                Path::new("/repo"),
469                GitAccess::ReadOnly,
470                &["status"],
471                DEADLINE,
472            )
473            .await
474            .unwrap();
475        assert_eq!(process.seen(), [git_key("status")]);
476    }
477
478    #[test]
479    fn only_an_untrusted_projects_git_outside_any_sandbox_is_refused() {
480        let sandboxed = Confinement::Sandboxed {
481            policy: SandboxPolicy::default(),
482            require_enforcement: false,
483            tmpdir: None,
484        };
485        for trust in [
486            ProjectTrust::NoProject,
487            ProjectTrust::Trusted,
488            ProjectTrust::Untrusted,
489        ] {
490            assert!(
491                matches!(
492                    admit_git(trust, &GitAccess::ReadOnly, &sandboxed),
493                    Admission::Run { .. }
494                ),
495                "{trust:?} in a sandbox"
496            );
497            let unconfined = admit_git(trust, &GitAccess::ReadOnly, &Confinement::Unconfined);
498            assert_eq!(
499                matches!(unconfined, Admission::Refuse(_)),
500                trust == ProjectTrust::Untrusted,
501                "{trust:?} unconfined: {unconfined:?}"
502            );
503        }
504    }
505
506    #[tokio::test]
507    async fn an_untrusted_projects_git_a_sandbox_cannot_hold_does_not_run() {
508        let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok(""));
509        let exec = ExecProviders {
510            sandbox: Arc::new(NoSandbox),
511            ..with_process(process.clone())
512        };
513        let engine = EngineExec::new(
514            exec,
515            Confinement::Sandboxed {
516                policy: SandboxPolicy::default(),
517                require_enforcement: false,
518                tmpdir: None,
519            },
520            ProjectTrust::Untrusted,
521        );
522        let refused = engine
523            .git(
524                Path::new("/repo"),
525                GitAccess::ReadOnly,
526                &["status"],
527                DEADLINE,
528            )
529            .await
530            .unwrap_err();
531        assert!(
532            matches!(refused, EngineExecError::Refused(_)),
533            "{refused:?}"
534        );
535        assert!(process.seen().is_empty(), "git ran anyway");
536    }
537
538    #[tokio::test]
539    async fn read_head_follows_a_gitdir_link_and_walks_up() {
540        use crate::interface::exec::in_process::InMemoryFileSystem;
541        let fs = InMemoryFileSystem::new();
542        fs.write_str(Path::new("/repo/.git/HEAD"), "ref: refs/heads/feature/x\n")
543            .await
544            .unwrap();
545        fs.create_dir_all(Path::new("/repo/src/deep"))
546            .await
547            .unwrap();
548        assert_eq!(
549            read_head(&fs, Path::new("/repo/src/deep")).await,
550            Some(Head {
551                branch: Some("feature/x".into()),
552                linked: false
553            })
554        );
555
556        fs.write_str(Path::new("/wt/.git"), "gitdir: /repo/.git/worktrees/wt\n")
557            .await
558            .unwrap();
559        fs.write_str(
560            Path::new("/repo/.git/worktrees/wt/HEAD"),
561            "0123456789abcdef0123456789abcdef01234567\n",
562        )
563        .await
564        .unwrap();
565        assert_eq!(
566            read_head(&fs, Path::new("/wt")).await,
567            Some(Head {
568                branch: None,
569                linked: true
570            })
571        );
572
573        fs.write_str(Path::new("/sub/.git"), "gitdir: ../repo/.git\n")
574            .await
575            .unwrap();
576        assert_eq!(
577            read_head(&fs, Path::new("/sub"))
578                .await
579                .and_then(|h| h.branch),
580            Some("feature/x".into())
581        );
582        fs.create_dir_all(Path::new("/plain")).await.unwrap();
583        assert_eq!(read_head(&fs, Path::new("/plain")).await, None);
584    }
585
586    #[tokio::test]
587    async fn a_helper_is_not_given_the_engines_git_options() {
588        let process = ScriptedProcess::new().with("pdftotext a.pdf -", ScriptedRun::ok("text"));
589        let engine = EngineExec::new(
590            with_process(process),
591            Confinement::Unconfined,
592            ProjectTrust::Trusted,
593        );
594        let out = engine
595            .helper(
596                ProcessSpec::new("pdftotext", "/").args(["a.pdf", "-"]),
597                &[],
598                DEADLINE,
599            )
600            .await
601            .unwrap();
602        assert_eq!(out.stdout_lossy(), "text");
603    }
604}