boundgraph-check 0.1.0

Layer 5 of BoundGraph: the checker engine and the ed25519 signing that makes a verdict evidence.
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Where a checker runs something it did not write.
//!
//! # Why this boundary is declared here
//!
//! Feature 09 owns the sandbox: what a capability is, how a filesystem grant
//! becomes a preopened descriptor, how a network grant becomes an egress proxy.
//! None of that exists yet, and the compile checker (US-0804) and the test-run
//! checker (US-0805) need exactly one thing from it — somewhere to run a
//! command and get its exit status back.
//!
//! So the boundary is declared here, as narrowly as it can be, exactly as
//! feature 07 declares `Store` for the content store it does not own and the
//! runtime declares `LedgerSink` for the log it does not own. Feature 09's
//! `Sandbox` will satisfy [`Sandbox`] unchanged.
//!
//! # The sandbox is handed the grant, and must refuse what it cannot enforce
//!
//! [`Sandbox::run`] takes a [`GrantSet`] as well as a [`Command`]. That is not
//! decoration: it is the whole contract. An implementation that cannot confine
//! a child to the granted authority must return
//! [`SandboxError::Unenforceable`] rather than run it anyway.
//!
//! The alternative — a sandbox that accepts any grant and enforces whichever
//! parts it happens to implement — produces a system where the compiler proved
//! a property that the runtime silently does not hold. Refusal keeps the
//! failure loud and local.
//!
//! # [`Unconfined`] is not a sandbox, and says so
//!
//! It runs the command as this process's user, on this machine, with this
//! machine's filesystem. It enforces a working directory, a timeout, and a
//! cleared environment, and it enforces *nothing else*. It is named for what it
//! is so that no flow definition can contain it by accident, and it is behind
//! the `unconfined` feature so that a deployment can make it impossible to
//! build.
//!
//! What it does do is refuse honestly: any grant beyond reading the workspace
//! and executing the named program is [`SandboxError::Unenforceable`], because
//! those are the only two it can even pretend to. That makes it useful for M3
//! — the compile and test checkers need nothing else — without it ever
//! claiming containment it does not provide.

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

use async_trait::async_trait;
use boundgraph_core::{GrantAtom, GrantSet};

/// How long a checker's command may run before it is killed.
///
/// A timeout is not a tuning knob here, it is what stops a hung compiler
/// becoming a hung commit. Every [`Command`] carries one.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);

/// How much of a command's output is kept.
///
/// A compiler having a bad day can emit tens of megabytes. Everything past this
/// is dropped, and the outcome says so.
pub const MAX_OUTPUT: usize = 256 * 1024;

/// What to run, and under what limits.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    /// The program, as the sandbox will resolve it.
    pub program: String,
    /// Its arguments, in order.
    pub args: Vec<String>,
    /// The directory to run it in, which is also the only directory a checker
    /// has any business reading.
    pub workspace: PathBuf,
    /// How long it may run before it is killed.
    pub timeout: Duration,
}

impl Command {
    /// A command in `workspace`, with the default timeout.
    pub fn new(
        program: impl Into<String>,
        args: impl IntoIterator<Item = impl Into<String>>,
        workspace: impl Into<PathBuf>,
    ) -> Self {
        Self {
            program: program.into(),
            args: args.into_iter().map(Into::into).collect(),
            workspace: workspace.into(),
            timeout: DEFAULT_TIMEOUT,
        }
    }

    /// Kill it after `timeout` rather than after [`DEFAULT_TIMEOUT`].
    #[must_use]
    pub fn within(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// The command as it would be typed, for a diagnostic.
    pub fn rendered(&self) -> String {
        std::iter::once(self.program.clone())
            .chain(self.args.iter().cloned())
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// What running a command produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome {
    /// The exit status, or `None` where the process was killed and never
    /// returned one.
    pub exit: Option<i32>,
    /// Standard output, truncated to [`MAX_OUTPUT`].
    pub stdout: String,
    /// Standard error, truncated to [`MAX_OUTPUT`].
    pub stderr: String,
    /// Whether it was killed for running past its timeout.
    ///
    /// Separate from `exit` being `None`, because "we killed it at the deadline"
    /// and "it died for some other reason" are different facts and only one of
    /// them is the checker's own doing.
    pub timed_out: bool,
    /// Whether output was dropped to fit [`MAX_OUTPUT`].
    pub truncated: bool,
    /// How long it ran.
    pub duration: Duration,
}

impl Outcome {
    /// Whether the command reported success.
    pub fn succeeded(&self) -> bool {
        self.exit == Some(0) && !self.timed_out
    }

    /// Standard error and standard output together, in that order.
    ///
    /// Diagnostics go to stderr for most tools and to stdout for some, and a
    /// checker that read only one of them would report "the build failed, no
    /// output" for half the ecosystem.
    pub fn diagnostics(&self) -> String {
        match (self.stderr.trim(), self.stdout.trim()) {
            ("", "") => String::new(),
            (err, "") => err.to_string(),
            ("", out) => out.to_string(),
            (err, out) => format!("{err}\n{out}"),
        }
    }
}

/// The command could not be run under the authority it was given.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SandboxError {
    /// This sandbox cannot enforce part of the grant, so it refuses to run.
    ///
    /// The important variant. See the module documentation: a sandbox that ran
    /// the command anyway would make the compiler's proof false at run time,
    /// silently.
    #[error("this sandbox cannot enforce `{atom}`, so it will not run {command}")]
    Unenforceable {
        /// The grant it could not honour.
        atom: String,
        /// What it declined to run.
        command: String,
    },

    /// The program could not be started.
    #[error("{command} could not be started: {detail}")]
    Spawn {
        /// What could not be started.
        command: String,
        /// Why.
        detail: String,
    },

    /// The sandbox itself is not available.
    #[error("the sandbox is unavailable: {0}")]
    Unavailable(String),
}

/// Runs a command under a grant, or refuses to.
///
/// Feature 09 will implement this with real isolation. Until then
/// [`Unconfined`] implements it with none, and says so.
#[async_trait]
pub trait Sandbox: Send + Sync + fmt::Debug {
    /// Run `command`, confined to `grant`.
    ///
    /// # Errors
    ///
    /// [`SandboxError::Unenforceable`] if this sandbox cannot confine the
    /// command to the grant — which it must return rather than run the command
    /// with more authority than was granted. [`SandboxError::Spawn`] if the
    /// program could not be started.
    ///
    /// A command that ran and failed is **not** an error: that is an
    /// [`Outcome`] with a non-zero exit, and deciding what it means is the
    /// checker's job.
    async fn run(&self, command: &Command, grant: &GrantSet) -> Result<Outcome, SandboxError>;
}

/// Truncate to [`MAX_OUTPUT`], keeping the start.
///
/// The start, because a compiler's first error is the one that caused the rest
/// — later errors are usually consequences of it. A test runner is the other
/// way round, which is why the test checker keeps the tail of what it is given
/// rather than relying on this.
#[cfg(any(feature = "unconfined", test))]
fn cap(bytes: Vec<u8>) -> (String, bool) {
    let truncated = bytes.len() > MAX_OUTPUT;
    let kept = if truncated {
        // On a character boundary, so the result is still valid UTF-8 text.
        // A UTF-8 continuation byte is `10xxxxxx`; back up off any of them.
        let mut end = MAX_OUTPUT;
        while end > 0 && (bytes[end] & 0xc0) == 0x80 {
            end -= 1;
        }
        &bytes[..end]
    } else {
        &bytes[..]
    };
    (String::from_utf8_lossy(kept).into_owned(), truncated)
}

/// What [`Unconfined`] is willing to pretend it enforces.
///
/// Reading and listing under the command's own workspace, and executing a
/// program. Nothing else — no writes, no network, no secrets, no access outside
/// the workspace.
#[cfg(any(feature = "unconfined", test))]
fn enforceable(atom: &GrantAtom, workspace: &Path) -> bool {
    match (atom.domain.as_str(), atom.action.as_str()) {
        ("proc", "exec") => true,
        ("fs", "read" | "list" | "stat") => {
            let root = normalise(workspace);
            let resource = atom.resource.replace('\\', "/");
            let resource = resource
                .strip_suffix("**")
                .unwrap_or(&resource)
                .trim_end_matches('/');

            // On a segment boundary, not a byte prefix. A plain `starts_with`
            // accepts `/work/repository` for a workspace of `/work/repo`, which
            // is a different directory that this would then claim to confine.
            resource == root || resource.starts_with(&format!("{root}/"))
        }
        _ => false,
    }
}

/// A path as a grant resource writes it: forward slashes, no trailing one.
///
/// Backslashes matter. A resource pattern is split on `/`, so a Windows path
/// left as `D:\work\**` is a single segment containing a `*`, which falls
/// outside the decidable fragment and makes every containment question
/// `Unknown` — and `Unknown` is a refusal. Normalising here is what keeps the
/// same grant decidable on every platform.
pub fn normalise(path: &Path) -> String {
    let text = path.to_string_lossy().replace('\\', "/");
    text.strip_suffix('/').unwrap_or(&text).to_string()
}

/// The grant a checker needs to run `program` over `workspace`, and no more.
///
/// Read and list under the workspace, and execute exactly that one program.
/// No write anywhere, nothing outside the workspace, and nothing that could
/// reach a network or a secret — so it is comfortably inside
/// [`checker_ceiling`](crate::checker_ceiling).
pub fn workspace_grant(workspace: &Path, program: &str) -> GrantSet {
    let root = normalise(workspace);
    GrantSet::new([
        GrantAtom::new("fs", "read", format!("{root}/**")),
        GrantAtom::new("fs", "list", format!("{root}/**")),
        GrantAtom::new("proc", "exec", program),
    ])
}

#[cfg(feature = "unconfined")]
pub use unconfined::Unconfined;

#[cfg(feature = "unconfined")]
mod unconfined {
    use super::*;

    /// Runs commands on this machine, with no isolation whatsoever.
    ///
    /// # Read this before using it
    ///
    /// This is **not a sandbox**. A command run through it has whatever access
    /// the BoundGraph process itself has: the whole filesystem, the network, the
    /// environment of whatever started it. If the command decides to delete the
    /// workspace, it will.
    ///
    /// What it actually enforces is three things:
    ///
    /// - the working directory is the command's workspace,
    /// - the process is killed at the timeout,
    /// - the child's environment is cleared except for the few variables a
    ///   toolchain cannot start without.
    ///
    /// And what it refuses is everything else: any grant beyond reading under
    /// the workspace and executing the named program is
    /// [`SandboxError::Unenforceable`]. It cannot make a `net:egress` grant
    /// true, so it will not accept one.
    ///
    /// It exists because the compile and test checkers are useful now and
    /// feature 09 is not written yet, and it is named [`Unconfined`] so that
    /// nobody reads a flow definition containing it and thinks otherwise.
    #[derive(Debug, Clone, Default)]
    pub struct Unconfined {
        keep_env: Vec<String>,
    }

    /// Environment variables a toolchain genuinely cannot start without.
    ///
    /// Deliberately short. Everything else is cleared, because an inherited
    /// environment is how a credential reaches a child that was never granted
    /// one.
    const ESSENTIAL_ENV: &[&str] = &[
        "PATH",
        "HOME",
        "SystemRoot",
        "SYSTEMROOT",
        "TEMP",
        "TMP",
        "USERPROFILE",
        "LANG",
        "LC_ALL",
    ];

    impl Unconfined {
        /// An unconfined runner.
        pub fn new() -> Self {
            Self::default()
        }

        /// Also pass `name` through to the child.
        ///
        /// For a toolchain that needs one — `CARGO_HOME`, `RUSTUP_HOME`,
        /// `VIRTUAL_ENV`. Every addition is a way for something the checker was
        /// not granted to reach the child, so add them one at a time and
        /// knowingly.
        #[must_use]
        pub fn passing_through(mut self, name: impl Into<String>) -> Self {
            self.keep_env.push(name.into());
            self
        }

        pub(super) fn keeps(&self, name: &str) -> bool {
            ESSENTIAL_ENV.contains(&name) || self.keep_env.iter().any(|k| k == name)
        }
    }

    #[async_trait]
    impl Sandbox for Unconfined {
        async fn run(&self, command: &Command, grant: &GrantSet) -> Result<Outcome, SandboxError> {
            // Refuse before running, not after: a grant this cannot honour must
            // never reach a child process.
            if let Some(atom) = grant
                .iter()
                .find(|atom| !enforceable(atom, &command.workspace))
            {
                return Err(SandboxError::Unenforceable {
                    atom: atom.to_string(),
                    command: command.rendered(),
                });
            }

            let mut child = tokio::process::Command::new(&command.program);
            child
                .args(&command.args)
                .current_dir(&command.workspace)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .kill_on_drop(true)
                .env_clear();

            for (name, value) in std::env::vars() {
                if self.keeps(&name) {
                    child.env(name, value);
                }
            }

            let started = std::time::Instant::now();

            let spawned = child.spawn().map_err(|e| SandboxError::Spawn {
                command: command.rendered(),
                detail: e.to_string(),
            })?;

            let finished = tokio::time::timeout(command.timeout, spawned.wait_with_output()).await;

            let duration = started.elapsed();

            match finished {
                Ok(Ok(output)) => {
                    let (stdout, out_cut) = cap(output.stdout);
                    let (stderr, err_cut) = cap(output.stderr);
                    Ok(Outcome {
                        exit: output.status.code(),
                        stdout,
                        stderr,
                        timed_out: false,
                        truncated: out_cut || err_cut,
                        duration,
                    })
                }
                Ok(Err(e)) => Err(SandboxError::Spawn {
                    command: command.rendered(),
                    detail: e.to_string(),
                }),
                // `kill_on_drop` means dropping the future kills the child, so
                // the deadline is a real deadline rather than a hope.
                Err(_elapsed) => Ok(Outcome {
                    exit: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    timed_out: true,
                    truncated: false,
                    duration,
                }),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn workspace() -> PathBuf {
        PathBuf::from("/work/repo")
    }

    #[test]
    fn a_command_renders_as_it_would_be_typed() {
        let c = Command::new("cargo", ["check", "--all-targets"], workspace());
        assert_eq!(c.rendered(), "cargo check --all-targets");
        assert_eq!(c.timeout, DEFAULT_TIMEOUT);
    }

    #[test]
    fn a_timeout_can_be_narrowed() {
        let c = Command::new("cargo", ["check"], workspace()).within(Duration::from_secs(5));
        assert_eq!(c.timeout, Duration::from_secs(5));
    }

    #[test]
    fn a_workspace_grant_reads_the_workspace_and_execs_one_program() {
        let grant = workspace_grant(&workspace(), "cargo");

        assert_eq!(grant.len(), 3);
        assert!(grant.iter().all(|a| a.action != "write"));
        assert!(grant.iter().any(|a| a.resource == "/work/repo/**"));
        assert!(
            grant
                .iter()
                .any(|a| a.domain == "proc" && a.resource == "cargo")
        );
    }

    /// The grant has to be inside what any checker may hold, or the trait
    /// refuses the checker before it runs.
    #[test]
    fn a_workspace_grant_is_within_the_checker_ceiling() {
        use boundgraph_grant::{Tri, set_leq};

        let grant = workspace_grant(&workspace(), "/usr/bin/cargo");
        assert_eq!(set_leq(&grant, &crate::checker_ceiling()), Tri::Yes);
    }

    /// A Windows path left with backslashes is one segment containing a `*`,
    /// which is outside the decidable fragment — and undecidable is a refusal.
    #[test]
    fn a_windows_path_still_yields_a_decidable_grant() {
        use boundgraph_grant::{Tri, set_leq};

        let grant = workspace_grant(Path::new(r"D:\work\repo"), "cargo.exe");
        assert!(grant.iter().any(|a| a.resource == "D:/work/repo/**"));
        assert_eq!(set_leq(&grant, &crate::checker_ceiling()), Tri::Yes);
    }

    #[test]
    fn normalising_drops_a_trailing_separator() {
        assert_eq!(normalise(Path::new("/work/repo/")), "/work/repo");
        assert_eq!(normalise(Path::new(r"D:\work\repo\")), "D:/work/repo");
    }

    // ── what an unconfined runner will and will not accept ──────────────────

    #[test]
    fn reading_under_the_workspace_and_execing_are_enforceable() {
        let root = workspace();
        for atom in [
            "fs:read:/work/repo/**",
            "fs:list:/work/repo/src/**",
            "fs:stat:/work/repo/Cargo.toml",
            "proc:exec:cargo",
        ] {
            let atom: GrantAtom = atom.parse().unwrap();
            assert!(enforceable(&atom, &root), "{atom} should be accepted");
        }
    }

    /// The point of the whole boundary: what it cannot enforce, it refuses.
    #[test]
    fn anything_it_cannot_enforce_is_refused() {
        let root = workspace();
        for atom in [
            "fs:write:/work/repo/**",
            "fs:read:/etc/**",
            "fs:read:/work/other/**",
            // A byte-prefix check would accept this: a different directory
            // whose name begins with the workspace's.
            "fs:read:/work/repository/**",
            "fs:read:/work/repo-backup/secrets",
            "net:egress:api.example.com:443",
            "secret:use:stripe_key",
            "env:read:AWS_SECRET_ACCESS_KEY",
        ] {
            let atom: GrantAtom = atom.parse().unwrap();
            assert!(!enforceable(&atom, &root), "{atom} should be refused");
        }
    }

    #[test]
    fn output_is_capped_on_a_character_boundary() {
        let long = "é".repeat(MAX_OUTPUT);
        let (kept, truncated) = cap(long.into_bytes());

        assert!(truncated);
        assert!(kept.len() <= MAX_OUTPUT);
        assert!(!kept.contains('\u{fffd}'), "cut mid-character");
    }

    #[test]
    fn short_output_is_kept_whole_and_not_flagged() {
        let (kept, truncated) = cap(b"error: expected `;`".to_vec());
        assert_eq!(kept, "error: expected `;`");
        assert!(!truncated);
    }

    #[test]
    fn diagnostics_read_both_streams() {
        let outcome = |out: &str, err: &str| Outcome {
            exit: Some(1),
            stdout: out.into(),
            stderr: err.into(),
            timed_out: false,
            truncated: false,
            duration: Duration::ZERO,
        };

        assert_eq!(outcome("", "on stderr").diagnostics(), "on stderr");
        assert_eq!(outcome("on stdout", "").diagnostics(), "on stdout");
        assert_eq!(outcome("out", "err").diagnostics(), "err\nout");
        assert!(outcome("", "").diagnostics().is_empty());
    }

    #[test]
    fn a_timed_out_command_did_not_succeed_whatever_its_exit_status() {
        let killed = Outcome {
            exit: Some(0),
            stdout: String::new(),
            stderr: String::new(),
            timed_out: true,
            truncated: false,
            duration: Duration::from_secs(300),
        };
        assert!(!killed.succeeded());
    }

    #[cfg(feature = "unconfined")]
    mod unconfined {
        use super::*;

        /// Two programs that exist everywhere, one succeeding and one failing.
        fn command(succeed: bool) -> Command {
            let workspace = std::env::temp_dir();
            if cfg!(windows) {
                let code = if succeed { "exit 0" } else { "exit 3" };
                Command::new("cmd", ["/C", code], workspace)
            } else {
                let code = if succeed { "0" } else { "3" };
                Command::new("sh", ["-c", &format!("exit {code}")], workspace)
            }
        }

        fn grant(command: &Command) -> GrantSet {
            workspace_grant(&command.workspace, &command.program)
        }

        #[tokio::test]
        async fn a_successful_command_reports_a_zero_exit() {
            let c = command(true);
            let outcome = Unconfined::new().run(&c, &grant(&c)).await.unwrap();

            assert_eq!(outcome.exit, Some(0));
            assert!(outcome.succeeded());
            assert!(!outcome.timed_out);
        }

        /// A command that ran and failed is an outcome, not an error. Deciding
        /// what a non-zero exit means is the checker's job, not the sandbox's.
        #[tokio::test]
        async fn a_failing_command_is_an_outcome_rather_than_an_error() {
            let c = command(false);
            let outcome = Unconfined::new().run(&c, &grant(&c)).await.unwrap();

            assert_eq!(outcome.exit, Some(3));
            assert!(!outcome.succeeded());
        }

        #[tokio::test]
        async fn output_comes_back_on_the_stream_it_was_written_to() {
            let workspace = std::env::temp_dir();
            let c = if cfg!(windows) {
                Command::new("cmd", ["/C", "echo hello"], workspace)
            } else {
                Command::new("sh", ["-c", "echo hello"], workspace)
            };

            let outcome = Unconfined::new().run(&c, &grant(&c)).await.unwrap();
            assert!(outcome.stdout.contains("hello"), "{outcome:?}");
        }

        /// The criterion behind both checkers that use this: a hung tool must
        /// not become a hung commit.
        #[tokio::test]
        async fn a_command_that_outlives_its_timeout_is_killed_and_says_so() {
            let workspace = std::env::temp_dir();
            // A busy loop rather than a sleep on Windows: `timeout` refuses a
            // redirected stdin and `ping` is not always on PATH, and neither
            // failure would be about what this test is checking.
            let c = if cfg!(windows) {
                Command::new(
                    "cmd",
                    ["/C", "for /L %i in (1,1,200000000) do @rem"],
                    workspace,
                )
            } else {
                Command::new("sh", ["-c", "sleep 30"], workspace)
            }
            .within(Duration::from_millis(250));

            let outcome = Unconfined::new().run(&c, &grant(&c)).await.unwrap();

            assert!(outcome.timed_out);
            assert_eq!(outcome.exit, None);
            assert!(!outcome.succeeded());
            assert!(outcome.duration < Duration::from_secs(10));
        }

        /// It cannot make a `net:egress` grant true, so it will not accept one.
        #[tokio::test]
        async fn a_grant_it_cannot_enforce_is_refused_before_anything_runs() {
            let c = command(true);
            let over = GrantSet::parse(["net:egress:api.example.com:443"]).unwrap();

            let err = Unconfined::new().run(&c, &over).await.unwrap_err();
            assert!(matches!(err, SandboxError::Unenforceable { .. }), "{err:?}");
        }

        #[tokio::test]
        async fn a_program_that_does_not_exist_is_a_spawn_error() {
            let c = Command::new("boundgraph-no-such-program", [""; 0], std::env::temp_dir());
            let err = Unconfined::new().run(&c, &grant(&c)).await.unwrap_err();

            assert!(matches!(err, SandboxError::Spawn { .. }), "{err:?}");
        }

        /// A variable this process has that `Unconfined` does not keep, if the
        /// environment offers one. `unsafe_code` is forbidden here, so the test
        /// cannot plant one and works with what is already there.
        fn a_non_essential_variable() -> Option<(String, String)> {
            let runner = Unconfined::new();
            std::env::vars().find(|(name, value)| {
                !runner.keeps(name)
                    && !value.is_empty()
                    && value.len() > 3
                    && value.chars().all(|c| c.is_ascii_alphanumeric())
            })
        }

        fn echoing(name: &str) -> Command {
            let workspace = std::env::temp_dir();
            if cfg!(windows) {
                Command::new(
                    "cmd",
                    ["/C".to_string(), format!("echo [%{name}%]")],
                    workspace,
                )
            } else {
                Command::new(
                    "sh",
                    ["-c".to_string(), format!("echo [${name}]")],
                    workspace,
                )
            }
        }

        /// An inherited environment is how a credential reaches a child that was
        /// never granted one.
        #[tokio::test]
        async fn the_child_environment_is_cleared_except_for_the_essentials() {
            let Some((name, value)) = a_non_essential_variable() else {
                return; // Nothing to prove with; see above.
            };

            let c = echoing(&name);
            let outcome = Unconfined::new().run(&c, &grant(&c)).await.unwrap();

            assert!(
                !outcome.stdout.contains(&value),
                "the child inherited `{name}`: {outcome:?}"
            );
        }

        #[tokio::test]
        async fn a_variable_can_be_passed_through_deliberately() {
            let Some((name, value)) = a_non_essential_variable() else {
                return;
            };

            let c = echoing(&name);
            let outcome = Unconfined::new()
                .passing_through(&name)
                .run(&c, &grant(&c))
                .await
                .unwrap();

            assert!(outcome.stdout.contains(&value), "{outcome:?}");
        }

        /// The essentials really are passed through, or no toolchain starts.
        #[tokio::test]
        async fn the_essentials_reach_the_child() {
            let c = echoing("PATH");
            let outcome = Unconfined::new().run(&c, &grant(&c)).await.unwrap();

            assert!(outcome.stdout.trim().len() > 3, "{outcome:?}");
            assert!(!outcome.stdout.contains("[]"), "{outcome:?}");
        }
    }
}