aither-sandbox 0.31.0

Terminal-first command execution with heel sandboxing
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Spawning on the host and container backends: streams, exit, tree kill,
//! live and derived grants, and the environment layers.

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

use async_channel::{Receiver, Sender};
use executor_core::tokio::TokioGlobal;

use super::{Backend, ChildExit, GrantSnapshot, Pipe, Sandbox, SandboxedChild, SpawnSpec, Stdio};
use crate::shell_session::ContainerExecOutcome;
use crate::{AnyContainerExec, ContainerExec, ContainerShellRuntime, HostRoute};

/// The bound on any wait for a process or a stream: a hang fails the test.
const BOUND: Duration = Duration::from_secs(60);

fn canonical_tempdir() -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = std::fs::canonicalize(dir.path()).expect("a temporary directory resolves");
    (dir, path)
}

async fn host_sandbox(working_dir: &Path) -> Sandbox {
    let heel = crate::test_heel::binary()
        .await
        .expect("a heel is available to the tests");
    Sandbox::new(Backend::Host { heel }, TokioGlobal, working_dir)
}

/// The programs of a container whose image the embedder prepared.
fn container_launch() -> crate::ContainerLaunch {
    let bin_dir = crate::ContainerPath::new("/opt/tools/bin").expect("an absolute path");
    let shell = bin_dir.join("bash");
    crate::ContainerLaunch::new(bin_dir, shell)
}

/// Everything a stream carried until it closed.
async fn drain(stream: Receiver<Vec<u8>>) -> String {
    let mut bytes = Vec::new();
    while let Ok(chunk) = stream.recv().await {
        bytes.extend(chunk);
    }
    String::from_utf8_lossy(&bytes).into_owned()
}

/// Runs `script` in `sh` to its end and returns how it ended and what it
/// printed on each stream.
async fn run(sandbox: &Sandbox, script: &str) -> (ChildExit, String, String) {
    run_spec(sandbox, SpawnSpec::new("/bin/sh").args(["-c", script])).await
}

async fn run_spec(sandbox: &Sandbox, spec: SpawnSpec) -> (ChildExit, String, String) {
    tokio::time::timeout(BOUND, async {
        let mut child = sandbox.spawn(spec).await.expect("the process starts");
        let stdout = drain(child.take_stdout().expect("stdout is piped"));
        let stderr = drain(child.take_stderr().expect("stderr is piped"));
        let (out, err) = tokio::join!(stdout, stderr);
        (child.wait().await, out, err)
    })
    .await
    .expect("the process ends within its bound")
}

fn exit_code(exit: &ChildExit) -> Option<i32> {
    match exit {
        ChildExit::Exited(status) => status.code(),
        ChildExit::Killed | ChildExit::Failed(_) => None,
    }
}

/// Whether a process with this id still exists.
fn alive(pid: &str) -> bool {
    std::process::Command::new("kill")
        .args(["-0", pid])
        .stderr(std::process::Stdio::null())
        .status()
        .expect("kill runs")
        .success()
}

#[tokio::test]
async fn a_host_process_streams_its_output_and_reports_its_exit() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let (exit, out, err) = run(&sandbox, "echo out; echo err >&2; exit 3").await;
    assert_eq!(exit_code(&exit), Some(3), "{exit:?}");
    assert_eq!(out, "out\n");
    assert_eq!(err, "err\n");
}

#[tokio::test]
async fn a_process_reads_what_is_sent_to_its_stdin_until_it_is_dropped() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let spec = SpawnSpec::new("/bin/cat").stdio(Stdio {
        stdin: Pipe::Piped,
        ..Stdio::default()
    });
    let (exit, out) = tokio::time::timeout(BOUND, async {
        let mut child = sandbox.spawn(spec).await.expect("the process starts");
        let stdin = child.take_stdin().expect("stdin is piped");
        let stdout = child.take_stdout().expect("stdout is piped");
        stdin.send(b"fed ".to_vec()).await.unwrap();
        stdin.send(b"through".to_vec()).await.unwrap();
        drop(stdin);
        (child.wait().await, drain(stdout).await)
    })
    .await
    .expect("cat ends once its input closes");
    assert!(exit.success(), "{exit:?}");
    assert_eq!(out, "fed through");
}

#[tokio::test]
async fn wait_answers_the_same_before_and_after_the_exit_and_to_every_caller() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let mut child = sandbox
        .spawn(SpawnSpec::new("/bin/sh").args(["-c", "exit 7"]))
        .await
        .unwrap();
    let (first, second) = tokio::join!(child.wait(), child.wait());
    assert_eq!(first, second);
    assert_eq!(exit_code(&first), Some(7));
    assert_eq!(
        child.wait().await,
        first,
        "a late wait gets the same answer"
    );
    drop((child.take_stdout(), child.take_stderr()));
}

#[tokio::test]
async fn kill_ends_the_whole_process_tree() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let mut child = sandbox
        .spawn(SpawnSpec::new("/bin/sh").args(["-c", "sleep 300 & echo $!; wait"]))
        .await
        .expect("the process starts");
    let stdout = child.take_stdout().unwrap();
    let grandchild = tokio::time::timeout(BOUND, stdout.recv())
        .await
        .expect("the descendant reports its id")
        .expect("stdout is open");
    let grandchild = String::from_utf8(grandchild).unwrap().trim().to_string();
    assert!(alive(&grandchild), "the descendant runs");

    child.kill().await.expect("the tree is killed");
    let exit = tokio::time::timeout(BOUND, child.wait())
        .await
        .expect("the killed process is waited for");
    assert!(!exit.success(), "{exit:?}");
    tokio::time::timeout(BOUND, async {
        while alive(&grandchild) {
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    })
    .await
    .expect("the descendant is gone with its parent");
    child
        .kill()
        .await
        .expect("killing an ended tree does nothing");
}

/// A grant changed through the sandbox's handle applies to the next spawn
/// and to none already running.
#[tokio::test]
async fn live_grants_apply_to_the_next_spawn() {
    let (_work, work) = canonical_tempdir();
    let (_target, target) = canonical_tempdir();
    let file = target.join("written");
    let script = format!("touch {}", file.display());
    let sandbox = host_sandbox(&work).await;

    let (exit, ..) = run(&sandbox, &script).await;
    assert!(!exit.success(), "nothing grants the directory yet");
    assert!(!file.exists());

    sandbox.grants().add_writable(&target);
    let (exit, ..) = run(&sandbox, &script).await;
    assert!(exit.success(), "{exit:?}");
    assert!(file.exists());

    std::fs::remove_file(&file).unwrap();
    sandbox.grants().revoke(&target);
    let (exit, ..) = run(&sandbox, &script).await;
    assert!(!exit.success(), "the revoked grant no longer applies");
    assert!(!file.exists());
}

/// A writable directory executes what it holds, and a readable one reads.
#[tokio::test]
async fn writable_directories_execute_and_readable_ones_read() {
    use std::os::unix::fs::PermissionsExt as _;
    let (_work, work) = canonical_tempdir();
    let (_writable, writable) = canonical_tempdir();
    let (_readable, readable) = canonical_tempdir();
    for dir in [&writable, &readable] {
        let script = dir.join("tool.sh");
        std::fs::write(&script, "#!/bin/sh\necho ran\n").unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    let sandbox = host_sandbox(&work).await;
    sandbox.grants().add_writable(&writable);
    sandbox.grants().add_readable(&readable);

    let (exit, out, _) = run_spec(
        &sandbox,
        SpawnSpec::new(writable.join("tool.sh").to_str().unwrap()),
    )
    .await;
    assert!(exit.success(), "{exit:?}");
    assert_eq!(out, "ran\n");
    let (_, out, _) = run(
        &sandbox,
        &format!("cat {}", readable.join("tool.sh").display()),
    )
    .await;
    assert!(out.contains("echo ran"), "a readable path reads: {out}");
}

/// A sandbox derived from another never writes what only the parent may.
#[tokio::test]
async fn a_derived_sandbox_cannot_widen_its_parent() {
    let (_work, work) = canonical_tempdir();
    let (_parents, parents) = canonical_tempdir();
    let (_owns, owns) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    sandbox.grants().add_writable(&parents);
    let child = sandbox.derived(GrantSnapshot {
        writable: vec![owns.clone()],
        ..GrantSnapshot::default()
    });

    let touch = |dir: &Path| format!("touch {}", dir.join("f").display());
    let (exit, ..) = run(&child, &touch(&owns)).await;
    assert!(
        exit.success(),
        "the derived sandbox writes its own: {exit:?}"
    );
    let (exit, ..) = run(&child, &touch(&parents)).await;
    assert!(
        !exit.success(),
        "the parent's writable path is not the child's"
    );
    assert!(!parents.join("f").exists());
    let (exit, ..) = run(&sandbox, &touch(&parents)).await;
    assert!(exit.success(), "the parent keeps its own: {exit:?}");
    assert!(parents.join("f").exists());
}

/// The spec's environment leads the source's, which leads the sandbox's.
#[tokio::test]
async fn environment_layers_resolve_spec_over_source_over_sandbox() {
    let (_work, work) = canonical_tempdir();
    let pair = |name: &str, value: &str| (name.to_string(), value.to_string());
    let sandbox = host_sandbox(&work)
        .await
        .with_environment(vec![pair("LAYER_A", "sandbox"), pair("LAYER_B", "sandbox")])
        .with_env_source(vec![pair("LAYER_B", "source"), pair("LAYER_C", "source")]);
    let spec = SpawnSpec::new("/bin/sh")
        .args(["-c", "echo $LAYER_A $LAYER_B $LAYER_C"])
        .env([pair("LAYER_C", "spec")]);
    let (exit, out, _) = run_spec(&sandbox, spec).await;
    assert!(exit.success(), "{exit:?}");
    assert_eq!(out, "sandbox source spec\n");
}

/// A space's variables lead the source's and the sandbox's and yield to the
/// spec's, and a sandbox derived from the space's carries none of them.
#[tokio::test]
async fn the_space_environment_leads_the_source_and_yields_to_the_spec() {
    let (_work, work) = canonical_tempdir();
    let (tmp, cache) = (work.join("tmp"), work.join("cache"));
    let pair = |name: &str, value: &str| (name.to_string(), value.to_string());
    let parent = host_sandbox(&work)
        .await
        .with_environment(vec![
            pair("SPACE_TMP", "sandbox"),
            pair("SPACE_CACHE", "sandbox"),
            pair("SPACE_HOME", "sandbox"),
        ])
        .with_env_source(vec![
            pair("SPACE_CACHE", "source"),
            pair("SPACE_HOME", "source"),
        ]);
    let child = parent
        .derived(GrantSnapshot::default())
        .with_space_environment(vec![
            ("SPACE_TMP".to_string(), tmp.clone()),
            ("SPACE_CACHE".to_string(), cache.clone()),
            ("SPACE_HOME".to_string(), work.join("home")),
        ]);
    let spec = || {
        SpawnSpec::new("/bin/sh")
            .args(["-c", "echo $SPACE_TMP $SPACE_CACHE $SPACE_HOME"])
            .env([pair("SPACE_HOME", "spec")])
    };
    let (exit, out, _) = run_spec(&child, spec()).await;
    assert!(exit.success(), "{exit:?}");
    assert_eq!(out, format!("{} {} spec\n", tmp.display(), cache.display()));

    let nested = child.derived(GrantSnapshot::default());
    let (exit, out, _) = run_spec(&nested, spec()).await;
    assert!(exit.success(), "{exit:?}");
    assert_eq!(
        out, "sandbox source spec\n",
        "a derived sandbox has no space variables of its parent's"
    );
}

/// A container exec that records its script, prints once and then waits for
/// the kill switch.
struct HangingExec {
    scripts: Arc<Mutex<Vec<String>>>,
}

impl ContainerExec for HangingExec {
    fn exec(
        &self,
        _container_id: &str,
        _script: &str,
        _working_dir: &str,
        _kill_rx: Receiver<()>,
        _stdin_rx: Receiver<Vec<u8>>,
        _lifetime: crate::ExecLifetime,
    ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send {
        std::future::ready(Err("the spawn layer streams its execs".into()))
    }

    fn exec_streamed(
        &self,
        _container_id: &str,
        script: &str,
        _working_dir: &str,
        kill_rx: Receiver<()>,
        _stdin_rx: Receiver<Vec<u8>>,
        stdout: Sender<Vec<u8>>,
        _lifetime: crate::ExecLifetime,
    ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send {
        self.scripts.lock().unwrap().push(script.to_string());
        async move {
            let _ = stdout.send(b"started\n".to_vec()).await;
            let _ = kill_rx.recv().await;
            Ok(ContainerExecOutcome::Killed)
        }
    }
}

fn container_sandbox(scripts: &Arc<Mutex<Vec<String>>>, working_dir: &Path) -> Sandbox {
    let runtime = ContainerShellRuntime::new(
        "aither-test-spawn",
        HostRoute::new(
            "host.docker.internal",
            std::net::IpAddr::from([127, 0, 0, 1]),
        )
        .expect("loopback is routable"),
        AnyContainerExec::new(Arc::new(HangingExec {
            scripts: scripts.clone(),
        })),
    );
    Sandbox::new(
        Backend::Container {
            runtime,
            launch: container_launch(),
        },
        TokioGlobal,
        working_dir,
    )
}

#[tokio::test]
async fn a_container_process_streams_and_kill_ends_its_exec() {
    let (_work, work) = canonical_tempdir();
    let scripts = Arc::new(Mutex::new(Vec::new()));
    let pair = |name: &str, value: &str| (name.to_string(), value.to_string());
    let sandbox = container_sandbox(&scripts, &work)
        .with_env_source(vec![pair("FROM_SOURCE", "source-value")]);
    let spec = SpawnSpec::new("long-job")
        .args(["--flag"])
        .env([pair("FROM_SPEC", "spec-value")]);
    let mut child: SandboxedChild = sandbox.spawn(spec).await.expect("the exec starts");
    let stdout = child.take_stdout().unwrap();
    let first = tokio::time::timeout(BOUND, stdout.recv())
        .await
        .expect("the exec prints")
        .expect("stdout is open");
    assert_eq!(first, b"started\n");

    let script = scripts.lock().unwrap().join("\n");
    assert!(script.contains("long-job --flag"), "{script}");
    assert!(
        script.contains("FROM_SPEC") && script.contains("spec-value"),
        "{script}"
    );
    assert!(
        script.contains("FROM_SOURCE") && script.contains("source-value"),
        "{script}"
    );

    child.kill().await.expect("the exec is killed");
    let exit = tokio::time::timeout(BOUND, child.wait())
        .await
        .expect("the killed exec is waited for");
    assert_eq!(exit, ChildExit::Killed);
    assert_eq!(child.wait().await, ChildExit::Killed);
}

/// A container process given no stdin pipe reads the null device, as a host
/// process does: its exec's attached stream is a pipe even when nothing feeds
/// it, so the script reads `/dev/null` first; a piped one reads the stream.
#[tokio::test]
async fn an_unpiped_container_stdin_is_the_null_device() {
    let (_work, work) = canonical_tempdir();
    let redirect =
        super::script_reading(Pipe::Null, String::new()).expect("the null stdin redirect renders");
    for (stdin, redirected) in [(Pipe::Null, true), (Pipe::Piped, false)] {
        let scripts = Arc::new(Mutex::new(Vec::new()));
        let spec = SpawnSpec::new("job").stdio(Stdio {
            stdin,
            ..Stdio::default()
        });
        let mut child = container_sandbox(&scripts, &work)
            .spawn(spec)
            .await
            .expect("the exec starts");
        let stdout = child.take_stdout().unwrap();
        tokio::time::timeout(BOUND, stdout.recv())
            .await
            .expect("the exec prints")
            .expect("stdout is open");
        let script = scripts.lock().unwrap().join("\n");
        assert_eq!(
            script.contains(redirect.trim_end()),
            redirected,
            "{stdin:?}: {script}"
        );
        child.kill().await.expect("the exec is killed");
    }
}

/// A container exec that records how it was started, reports the descendants
/// it killed and, for a background exec, that its stdin blocked.
struct ReportingExec {
    started: Arc<Mutex<Vec<(String, bool)>>>,
    killed: Vec<crate::JobProcess>,
}

impl ContainerExec for ReportingExec {
    fn exec(
        &self,
        _container_id: &str,
        _script: &str,
        _working_dir: &str,
        _kill_rx: Receiver<()>,
        _stdin_rx: Receiver<Vec<u8>>,
        _lifetime: crate::ExecLifetime,
    ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send {
        std::future::ready(Err("the spawn layer streams its execs".into()))
    }

    async fn exec_streamed(
        &self,
        _container_id: &str,
        script: &str,
        _working_dir: &str,
        _kill_rx: Receiver<()>,
        _stdin_rx: Receiver<Vec<u8>>,
        _stdout: Sender<Vec<u8>>,
        lifetime: crate::ExecLifetime,
    ) -> Result<ContainerExecOutcome, String> {
        let foreground = matches!(lifetime, crate::ExecLifetime::Foreground);
        self.started
            .lock()
            .unwrap()
            .push((script.to_string(), foreground));
        if let crate::ExecLifetime::Background { stdin_blocked } = lifetime {
            let _ = stdin_blocked.send(crate::StdinWatchSignal::Blocked).await;
        }
        Ok(ContainerExecOutcome::Completed {
            output: std::process::Output {
                status: std::os::unix::process::ExitStatusExt::from_raw(0),
                stdout: Vec::new(),
                stderr: Vec::new(),
            },
            killed: self.killed.clone(),
        })
    }
}

fn reporting_sandbox(
    exec: ReportingExec,
    working_dir: &Path,
    mount: Option<crate::MountRoot>,
) -> Sandbox {
    let mut runtime = ContainerShellRuntime::new(
        "aither-test-reporting",
        HostRoute::new(
            "host.docker.internal",
            std::net::IpAddr::from([127, 0, 0, 1]),
        )
        .expect("loopback is routable"),
        AnyContainerExec::new(Arc::new(exec)),
    );
    if let Some(mount) = mount {
        runtime = runtime.with_workspace_mount(mount);
    }
    Sandbox::new(
        Backend::Container {
            runtime,
            launch: container_launch(),
        },
        TokioGlobal,
        working_dir,
    )
}

#[tokio::test]
async fn a_foreground_container_child_reports_the_descendants_its_exec_killed() {
    let (_work, work) = canonical_tempdir();
    let started = Arc::new(Mutex::new(Vec::new()));
    let survivor = crate::JobProcess {
        pid: 7,
        name: "sleep".to_string(),
    };
    let sandbox = reporting_sandbox(
        ReportingExec {
            started: started.clone(),
            killed: vec![survivor.clone()],
        },
        &work,
        None,
    );
    let child = sandbox
        .spawn(SpawnSpec::script("sleep 300 &").lifetime(crate::TreeLifetime::Foreground))
        .await
        .expect("the exec starts");
    assert!(child.wait().await.success());
    assert_eq!(
        child.descendants_killed().await,
        crate::Descendants::Killed(vec![survivor])
    );
    assert!(started.lock().unwrap()[0].1, "the exec is a foreground one");
}

#[tokio::test]
async fn a_background_container_child_signals_a_blocked_stdin() {
    let (_work, work) = canonical_tempdir();
    let started = Arc::new(Mutex::new(Vec::new()));
    let sandbox = reporting_sandbox(
        ReportingExec {
            started: started.clone(),
            killed: Vec::new(),
        },
        &work,
        None,
    );
    let mut child = sandbox
        .spawn(SpawnSpec::script("cat").stdio(Stdio {
            stdin: Pipe::Piped,
            ..Stdio::default()
        }))
        .await
        .expect("the exec starts");
    let signals = child.take_stdin_blocked().expect("stdin is watched");
    let signal = tokio::time::timeout(BOUND, signals.recv())
        .await
        .expect("the watch reports")
        .expect("the watch is open");
    assert!(
        matches!(signal, crate::StdinWatchSignal::Blocked),
        "{signal:?}"
    );
    assert!(
        !started.lock().unwrap()[0].1,
        "the exec is a background one"
    );
}

#[tokio::test]
async fn a_container_setup_runs_outside_the_sandbox_that_a_confined_child_gets() {
    let (_work, work) = canonical_tempdir();
    let space = work.join("space");
    std::fs::create_dir(&space).unwrap();
    let started = Arc::new(Mutex::new(Vec::new()));
    let mount = crate::MountRoot::new(
        work.clone(),
        crate::ContainerPath::new("/workspace").unwrap(),
    );
    let parent = reporting_sandbox(
        ReportingExec {
            started: started.clone(),
            killed: Vec::new(),
        },
        &work,
        Some(mount),
    );
    let child = parent
        .derived(GrantSnapshot {
            writable: vec![space.clone()],
            ..GrantSnapshot::default()
        })
        .with_priority(heel::ProcessPriority::new(
            heel::CpuPriority::Nice(heel::NiceLevel::new(5).unwrap()),
            heel::IoPriority::Normal,
        ));
    let spec = SpawnSpec::script("make")
        .grants([super::SpawnGrant::Container {
            path: crate::ContainerPath::new("/tmp/aither-test.fifo").unwrap(),
            access: heel::Access::WRITE,
        }])
        .ipc(Some(heel::IpcRouter::new().register(Probe)));
    let process = child.spawn(spec).await.expect("the exec starts");
    assert!(process.wait().await.success());

    let script = started.lock().unwrap()[0].0.clone();
    assert!(script.starts_with("AITHER_IPC_BIN="), "{script}");
    assert!(
        script.contains(
            r#"--commands '{"probe":{"positional_args":[],"stdin_arg":null,"raw_args":false}}'"#
        ),
        "{script}"
    );
    assert!(
        script.contains("run --working-dir '/workspace' "),
        "{script}"
    );
    assert!(script.contains("--grant '/workspace/space=rw'"), "{script}");
    assert!(
        script.contains("--grant '/tmp/aither-test.fifo=rw'"),
        "{script}"
    );
    assert!(
        script.contains(" --ipc-endpoint 'tcp://host.docker.internal:"),
        "{script}"
    );
    assert!(
        script.contains(" --grant \"$AITHER_IPC_DIR=rx\" --nice 5 "),
        "{script}"
    );
}

/// A container child exports its space's variables with each directory as
/// the container spells it, after the source's exports and before the
/// spec's, and a sandbox derived from it exports none of them.
#[tokio::test]
async fn a_container_child_exports_its_space_environment_through_the_mount() {
    let (_work, work) = canonical_tempdir();
    let space = work.join("space");
    let inner = space.join("inner");
    std::fs::create_dir_all(&inner).unwrap();
    let started = Arc::new(Mutex::new(Vec::new()));
    let mount = crate::MountRoot::new(
        work.clone(),
        crate::ContainerPath::new("/workspace").unwrap(),
    );
    let pair = |name: &str, value: &str| (name.to_string(), value.to_string());
    let parent = reporting_sandbox(
        ReportingExec {
            started: started.clone(),
            killed: Vec::new(),
        },
        &work,
        Some(mount),
    )
    .with_env_source(vec![pair("TMPDIR", "source-tmp")]);
    let child = parent
        .derived(GrantSnapshot {
            writable: vec![space.clone()],
            ..GrantSnapshot::default()
        })
        .with_working_dir(&space)
        .with_space_environment(vec![
            ("TMPDIR".to_string(), space.join("tmp")),
            ("XDG_CACHE_HOME".to_string(), space.join("cache")),
        ]);
    let spec = || SpawnSpec::script("make").env([pair("TMPDIR", "spec-tmp")]);
    let process = child.spawn(spec()).await.expect("the exec starts");
    assert!(process.wait().await.success());
    let nested = child
        .derived(GrantSnapshot {
            writable: vec![inner.clone()],
            ..GrantSnapshot::default()
        })
        .with_working_dir(&inner);
    let process = nested.spawn(spec()).await.expect("the exec starts");
    assert!(process.wait().await.success());

    let scripts: Vec<String> = started
        .lock()
        .unwrap()
        .iter()
        .map(|(script, _)| script.clone())
        .collect();
    let script = &scripts[0];
    let at = |needle: &str| {
        script
            .find(needle)
            .unwrap_or_else(|| panic!("{needle} is exported: {script}"))
    };
    assert!(
        at("source-tmp") < at("/workspace/space/tmp")
            && at("/workspace/space/tmp") < at("spec-tmp"),
        "the space's exports follow the source's and precede the spec's: {script}"
    );
    assert!(
        script.contains("export XDG_CACHE_HOME=") && script.contains("/workspace/space/cache"),
        "{script}"
    );
    assert!(
        !script.contains(&space.join("cache").display().to_string()),
        "the container sees no host spelling: {script}"
    );
    let nested_script = &scripts[1];
    assert!(
        !nested_script.contains("XDG_CACHE_HOME")
            && !nested_script.contains("/workspace/space/tmp"),
        "a derived sandbox exports no space variables of its parent's: {nested_script}"
    );
}

/// A command a spawn's router offers.
struct Probe;

#[derive(serde::Deserialize, schemars::JsonSchema)]
struct ProbeArgs {}

impl heel::IpcCommand for Probe {
    fn name(&self) -> std::borrow::Cow<'static, str> {
        "probe".into()
    }
    type Args = ProbeArgs;
    type Response = String;
    fn handle(
        &self,
        _args: ProbeArgs,
        _context: heel::IpcContext,
    ) -> impl Future<Output = Result<String, heel::IpcError>> {
        std::future::ready(Ok("probe_ok".into()))
    }
}

#[tokio::test]
async fn a_confined_container_child_starts_where_it_was_asked_inside_its_own_sandbox() {
    let (_work, work) = canonical_tempdir();
    let space = work.join("space");
    let start = space.join("sub");
    std::fs::create_dir_all(&start).unwrap();
    let started = Arc::new(Mutex::new(Vec::new()));
    let mount = crate::MountRoot::new(
        work.clone(),
        crate::ContainerPath::new("/workspace").unwrap(),
    );
    let parent = reporting_sandbox(
        ReportingExec {
            started: started.clone(),
            killed: Vec::new(),
        },
        &work,
        Some(mount),
    );
    let child = parent
        .derived(GrantSnapshot {
            writable: vec![space.clone()],
            ..GrantSnapshot::default()
        })
        .with_working_dir(&space);
    let process = child
        .spawn(SpawnSpec::script("make").cwd(&start))
        .await
        .expect("the exec starts");
    assert!(process.wait().await.success());

    let script = started.lock().unwrap()[0].0.clone();
    assert!(
        script.contains("run --working-dir '/workspace/space' "),
        "the sandbox is rooted at the child's own directory: {script}"
    );
    assert!(
        script.contains("sh -c 'cd '\"'\"'/workspace/space/sub'\"'\"' || exit 1\n"),
        "the start directory is entered inside it: {script}"
    );
}

#[tokio::test]
async fn each_backend_refuses_the_grant_and_command_it_cannot_honour() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let error = sandbox
        .spawn(
            SpawnSpec::new("/bin/true").grants([super::SpawnGrant::Container {
                path: crate::ContainerPath::new("/tmp/fifo").unwrap(),
                access: heel::Access::WRITE,
            }]),
        )
        .await
        .expect_err("a host path is the only one the host honours");
    assert!(
        matches!(
            error,
            super::SpawnError::Unsupported {
                backend: "host",
                ..
            }
        ),
        "{error}"
    );
    let error = sandbox
        .spawn(SpawnSpec::script("true"))
        .await
        .expect_err("the host has no managed shell");
    assert!(
        matches!(
            error,
            super::SpawnError::Unsupported {
                backend: "host",
                ..
            }
        ),
        "{error}"
    );
}

#[tokio::test]
async fn a_foreground_host_child_reports_the_descendants_it_killed() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let spec = SpawnSpec::new("/bin/sh")
        .args(["-c", "sleep 300 & sleep 300 & exit 0"])
        .lifetime(crate::TreeLifetime::Foreground);
    let child = sandbox.spawn(spec).await.expect("the process starts");
    let exit = tokio::time::timeout(BOUND, child.wait())
        .await
        .expect("the process ends");
    assert!(exit.success(), "{exit:?}");
    let crate::Descendants::Killed(killed) = child.descendants_killed().await else {
        panic!("a host child's descendants are observed");
    };
    assert_eq!(killed.len(), 2, "{killed:?}");
    assert!(
        killed.iter().all(|process| process.name.contains("sleep")),
        "{killed:?}"
    );
}

#[tokio::test]
async fn a_background_host_child_signals_a_blocked_stdin() {
    let (_work, work) = canonical_tempdir();
    let sandbox = host_sandbox(&work).await;
    let spec = SpawnSpec::new("/bin/cat").stdio(Stdio {
        stdin: Pipe::Piped,
        ..Stdio::default()
    });
    let mut child = sandbox.spawn(spec).await.expect("the process starts");
    let signals = child.take_stdin_blocked().expect("stdin is watched");
    let stdin = child.take_stdin().expect("stdin is piped");
    let signal = tokio::time::timeout(BOUND, signals.recv())
        .await
        .expect("the watch reports")
        .expect("the watch is open");
    assert!(
        matches!(signal, crate::StdinWatchSignal::Blocked),
        "{signal:?}"
    );
    drop(stdin);
    let exit = tokio::time::timeout(BOUND, child.wait())
        .await
        .expect("cat ends at EOF");
    assert!(exit.success(), "{exit:?}");
}