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
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//! Signals to a child behind an elevation front, on an ordinary `cat` this test owns and reports as
//! launched by `sudo` or `osascript` (`set_elevation_report`). No forced kill may signal a live front, and
//! no `SIGTERM` a live osascript. The cgroup lane's cases are in `front_cgroup_tests.rs`.
//!
//! Whether anything signalled the `cat` is read from how it ended: it exits 0 once the test closes
//! its stdin, and dies of `SIGKILL` if it was killed first.

use std::io::Read as _;

use crate::PipeWriter;

use crate::test_child::Console;
use std::os::unix::process::ExitStatusExt as _;
use std::time::Duration;

use crate::child::owned::seams::record_root_teardowns;
use crate::command::Command;
use crate::elevation::elevation_tests::report;
use crate::elevation::{Backend, ElevatedVia, ElevationReport};
use crate::error::{ElevationErrorKind, Error};
use crate::os_process::fake::failed_signal;
use crate::signal::Sig;
use crate::{ContainMode, Stdio};

/// The report of a child launched by `sudo`.
pub(crate) fn sudo_report() -> Option<ElevationReport> {
    Some(report(ElevatedVia::Wrapped(Backend::Sudo)))
}

/// Spawns `cmd` with a piped stdin, as the backend `via` launches, and reported so.
pub(crate) fn spawn_as(cmd: Command, via: ElevatedVia) -> (crate::Child, PipeWriter) {
    spawn_as_over(cmd, via, crate::identity::HostKernel)
}

/// [`spawn_as`] over `kernel`, the one the spawn and every box it builds ask.
pub(crate) fn spawn_as_over(
    mut cmd: Command,
    via: ElevatedVia,
    kernel: impl crate::identity::Kernel + Send + 'static,
) -> (crate::Child, PipeWriter) {
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    cmd.set_elevation_report(Some(report(via)));
    let mut child = crate::child::spawn::spawn_with(&mut cmd, kernel)
        .map_err(crate::error::Error::from)
        .expect("spawn");
    let stdin = child.stdin().expect("stdin pipe");
    (child, stdin)
}

pub(crate) fn cat() -> Command {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["cat"]);
    cmd
}

/// `r` is the `Unkillable` refusal of the live sudo front `pid`.
#[track_caller]
pub(crate) fn assert_unkillable_front<T: std::fmt::Debug>(r: Result<T, Error>, pid: u32) {
    assert_refused_by(r, &format!("pid {pid} is what sudo left"));
}

/// `r` is an `Unkillable` refusal whose detail contains `names`.
#[track_caller]
pub(crate) fn assert_refused_by<T: std::fmt::Debug>(r: Result<T, Error>, names: &str) {
    match r {
        Err(Error::Elevation {
            kind: ElevationErrorKind::Unkillable,
            detail,
            ..
        }) => assert!(detail.contains(names), "{detail}"),
        other => panic!("expected Unkillable naming {names:?}, got {other:?}"),
    }
}

/// Closes the `cat`'s stdin and reaps it: it must exit 0, so nothing signalled it.
#[track_caller]
pub(crate) fn assert_ends_unsignalled(child: &crate::Child, stdin: PipeWriter) {
    drop(stdin);
    let status = child.wait().expect("wait");
    assert!(status.success(), "the front was signalled: {status:?}");
}

#[skuld::test]
fn kill_of_a_live_front_is_unkillable_and_sends_nothing() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    assert_unkillable_front(child.kill(), child.pid());
    assert_ends_unsignalled(&child, stdin);
}

/// A front that has exited orphans nothing, so its kill answers as any child's, even where the
/// signal to its zombie is refused, as the root program's is with direct exec.
#[skuld::test]
fn kill_of_an_exited_front_is_ok() {
    let (mut child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    drop(stdin);
    crate::test_child::wait_until_zombie(child.pid());
    let fake = child.proc.script_over(|f| f.signals([failed_signal(libc::EPERM)]));
    child.kill().expect("an exited front is killed like any child");
    assert_eq!(fake.signal_calls(), [Sig::Kill], "the refusal was the kill's");
    assert!(child.wait().expect("wait").success());
}

/// An exited front's kill that fails other than by a refusal fails.
#[skuld::test]
fn kill_of_an_exited_front_returns_any_other_failure() {
    let (mut child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    drop(stdin);
    crate::test_child::wait_until_zombie(child.pid());
    child.proc.script_over(|f| f.signals([failed_signal(libc::EINVAL)]));
    match child.kill() {
        Err(Error::Io(io)) => assert_eq!(io.kind(), std::io::ErrorKind::InvalidInput, "{io}"),
        other => panic!("expected the kill's own failure, got {other:?}"),
    }
    assert!(child.wait().expect("wait").success());
}

/// An exited front's tree is killed as any child's. An exited front needs no backstop, so the
/// root's own signal, which would be refused, is not sent.
#[skuld::test]
fn kill_tree_of_an_exited_front_is_ok() {
    let mut cmd = cat();
    cmd.contain_with(ContainMode::Session);
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    drop(stdin);
    crate::test_child::wait_until_zombie(child.pid());
    let fake = child.proc.script_over(|f| f);
    child
        .kill_tree()
        .expect("an exited front's tree is killed like any child's");
    assert_eq!(fake.signal_calls(), Vec::<Sig>::new(), "the root was signalled");
    assert!(child.wait().expect("wait").success());
}

/// An exited front's tree whose group the sweep skips (the root's own handle cannot say whether the root
/// was reaped, so the group's number is not trusted, below 6.9) is left to the root's own kill. That
/// kill, refused as an exited front's is, counts as made (`Ok`): the answer is the skip's
/// `Unassessable`, not the refusal's `Unkillable` or `Io`.
///
/// Mutant: `OwnedChild::send_kill` maps a refused kill of an exited front as a live front's.
#[cfg(target_os = "linux")]
#[skuld::test]
fn kill_tree_of_an_exited_front_whose_group_is_skipped_counts_its_refused_kill_as_made() {
    use crate::os_process::child::{ExitRecord, PeekOutcome};

    let mut cmd = cat();
    cmd.contain_with(ContainMode::Session);
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    drop(stdin);
    crate::test_child::wait_until_zombie(child.pid());
    // The rule reads the front as exited; the sweep's look at the root's handle then fails.
    let fake = child.proc.script_over(|f| {
        f.peeks([
            Ok(PeekOutcome::Exit(ExitRecord::Status(Default::default()))),
            Err(std::io::Error::other("the handle cannot say")),
        ])
        .signals([failed_signal(libc::EPERM)])
    });
    let old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    let result = child.kill_tree();
    drop(old_kernel);
    assert_eq!(fake.signal_calls(), [Sig::Kill], "the sweep left the root its own kill");
    match result {
        Err(Error::Unassessable { detail, .. }) => assert!(
            detail.contains("it did not kill its process group")
                && detail.ends_with("and killed the root through its pidfd, which names it exactly"),
            "{detail}"
        ),
        other => panic!("expected the skip's Unassessable, got {other:?}"),
    }
    assert!(child.wait().expect("wait").success());
}

/// The drop of an exited front tears it down as any child's, reaping it, and warns of nothing.
#[skuld::test]
fn drop_of_an_exited_front_reaps_it_and_warns_of_nothing() {
    crate::log_capture::install();
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    let pid = child.pid();
    drop(stdin);
    crate::test_child::wait_until_zombie(pid);
    let mark = crate::log_capture::mark();
    drop(child);
    // The reap is said at `debug`, as "reaped it": only a warn is a complaint.
    let warns = crate::log_capture::warns_since(mark, "Child::drop");
    assert!(warns.is_empty(), "{warns:?}");
    assert_eq!(reap(pid), None, "the drop reaps an exited front");
}

/// doas leaves this process tracking a front, as sudo does.
#[skuld::test]
fn kill_of_a_live_doas_front_is_unkillable_and_sends_nothing() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Doas));
    assert_refused_by(child.kill(), &format!("pid {} is what doas left", child.pid()));
    assert_ends_unsignalled(&child, stdin);
}

/// A live front's containments outside a cgroup that tell nothing of it: none, and a tree walk.
pub(crate) fn uncontained_cats() -> [Command; 2] {
    let mut walked = cat();
    walked.contain_with(ContainMode::TreeWalk);
    [cat(), walked]
}

/// A live front with no group, uncontained or in a walked tree, is sent nothing by `kill`.
#[skuld::test]
fn kill_of_a_live_front_without_a_group_sends_nothing() {
    for cmd in uncontained_cats() {
        let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
        assert_unkillable_front(child.kill(), child.pid());
        assert_ends_unsignalled(&child, stdin);
    }
}

/// A live front with no group, uncontained or in a walked tree, is sent nothing by the drop.
#[skuld::test]
fn drop_of_a_live_front_without_a_group_sends_nothing() {
    for cmd in uncontained_cats() {
        let teardowns = record_root_teardowns();
        let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
        let pid = child.pid();
        drop(child);
        assert_eq!(teardowns.count(), 0, "the drop must not kill or reap a live front");
        drop(stdin);
        assert_reaped_unsignalled(pid);
    }
}

/// A live front with no group, uncontained or in a walked tree, is sent nothing by a failed
/// password write's teardown.
#[skuld::test]
fn a_failed_password_write_sends_a_live_front_without_a_group_nothing() {
    for cmd in uncontained_cats() {
        let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
        let id = child.id().expect(crate::test_child::IDENTITY_READ);
        let pid = id.pid();
        let (detail, cleanup, fate, handed_back) = failed_password_write_detail(child, stdin);
        assert_eq!(
            fate,
            crate::error::ChildFate::Running { id: Some(id) },
            "a live front is handed back"
        );
        assert_eq!(handed_back.unreaped().pid(), Some(pid));
        assert!(detail.contains("could not be terminated"), "{detail}");
        // The refusal is the cleanup's, an `Unkillable` that names the front; the detail says only
        // what was done.
        assert!(!detail.contains("is what sudo left"), "{detail}");
        let cleanup = cleanup.expect("the refused kill is the cleanup");
        assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
        assert!(
            matches!(
                &**cleanup.first(),
                Error::Elevation { kind: ElevationErrorKind::Unkillable, detail, .. }
                    if detail.contains(&format!("pid {pid} is what sudo left"))
            ),
            "{cleanup:?}"
        );
        let status = handed_back.wait();
        assert!(status.success(), "the front was signalled: {status:?}");
    }
}

/// The `detail` of the error the sync `finish_elevated` returns for `child` after a failed
/// password write, the `cleanup` of the error (the failures of the teardown, if any), its fate, and
/// the child it handed back, if it did, with `release` (what lets the front exit; `()`: nothing).
pub(crate) fn failed_password_write_detail<R>(
    child: crate::Child,
    release: R,
) -> (
    String,
    Option<crate::error::Failures>,
    crate::error::ChildFate,
    crate::test_child::HandedBack<R>,
) {
    let error = Error::from(
        crate::child::spawn::finish_elevated(
            child,
            Err(Error::Elevation {
                kind: ElevationErrorKind::AuthFailed,
                detail: "forced password-write failure".into(),
                source: None,
            }),
        )
        .expect_err("a failed write fails the spawn"),
    );
    let Error::MayHaveStarted { cleanup, .. } = &error else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    let cleanup = cleanup.clone();
    let detail = crate::test_child::detail_of(&error);
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, release);
    (detail, cleanup, fate, handed_back)
}

/// A front that exits on its `SIGTERM` within the grace is not escalated against: its status is
/// returned.
#[skuld::test]
fn graceful_shutdown_of_a_front_that_exits_within_the_grace_returns_its_status() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    // Released once the `SIGTERM` has been sent (see `release_at`): a `terminate` that sent nothing
    // lets the `cat` exit 0 and fails the assertion below, where the hour of grace would not end.
    let _release = crate::graceful_hooks::release_at(crate::graceful_hooks::HookPoint::AfterTerminate, stdin);
    let status = child
        .graceful_shutdown(Duration::from_secs(3600))
        .expect("the relayed SIGTERM ends the front");
    assert_eq!(status.signal(), Some(libc::SIGTERM));
}

/// A front that exits after its grace runs out, before its escalation, is killed as any exited
/// child: its refused kill is `Ok`, and any other failure fails. The `cat` ignores `SIGTERM`; a hook
/// before the escalation ends it and arms the kill's outcome.
#[skuld::test]
fn graceful_shutdown_of_a_front_that_exits_before_its_escalation() {
    use crate::child::graceful::fault::{at, HookPoint};
    for errno in [libc::EPERM, libc::EINVAL] {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
        cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
        let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
        let mut ready = [0u8; 6];
        child
            .stdout()
            .expect("stdout pipe")
            .read_exact(&mut ready)
            .expect("read `ready`");
        let pid = child.pid();
        let fake = child.proc.script_over(|f| f);
        let sent = fake.clone();
        let _hook = at(HookPoint::BeforeEscalation, move || {
            drop(stdin);
            crate::test_child::wait_until_zombie(pid);
            drop(fake.signals([failed_signal(errno)]));
        });
        let result = child.graceful_shutdown(Duration::ZERO);
        if errno == libc::EPERM {
            assert!(result.expect("a refused kill of an exited front is Ok").success());
        } else {
            match result {
                Err(Error::Io(io)) => assert_eq!(io.kind(), std::io::ErrorKind::InvalidInput, "{io}"),
                other => panic!("expected the kill's own failure, got {other:?}"),
            }
            assert!(child.wait().expect("wait").success());
        }
        assert_eq!(
            sent.signal_calls(),
            [Sig::Term, Sig::Kill],
            "the refusal was the escalation's kill"
        );
    }
}

/// A failed password write to a front someone else already reaped says the front had exited.
#[skuld::test]
fn a_failed_password_write_to_a_front_someone_else_reaped_says_it_had_exited() {
    let mut cmd = cat();
    cmd.kill_on_drop(false);
    let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    let pid = child.pid();
    drop(stdin);
    crate::test_child::wait_until_zombie(pid);
    assert!(reap(pid).is_some(), "the test reaps the front itself");
    let (detail, _cleanup, fate, handed_back) = failed_password_write_detail(child, ());
    assert!(handed_back.is_none(), "a front someone else reaped is not handed back");
    assert_eq!(fate, crate::error::ChildFate::Gone);
    assert!(
        detail.contains("the elevated child had already exited, and was reaped by someone else"),
        "{detail}"
    );
}

/// pkexec execs the program, so the tracked process is the program: it is signalled.
#[skuld::test]
fn kill_of_a_pkexec_child_signals_it() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Pkexec));
    child.kill().expect("kill");
    // Closed first: a front nothing killed then exits 0, and the assertion fails.
    drop(stdin);
    assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}

/// A process group or a walked tree is signalled subject to the target's credentials, so it does
/// not reach the program either.
#[skuld::test]
fn kill_tree_of_a_live_front_outside_a_cgroup_is_unkillable_and_sends_nothing() {
    let mut cmd = cat();
    cmd.contain_with(ContainMode::Session);
    let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    assert_eq!(child.containment(), crate::test_child::session_gives());
    assert_unkillable_front(child.kill_tree(), child.pid());
    assert_ends_unsignalled(&child, stdin);
}

/// The escalation is the kill the rule decides. A `cat` that ignores `SIGTERM` outlives the grace.
#[skuld::test]
fn graceful_shutdown_of_a_front_that_outlives_the_grace_is_unkillable() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    // An ignored disposition survives `exec`; `ready` says it is set.
    cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    assert_eq!(&ready, b"ready\n");
    assert_unkillable_front(child.graceful_shutdown(Duration::ZERO), child.pid());
    assert_ends_unsignalled(&child, stdin);
}

/// The grace wait's failure is not subsumed by the refusal: the escalation's `Unkillable` is the
/// answer, with the watch failure as its cause.
///
/// Mutant: the watch failure is logged and dropped, or replaces the refusal.
#[skuld::test]
fn graceful_shutdown_of_a_front_whose_grace_wait_failed_is_unkillable_with_the_watch_failure_as_its_cause() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    crate::wait::fault::set_force_watch_error(true);

    let err = child
        .graceful_shutdown(Duration::ZERO)
        .expect_err("a live front is not killed");

    match &err {
        Error::Elevation {
            kind: ElevationErrorKind::Unkillable,
            source: Some(cause),
            ..
        } => assert!(
            crate::error::said(&**cause).contains("forced grace-watch failure"),
            "{err:?}"
        ),
        other => panic!("expected Unkillable with the watch failure as its cause, got {other:?}"),
    }
    assert_ends_unsignalled(&child, stdin);
}

/// The drop neither kills nor waits for a live front, and says so.
#[skuld::test]
fn drop_of_a_live_front_leaves_it_running_unreaped_and_warns() {
    crate::log_capture::install();
    let teardowns = record_root_teardowns();
    let mut cmd = cat();
    cmd.contain_with(ContainMode::Session);
    let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    let pid = child.pid();

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(teardowns.count(), 0, "the drop must not kill or reap a live front");
    let warns = crate::log_capture::records_since_on_current_thread(mark, "Child::drop");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert_eq!(warns[0].0, log::Level::Warn);
    assert!(
        warns[0].1.contains(&format!("pid {pid} is what sudo left")),
        "{warns:?}"
    );

    drop(stdin);
    assert_reaped_unsignalled(pid);
}

/// Reaps `pid`, an unreaped child of this process that nothing else reaps, and asserts it exited 0.
#[track_caller]
pub(crate) fn assert_reaped_unsignalled(pid: u32) {
    let mut status = 0;
    // SAFETY: `status` is a valid out-parameter.
    let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
    assert_eq!(
        reaped,
        pid as libc::pid_t,
        "waitpid: {}",
        std::io::Error::last_os_error()
    );
    assert!(
        libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
        "the front was signalled: raw status {status:#x}"
    );
}

/// A failed password write's teardown signals neither a live front nor its group, and says why. The
/// `killpg` recorder stands in for the group kill.
#[skuld::test]
fn a_failed_password_write_signals_neither_a_live_front_nor_its_group() {
    let groups = crate::containment::unix::fault::record_kill_group();
    let mut cmd = cat();
    cmd.contain_with(ContainMode::Session);
    let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let pid = id.pid();
    let (detail, cleanup, fate, handed_back) = failed_password_write_detail(child, stdin);
    assert_eq!(
        fate,
        crate::error::ChildFate::Running { id: Some(id) },
        "a live front is handed back"
    );
    assert_eq!(handed_back.unreaped().pid(), Some(pid));
    assert_eq!(
        groups.killed(),
        Vec::<i32>::new(),
        "no group kill of a live front: {detail}"
    );
    assert!(detail.contains("could not be terminated"), "{detail}");
    assert!(
        detail.contains(crate::child::owned::owned_tests::teardown_lines::HANDED_BACK),
        "{detail}"
    );
    // The refusal that says why is the cleanup's, not the detail's.
    assert!(!detail.contains("is what sudo left"), "{detail}");
    let cleanup = cleanup.expect("the refused kill is the cleanup");
    assert!(
        cleanup
            .first()
            .to_string()
            .contains(&format!("pid {pid} is what sudo left")),
        "{cleanup:?}"
    );
    // Released: the front exits by itself, unsignalled.
    let status = handed_back.wait();
    assert!(status.success(), "the front was signalled: {status:?}");
}

/// The fate of the `finish_elevated` a failed password write runs for a live sudo front `child`,
/// and the front it handed back, if it did.
fn failed_password_write_fate<R>(
    child: crate::Child,
    release: R,
) -> (crate::error::ChildFate, crate::test_child::HandedBack<R>) {
    let (_, fate, handed_back) = crate::child::spawn::finish_elevated(
        child,
        Err(Error::Elevation {
            kind: ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
            source: None,
        }),
    )
    .expect_err("a failed write fails the spawn")
    .expect_may_have_started_parts(release);
    (fate, handed_back)
}

/// A live front is handed back, running, and its fate names it by its identity.
///
/// Mutant: the refused kill's fate is `Unknown`, or carries no identity; the front is not handed back.
#[skuld::test]
fn a_failed_password_write_hands_back_a_live_front_and_names_it() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let (fate, handed_back) = failed_password_write_fate(child, stdin);
    assert_eq!(fate, crate::error::ChildFate::Running { id: Some(id) });
    assert_eq!(handed_back.unreaped().id(), Some(id));
    let status = handed_back.wait();
    assert!(status.success(), "the front was signalled: {status:?}");
}

/// The failed password write's error says whether the child is an elevation front: a sudo child is
/// one, and a pkexec or an already-elevated child is not.
///
/// Mutants: `finish_elevated` marks every failure, or none, or marks by `report.is_some()`.
#[skuld::test]
fn a_failed_password_write_flags_a_front_and_no_other_child() {
    let mut vias = vec![(ElevatedVia::Wrapped(Backend::Sudo), true)];
    vias.extend(crate::elevation::elevation_tests::VIAS_WITHOUT_A_FRONT.map(|via| (via, false)));
    for (via, front) in vias {
        let (child, stdin) = spawn_as(cat(), via.clone());
        let error = Error::from(
            crate::child::spawn::finish_elevated(
                child,
                Err(Error::Elevation {
                    kind: ElevationErrorKind::AuthFailed,
                    detail: "forced password-write failure".into(),
                    source: None,
                }),
            )
            .expect_err("a failed write fails the spawn"),
        );
        let Error::MayHaveStarted { wrapper_elevated, .. } = &error else {
            panic!("{via:?}: expected MayHaveStarted, got {error:?}");
        };
        assert_eq!(*wrapper_elevated, front, "{via:?}: {error}");
        let (_, _, handed_back) = crate::test_child::expect_may_have_started_parts(error, stdin);
        if !handed_back.is_none() {
            assert!(handed_back.wait().success(), "{via:?}: the front was signalled");
        }
    }
}

/// A live front, refused its kill, that exits and is reaped by someone else before the failure's
/// look, is not running: the look finds no child (`ECHILD`), and says `Gone`.
///
/// Mutant: any failed look is `Running`.
#[skuld::test]
fn a_live_front_reaped_elsewhere_after_the_refused_kill_is_gone() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    let pid = child.pid();
    let _foreign_reap = crate::child::spawn::fault::set_between_kill_and_wait(move || {
        drop(stdin);
        crate::test_child::wait_until_zombie(pid);
        let mut status = 0;
        // SAFETY: `pid` is this test's own zombie child; this plays the application that reaps it.
        let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
        assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
    });
    let (fate, handed_back) = failed_password_write_fate(child, ());
    assert!(handed_back.is_none(), "a front someone else reaped is not handed back");
    assert_eq!(fate, crate::error::ChildFate::Gone);
}

/// A failed password write whose front had already exited says so, not that it terminated the
/// front. With direct exec the front is the root program, which refuses this process's signal even
/// as a zombie: a scripted `EPERM` stands in for that refusal, and it is the kill's alone.
#[skuld::test]
fn a_failed_password_write_to_a_front_that_had_exited_says_so() {
    let mut cmd = cat();
    // The drop, whose own teardown would send its own kill, is opted out of.
    cmd.kill_on_drop(false);
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    drop(stdin);
    crate::test_child::wait_until_zombie(child.pid());
    let fake = child.proc.script_over(|f| f.signals([failed_signal(libc::EPERM)]));
    let err = Error::from(
        crate::child::spawn::finish_elevated(
            child,
            Err(Error::Elevation {
                kind: ElevationErrorKind::AuthFailed,
                detail: "forced password-write failure".into(),
                source: None,
            }),
        )
        .expect_err("a failed write fails the spawn"),
    );
    let detail = crate::test_child::detail_of(&err);
    let (_, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
    assert_eq!(
        fate,
        crate::error::ChildFate::Reaped,
        "the non-blocking look reaps the exited front"
    );
    assert_eq!(fake.signal_calls(), [Sig::Kill], "the refusal was the kill's: {detail}");
    assert!(detail.contains("the elevated child had already exited"), "{detail}");
    assert!(!detail.contains("terminated"), "{detail}");
}

/// A failed password write to a front that had exited, whose reap then fails (as when someone else
/// reaps the zombie first), says the front had exited, not that it was killed. The reap failure is
/// forced; it still reaps first.
#[skuld::test]
fn a_failed_password_write_whose_exited_front_cannot_be_reaped_says_it_had_exited() {
    let mut cmd = cat();
    cmd.kill_on_drop(false);
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
    drop(stdin);
    crate::test_child::wait_until_zombie(child.pid());
    let fake = child.proc.script_over(|f| f.signals([failed_signal(libc::EPERM)]));
    crate::child::spawn::fault::set_force_reap_failure("forced reap failure");
    let error = Error::from(
        crate::child::spawn::finish_elevated(
            child,
            Err(Error::Elevation {
                kind: ElevationErrorKind::AuthFailed,
                detail: "forced password-write failure".into(),
                source: None,
            }),
        )
        .expect_err("a failed write fails the spawn"),
    );
    // The failed wait is the teardown's failure, so it is the cleanup's; the detail says it failed.
    let cleanup = crate::test_child::cleanup_of(&error);
    assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
    assert!(
        crate::error::said(&**cleanup.first()).contains("forced reap failure"),
        "{cleanup:?}"
    );
    let detail = crate::test_child::detail_of(&error);
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, ());
    assert_eq!(fate, crate::error::ChildFate::Killed, "the exit was not collected");
    // Not shown collected, so handed back. The forced failure reaps first, so settling it finds it
    // reaped elsewhere and returns at once.
    handed_back.unreaped();
    drop(handed_back);
    assert_eq!(fake.signal_calls(), [Sig::Kill], "the refusal was the kill's");
    assert!(detail.contains("(it had already exited): the wait failed"), "{detail}");
    assert!(
        !detail.contains("forced reap failure"),
        "the failure is in the detail: {detail}"
    );
    assert!(!detail.contains("killed"), "{detail}");
}

/// A `SIGTERM` would end osascript and orphan the program, so `terminate()` on a live osascript
/// front sends nothing.
#[skuld::test]
fn terminate_of_a_live_osascript_is_unkillable_and_sends_nothing() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::MacosOsascript);
    let pid = child.pid();
    assert_refused_by(child.terminate(), &format!("pid {pid} is osascript"));
    assert_ends_unsignalled(&child, stdin);
}

/// The graceful path starts with `terminate()`, so it is refused before any grace or kill. Then a
/// kill is refused too, as it was before the attempt.
#[skuld::test]
fn graceful_shutdown_of_a_live_osascript_is_unkillable_and_sends_nothing() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::MacosOsascript);
    let pid = child.pid();
    assert_refused_by(
        child.graceful_shutdown(Duration::ZERO),
        &format!("pid {pid} is osascript"),
    );
    assert_refused_by(child.kill(), &format!("pid {pid} is osascript"));
    assert_ends_unsignalled(&child, stdin);
}

/// sudo relays `SIGTERM` to the program, so it is sent.
#[skuld::test]
fn terminate_of_a_live_sudo_front_is_sent() {
    let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
    child.terminate().expect("sudo relays SIGTERM");
    // Closed first: a front nothing killed then exits 0, and the assertion fails.
    drop(stdin);
    assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGTERM));
}

/// Spawns of a `cat` marked as an elevation-derived `sudo` front, in `contain` mode if any, that fail
/// after their fork: once in the attach, once in the identity check. Returns each failure's cause and
/// `detail` (what the spawn did with the front) with the child's pid and the child it handed back, if
/// it did. The failed spawn closes the `cat`'s stdin, so a front left alone exits 0.
#[cfg(target_os = "linux")]
pub(crate) fn failed_front_spawns(
    contain: Option<ContainMode>,
    spawn: impl Fn(&mut Command) -> Result<(), Error>,
) -> [(Error, String, u32, crate::test_child::HandedBack<()>); 2] {
    use crate::child::spawn::fault;
    // Each arm, and whether it comes after the identity read, which then names the front.
    let arms: [(fn(bool), bool); 2] = [
        (fault::set_force_attach_failure, true),
        (fault::set_force_identity_vanished, false),
    ];
    arms.map(|(force_arm, identified)| {
        let mut cmd = cat();
        cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
        if let Some(mode) = contain {
            cmd.contain_with(mode);
        }
        cmd.set_elevation_report(sudo_report());
        force_arm(true);
        let err = spawn(&mut cmd);
        force_arm(false);
        // Both arms come after `exec`.
        let err = err.expect_err("the forced arm fails the spawn");
        let detail = crate::test_child::detail_of(&err);
        let (err, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, ());
        let crate::identity::Resolved::Found(id) = fault::take_captured().expect("the seam captured the child") else {
            panic!("the seam must capture a resolved identity");
        };
        // A front in a cgroup leaf is torn down as any child; any other is left running.
        let expected = if contain.is_some() {
            crate::error::ChildFate::Reaped
        } else {
            crate::error::ChildFate::Running {
                id: identified.then_some(id),
            }
        };
        assert_eq!(fate, expected, "{err}");
        (err, detail, id.pid(), handed_back)
    })
}

/// Reaps `pid`, this process's own child, and answers how it ended: `None` if something reaped it
/// already.
pub(crate) fn reap(pid: u32) -> Option<std::process::ExitStatus> {
    let mut raw = 0;
    // SAFETY: `raw` is a valid out-parameter; `pid` is this process's own child.
    let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut raw, 0) };
    if reaped == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD) {
        return None;
    }
    assert_eq!(
        reaped,
        pid as libc::pid_t,
        "waitpid: {}",
        std::io::Error::last_os_error()
    );
    Some(std::os::unix::process::ExitStatusExt::from_raw(raw))
}

/// The two failures' causes are an attach's `Containment` and an identity check's `Io`, and their
/// `detail` carries the front's fate, `fate`.
#[cfg(target_os = "linux")]
#[track_caller]
pub(crate) fn assert_noted(failures: &[(Error, String, u32, crate::test_child::HandedBack<()>); 2], fate: &str) {
    let [(attach, attach_detail, attach_pid, _), (identity, identity_detail, identity_pid, _)] = failures;
    assert!(
        matches!(attach, Error::Containment { .. }),
        "the attach failure's cause is a Containment: {attach:?}"
    );
    assert!(
        matches!(identity, Error::Io(_)),
        "the identity failure's cause is an Io: {identity:?}"
    );
    for (text, pid) in [(attach_detail, attach_pid), (identity_detail, identity_pid)] {
        assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
        assert!(text.contains(fate), "{text}");
    }
}

/// A spawn that fails after its fork sends an elevation front nothing (a kill would orphan the
/// program), hands it back in the error, and says so on the error it would have returned anyway.
///
/// Mutants: the front is left running and dropped; the note says it is left unreaped.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_spawn_hands_back_an_elevation_front_and_says_so() {
    let failures = failed_front_spawns(None, |cmd| cmd.spawn().map(drop));
    assert_noted(
        &failures,
        "the elevated program may be running; handed back to the caller in the error",
    );
    for (_, _, pid, handed_back) in failures {
        assert_eq!(handed_back.unreaped().pid(), Some(pid));
        // The failed spawn closed the front's stdin, so it exits by itself, unsignalled.
        let status = handed_back.wait();
        assert!(status.success(), "the teardown signalled the front: {status:?}");
    }
}

/// A spawn that fails after its fork says whether the child is an elevation front: one reported as
/// sudo's is, and one reported as pkexec's, UAC's or an already-elevated parent's is not.
///
/// Mutants: `spawn_unelevated` drops its `map_err(behind_front)`, inverts its test, or marks by
/// `report.is_some()`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_spawn_that_fails_after_its_fork_flags_a_front_and_no_other_child() {
    let mut vias = vec![(ElevatedVia::Wrapped(Backend::Sudo), true)];
    vias.extend(crate::elevation::elevation_tests::VIAS_WITHOUT_A_FRONT.map(|via| (via, false)));
    for (via, front) in vias {
        let mut cmd = cat();
        cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
        cmd.set_elevation_report(Some(report(via.clone())));
        crate::child::spawn::fault::set_force_attach_failure(true);
        let error = cmd.spawn().expect_err("the forced attach failure fails the spawn");
        crate::child::spawn::fault::set_force_attach_failure(false);
        let Error::MayHaveStarted { wrapper_elevated, .. } = &error else {
            panic!("{via:?}: expected MayHaveStarted, got {error:?}");
        };
        assert_eq!(*wrapper_elevated, front, "{via:?}: {error}");
        // The failed spawn closed the `cat`'s stdin, so a front it handed back exits by itself.
        let (_, _, handed_back) = crate::test_child::expect_may_have_started_parts(error, ());
        if !handed_back.is_none() {
            assert!(handed_back.wait().success(), "{via:?}: the front was signalled");
        }
    }
}

/// A pkexec child is not a front, so its escalation sends the kill, and a refused one answers as
/// [`Child::kill`] does: `Unkillable`, with the OS's refusal as its cause and a failed grace wait
/// beside it. Its `SIGTERM` is answered as delivered and its kill is refused, so the escalation runs.
///
/// Mutant: the escalation answers the raw `Io`, skipping the elevation mapping, or drops the watch
/// failure.
#[skuld::test]
fn a_pkexec_childs_refused_escalation_is_unkillable_as_for_kill() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    let (mut child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Pkexec));
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    let fake = child
        .proc
        .script_over(|f| f.signals([Ok(crate::signal::Sent::Delivered), failed_signal(libc::EPERM)]));
    crate::wait::fault::set_force_watch_error(true);
    let err = child
        .graceful_shutdown(Duration::ZERO)
        .expect_err("the kill is refused");
    let Error::Elevation {
        kind: ElevationErrorKind::Unkillable,
        ..
    } = &err
    else {
        panic!("expected Unkillable, got {err:?}");
    };
    let below = err.failures_below();
    assert!(
        matches!(&below[..], [Error::Io(e), watch]
            if e.kind() == std::io::ErrorKind::PermissionDenied
                && crate::error::said(*watch).contains("forced grace-watch failure")),
        "{below:?}"
    );
    assert_eq!(
        fake.signal_calls(),
        [Sig::Term, Sig::Kill],
        "the escalation was reached"
    );
    assert_ends_unsignalled(&child, stdin);
}

/// A child that cannot run as another user answers a refused escalation with the raw `Io`: it is the
/// OS call's failure, with its code, whatever else failed. A failed grace wait beside it is logged at
/// warn, not carried.
///
/// Mutant: the `Io` goes below an `Unassessable` once it has a peer, or the watch failure is dropped.
#[skuld::test]
fn a_refused_escalation_of_a_child_that_cannot_run_as_another_user_is_the_io_and_the_watch_failure_a_warn() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    child
        .proc
        .script_over(|f| f.signals([Ok(crate::signal::Sent::Delivered), failed_signal(libc::EPERM)]));
    crate::wait::fault::set_force_watch_error(true);
    let err = child
        .graceful_shutdown(Duration::ZERO)
        .expect_err("the kill is refused");
    match &err {
        Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e}"),
        other => panic!("expected the raw Io(PermissionDenied), got {other:?}"),
    }
    let logged = crate::log_capture::records_since_on_current_thread(mark, "forced grace-watch failure");
    let call = format!("graceful_shutdown({})", child.pid());
    assert!(
        matches!(&logged[..], [(log::Level::Warn, line)] if line.starts_with(&call)),
        "{logged:?}"
    );
    assert_ends_unsignalled(&child, stdin);
}

/// While it lives, this thread's spawns fail their attach (a test seam: a macOS attach reads
/// nothing, so it cannot fail on its own).
#[cfg(target_os = "macos")]
pub(crate) fn fail_the_attach() -> AttachFails {
    crate::child::spawn::fault::set_force_attach_failure(true);
    AttachFails
}

/// Fails attaches until dropped (see [`fail_the_attach`]).
#[cfg(target_os = "macos")]
#[must_use = "attaches succeed again as soon as the guard is dropped"]
pub(crate) struct AttachFails;

#[cfg(target_os = "macos")]
impl Drop for AttachFails {
    fn drop(&mut self) {
        crate::child::spawn::fault::set_force_attach_failure(false);
    }
}

/// `err` is a failed attach whose `detail` says it handed the front `pid` back, running and
/// unreaped, and the log says the attach failed, not that its identity could not be read: it was
/// verified.
#[cfg(target_os = "macos")]
#[track_caller]
pub(crate) fn assert_attach_failure_left_the_front(err: &Error, text: &str, pid: u32, mark: usize) {
    assert!(
        matches!(err, Error::Containment { .. }),
        "the cause is a Containment: {err:?}"
    );
    assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
    assert!(text.contains("handed back to the caller in the error"), "{text}");
    assert!(
        crate::log_capture::contains_since(mark, "attach failed"),
        "the warning says the attach failed"
    );
    assert!(
        !crate::log_capture::contains_since(mark, "could not be read"),
        "the identity was read, so the log must not say it was not"
    );
}

/// macOS: a front whose attach fails (which only a seam makes it do) is sent nothing and, still
/// running, handed back in the error, not killed like another child; the error keeps its variant and
/// says so.
///
/// Mutant: the arm kills and reaps it as any child.
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_front_whose_attach_fails_is_handed_back_and_noted() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (err, detail, id, fate) = fail_a_front_spawn(|_| {}, fail_the_attach, |cmd| cmd.spawn().map(drop));
    // The attach comes after the identity read, so the front is named by it.
    assert_eq!(
        fate,
        crate::error::ChildFate::Running { id: Some(id) },
        "the front is left running"
    );
    assert_attach_failure_left_the_front(&err, &detail, id.pid(), mark);
}

/// macOS: what became of a front is what the teardown's own look at it finds, not what the identity
/// check said: a check forced to find the front gone, while it still runs, leaves a front that is
/// looked at, found running, and handed back.
///
/// Mutant: the check's verdict is the front's fate (`Gone`), and the running front is dropped.
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_front_the_identity_check_called_gone_is_looked_at_and_handed_back() {
    let (_, detail, _id, fate) = fail_a_front_spawn(|_| {}, identity_finds_the_front_gone, |cmd| cmd.spawn().map(drop));
    assert_eq!(
        fate,
        crate::error::ChildFate::Running { id: None },
        "the front still runs"
    );
    assert!(detail.contains("handed back to the caller in the error"), "{detail}");
}

/// While it lives, this thread's identity checks find the spawned child gone.
#[cfg(target_os = "macos")]
pub(crate) fn identity_finds_the_front_gone() -> IdentityFindsGone {
    crate::child::spawn::fault::set_force_identity_vanished(true);
    IdentityFindsGone
}

/// Finds identities gone until dropped (see [`identity_finds_the_front_gone`]).
#[cfg(target_os = "macos")]
#[must_use = "identity checks succeed again as soon as the guard is dropped"]
pub(crate) struct IdentityFindsGone;

#[cfg(target_os = "macos")]
impl Drop for IdentityFindsGone {
    fn drop(&mut self) {
        crate::child::spawn::fault::set_force_identity_vanished(false);
    }
}

/// macOS: a spawn whose own read of the front's unique-id report fails cannot adopt it, and leaves
/// it as any unadopted child: sent nothing, and unreaped. The error, its variant kept, says so. The
/// `cat`'s stdin is a pipe this test owns, so the front is shown unsignalled by its exit.
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_front_whose_report_read_fails_is_left_and_noted() {
    let (err, detail, id, fate) = fail_a_front_spawn(|_| {}, fail_the_report_read, |cmd| cmd.spawn().map(drop));
    // No unique id was read, so no identity names it.
    assert_eq!(
        fate,
        crate::error::ChildFate::Running { id: None },
        "the front is left running"
    );
    assert_unadopted_front_noted(&err, &detail, id.pid());
}

/// macOS: a contained spawn whose check of the front's identity is refused (`Unknown`) cannot attach
/// its marker, which needs the identity, so it fails the attach with the read's error and tears the
/// front down as every front is: sent nothing, and looked at. The refusal is forced to last into that
/// look too (a peek row of the spawn's kernel), which cannot say whether the front exited, so the
/// front is handed back, its fate unknown, and the error says so. (An uncontained front is kept, with
/// no identity.)
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_contained_front_whose_identity_is_refused_is_handed_back_and_noted() {
    use crate::identity::{FakeKernel, HostKernel};
    let kernel = std::sync::Arc::new(FakeKernel::over(&HostKernel));
    let (err, detail, id, fate) = fail_a_front_spawn(
        |cmd| _ = cmd.contain(),
        || refuse_the_identity(&kernel),
        |cmd| crate::child::spawn::identity_macos_tests::spawn_over(cmd, std::sync::Arc::clone(&kernel)).map(drop),
    );
    assert!(
        kernel.all_rows_taken(),
        "the teardown's look at the front was the refused one"
    );
    assert!(
        matches!(err, Error::Unassessable { .. }),
        "the cause is the identity's Unassessable: {err:?}"
    );
    assert_eq!(fate, crate::error::ChildFate::Unknown, "the look at the front failed");
    assert!(
        detail.contains(&format!("pid {} is what sudo left", id.pid())),
        "{detail}"
    );
    assert!(
        detail.contains("could not be waited on") && detail.contains("handed back to the caller in the error"),
        "{detail}"
    );
}

/// While it lives, this thread's reads of a spawned child's own unique-id report fail.
#[cfg(target_os = "macos")]
pub(crate) fn fail_the_report_read() -> crate::child::spawn::unique_report::seams::FailedParentRead {
    crate::child::spawn::unique_report::seams::fail_parent_read(libc::EIO)
}

/// While it lives, this thread's reads of a spawned child's identity are refused: the spawn's own
/// check (`Unknown`), and, as a row of `kernel` stated once the child has a pid, the next peek of it.
#[cfg(target_os = "macos")]
pub(crate) fn refuse_the_identity(kernel: &std::sync::Arc<crate::identity::FakeKernel<'static>>) -> RefusedIdentity {
    use crate::child::spawn::fault::{set_at, spawn_pid, SpawnPoint};
    crate::child::spawn::fault::set_force_identity_unknown(true);
    let kernel = std::sync::Arc::clone(kernel);
    RefusedIdentity(set_at(SpawnPoint::BeforeIdentity, move || {
        kernel.state_peek(spawn_pid(), Err(std::io::Error::from_raw_os_error(libc::EPERM)));
    }))
}

/// Refuses identity reads until dropped (see [`refuse_the_identity`]).
#[cfg(target_os = "macos")]
#[must_use = "identity reads succeed again as soon as the guard is dropped"]
pub(crate) struct RefusedIdentity(#[allow(dead_code, reason = "held for its drop")] crate::oneshot_hook::Armed);

#[cfg(target_os = "macos")]
impl Drop for RefusedIdentity {
    fn drop(&mut self) {
        crate::child::spawn::fault::set_force_identity_unknown(false);
    }
}

/// Spawns, through `spawn` and with `force` armed, a `cat` front, `configure`d, whose stdin is a pipe this function
/// owns, and returns the spawn's cause and `detail` with the front's pid once the front has been shown
/// to end unsignalled, after its stdin closed.
#[cfg(target_os = "macos")]
pub(crate) fn fail_a_front_spawn<G>(
    configure: impl FnOnce(&mut Command),
    force: impl FnOnce() -> G,
    spawn: impl FnOnce(&mut Command) -> Result<(), Error>,
) -> (Error, String, crate::identity::ProcessId, crate::error::ChildFate) {
    use std::os::fd::OwnedFd;

    use crate::child::spawn::fault;
    let (reader, writer) = std::io::pipe().expect("pipe");
    let mut cmd = cat();
    cmd.stdin(Stdio::from_file(std::fs::File::from(OwnedFd::from(reader))))
        .expect("stdin");
    cmd.set_elevation_report(sudo_report());
    configure(&mut cmd);
    let err = {
        let _forced = force();
        spawn(&mut cmd).expect_err("the forced failure fails the spawn")
    };
    // Every failure this forces comes after the front ran.
    let detail = crate::test_child::detail_of(&err);
    // A front still running is handed back in the error, with `writer` to release it by; one the spawn
    // could not adopt is left, and reaped here.
    let (err, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, writer);
    let crate::identity::Resolved::Found(id) = fault::take_captured().expect("the spawn captured the child") else {
        panic!("the spawn must capture a resolved identity");
    };
    let status = if handed_back.is_none() {
        drop(handed_back);
        reap(id.pid()).expect("the front was left unreaped")
    } else {
        handed_back.wait()
    };
    assert!(status.success(), "the front was signalled: {status:?}");
    (err, detail, id, fate)
}

/// `err`, the cause, is an `Unassessable`, and `text`, the `detail`, notes that the front `pid` is left
/// unreaped.
#[cfg(target_os = "macos")]
#[track_caller]
pub(crate) fn assert_unadopted_front_noted(err: &Error, text: &str, pid: u32) {
    assert!(
        matches!(err, Error::Unassessable { .. }),
        "the cause is an Unassessable: {err:?}"
    );
    assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
    assert!(
        text.contains("the elevated program may be running; left unreaped"),
        "{text}"
    );
}