agix-base 0.4.4

Agix — foundation types, traits, and context
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! The subprocesses the engine starts on a session's behalf — its own git and
//! helpers such as `pdftotext` — and the one way it starts them: through that
//! session's [`ExecProviders`].
//!
//! Going through the session's `exec.process` is what puts them where the
//! session's commands are: on the machine (or remote) the host chose, under
//! the same `sandbox.env`, in a session of their own with no
//! controlling terminal, and stopped as a whole group when they time out. In a
//! session whose commands the OS sandbox confines they are confined too, so
//! whatever a repository a confined command configured makes git run is held
//! to the same roots.

use std::path::{Path, PathBuf};
use std::time::Duration;

use tokio_util::sync::CancellationToken;

use crate::interface::exec::{
    capture, Captured, Enforcement, ExecError, ExecProviders, FileSystem, NetworkMode, ProcessSpec,
    SandboxPolicy,
};
use crate::permission::ProjectTrust;

/// Options every git the engine runs itself puts before its subcommand.
///
/// They turn off the fsmonitor and hooks a repository names: one a sandboxed
/// command may have written must not start a program through them, whether
/// or not the git reading it is confined. Filter drivers cannot be turned off
/// this way; [`Confinement::Sandboxed`] is what confines them.
pub const ENGINE_GIT_OPTIONS: &[&str] = &[
    "-c",
    "core.fsmonitor=false",
    "-c",
    "core.hooksPath=/dev/null",
];

/// The engine's subprocesses for one session.
#[derive(Clone)]
pub struct EngineExec {
    exec: ExecProviders,
    confinement: Confinement,
    trust: ProjectTrust,
    min_deadline: Duration,
}

/// Whether the engine's subprocesses run in the session's sandbox.
#[derive(Debug, Clone, Default)]
#[allow(clippy::large_enum_variant)]
pub enum Confinement {
    /// The session's commands are not confined, so a confined command cannot
    /// have prepared the repository.
    #[default]
    Unconfined,
    /// Inside `exec.sandbox`, under the session's own `policy` narrowed per
    /// call: no network, and nothing writable but `tmpdir` and what the call
    /// names. `tmpdir` becomes the subprocess's `TMPDIR`.
    Sandboxed {
        policy: SandboxPolicy,
        require_enforcement: bool,
        tmpdir: Option<PathBuf>,
    },
}

/// What a git the engine runs may write.
#[derive(Debug, Clone, Copy)]
pub enum GitAccess<'a> {
    ReadOnly,
    Writes(&'a [PathBuf]),
}

impl<'a> GitAccess<'a> {
    fn writable(&self) -> &'a [PathBuf] {
        match self {
            Self::ReadOnly => &[],
            Self::Writes(paths) => paths,
        }
    }
}

/// Whether a git may start, decided before anything does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
    Run { options: &'static [&'static str] },
    Refuse(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Program {
    Git,
    Helper,
}

#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum EngineExecError {
    /// Not started: the admission refused it, or it has to be sandboxed and
    /// the sandbox cannot hold it.
    #[error("not run: {0}")]
    Refused(String),
    #[error("timed out after {0:?}")]
    TimedOut(Duration),
    #[error(transparent)]
    Failed(#[from] ExecError),
}

/// The one decision point for every git the engine starts.
///
/// An untrusted project's repository configuration is whoever wrote the
/// project's: the programs it names (filter drivers, `diff.external`,
/// `core.sshCommand`) git starts on its own. So a git outside any sandbox
/// does not run in one.
pub fn admit_git(
    trust: ProjectTrust,
    _access: &GitAccess<'_>,
    confinement: &Confinement,
) -> Admission {
    match (confinement, trust) {
        (Confinement::Sandboxed { .. }, _)
        | (Confinement::Unconfined, ProjectTrust::Trusted | ProjectTrust::NoProject) => {
            Admission::Run {
                options: ENGINE_GIT_OPTIONS,
            }
        }
        (Confinement::Unconfined, ProjectTrust::Untrusted) => {
            Admission::Refuse(UNTRUSTED_UNCONFINED.into())
        }
    }
}

const UNTRUSTED_UNCONFINED: &str = "the project is not trusted and the engine's git would run \
     outside any sandbox, where the programs its repository configuration names would run \
     unconfined; trust the project (`project.trust`) or let the sandbox hold the session's commands";

/// What a repository's `HEAD` says, read as a file rather than asked of git.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Head {
    /// The branch checked out; `None` when `HEAD` is detached.
    pub branch: Option<String>,
    /// The repository's `.git` is a `gitdir:` link: a worktree or a
    /// submodule checkout.
    pub linked: bool,
}

/// The `HEAD` of the repository `dir` is in: the first `.git` in `dir` or
/// above it, a directory or a file whose `gitdir:` line names one. `None`
/// where there is no repository or its `HEAD` cannot be read.
///
/// For a snapshot of a repository whose git the engine may not run: nothing
/// in the repository is executed or interpreted beyond these two files.
pub async fn read_head(fs: &dyn FileSystem, dir: &Path) -> Option<Head> {
    for at in dir.ancestors() {
        let dot_git = at.join(".git");
        let Ok(meta) = fs.metadata_following_symlinks(&dot_git).await else {
            continue;
        };
        let (git_dir, linked) = if meta.is_dir {
            (dot_git, false)
        } else {
            let link = fs.read_to_string(&dot_git).await.ok()?;
            let target = link.lines().next()?.strip_prefix("gitdir:")?.trim();
            (at.join(target), true)
        };
        let head = fs.read_to_string(&git_dir.join("HEAD")).await.ok()?;
        let head = head.trim();
        let branch = head
            .strip_prefix("ref:")
            .map(str::trim)
            .and_then(|r| r.strip_prefix("refs/heads/"))
            .map(str::to_string);
        return Some(Head { branch, linked });
    }
    None
}

impl EngineExec {
    pub fn new(exec: ExecProviders, confinement: Confinement, trust: ProjectTrust) -> Self {
        Self {
            exec,
            confinement,
            trust,
            min_deadline: Duration::ZERO,
        }
    }

    /// Every call may take at least `floor`, whatever deadline it asks for.
    pub fn with_min_deadline(mut self, floor: Duration) -> Self {
        self.min_deadline = floor;
        self
    }

    pub fn exec(&self) -> &ExecProviders {
        &self.exec
    }

    pub fn is_sandboxed(&self) -> bool {
        matches!(self.confinement, Confinement::Sandboxed { .. })
    }

    /// The session's own temporary directory, when the engine's processes
    /// are sandboxed and it has been made.
    pub fn tmpdir(&self) -> Option<&Path> {
        match &self.confinement {
            Confinement::Sandboxed { tmpdir, .. } => tmpdir.as_deref(),
            Confinement::Unconfined => None,
        }
    }

    /// `git <options> <args>` in `cwd`, never asking for credentials on a
    /// terminal. The only way the engine starts git.
    pub async fn git(
        &self,
        cwd: &Path,
        access: GitAccess<'_>,
        args: &[&str],
        deadline: Duration,
    ) -> Result<Captured, EngineExecError> {
        let options = match admit_git(self.trust, &access, &self.confinement) {
            Admission::Run { options } => options,
            Admission::Refuse(why) => return Err(EngineExecError::Refused(why)),
        };
        let mut spec = ProcessSpec::new("git", cwd)
            .args(options.iter().copied())
            .args(args.iter().copied());
        spec.env.extend([
            ("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
            ("GIT_ASKPASS".to_string(), String::new()),
        ]);
        self.run(spec, access.writable(), Program::Git, deadline)
            .await
    }

    /// A helper program, confined as the session's commands are, writing
    /// nothing but `writable`.
    pub async fn helper(
        &self,
        spec: ProcessSpec,
        writable: &[PathBuf],
        deadline: Duration,
    ) -> Result<Captured, EngineExecError> {
        self.run(spec, writable, Program::Helper, deadline).await
    }

    async fn run(
        &self,
        spec: ProcessSpec,
        writable: &[PathBuf],
        program: Program,
        deadline: Duration,
    ) -> Result<Captured, EngineExecError> {
        let spec = self.confine(spec, writable, program)?;
        let deadline = deadline.max(self.min_deadline);
        let captured = tokio::time::timeout(
            deadline,
            capture(&*self.exec.process, spec, CancellationToken::new()),
        )
        .await
        .map_err(|_| EngineExecError::TimedOut(deadline))??;
        Ok(captured)
    }

    /// `spec` as it has to be started. A sandbox that cannot hold it when
    /// nothing requires one gives the same unconfined program the session's
    /// own commands then get.
    fn confine(
        &self,
        spec: ProcessSpec,
        writable: &[PathBuf],
        program: Program,
    ) -> Result<ProcessSpec, EngineExecError> {
        let Confinement::Sandboxed {
            policy,
            require_enforcement,
            tmpdir,
        } = &self.confinement
        else {
            return Ok(spec);
        };
        let mut policy = policy.clone();
        policy.only_additional_writable = true;
        policy.network_mode = NetworkMode::DenyAll;
        policy.additional_writable = tmpdir.iter().chain(writable).cloned().collect();
        let mut confined = self.exec.sandbox.confine(spec.clone(), &policy);
        if confined.enforcement == Enforcement::None {
            let unmet = confined.unmet.join("; ");
            if *require_enforcement {
                return Err(EngineExecError::Refused(format!(
                    "the session's commands are sandboxed and `sandbox.require` \
                     is on, but {} cannot be sandboxed here ({unmet})",
                    spec.program
                )));
            }
            if program == Program::Git && self.trust.is_untrusted() {
                return Err(EngineExecError::Refused(format!(
                    "{UNTRUSTED_UNCONFINED} ({unmet})"
                )));
            }
            warn_unconfined_once(&unmet);
            return Ok(spec);
        }
        if let Some(tmp) = tmpdir {
            confined
                .spec
                .env
                .push(("TMPDIR".to_string(), tmp.display().to_string()));
        }
        Ok(confined.spec)
    }
}

impl std::fmt::Debug for EngineExec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EngineExec")
            .field("confinement", &self.confinement)
            .field("trust", &self.trust)
            .finish_non_exhaustive()
    }
}

fn warn_unconfined_once(unmet: &str) {
    static WARNED: std::sync::Once = std::sync::Once::new();
    WARNED.call_once(|| {
        tracing::warn!(
            unmet,
            "the engine's own subprocesses run unsandboxed: the sandbox cannot hold them \
             on this build or platform"
        );
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interface::exec::in_process::{NoSandbox, ScriptedProcess, ScriptedRun};
    use crate::interface::exec::{Confined, Sandbox};
    use std::sync::{Arc, Mutex};

    const DEADLINE: Duration = Duration::from_secs(5);

    fn with_process(process: ScriptedProcess) -> ExecProviders {
        ExecProviders {
            process: Arc::new(process),
            ..ExecProviders::in_process()
        }
    }

    fn git_key(args: &str) -> String {
        format!("git {} {args}", ENGINE_GIT_OPTIONS.join(" "))
    }

    #[tokio::test]
    async fn git_runs_through_the_sessions_process_with_the_engines_options() {
        let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok("clean"));
        let engine = EngineExec::new(
            with_process(process.clone()),
            Confinement::Unconfined,
            ProjectTrust::Trusted,
        );
        let out = engine
            .git(
                Path::new("/repo"),
                GitAccess::ReadOnly,
                &["status"],
                DEADLINE,
            )
            .await
            .unwrap();
        assert_eq!(out.stdout_lossy(), "clean");
        assert_eq!(process.seen(), [git_key("status")]);
    }

    /// Records the policy it was asked to confine under, and confines fully
    /// by prefixing the program.
    #[derive(Default)]
    struct RecordingSandbox(Mutex<Vec<SandboxPolicy>>);

    impl Sandbox for RecordingSandbox {
        fn confine(&self, spec: ProcessSpec, policy: &SandboxPolicy) -> Confined {
            self.0.lock().unwrap().push(policy.clone());
            let mut wrapped = ProcessSpec::new("boxed", spec.cwd.clone()).arg(spec.program);
            wrapped.args.extend(spec.args);
            wrapped.env = spec.env;
            Confined {
                spec: wrapped,
                mode: crate::interface::exec::SandboxMode::LinuxBwrap,
                enforcement: Enforcement::Full,
                unmet: Vec::new(),
            }
        }
    }

    #[tokio::test]
    async fn a_sandboxed_git_writes_only_what_it_names_and_reaches_no_network() {
        let sandbox = Arc::new(RecordingSandbox::default());
        let process = ScriptedProcess::new().with(
            format!("boxed {}", git_key("worktree prune")),
            ScriptedRun::ok(""),
        );
        let exec = ExecProviders {
            sandbox: sandbox.clone(),
            ..with_process(process.clone())
        };
        let engine = EngineExec::new(
            exec,
            Confinement::Sandboxed {
                policy: SandboxPolicy {
                    additional_writable: vec![PathBuf::from("/elsewhere")],
                    ..Default::default()
                },
                require_enforcement: true,
                tmpdir: Some(PathBuf::from("/tmp/session")),
            },
            ProjectTrust::Trusted,
        );
        let writable = [PathBuf::from("/repo/.git")];
        engine
            .git(
                Path::new("/repo"),
                GitAccess::Writes(&writable),
                &["worktree", "prune"],
                DEADLINE,
            )
            .await
            .unwrap();
        let policy = sandbox.0.lock().unwrap()[0].clone();
        assert!(policy.only_additional_writable);
        assert_eq!(policy.network_mode, NetworkMode::DenyAll);
        assert_eq!(
            policy.additional_writable,
            [PathBuf::from("/tmp/session"), PathBuf::from("/repo/.git")]
        );
    }

    #[tokio::test]
    async fn a_git_the_sandbox_cannot_hold_is_refused_only_when_one_is_required() {
        let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok(""));
        let exec = ExecProviders {
            sandbox: Arc::new(NoSandbox),
            ..with_process(process.clone())
        };
        let engine = |require_enforcement| {
            EngineExec::new(
                exec.clone(),
                Confinement::Sandboxed {
                    policy: SandboxPolicy::default(),
                    require_enforcement,
                    tmpdir: None,
                },
                ProjectTrust::Trusted,
            )
        };
        let refused = engine(true)
            .git(
                Path::new("/repo"),
                GitAccess::ReadOnly,
                &["status"],
                DEADLINE,
            )
            .await
            .unwrap_err();
        assert!(
            matches!(refused, EngineExecError::Refused(_)),
            "{refused:?}"
        );
        assert!(process.seen().is_empty(), "git ran anyway");

        engine(false)
            .git(
                Path::new("/repo"),
                GitAccess::ReadOnly,
                &["status"],
                DEADLINE,
            )
            .await
            .unwrap();
        assert_eq!(process.seen(), [git_key("status")]);
    }

    #[test]
    fn only_an_untrusted_projects_git_outside_any_sandbox_is_refused() {
        let sandboxed = Confinement::Sandboxed {
            policy: SandboxPolicy::default(),
            require_enforcement: false,
            tmpdir: None,
        };
        for trust in [
            ProjectTrust::NoProject,
            ProjectTrust::Trusted,
            ProjectTrust::Untrusted,
        ] {
            assert!(
                matches!(
                    admit_git(trust, &GitAccess::ReadOnly, &sandboxed),
                    Admission::Run { .. }
                ),
                "{trust:?} in a sandbox"
            );
            let unconfined = admit_git(trust, &GitAccess::ReadOnly, &Confinement::Unconfined);
            assert_eq!(
                matches!(unconfined, Admission::Refuse(_)),
                trust == ProjectTrust::Untrusted,
                "{trust:?} unconfined: {unconfined:?}"
            );
        }
    }

    #[tokio::test]
    async fn an_untrusted_projects_git_a_sandbox_cannot_hold_does_not_run() {
        let process = ScriptedProcess::new().with(git_key("status"), ScriptedRun::ok(""));
        let exec = ExecProviders {
            sandbox: Arc::new(NoSandbox),
            ..with_process(process.clone())
        };
        let engine = EngineExec::new(
            exec,
            Confinement::Sandboxed {
                policy: SandboxPolicy::default(),
                require_enforcement: false,
                tmpdir: None,
            },
            ProjectTrust::Untrusted,
        );
        let refused = engine
            .git(
                Path::new("/repo"),
                GitAccess::ReadOnly,
                &["status"],
                DEADLINE,
            )
            .await
            .unwrap_err();
        assert!(
            matches!(refused, EngineExecError::Refused(_)),
            "{refused:?}"
        );
        assert!(process.seen().is_empty(), "git ran anyway");
    }

    #[tokio::test]
    async fn read_head_follows_a_gitdir_link_and_walks_up() {
        use crate::interface::exec::in_process::InMemoryFileSystem;
        let fs = InMemoryFileSystem::new();
        fs.write_str(Path::new("/repo/.git/HEAD"), "ref: refs/heads/feature/x\n")
            .await
            .unwrap();
        fs.create_dir_all(Path::new("/repo/src/deep"))
            .await
            .unwrap();
        assert_eq!(
            read_head(&fs, Path::new("/repo/src/deep")).await,
            Some(Head {
                branch: Some("feature/x".into()),
                linked: false
            })
        );

        fs.write_str(Path::new("/wt/.git"), "gitdir: /repo/.git/worktrees/wt\n")
            .await
            .unwrap();
        fs.write_str(
            Path::new("/repo/.git/worktrees/wt/HEAD"),
            "0123456789abcdef0123456789abcdef01234567\n",
        )
        .await
        .unwrap();
        assert_eq!(
            read_head(&fs, Path::new("/wt")).await,
            Some(Head {
                branch: None,
                linked: true
            })
        );

        fs.write_str(Path::new("/sub/.git"), "gitdir: ../repo/.git\n")
            .await
            .unwrap();
        assert_eq!(
            read_head(&fs, Path::new("/sub"))
                .await
                .and_then(|h| h.branch),
            Some("feature/x".into())
        );
        fs.create_dir_all(Path::new("/plain")).await.unwrap();
        assert_eq!(read_head(&fs, Path::new("/plain")).await, None);
    }

    #[tokio::test]
    async fn a_helper_is_not_given_the_engines_git_options() {
        let process = ScriptedProcess::new().with("pdftotext a.pdf -", ScriptedRun::ok("text"));
        let engine = EngineExec::new(
            with_process(process),
            Confinement::Unconfined,
            ProjectTrust::Trusted,
        );
        let out = engine
            .helper(
                ProcessSpec::new("pdftotext", "/").args(["a.pdf", "-"]),
                &[],
                DEADLINE,
            )
            .await
            .unwrap();
        assert_eq!(out.stdout_lossy(), "text");
    }
}