cosca 0.7.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
//! 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`). 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::{Backend, ElevatedStdio, ElevatedVia, ElevationReport};
use crate::error::{ElevationErrorKind, Error};
use crate::os_process::fake::failed_signal;
use crate::signal::Sig;
use crate::{ContainMode, Containment, Stdio};

pub(crate) fn report(via: ElevatedVia) -> Option<ElevationReport> {
    Some(ElevationReport {
        via,
        stripped_env: Vec::new(),
        stdio: ElevatedStdio::Passthrough,
    })
}

/// Spawns `cmd` with a piped stdin, as the front `via` launches, and reported so.
pub(crate) fn spawn_as(mut cmd: Command, via: ElevatedVia) -> (crate::Child, PipeWriter) {
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    cmd.set_elevation_front(crate::elevation::front::front(Some(&via)));
    let mut child = cmd.spawn().expect("spawn");
    child.set_elevation(report(via));
    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());
}

/// 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");
}

/// A front its spawn found is what the gates read, not the elevation report: a child with a report
/// and no front is killed as any child.
#[skuld::test]
fn kill_reads_the_front_its_spawn_found_not_its_report() {
    let mut cmd = cat();
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    let mut child = cmd.spawn().expect("spawn");
    child.set_elevation(report(ElevatedVia::Wrapped(Backend::Sudo)));
    let stdin = child.stdin().expect("stdin pipe");
    child.kill().expect("a child with no front is killed as any child");
    // Closed first: a child nothing killed then exits 0, and the assertion fails.
    drop(stdin);
    assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}

/// 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, 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}");
        assert!(detail.contains(&format!("pid {pid} is what sudo left")), "{detail}");
        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, 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, crate::error::ChildFate, crate::test_child::HandedBack<R>) {
    let (err, fate, handed_back) = crate::child::spawn::finish_elevated(
        child,
        Err(Error::Elevation {
            kind: ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
        }),
    )
    .expect_err("a failed write fails the spawn")
    .expect_may_have_started_parts(release);
    let Error::Elevation { detail, .. } = err else {
        panic!("expected an Elevation error, got {err:?}");
    };
    (detail, 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, 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_ne!(child.containment(), Containment::CgroupV2);
    assert_unkillable_front(child.kill_tree(), child.pid());
    assert_ends_unsignalled(&child, stdin);
}

/// The escalation is the gated kill. 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 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 (err, fate, handed_back) = crate::child::spawn::finish_elevated(
        child,
        Err(Error::Elevation {
            kind: ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
        }),
    )
    .expect_err("a failed write fails the spawn")
    .expect_may_have_started_parts(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: {err}"
    );
    let Error::Elevation { detail, .. } = &err else {
        panic!("expected an Elevation error, got {err:?}");
    };
    assert!(detail.contains("could not be terminated"), "{detail}");
    assert!(
        detail.contains(crate::child::owned::owned_tests::teardown_lines::HANDED_BACK),
        "{detail}"
    );
    assert!(detail.contains(&format!("pid {pid} is what sudo left")), "{detail}");
    // 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(),
        }),
    )
    .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:?}");
}

/// 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, and asks the gate once. 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.
#[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 ask the gate again, 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 gates = crate::elevation::front::seams::count_kill_gates();
    let (err, fate) = crate::child::spawn::finish_elevated(
        child,
        Err(Error::Elevation {
            kind: ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
        }),
    )
    .expect_err("a failed write fails the spawn")
    .expect_may_have_started_with();
    assert_eq!(
        fate,
        crate::error::ChildFate::Reaped,
        "the non-blocking look reaps the exited front"
    );
    assert_eq!(gates.count(), 1, "{err}");
    assert_eq!(fake.signal_calls(), [Sig::Kill], "the refusal was the kill's");
    let Error::Elevation { detail, .. } = &err else {
        panic!("expected an Elevation error, got {err:?}");
    };
    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 (err, fate, handed_back) = crate::child::spawn::finish_elevated(
        child,
        Err(Error::Elevation {
            kind: ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
        }),
    )
    .expect_err("a failed write fails the spawn")
    .expect_may_have_started_parts(());
    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");
    let Error::Elevation { detail, .. } = &err else {
        panic!("expected an Elevation error, got {err:?}");
    };
    assert!(
        detail.contains("(it had already exited): the wait failed: forced reap failure"),
        "{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 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, 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_front(crate::elevation::front::front(Some(&ElevatedVia::Wrapped(
            Backend::Sudo,
        ))));
        force_arm(true);
        let err = spawn(&mut cmd);
        force_arm(false);
        // Both arms come after `exec`.
        let (err, fate, handed_back) =
            crate::test_child::expect_may_have_started_parts(err.expect_err("the forced arm fails the spawn"), ());
        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, 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 keep their variants (an attach's `Containment`, an identity check's `Io`) and
/// carry the front's fate in their text, `fate`.
#[cfg(target_os = "linux")]
#[track_caller]
pub(crate) fn assert_noted(failures: &[(Error, u32, crate::test_child::HandedBack<()>); 2], fate: &str) {
    let [(attach, attach_pid, _), (identity, identity_pid, _)] = failures;
    assert!(
        matches!(attach, Error::Containment { .. }),
        "the attach failure keeps its variant: {attach:?}"
    );
    assert!(
        matches!(identity, Error::Io(_)),
        "the identity failure keeps its variant: {identity:?}"
    );
    for (err, pid) in [(attach, attach_pid), (identity, identity_pid)] {
        let text = err.to_string();
        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 child that is not a front outside a cgroup keeps its refused escalation the raw `Io`, not
/// `Unkillable`. A pkexec child is one, as is any child in a cgroup. Its `SIGTERM` is answered as
/// delivered and its kill is refused, so the escalation runs.
#[skuld::test]
fn graceful_shutdown_of_a_child_that_is_not_a_front_keeps_its_io_refusal() {
    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)]));
    match child.graceful_shutdown(Duration::ZERO) {
        Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e}"),
        other => panic!("expected the raw Io(PermissionDenied), got {other:?}"),
    }
    assert_eq!(
        fake.signal_calls(),
        [Sig::Term, Sig::Kill],
        "the escalation was reached"
    );
    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 that left the front `pid` 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, pid: u32, mark: usize) {
    assert!(matches!(err, Error::Containment { .. }), "the variant is kept: {err:?}");
    let text = err.to_string();
    assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
    assert!(text.contains("; left unreaped"), "{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 left
/// running and unreaped, 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_left_unreaped_and_noted() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (err, 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, id.pid(), mark);
}

/// macOS: an identity check that found the front gone, reaped by someone else, says it could not be
/// waited on, not that it is left unreaped.
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_an_identity_check_that_found_the_front_gone_does_not_claim_it_unreaped() {
    let (err, _id, fate) = fail_a_front_spawn(|_| {}, identity_finds_the_front_gone, |cmd| cmd.spawn().map(drop));
    assert_eq!(
        fate,
        crate::error::ChildFate::Gone,
        "the check found it reaped by someone else"
    );
    assert_noted_unaccounted(&err);
}

/// 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);
    }
}

/// `err` notes a front that could not be waited on, and never says it is left unreaped.
#[cfg(target_os = "macos")]
#[track_caller]
pub(crate) fn assert_noted_unaccounted(err: &Error) {
    let text = err.to_string();
    assert!(text.contains("what sudo left"), "{text}");
    assert!(text.contains("could not be waited on"), "{text}");
    assert!(!text.contains("left unreaped"), "{text}");
}

/// A child left unverified because someone else reaped it is unaccounted for, never "left
/// unreaped"; one whose identity was refused is left unreaped.
#[skuld::test]
fn an_unverified_childs_fate_follows_its_identity() {
    use crate::child::spawn::FrontFate;
    use crate::containment::RootIdentity;
    assert_eq!(FrontFate::of_unverified(RootIdentity::Gone), FrontFate::Unaccounted);
    assert_eq!(FrontFate::of_unverified(RootIdentity::Unknown), FrontFate::LeftUnreaped);
}

/// 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, 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, 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 leaves the
/// front unverified: sent nothing, and unreaped. The error says so, as for a report it could not
/// read. (An uncontained front is kept, with no identity.)
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_contained_front_whose_identity_is_refused_is_left_and_noted() {
    let (err, id, fate) = fail_a_front_spawn(
        |cmd| _ = cmd.contain(),
        refuse_the_identity,
        |cmd| cmd.spawn().map(drop),
    );
    // Its identity is what could not be read.
    assert_eq!(
        fate,
        crate::error::ChildFate::Running { id: None },
        "the front is left running"
    );
    assert_unadopted_front_noted(&err, id.pid());
}

/// 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 the next peek that reads its unique id.
#[cfg(target_os = "macos")]
pub(crate) fn refuse_the_identity() -> RefusedIdentity {
    crate::child::spawn::fault::set_force_identity_unknown(true);
    RefusedIdentity(crate::wait::exit_only::seams::force_peek_once(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::wait::exit_only::seams::Forced,
);

#[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 error 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, 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_front(crate::elevation::front::front(Some(&ElevatedVia::Wrapped(
        Backend::Sudo,
    ))));
    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 (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
    let crate::identity::Resolved::Found(id) = fault::take_captured().expect("the spawn captured the child") else {
        panic!("the spawn must capture a resolved identity");
    };
    drop(writer);
    let status = reap(id.pid()).expect("the front was left unreaped");
    assert!(status.success(), "the front was signalled: {status:?}");
    (err, id, fate)
}

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