cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
use crate::command::{Command, CommandInput, ExecutableSpec};
use crate::containment::Nesting;
use crate::stdio::{Direction, ResolvedStdio, Stdio};
use crate::test_child::Console;
use crate::{ContainMode, Fd};
use std::ffi::OsString;
use std::path::Path;

fn argv(cmd: &Command) -> Vec<String> {
    match cmd.input() {
        CommandInput::Argv(v) => v.iter().map(|s| s.to_string_lossy().into_owned()).collect(),
        other => panic!("expected Argv, got {:?}", other),
    }
}

#[skuld::test]
fn new_is_empty() {
    let cmd = crate::test_child::command(Console::Hidden);
    assert!(matches!(cmd.input(), CommandInput::Empty));
    assert!(cmd.executable_path().is_none());
}

#[skuld::test]
fn args_sets_and_extends_argv() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["git", "status"]).args(["--short"]);
    assert_eq!(argv(&cmd), ["git", "status", "--short"]);
}

#[skuld::test]
fn arg_appends_one() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.arg("echo").arg("hi");
    assert_eq!(argv(&cmd), ["echo", "hi"]);
}

#[skuld::test]
fn commandline_sets_string_source() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.commandline(r#"git "status""#);
    match cmd.input() {
        CommandInput::CommandLine(s) => assert_eq!(s, &OsString::from(r#"git "status""#)),
        other => panic!("expected CommandLine, got {:?}", other),
    }
}

#[skuld::test]
fn commandline_then_args_switches_source_and_discards() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.commandline("ignored string").args(["real", "argv"]);
    assert_eq!(argv(&cmd), ["real", "argv"]);
}

#[skuld::test]
fn args_then_commandline_switches_to_string() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["a", "b"]).commandline("c d");
    assert!(matches!(cmd.input(), CommandInput::CommandLine(_)));
}

#[skuld::test]
fn executable_overrides_load_path_independently_of_argv() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.executable("/bin/busybox").args(["sh", "-c", "echo hi"]);
    assert_eq!(cmd.executable_path(), Some(Path::new("/bin/busybox")));
    assert_eq!(argv(&cmd), ["sh", "-c", "echo hi"]);
}

#[skuld::test]
fn stdout_shorthand_records_resolved_pipe_out() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["x"]);
    cmd.stdout(Stdio::pipe()).unwrap();
    let fds = cmd.fds();
    assert!(matches!(
        fds.get(&Fd::STDOUT),
        Some(ResolvedStdio::Pipe(Direction::Out))
    ));
}

#[skuld::test]
fn stdin_pipe_infers_in() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.stdin(Stdio::pipe()).unwrap();
    assert!(matches!(
        cmd.fds().get(&Fd::STDIN),
        Some(ResolvedStdio::Pipe(Direction::In))
    ));
}

#[skuld::test]
fn bare_pipe_on_fd3_errs_at_attach() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    assert!(cmd.fd(3, Stdio::pipe()).is_err());
}

#[skuld::test]
fn explicit_pipe_out_on_fd3_attaches() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.fd(3, Stdio::pipe_out()).unwrap();
    assert!(matches!(
        cmd.fds().get(&Fd::from(3)),
        Some(ResolvedStdio::Pipe(Direction::Out))
    ));
}

/// A negative fd number must be refused explicitly, in both debug and release builds — not
/// silently accepted (and later dropped or aborted downstream), and not left to a debug-only
/// `debug_assert!` inside `Fd`'s `From<i32>` (which would panic here rather than return `Err`,
/// and would do nothing at all in release).
#[skuld::test]
fn fd_rejects_negative_slot_with_invalid_input() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    let err = cmd.fd(-1, Stdio::null()).expect_err("a negative fd must be rejected");
    match err {
        crate::error::Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput),
        other => panic!("expected Io(InvalidInput), got {other:?}"),
    }
    // The rejection must not have inserted anything into the map.
    assert!(cmd.fds().is_empty());
}

/// `i32::MIN` is the sharpest edge for the non-negativity check: `.abs()` or a naive negation
/// would overflow on it. Also must be an explicit `Err`, not a panic.
#[skuld::test]
fn fd_rejects_i32_min_slot_with_invalid_input() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    let err = cmd.fd(i32::MIN, Stdio::null()).expect_err("i32::MIN must be rejected");
    match err {
        crate::error::Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput),
        other => panic!("expected Io(InvalidInput), got {other:?}"),
    }
}

#[skuld::test]
fn kill_on_drop_defaults_true_and_toggles() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    assert!(cmd.kill_on_drop_flag());
    cmd.kill_on_drop(false);
    assert!(!cmd.kill_on_drop_flag());
}

#[skuld::test]
fn fd_last_set_wins_for_same_slot() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.stdout(Stdio::pipe()).unwrap();
    cmd.stdout(Stdio::null()).unwrap();
    assert!(matches!(cmd.fds().get(&Fd::STDOUT), Some(ResolvedStdio::Null)));
}

#[skuld::test]
fn inherit_resolves_through_builder() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.stderr(Stdio::inherit()).unwrap();
    assert!(matches!(cmd.fds().get(&Fd::STDERR), Some(ResolvedStdio::Inherit)));
}

#[skuld::test]
fn null_resolves_through_builder() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.stdin(Stdio::null()).unwrap();
    assert!(matches!(cmd.fds().get(&Fd::STDIN), Some(ResolvedStdio::Null)));
}

#[skuld::test]
fn merge_resolves_through_builder() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.stderr(Stdio::merge(Fd::STDOUT)).unwrap();
    assert!(matches!(
        cmd.fds().get(&Fd::STDERR),
        Some(ResolvedStdio::Merge(Fd::STDOUT))
    ));
}

#[skuld::test]
fn env_ops_recorded_in_order() {
    use crate::command::EnvOp;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.env_clear();
    cmd.env("A", "1");
    cmd.env_remove("B");
    cmd.envs([("C", "3"), ("D", "4")]);
    let ops = cmd.env_ops();
    assert!(matches!(ops[0], EnvOp::Clear));
    assert!(matches!(&ops[1], EnvOp::Set(k, v) if k == "A" && v == "1"));
    assert!(matches!(&ops[2], EnvOp::Remove(k) if k == "B"));
    assert!(matches!(&ops[3], EnvOp::Set(k, v) if k == "C" && v == "3"));
    assert!(matches!(&ops[4], EnvOp::Set(k, v) if k == "D" && v == "4"));
    assert_eq!(ops.len(), 5);
}

#[skuld::test]
fn envs_empty_iterator_records_nothing() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.envs::<_, &str, &str>([]);
    assert!(cmd.env_ops().is_empty());
}

#[skuld::test]
fn cwd_recorded() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.current_dir("/tmp");
    assert_eq!(cmd.cwd(), Some(Path::new("/tmp")));
}

#[skuld::test]
fn contain_records_strongest_request() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.contain();
    let req = cmd.contain_request();
    assert_eq!(req.mode, Some(ContainMode::Strongest));
    assert_eq!(req.nesting, Nesting::Mark);
}

#[skuld::test]
fn uncontained_by_default() {
    assert_eq!(crate::test_child::command(Console::Hidden).contain_request().mode, None);
}

#[skuld::test]
fn contain_with_and_nesting_recorded() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.contain_with(ContainMode::TreeWalk).nesting(Nesting::Opaque);
    let req = cmd.contain_request();
    assert_eq!(req.mode, Some(ContainMode::TreeWalk));
    assert_eq!(req.nesting, Nesting::Opaque);
}

#[skuld::test]
fn elevate_enables_with_defaults() {
    let mut c = crate::test_child::command(Console::Hidden);
    c.args(["id", "-u"]).elevate();
    let req = c.elevation_request();
    assert!(req.enabled);
    assert_eq!(req.backend, crate::elevation::Backend::Auto);
    assert!(matches!(req.auth, crate::elevation::Auth::Interactive));
}

#[skuld::test]
fn elevation_overrides_apply_and_enable() {
    let mut c = crate::test_child::command(Console::Hidden);
    c.arg("id")
        .elevation_backend(crate::elevation::Backend::Doas)
        .elevation_auth(crate::elevation::Auth::NonInteractive);
    let req = c.elevation_request();
    assert!(req.enabled);
    assert_eq!(req.backend, crate::elevation::Backend::Doas);
    assert!(matches!(req.auth, crate::elevation::Auth::NonInteractive));
}

#[skuld::test]
fn command_without_elevate_is_disabled() {
    let c = crate::test_child::command(Console::Hidden);
    assert!(!c.elevation_request().enabled);
}

// output()/status()/read() each force their own stdin default (null or inherit) before
// spawning. Auth::Stdin needs SOLE ownership of fd0 to feed the backend the password, so
// that internal default must not trip the same "caller-configured stdin" rejection a real
// user-supplied stdin would — that would make Auth::Stdin unusable via any of the three
// convenience methods, a regression this pins at the builder level (no live spawn needed).
#[skuld::test]
fn default_stdin_is_not_forced_when_auth_stdin_reserves_fd0() {
    let mut c = crate::test_child::command(Console::Hidden);
    c.args(["id"])
        .elevation_auth(crate::elevation::Auth::Stdin(crate::elevation::Secret::new("pw")));
    c.apply_default_stdin(Stdio::null()).unwrap();
    assert!(
        c.fds().get(&Fd::STDIN).is_none(),
        "Auth::Stdin must keep fd0 unconfigured until the elevation rewrite wires its password channel"
    );
}

#[skuld::test]
fn default_stdin_is_forced_without_auth_stdin() {
    let mut c = crate::test_child::command(Console::Hidden);
    c.args(["id"]);
    c.apply_default_stdin(Stdio::null()).unwrap();
    assert!(matches!(c.fds().get(&Fd::STDIN), Some(ResolvedStdio::Null)));
}

#[skuld::test]
fn suppress_fd_marker_sets_the_flag_a_fresh_command_does_not_have() {
    let mut derived = crate::test_child::command(Console::Hidden);
    assert!(!derived.fd_marker_suppressed(), "a fresh command suppresses nothing");
    derived.suppress_fd_marker();
    assert!(derived.fd_marker_suppressed());
}

// ===== creation flags =====

/// `no_window()` is the one portable flag intent: it records the same request on every platform,
/// and only the lowering differs (a creation flag / a show-command / nothing at all).
#[skuld::test]
fn no_window_is_recorded_on_every_platform() {
    let mut cmd = crate::test_child::command(Console::Asked);
    assert!(!cmd.flags_request().no_window, "the default requests nothing");
    cmd.no_window();
    assert!(cmd.flags_request().no_window);
}

#[cfg(windows)]
#[skuld::test]
fn detached_and_raw_flags_are_recorded() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    let before = *cmd.flags_request();
    assert!(!before.detached);
    assert_eq!(before.raw, 0);
    cmd.detached().creation_flags(0x0000_0040);
    let after = *cmd.flags_request();
    assert!(after.detached);
    assert_eq!(after.raw, 0x0000_0040);
}

/// `creation_flags` REPLACES, matching `std::os::windows::process::CommandExt::creation_flags`
/// (`self.flags = flags;`). Or-in would make a bit unclearable, which is the one thing a raw
/// hatch must never do — so `creation_flags(0)` is the documented way to clear a word set
/// earlier, and this test would fail under an or-in implementation at both later calls.
#[cfg(windows)]
#[skuld::test]
fn repeated_creation_flags_calls_replace_rather_than_accumulate() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.creation_flags(0x0000_0040);
    assert_eq!(cmd.flags_request().raw, 0x0000_0040);
    cmd.creation_flags(0x0000_0080);
    assert_eq!(
        cmd.flags_request().raw,
        0x0000_0080,
        "the second call replaces the first"
    );
    cmd.creation_flags(0);
    assert_eq!(cmd.flags_request().raw, 0, "zero clears a word set earlier");
}

// ===== executable vs raw_executable =====

/// The two setters differ only in whether the path is later resolved, so the discriminant IS the
/// feature: with one field and no variant, nothing downstream can tell "find this for me" from
/// "load exactly this", and both contracts cannot coexist.
#[skuld::test]
fn executable_records_search_and_raw_executable_records_exact() {
    let mut a = crate::test_child::command(Console::Hidden);
    a.executable("helper");
    assert!(matches!(a.executable_spec(), Some(ExecutableSpec::Search(p)) if p == Path::new("helper")));

    let mut b = crate::test_child::command(Console::Hidden);
    b.raw_executable("helper");
    assert!(matches!(b.executable_spec(), Some(ExecutableSpec::Exact(p)) if p == Path::new("helper")));
}

/// One field, two setters: they are alternatives rather than additive, and the LAST call wins
/// whichever order they arrive in. A caller switching from one to the other must not end up
/// carrying both intents.
#[skuld::test]
fn last_executable_setter_wins_in_either_order() {
    let mut a = crate::test_child::command(Console::Hidden);
    a.executable("search-me").raw_executable("exact-me");
    assert!(matches!(a.executable_spec(), Some(ExecutableSpec::Exact(p)) if p == Path::new("exact-me")));

    let mut b = crate::test_child::command(Console::Hidden);
    b.raw_executable("exact-me").executable("search-me");
    assert!(matches!(b.executable_spec(), Some(ExecutableSpec::Search(p)) if p == Path::new("search-me")));
}

/// `executable_path()` stays variant-agnostic on purpose: most callers (the elevation `argv[0]`
/// guards, backend routing, the argv and command-line builders) want only the path and don't care
/// which setter produced it. Keeping this getter working means only the sites that actually
/// resolve need to special-case `Exact`.
#[skuld::test]
fn executable_path_is_variant_agnostic() {
    let mut a = crate::test_child::command(Console::Hidden);
    a.executable("/bin/busybox");
    assert_eq!(a.executable_path(), Some(Path::new("/bin/busybox")));

    let mut b = crate::test_child::command(Console::Hidden);
    b.raw_executable("/bin/busybox");
    assert_eq!(b.executable_path(), Some(Path::new("/bin/busybox")));
}

// A failure after the spawn reports what became of the child =====

#[cfg(unix)]
use crate::test_child::held_uncontained_blocker as held_blocker;
#[cfg(unix)]
use crate::test_groups::setuid;

/// A run-to-completion helper that fails after its spawn kills and reaps the child, as its drop
/// would, and says so.
///
/// Mutant: the failure reports `Unknown` without tearing the child down.
#[cfg(unix)]
#[skuld::test]
fn a_failure_after_the_spawn_tears_the_child_down_and_says_so() {
    let (child, writer) = held_blocker(true);
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    // Released after the kill: a kill that sent nothing exits 0.
    let teardown = crate::child::spawn::fault::release_at_drop_kill(writer);
    let error = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), child);
    teardown.assert_killed();
    assert_eq!(error.fate(), Some(crate::error::ChildFate::Reaped), "{error}");
    assert!(
        matches!(error, crate::error::Error::MayHaveStarted { unreaped: None, .. }),
        "{error}"
    );
    assert_eq!(id.is_alive(), crate::identity::Liveness::Dead, "{error}");
}

/// A child `kill_on_drop(false)` keeps is left alone, and the failure names it.
///
/// Mutant: the failure tears down a child that opted out of it.
#[cfg(unix)]
#[skuld::test]
fn a_failure_after_the_spawn_leaves_a_child_that_opted_out() {
    let (child, writer) = held_blocker(false);
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let error = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), child);
    assert_eq!(
        error.fate(),
        Some(crate::error::ChildFate::Running { id: Some(id) }),
        "{error}"
    );
    assert!(
        matches!(error, crate::error::Error::MayHaveStarted { unreaped: None, .. }),
        "the caller chose to keep this child: {error}"
    );
    assert_eq!(id.is_alive(), crate::identity::Liveness::Alive, "{error}");
    drop(writer);
}

/// A child that opted out of the teardown and had its exit collected is reaped, not running.
///
/// Mutant: an opted-out child is always reported `Running`.
#[cfg(unix)]
#[skuld::test]
fn a_failure_after_the_spawn_does_not_call_a_collected_child_running() {
    let (child, writer) = held_blocker(false);
    drop(writer);
    child.wait().expect("the child exits once its stdin closes");
    let error = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), child);
    assert_eq!(error.fate(), Some(crate::error::ChildFate::Reaped), "{error}");
}

/// A failure after the spawn of an elevation front that has ended says an elevated program behind
/// it may still run; one of a plain child does not. A front still running is sent no kill (a kill
/// would orphan the program), looked at and handed back running in the error, which says its child
/// may still be running and carries no note.
///
/// Mutants: the note on a plain child; no note on an ended front; the note on a running front; the
/// running front is killed.
#[cfg(unix)]
#[skuld::test]
fn a_failure_after_the_spawn_notes_the_elevated_program_only_behind_a_front() {
    let note = "an elevated program behind it may still run";
    // Released after the kill: a kill that sent nothing exits 0.
    let (plain, w1) = held_blocker(true);
    let teardown = crate::child::spawn::fault::release_at_drop_kill(w1);
    let plain = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), plain);
    assert!(!plain.to_string().contains(note), "{plain}");
    teardown.assert_killed();
    drop(teardown);

    let sudo = || {
        crate::child::front_kill_tests::spawn_as(
            crate::child::front_kill_tests::cat(),
            crate::elevation::ElevatedVia::Wrapped(crate::elevation::Backend::Sudo),
        )
    };
    // Ended: its exit is collected by the teardown, and the elevated program may outlive it.
    let (ended, writer) = sudo();
    drop(writer);
    crate::test_child::wait_until_zombie(ended.pid());
    let ended = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), ended);
    assert!(ended.to_string().contains(note), "{ended}");
    assert_eq!(ended.fate(), Some(crate::error::ChildFate::Reaped), "{ended}");

    // Running: sent no kill, so it ends 0 once released.
    let (running, writer) = sudo();
    let id = running.id().expect(crate::test_child::IDENTITY_READ);
    let running = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), running);
    assert!(!running.to_string().contains(note), "{running}");
    assert_eq!(
        running.fate(),
        Some(crate::error::ChildFate::Running { id: Some(id) }),
        "{running}"
    );
    let (_, _, handed_back) = crate::test_child::expect_handed_back(running, writer);
    assert!(handed_back.wait().success(), "a front is sent no kill");
}

/// A run-to-completion helper whose child refuses the kill of its teardown (a setuid-root process
/// the caller may not signal) hands the child back in the error, running, with the same identity.
///
/// Mutants: the child is left running and dropped; the fate is `Unknown`; the warn says the child
/// is left running.
#[cfg(unix)]
#[skuld::test]
fn a_failure_after_the_spawn_hands_back_a_child_whose_kill_is_refused(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    crate::log_capture::install();
    let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let mark = crate::log_capture::mark();

    let error = super::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), child);

    // The refused kill is the teardown's failure, beside the pump's: its code is the OS's refusal.
    let crate::error::Error::MayHaveStarted { cleanup, .. } = &error else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    let cleanup = cleanup.as_ref().expect("the refused kill is in the cleanup");
    assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
    assert_eq!(
        crate::error::first_os_code(&**cleanup.first()),
        Some(libc::EPERM),
        "{cleanup:?}"
    );
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, stdin);

    assert_eq!(fate, crate::error::ChildFate::Running { id: Some(id) });
    assert_eq!(handed_back.unreaped().pid(), Some(id.pid()));
    assert_eq!(id.is_alive(), crate::identity::Liveness::Alive);
    let warns = crate::log_capture::records_since_on_current_thread(mark, "handed back to the caller");
    assert_eq!(warns.len(), 1, "{warns:?}");
    let status = handed_back.wait();
    assert!(status.success(), "the helper exits on EOF: {status:?}");
}

// A run-to-completion helper that fails after its spawn =====

/// The answer of a run-to-completion helper that failed after its spawn: the program may have
/// started, the fate is `fate`, no child is handed back, the wrapper flag is `wrapper`, and the cause
/// is the seam's.
#[track_caller]
fn assert_failed_after_the_spawn(error: crate::error::Error, fate: crate::error::ChildFate, wrapper: bool) {
    let crate::error::Error::MayHaveStarted {
        fate: got,
        wrapper_elevated,
        detail,
        source,
        unreaped,
        cleanup,
    } = &error
    else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    assert!(unreaped.is_none(), "a reaped child is not handed back: {error:?}");
    assert!(cleanup.is_none(), "nothing in the teardown failed: {error:?}");
    assert!(
        detail.is_none(),
        "nothing was done with a child that is not a front: {error:?}"
    );
    assert_eq!(*got, fate, "{error}");
    assert_eq!(*wrapper_elevated, wrapper, "{error}");
    assert!(
        matches!(**source, crate::error::Error::Io(ref e) if e.to_string() == crate::child::spawn::failure::seams::FAILURE),
        "{source:?}"
    );
}

/// `output`, `status` and `read` each say the program may have started when their pump or wait
/// fails after the spawn, with the fate their teardown gave the child. Pins each public method's
/// routing through `after_the_spawn`.
///
/// Mutants: a helper returns the cause bare; drops the fate.
#[skuld::test]
fn output_status_and_read_fail_as_may_have_started_after_the_spawn() {
    use crate::child::spawn::failure::seams;
    use crate::error::ChildFate;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    let _pump = seams::fail_the_next_pump();
    assert_failed_after_the_spawn(
        cmd.output().expect_err("a failed pump fails `output`"),
        ChildFate::Reaped,
        false,
    );
    let _pump = seams::fail_the_next_pump();
    assert_failed_after_the_spawn(
        cmd.read().expect_err("a failed pump fails `read`"),
        ChildFate::Reaped,
        false,
    );
    let _wait = seams::fail_the_next_wait();
    assert_failed_after_the_spawn(
        cmd.status().expect_err("a failed wait fails `status`"),
        ChildFate::Reaped,
        false,
    );
}

/// A child reported as an elevation that leaves no front (pkexec execs the program; UAC and an
/// already-elevated parent track it) fails after its spawn without the wrapper flag, and its error
/// has no note that an elevated program may still run.
///
/// Mutants: a helper sets the flag from `report.is_some()` or from `TrackedKind::runs_as_another_user`.
#[skuld::test]
fn a_failure_after_the_spawn_of_a_child_reported_without_a_front_sets_no_wrapper_flag() {
    use crate::child::spawn::failure::seams;
    use crate::elevation::elevation_tests::VIAS_WITHOUT_A_FRONT;
    use crate::error::ChildFate;
    let note = "an elevated program behind it may still run";
    for via in VIAS_WITHOUT_A_FRONT {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        cmd.set_elevation_report(Some(crate::elevation::elevation_tests::report(via.clone())));
        let _pump = seams::fail_the_next_pump();
        let output = cmd.output().expect_err("a failed pump fails `output`");
        let _pump = seams::fail_the_next_pump();
        let read = cmd.read().expect_err("a failed pump fails `read`");
        let _wait = seams::fail_the_next_wait();
        let status = cmd.status().expect_err("a failed wait fails `status`");
        for error in [output, read, status] {
            assert!(!error.to_string().contains(note), "{via:?}: {error}");
            assert_failed_after_the_spawn(error, ChildFate::Reaped, false);
        }
    }
}

/// A live `sudo` front, which `output`, `status` and `read` leave running when their pump or wait
/// fails after the spawn: the teardown sends it no kill and hands it back running, and the error
/// carries the wrapper flag. The root reads fd 4, which the helpers leave alone, so only the test's
/// release ends it.
///
/// Mutants: a helper drops the wrapper flag of a front; the teardown kills the front.
#[cfg(unix)]
#[skuld::test]
fn output_status_and_read_hand_a_live_front_back_after_the_spawn() {
    use crate::child::spawn::failure::seams;
    for name in ["output", "read", "status"] {
        let (gate, release) = crate::test_child::held_writer_stdin();
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(["sh", "-c", "exec cat <&4 4<&-"]);
        cmd.fd(4, gate).expect("set the front's release pipe");
        cmd.set_elevation_report(crate::child::front_kill_tests::sudo_report());
        let _armed = if name == "status" {
            seams::fail_the_next_wait()
        } else {
            seams::fail_the_next_pump()
        };
        let error = match name {
            "output" => cmd.output().map(drop),
            "read" => cmd.read().map(drop),
            _ => cmd.status().map(drop),
        }
        .expect_err("the armed failure fails the helper");
        assert!(
            matches!(
                error,
                crate::error::Error::MayHaveStarted {
                    wrapper_elevated: true,
                    ..
                }
            ),
            "{name}: {error:?}"
        );
        let (cause, fate, handed_back) = crate::test_child::expect_handed_back(error, release);
        assert!(
            matches!(fate, crate::error::ChildFate::Running { .. }),
            "{name}: a front is left running: {fate:?}"
        );
        assert!(
            matches!(cause, crate::error::Error::Io(ref e) if e.to_string() == seams::FAILURE),
            "{name}: {cause:?}"
        );
        assert!(handed_back.wait().success(), "{name}: a front is sent no kill");
    }
}

/// `read`'s invalid UTF-8 of a child behind a front keeps the wrapper flag, as the pump's and
/// wait's failures do, and one reported as pkexec or already elevated has none. The front, `printf`
/// reported as launched by `sudo`, ends by itself, and `read` collects its exit before it fails.
///
/// Mutants: `read` builds the invalid-UTF-8 error without the child's wrapper flag, or sets it
/// from `report.is_some()`.
#[cfg(unix)]
#[skuld::test]
fn read_of_invalid_utf8_behind_a_front_keeps_the_wrapper_flag() {
    use crate::elevation::{Backend, ElevatedVia};
    let reports = [
        (None, false),
        (Some(ElevatedVia::Wrapped(Backend::Pkexec)), false),
        (Some(ElevatedVia::AlreadyElevated), false),
        (Some(ElevatedVia::Wrapped(Backend::Sudo)), true),
    ];
    for (via, wrapper) in reports {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(["printf", "\\377"]);
        if let Some(via) = via {
            cmd.set_elevation_report(Some(crate::elevation::elevation_tests::report(via)));
        }
        let error = cmd.read().expect_err("invalid UTF-8 fails `read`");
        let crate::error::Error::MayHaveStarted {
            fate,
            wrapper_elevated,
            source,
            ..
        } = &error
        else {
            panic!("expected MayHaveStarted, got {error:?}");
        };
        assert_eq!(*fate, crate::error::ChildFate::Reaped, "`read` collected the exit");
        assert_eq!(*wrapper_elevated, wrapper, "{error}");
        assert!(
            matches!(**source, crate::error::Error::Io(ref e) if e.kind() == std::io::ErrorKind::InvalidData),
            "{source:?}"
        );
    }
}

/// The command an elevated spawn runs in the caller's place carries the caller's stdio (moved out),
/// cwd, containment, kill-on-drop and creation flags and the report it is given, and starts with no
/// elevation request, executable or fd-marker suppression. Its argument source and environment are
/// the ones passed in, not the caller's.
///
/// Mutants: the construction drops or defaults any one of those fields, or carries the caller's
/// elevation request, executable or fd-marker suppression.
#[skuld::test]
fn a_command_derived_for_elevation_carries_the_spawn_settings_and_nothing_else() {
    use crate::elevation::{Backend, ElevatedVia};
    let mut cmd = Command::new();
    cmd.args(["caller-program"]).env("CALLER", "1");
    cmd.executable("caller-exe");
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    cmd.current_dir("some-dir");
    cmd.contain_with(ContainMode::Strongest).nesting(Nesting::Opaque);
    cmd.kill_on_drop(false);
    cmd.no_window();
    #[cfg(windows)]
    cmd.detached().creation_flags(0x1);
    cmd.elevate();
    cmd.suppress_fd_marker();

    let derived = cmd.derive_for_elevation(
        CommandInput::Argv(vec![OsString::from("derived-program")]),
        Vec::new(),
        crate::elevation::elevation_tests::report(ElevatedVia::Wrapped(Backend::Pkexec)),
    );

    assert_eq!(argv(&derived), ["derived-program"]);
    assert!(derived.env_ops().is_empty(), "the environment is the one passed in");
    assert!(
        matches!(
            derived.fds().get(&Fd::STDOUT),
            Some(ResolvedStdio::Pipe(Direction::Out))
        ),
        "the stdio moves to the derived command"
    );
    assert!(cmd.fds().is_empty(), "and leaves the caller's");
    assert_eq!(derived.cwd(), Some(Path::new("some-dir")));
    assert_eq!(derived.contain_request(), cmd.contain_request());
    assert_eq!(derived.contain_request().mode, Some(ContainMode::Strongest));
    assert_eq!(derived.contain_request().nesting, Nesting::Opaque);
    assert!(!derived.kill_on_drop_flag());
    assert_eq!(derived.flags_request(), cmd.flags_request());
    assert!(derived.flags_request().no_window);
    assert!(matches!(
        derived.elevation_report().map(|r| &r.via),
        Some(ElevatedVia::Wrapped(Backend::Pkexec))
    ));
    assert!(!derived.elevation_request().enabled, "it cannot elevate again");
    assert!(derived.executable_path().is_none());
    assert!(!derived.fd_marker_suppressed());
    assert!(
        cmd.elevation_report().is_none(),
        "the caller's command is left unreported"
    );
}