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
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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
//! Forced kills of a front in a cgroup: the cgroup lane (the `cgroup` group, as root). The front is
//! an ordinary child reported as launched by `sudo`.
//!
//! A cgroup kill reaches a member whatever its credentials, and nothing is signalled after it: with
//! direct exec the tracked process is the root program, which refuses the caller's signal. That case
//! is real here. The front runs as `nobody`, and the test thread drops `CAP_KILL` from its
//! effective set, so a signal to the front fails with `EPERM` while the `cgroup.kill` write, a file
//! write, still succeeds.

use std::cell::{Cell, RefCell};

use crate::test_child::Console;
use std::io::Read as _;

use crate::{PipeReader, PipeWriter};
use std::os::fd::{AsFd as _, OwnedFd};
use std::os::unix::process::ExitStatusExt as _;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use crate::child::front_kill_tests::{
    assert_ends_unsignalled, assert_reaped_unsignalled, assert_refused_by, assert_unkillable_front, cat, spawn_as,
};
use crate::child::owned::seams::record_root_teardowns;
use crate::command::Command;
use crate::elevation::{Backend, ElevatedVia};
use crate::os_process::fake::ReapAnswer;
use crate::test_groups::{cgroup, Group};
use crate::{ContainMode, Containment, Stdio};

pub(crate) const SUDO: ElevatedVia = ElevatedVia::Wrapped(Backend::Sudo);

/// A forced kill of a child: `kill` or `kill_tree`.
type Kill = fn(&crate::Child) -> Result<(), crate::error::Error>;

/// `cmd`, contained in a cgroup.
pub(crate) fn in_cgroup(mut cmd: Command) -> Command {
    cmd.contain_with(ContainMode::Strongest);
    cmd
}

/// A `cat` that runs as `nobody` in a cgroup, reported as launched by `sudo`: a front whose signal a
/// thread without `CAP_KILL` is refused. Returns once it runs as `nobody`.
pub(crate) fn nobody_cat() -> Command {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args([
        "setpriv",
        "--reuid=65534",
        "--regid=65534",
        "--clear-groups",
        "sh",
        "-c",
        "echo ready; exec cat",
    ]);
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    in_cgroup(cmd)
}

/// Spawns [`nobody_cat`] as a `sudo` front, and waits for its `ready`.
fn spawn_nobody_front() -> (crate::Child, PipeWriter) {
    let (mut child, stdin) = spawn_as(nobody_cat(), SUDO);
    assert_eq!(child.containment(), Containment::CgroupV2);
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    assert_eq!(&ready, b"ready\n");
    (child, stdin)
}

/// While it lives, this thread has no `CAP_KILL` in its effective set: its signal to another user's
/// process is refused. Capabilities are per thread, so the test's own thread is the only one
/// affected; the guard puts the capability back.
#[must_use = "the capability returns as soon as the guard is dropped"]
pub(crate) struct WithoutKillCap(rustix::thread::CapabilitySets);

impl WithoutKillCap {
    /// Drops `CAP_KILL`, and asserts a signal to `pid`, another user's process, is now refused.
    pub(crate) fn refusing(pid: u32) -> WithoutKillCap {
        use rustix::thread::{capabilities, set_capabilities, CapabilitySet};
        let saved = capabilities(None).expect("capget");
        assert!(
            saved.effective.contains(CapabilitySet::KILL),
            "the cgroup lane runs as root, with CAP_KILL: {saved:?}"
        );
        let mut without = saved;
        without.effective.remove(CapabilitySet::KILL);
        set_capabilities(None, without).expect("capset without CAP_KILL");
        let guard = WithoutKillCap(saved);
        let target = rustix::process::Pid::from_raw(pid as i32).expect("a positive pid");
        assert_eq!(
            rustix::process::test_kill_process(target),
            Err(rustix::io::Errno::PERM),
            "the front {pid} must refuse this thread's signal"
        );
        guard
    }
}

impl Drop for WithoutKillCap {
    fn drop(&mut self) {
        rustix::thread::set_capabilities(None, self.0).expect("capset to restore CAP_KILL");
    }
}

/// A pidfd for `pid`, an unreaped child of this process, to read its end without reaping it.
pub(crate) fn pidfd_of(pid: u32) -> OwnedFd {
    let pid = rustix::process::Pid::from_raw(pid as i32).expect("a positive pid");
    rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).expect("pidfd_open")
}

/// Whether the child `pidfd` names has been reaped, by anyone. Consumes nothing.
pub(crate) fn reaped(pidfd: &OwnedFd) -> bool {
    loop {
        match rustix::process::waitid(
            rustix::process::WaitId::PidFd(pidfd.as_fd()),
            rustix::process::WaitIdOptions::EXITED
                | rustix::process::WaitIdOptions::NOHANG
                | rustix::process::WaitIdOptions::NOWAIT,
        ) {
            Ok(_) => return false,
            Err(rustix::io::Errno::CHILD) => return true,
            Err(rustix::io::Errno::INTR) => {}
            Err(e) => panic!("waitid on a pidfd: {e}"),
        }
    }
}

/// The signal that ended the child `pidfd` names, or `None` if it exited by itself, read without
/// reaping it. Blocks until it has ended, so only for a child whose end is certain: one that has
/// just been released.
fn end_signal(pidfd: &OwnedFd) -> Option<i32> {
    loop {
        match rustix::process::waitid(
            rustix::process::WaitId::PidFd(pidfd.as_fd()),
            rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOWAIT,
        ) {
            Ok(Some(status)) => return status.terminating_signal(),
            Ok(None) => unreachable!("a blocking waitid returns a status"),
            Err(rustix::io::Errno::INTR) => {}
            Err(e) => panic!("waitid on the pidfd of a child nothing has reaped: {e}"),
        }
    }
}

/// An observed child's pid and the signal that ended it, if one did.
type EndedBy = (u32, Option<i32>);

/// What the release saw: whether it ran as a `cgroup.kill` write returned (and not at a wait), and
/// how each observed child ended.
type Released = (bool, Vec<EndedBy>);

/// The release, until it runs.
type Once = Box<dyn FnOnce()>;

/// Releases `held` at the first of: a successful `cgroup.kill` write returning on this thread, the
/// drain wait about to block, or the child wait after a kill taken as delivered
/// (`set_between_kill_and_wait`). A kill that sent nothing then makes the fixture end by itself, so
/// the test fails by assertion. The children [`observe`](Self::observe)d are then waited for
/// unreaped and their ends recorded for [`assert_killed`](Self::assert_killed). A delivered
/// `SIGKILL` is already pending, so it beats the release.
///
/// The wait seam is one-shot, so a test that needs it for anything else gives that to
/// [`release_by_cgroup_kill_and_at_wait`] instead of arming it beside this.
///
/// A child that the teardown reaps cannot have its status read afterwards, so it must be observed.
/// Only a child that ends once `held` is dropped may be: the hook waits for it.
#[must_use = "dropping this disarms the release"]
pub(crate) struct KillRelease {
    _after_write: crate::oneshot_hook::Armed,
    _before_drain: crate::oneshot_hook::Armed,
    _before_wait: crate::oneshot_hook::Armed,
    observed: Rc<RefCell<Vec<(u32, OwnedFd)>>>,
    ended: Rc<RefCell<Option<Released>>>,
}

/// Arms a [`KillRelease`] of `held`.
pub(crate) fn release_after_cgroup_kill(held: impl Sized + 'static) -> KillRelease {
    release_by_cgroup_kill(move || drop(held))
}

/// Arms a [`KillRelease`] that runs `release`.
pub(crate) fn release_by_cgroup_kill(release: impl FnOnce() + 'static) -> KillRelease {
    release_by_cgroup_kill_and_at_wait(release, || {})
}

/// Arms a [`KillRelease`] that runs `release`, and runs `at_wait` as well when the teardown is about to
/// block on its child: for a test whose teardown must not wait there, and releases what such a wait
/// would then end, so that a wait fails the test instead of hanging it.
pub(crate) fn release_by_cgroup_kill_and_at_wait(
    release: impl FnOnce() + 'static,
    at_wait: impl FnOnce() + 'static,
) -> KillRelease {
    let observed: Rc<RefCell<Vec<(u32, OwnedFd)>>> = Rc::default();
    let ended = Rc::new(RefCell::new(None));
    let release: Rc<Cell<Option<Once>>> = Rc::new(Cell::new(Some(Box::new(release))));
    // The three points share one release: whichever is reached first runs it, and the others find it gone.
    let fire: Rc<dyn Fn(bool)> = {
        let (observed, ended) = (Rc::clone(&observed), Rc::clone(&ended));
        Rc::new(move |by_write| {
            let Some(release) = release.take() else {
                return;
            };
            release();
            let how = observed
                .borrow()
                .iter()
                .map(|(pid, pidfd)| (*pid, end_signal(pidfd)))
                .collect();
            *ended.borrow_mut() = Some((by_write, how));
        })
    };
    let after_write = crate::containment::cgroup::fault::set_after_kill_write({
        let fire = Rc::clone(&fire);
        move || fire(true)
    });
    let before_drain = crate::containment::cgroup::fault::set_before_drain_block({
        let fire = Rc::clone(&fire);
        move || fire(false)
    });
    let before_wait = crate::child::spawn::fault::set_between_kill_and_wait({
        let fire = Rc::clone(&fire);
        move || {
            at_wait();
            fire(false);
        }
    });
    KillRelease {
        _after_write: after_write,
        _before_drain: before_drain,
        _before_wait: before_wait,
        observed,
        ended,
    }
}

impl KillRelease {
    /// Watches the child `pid`, which must not be reaped before the release.
    pub(crate) fn observe(&self, pid: u32) {
        self.observed.borrow_mut().push((pid, pidfd_of(pid)));
    }

    /// The kill was written before the teardown's waits, and each child observed died of
    /// `SIGKILL`, not by itself once released. With no child observed it proves only the first,
    /// so the test also checks what the tree's other members did.
    #[track_caller]
    pub(crate) fn assert_killed(&self) {
        let ended = self.ended.borrow();
        let (by_write, ended) = ended
            .as_ref()
            .expect("the teardown released its holder, at the cgroup kill or before its drain wait");
        assert!(*by_write, "cgroup.kill was written before the teardown's waits");
        for (pid, signal) in ended {
            assert_eq!(
                *signal,
                Some(libc::SIGKILL),
                "pid {pid} must die of the cgroup kill, not exit by itself once released"
            );
        }
    }
}

/// Moves `pid` out of its leaf into this process's own cgroup, as pam_systemd moves sudo into a
/// session scope. The lane's cgroup enables no controllers, so it may hold processes.
pub(crate) fn move_out_of_its_leaf(pid: u32) {
    let own = std::fs::read_to_string("/proc/self/cgroup").expect("read /proc/self/cgroup");
    let path = own
        .lines()
        .find_map(|line| line.strip_prefix("0::"))
        .expect("a cgroup v2 `0::` line");
    let procs = format!("/sys/fs/cgroup{path}/cgroup.procs");
    std::fs::write(&procs, pid.to_string()).unwrap_or_else(|e| panic!("move {pid} into {procs}: {e}"));
}

/// The cgroup directory `pid` is in.
pub(crate) fn cgroup_dir_of(pid: u32) -> String {
    let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the cgroup");
    let path = own
        .lines()
        .find_map(|line| line.strip_prefix("0::"))
        .expect("a cgroup v2 `0::` line");
    format!("/sys/fs/cgroup{path}")
}

/// Moves `pid` from its leaf into a new cgroup beside it, named as the leaf with ` (deleted)` after
/// it, as `/proc` prints the leaf once it is removed.
pub(crate) fn move_into_a_namesake_of_its_leaf(pid: u32) {
    let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the front's cgroup");
    let leaf = own
        .lines()
        .find_map(|line| line.strip_prefix("0::"))
        .expect("a cgroup v2 `0::` line");
    let namesake = format!("/sys/fs/cgroup{leaf} (deleted)");
    std::fs::create_dir(&namesake).unwrap_or_else(|e| panic!("make {namesake}: {e}"));
    std::fs::write(format!("{namesake}/cgroup.procs"), pid.to_string())
        .unwrap_or_else(|e| panic!("move {pid} into {namesake}: {e}"));
}

/// Moves `pid` from its leaf into a cgroup two levels under it, `a/b`, as a program may make one,
/// and returns that cgroup's directory.
pub(crate) fn move_under_its_leaf(pid: u32) -> String {
    let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the front's cgroup");
    let leaf = own
        .lines()
        .find_map(|line| line.strip_prefix("0::"))
        .expect("a cgroup v2 `0::` line");
    let nested = format!("/sys/fs/cgroup{leaf}/a/b");
    std::fs::create_dir_all(&nested).unwrap_or_else(|e| panic!("make {nested}: {e}"));
    std::fs::write(format!("{nested}/cgroup.procs"), pid.to_string())
        .unwrap_or_else(|e| panic!("move {pid} into {nested}: {e}"));
    nested
}

/// The kill goes through `cgroup.kill`, and sends the front nothing after it.
#[skuld::test]
fn cgroup_kill_of_a_front_goes_through_the_cgroup_alone(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    assert_eq!(child.containment(), Containment::CgroupV2);
    let sent = crate::send_log::Capture::start();
    child.kill().expect("the cgroup kill reaches the program");
    assert_eq!(sent.entries(), [], "nothing is signalled after it");
    drop(sent);
    assert!(child.tree_killed.is_set(), "the kill must go through the cgroup");
    // 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));
}

/// `kill_tree` likewise.
#[skuld::test]
fn cgroup_kill_tree_of_a_front_goes_through_the_cgroup_alone(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let sent = crate::send_log::Capture::start();
    child.kill_tree().expect("the cgroup kill reaches the program");
    assert_eq!(sent.entries(), [], "nothing is signalled after it");
    drop(sent);
    assert!(child.tree_killed.is_set());
    // 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));
}

/// The drop kills the front through the cgroup and reaps it, sending it nothing.
#[skuld::test]
fn cgroup_drop_of_a_front_kills_it_through_the_cgroup_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let teardowns = record_root_teardowns();
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = child.pid();
    let pidfd = pidfd_of(pid);
    // Released as the kill returns; see [`KillRelease`].
    let release = release_after_cgroup_kill(stdin);
    release.observe(pid);
    let mark = crate::log_capture::mark();
    drop(child);
    release.assert_killed();
    assert_eq!(teardowns.count(), 0, "the drop sends the front no kill of its own");
    assert!(reaped(&pidfd), "the drop reaps the front its cgroup kill ended");
    let said = crate::log_capture::records_since_on_current_thread(mark, "Child::drop");
    assert_said_reaped_at_debug(&said, pid, "a front the cgroup killed is not left behind");
}

/// A drop's records about the front `pid` it reaped with its status: none above `debug`, and the
/// reap itself said once, at `debug`, led by the drop's name ("after the kill" only if the look found
/// the front still running and waited for it, which the first look does not always find).
#[track_caller]
fn assert_said_reaped_at_debug(said: &[(log::Level, String)], pid: u32, what: &str) {
    let reaped = format!("Child::drop: elevation front pid {pid}: reaped it");
    let reaped_after_the_kill = format!("{reaped} after the kill");
    assert!(
        said.iter().all(|(level, _)| *level >= log::Level::Debug),
        "{what}: a record above debug: {said:?}"
    );
    let reaps: Vec<_> = said
        .iter()
        .filter(|(_, text)| *text == reaped || *text == reaped_after_the_kill)
        .collect();
    assert_eq!(reaps.len(), 1, "{what}: the reap is said once: {said:?}");
}

/// A failed cgroup kill may leave the program running, so the front is not signalled either.
#[skuld::test]
fn cgroup_a_failed_kill_of_a_front_leaves_the_front_alone(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    {
        let _failing = crate::containment::cgroup::fault::fail_kill_writes();
        crate::child::front_kill_tests::assert_refused_by(child.kill(), "its cgroup kill failed");
        crate::child::front_kill_tests::assert_refused_by(child.kill_tree(), "its cgroup kill failed");
    }
    assert_ends_unsignalled(&child, stdin);
}

/// The drop, too, leaves a front alone when its cgroup kill fails.
#[skuld::test]
fn cgroup_a_failed_drop_kill_of_a_front_leaves_the_front_alone(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let teardowns = record_root_teardowns();
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let crate::containment::Attached::Cgroup(leaf) = &child.attached else {
        panic!("expected a cgroup leaf, got {:?}", child.attached);
    };
    let leaf = leaf.path().to_path_buf();
    let pid = child.pid();
    let mark = crate::log_capture::mark();
    let stdin = Rc::new(std::cell::Cell::new(Some(stdin)));
    {
        let _failing = crate::containment::cgroup::fault::fail_kill_writes_releasing_on_unwritten_kill({
            let stdin = Rc::clone(&stdin);
            move || drop(stdin.take())
        });
        drop(child);
    }
    let stdin = stdin.take().expect("released only before a failure");
    let warns = crate::log_capture::warns_since(mark, "Child::drop");
    assert_eq!(warns.len(), 1, "one warn for the one event: {warns:?}");
    assert!(
        warns[0].contains("contained-tree teardown did not fully succeed") && warns[0].contains("elevation front pid"),
        "the failed kill and the front are in it: {warns:?}"
    );
    assert_eq!(teardowns.count(), 0, "the drop must not kill or reap the front");
    drop(stdin);
    assert_reaped_unsignalled(pid);
    // The failed kill left the leaf behind; it is empty now.
    std::fs::remove_dir(&leaf).unwrap_or_else(|e| panic!("remove the leaf {}: {e}", leaf.display()));
}

/// The shell of a [`spawn_front_with_member`] tree: a member that reads the pipe on its fd 2, and
/// prints `eof` if that ends it, then the front. A member a kill ended prints nothing.
pub(crate) const FRONT_WITH_MEMBER_SH: &str = "{ cat <&2 2>&- && echo eof; } & echo $!; exec cat";

/// A `cat` front contained and reported as launched by `sudo`, plus a leaf member: a shell running a
/// `cat` on its own pipe that prints `eof` if the `cat` ends by itself (a killed one prints nothing).
/// See [`assert_nothing_ended_by_itself`].
pub(crate) struct FrontWithMember {
    pub(crate) child: crate::Child,
    pub(crate) stdin: PipeWriter,
    pub(crate) member_stdin: PipeWriter,
    /// A pidfd of the member's shell, not a child of this process.
    pub(crate) member: OwnedFd,
    /// The tree's stdout, past the member's pid; every member of the tree holds its write end.
    pub(crate) stdout: PipeReader,
}

/// Spawns a [`FrontWithMember`], once the member has said its pid.
pub(crate) fn spawn_front_with_member() -> FrontWithMember {
    let (member_reader, member_stdin) = std::io::pipe().expect("pipe");
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["sh", "-c", FRONT_WITH_MEMBER_SH]);
    cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
    cmd.stderr(Stdio::from_file(std::fs::File::from(OwnedFd::from(member_reader))))
        .expect("stderr");
    let (mut child, stdin) = spawn_as(in_cgroup(cmd), SUDO);
    let mut line = Vec::new();
    let mut stdout = child.stdout().expect("stdout pipe");
    let mut byte = [0u8; 1];
    while stdout.read_exact(&mut byte).is_ok() && byte[0] != b'\n' {
        line.push(byte[0]);
    }
    let member: u32 = String::from_utf8(line)
        .expect("utf8")
        .trim()
        .parse()
        .expect("the member's pid");
    FrontWithMember {
        child,
        stdin,
        member_stdin: member_stdin.into(),
        member: pidfd_of(member),
        stdout,
    }
}

/// The tree's `stdout` has ended, every member gone, and no member said `eof`: each was killed
/// by a signal, not by itself.
#[track_caller]
pub(crate) fn assert_nothing_ended_by_itself(rest: &[u8]) {
    assert!(
        rest.is_empty(),
        "a member ended by itself, so the kill did not reach it: {}",
        String::from_utf8_lossy(rest)
    );
}

/// Blocks until the process `pidfd` names (it need not be a child) has exited. Only for a process
/// whose kill has been shown to have been written, so the wait is for the kill's effect.
pub(crate) fn wait_until_exited(pidfd: &OwnedFd) {
    let mut fds = [rustix::event::PollFd::from_borrowed_fd(
        pidfd.as_fd(),
        rustix::event::PollFlags::IN,
    )];
    crate::wait::poll_ready(&mut fds).expect("poll the pidfd");
}

/// What a drop that keeps its leaf armed does with a front in the leaf: the leaf's kill ends the
/// front and every other member, the drop reaps the front (a later `waitid` on its pidfd finds
/// nothing to wait for), says so at `debug` with how it died, and never says the front is left
/// running. `fault` arms whatever made the drop's own look at the front fail.
#[track_caller]
fn assert_drop_kills_the_leaf_and_reaps_the_front(fault: impl FnOnce() -> Box<dyn std::any::Any>) {
    crate::log_capture::install();
    let FrontWithMember {
        mut child,
        stdin,
        member_stdin,
        member,
        mut stdout,
    } = spawn_front_with_member();
    let front = pidfd_of(child.pid());
    let pid = child.pid();
    // Released as the kill returns; see [`KillRelease`].
    let release = release_after_cgroup_kill((stdin, member_stdin));
    release.observe(pid);
    // Before Linux 6.19 a task leaves its cgroup before it can be collected, so a front the leaf's
    // kill ended may still read as running at the look: the look awaits its end, but only once the
    // kill was written. A failed kill would otherwise hang the look; the assertions below fail on
    // the missing write instead.
    let awaited = Arc::new(AtomicBool::new(false));
    crate::containment::cgroup::fault::record_leaf_steps();
    child.proc.script_over(|fake| fake).on_look({
        let awaited = Arc::clone(&awaited);
        move |_| {
            if crate::containment::cgroup::fault::peek_leaf_steps()
                .iter()
                .any(|step| step == "kill")
            {
                crate::test_child::wait_until_zombie(pid);
                awaited.store(true, Ordering::SeqCst);
            }
        }
    });
    let mark = crate::log_capture::mark();
    {
        let _fault = fault();
        drop(child);
    }
    let steps = crate::containment::cgroup::fault::take_leaf_steps();
    release.assert_killed();
    assert!(
        awaited.load(Ordering::SeqCst),
        "some look came after the leaf's kill was written, and awaited the front's end"
    );
    let said =
        crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
    assert_said_reaped_at_debug(&said, pid, "a front reaped with its status needs no warn");
    assert!(reaped(&front), "the drop reaps the front its leaf's kill ended");
    assert!(steps.iter().any(|s| s == "kill"), "{steps:?}");
    wait_until_exited(&member);
    let mut rest = Vec::new();
    stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
    assert_nothing_ended_by_itself(&rest);
}

/// A drop whose placement read fails (so it cannot tell the front is in its leaf) still lets the
/// armed leaf kill the leaf, front included, and reaps the front after the leaf's drain. Mutants:
/// "the drop disarms the leaf" (the front survives), "the drop does not reap".
#[skuld::test]
fn cgroup_a_drop_whose_placement_read_fails_kills_the_leaf_and_reaps_the_front(#[fixture(cgroup)] _group: &Group) {
    assert_drop_kills_the_leaf_and_reaps_the_front(|| Box::new(crate::containment::cgroup::fault::fail_pidfd_info()));
}

/// A drop whose kill landed but whose reach cannot be read: the front is looked at once the leaf
/// has drained, found exited, and reaped. Mutant: "the drop warns the front is not reached without
/// looking".
#[skuld::test]
fn cgroup_a_drop_whose_post_kill_read_fails_reaps_the_front_the_kill_ended(#[fixture(cgroup)] _group: &Group) {
    assert_drop_kills_the_leaf_and_reaps_the_front(|| {
        let unreadable = std::rc::Rc::new(std::cell::RefCell::new(None));
        let arming = crate::containment::cgroup::fault::set_before_kill_write({
            let unreadable = std::rc::Rc::clone(&unreadable);
            move || *unreadable.borrow_mut() = Some(crate::containment::cgroup::fault::fail_pidfd_info())
        });
        let running = crate::elevation::front::seams::read_front_running_at_every_reach_read();
        Box::new((arming, running, unreadable))
    });
}

/// What a drop does with a front its leaf's kill ended, when the look at its exit still reads it as
/// running, as on a kernel before 6.19, where a killed task leaves its cgroup (ending the leaf's
/// drain) before it can be collected: its place says it is dying, so it is waited for and reaped,
/// and never called running. Neither the drain nor the look's hook waits for it. Mutant: "the look
/// trusts the exit alone" (the warning then says it is left running, and nothing reaps it).
///
/// The one `cgroup.kill` write lands, but the drop cannot read whether it reached the front (the
/// place read fails from the write on), so the front is looked at after the leaf's teardown, as the
/// first look finds the place readable again.
#[skuld::test]
fn cgroup_a_drop_places_a_front_that_reads_as_running_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault;

    crate::log_capture::install();
    let FrontWithMember {
        mut child,
        stdin,
        member_stdin,
        member,
        mut stdout,
    } = spawn_front_with_member();
    let pid = child.pid();
    let front = pidfd_of(pid);
    let release = release_after_cgroup_kill((stdin, member_stdin));
    release.observe(pid);
    let unreadable = Arc::new(std::sync::Mutex::new(None));
    fault::record_leaf_steps();
    // The look reads the front as running, as on a kernel before 6.19. A look after the kill finds
    // the place readable again; one before it (none is known) would find it as it was.
    child
        .proc
        .script_over(|fake| fake.reaps([ReapAnswer::Running]))
        .on_look({
            let unreadable = Arc::clone(&unreadable);
            move |_| {
                if fault::peek_leaf_steps().iter().any(|step| step == "kill") {
                    drop(unreadable.lock().expect("lock").take());
                }
            }
        });
    let mark = crate::log_capture::mark();
    {
        let _arming = fault::set_before_kill_write({
            let unreadable = Arc::clone(&unreadable);
            move || *unreadable.lock().expect("lock") = Some(fault::fail_pidfd_info())
        });
        let _running = crate::elevation::front::seams::read_front_running_at_every_reach_read();
        drop(child);
    }
    fault::take_leaf_steps();
    release.assert_killed();
    let said =
        crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
    assert_said_reaped_at_debug(&said, pid, "a front reaped with its status needs no warn");
    assert!(reaped(&front), "the drop reaps the front");
    wait_until_exited(&member);
    let mut rest = Vec::new();
    stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
    assert_nothing_ended_by_itself(&rest);
}

/// The same front whose place cannot be read (its pidfd's cgroup id fails) is not called running,
/// nor waited for: one warning says where it is cannot be read. Mutant: "an unreadable place is
/// taken for running".
#[skuld::test]
fn cgroup_a_drop_that_cannot_place_a_front_does_not_call_it_running(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let FrontWithMember {
        mut child,
        stdin,
        member_stdin,
        member,
        mut stdout,
    } = spawn_front_with_member();
    let pid = child.pid();
    let release = release_after_cgroup_kill((stdin, member_stdin));
    release.observe(pid);
    // The look reads the front as running, as on a kernel before 6.19.
    child.proc.script_over(|fake| fake.reaps([ReapAnswer::Running]));
    let mark = crate::log_capture::mark();
    {
        let _unreadable = crate::containment::cgroup::fault::fail_pidfd_info();
        drop(child);
    }
    release.assert_killed();
    let said =
        crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
    assert_eq!(said.len(), 1, "{said:?}");
    assert_eq!(said[0].0, log::Level::Warn, "{said:?}");
    assert!(said[0].1.contains("cannot be read"), "{said:?}");
    assert!(!said[0].1.contains("left running"), "{said:?}");
    // The leaf's kill ended it, and the drop left it unreaped.
    crate::child::front_kill_tests::reap(pid);
    wait_until_exited(&member);
    let mut rest = Vec::new();
    stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
    assert_nothing_ended_by_itself(&rest);
}

/// A front outside its leaf (moved out) is left running, with the warning true: the look finds it
/// running. The rest of the leaf is killed all the same, since the leaf stays armed. Mutants: "the
/// drop disarms the leaf" (the member survives), "the drop never looks" (no warning).
#[skuld::test]
fn cgroup_drop_of_a_front_outside_its_leaf_leaves_it_running_and_kills_the_rest(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let FrontWithMember {
        child,
        stdin,
        member_stdin,
        member,
        mut stdout,
    } = spawn_front_with_member();
    let pid = child.pid();
    move_out_of_its_leaf(pid);
    // The member is released as the kill returns (see [`KillRelease`]), the front at the wait a drop
    // makes for a front it places in its leaf, which this one is not in: a drop that waited for it
    // would end it and fail the warning below.
    let stdin = Rc::new(std::cell::Cell::new(Some(stdin)));
    let release = release_by_cgroup_kill_and_at_wait(move || drop(member_stdin), {
        let stdin = Rc::clone(&stdin);
        move || drop(stdin.take())
    });
    crate::containment::cgroup::fault::record_leaf_steps();
    let mark = crate::log_capture::mark();
    drop(child);
    let steps = crate::containment::cgroup::fault::take_leaf_steps();
    let said =
        crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
    assert_eq!(said.len(), 1, "{said:?}");
    assert_eq!(said[0].0, log::Level::Warn);
    assert!(said[0].1.contains("is left running and unreaped"), "{said:?}");
    assert!(steps.iter().any(|s| s == "kill"), "the leaf was killed: {steps:?}");
    release.assert_killed();
    wait_until_exited(&member);
    drop(stdin.take().expect("the drop must not wait for the front"));
    assert_reaped_unsignalled(pid);
    let mut rest = Vec::new();
    stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
    assert_nothing_ended_by_itself(&rest);
}

/// A front whose signal is refused (direct exec: the root program) is still killed, through the
/// cgroup, and `kill`/`kill_tree` answer `Ok`.
#[skuld::test]
fn cgroup_kill_of_a_front_that_refuses_signals_is_ok(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_nobody_front();
    {
        let _refusing = WithoutKillCap::refusing(child.pid());
        child.kill().expect("the cgroup kill ends the front");
        child.kill_tree().expect("the cgroup kill ends the front");
    }
    // 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));
}

/// The drop of such a front kills it through the cgroup and reaps it, warning of nothing.
#[skuld::test]
fn cgroup_drop_of_a_front_that_refuses_signals_reaps_it(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let (child, stdin) = spawn_nobody_front();
    let pidfd = pidfd_of(child.pid());
    let release = release_after_cgroup_kill(stdin);
    release.observe(child.pid());
    let mark = crate::log_capture::mark();
    {
        let _refusing = WithoutKillCap::refusing(child.pid());
        drop(child);
    }
    release.assert_killed();
    assert!(reaped(&pidfd), "the drop reaps the front its cgroup kill ended");
    let warns = crate::log_capture::records_since_on_current_thread(mark, "could not be terminated");
    assert_eq!(warns, [], "nothing was refused");
}

/// A failed password write's teardown of such a front says it was terminated.
#[skuld::test]
fn cgroup_a_failed_password_write_terminates_a_front_that_refuses_signals(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_nobody_front();
    let pid = child.pid();
    let _refusing = WithoutKillCap::refusing(pid);
    let reaps = crate::child::spawn::fault::record_teardown_reaps();
    // Closed at the teardown's wait: a front nothing killed then exits 0, and the status below fails.
    let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(stdin)));
    let _released = crate::child::spawn::fault::set_between_kill_and_wait({
        let stdin = std::rc::Rc::clone(&stdin);
        move || drop(stdin.take())
    });
    let err = crate::child::spawn::finish_elevated(
        child,
        Err(crate::error::Error::Elevation {
            kind: crate::error::ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
        }),
    )
    .expect_err("a failed write fails the spawn");
    let (err, fate) = err.expect_may_have_started_with();
    assert_eq!(
        fate,
        crate::error::ChildFate::Reaped,
        "the cgroup kill ended the front and the teardown reaped it"
    );
    let rendered = err.to_string();
    assert!(rendered.contains("the elevated child was terminated"), "{rendered}");
    let (_, status) = reaps
        .recorded()
        .into_iter()
        .find(|(reaped, _)| *reaped == pid)
        .expect("the teardown reaped the front");
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "the front ended by the cgroup kill"
    );
}

/// A failed password write whose cgroup kill fails refuses the front's kill as `kill` does,
/// naming the failure, and sends the front nothing. The front is handed back, ends on its stdin,
/// unsignalled, and the leaf the failed kill left behind is removed.
#[skuld::test]
fn cgroup_a_failed_password_write_whose_cgroup_kill_fails_refuses_as_kill_does(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let pid = id.pid();
    let leaf = leaf_of(&child).path().to_path_buf();
    let stdin = Rc::new(std::cell::Cell::new(Some(stdin)));
    let err = {
        let _failing = crate::containment::cgroup::fault::fail_kill_writes_releasing_on_unwritten_kill({
            let stdin = Rc::clone(&stdin);
            move || drop(stdin.take())
        });
        crate::child::spawn::finish_elevated(
            child,
            Err(crate::error::Error::Elevation {
                kind: crate::error::ElevationErrorKind::AuthFailed,
                detail: "forced password-write failure".into(),
            }),
        )
        .expect_err("a failed write fails the spawn")
    };
    let release = stdin.take().expect("the teardown must not release the front");
    let (err, fate, handed_back) = err.expect_may_have_started_parts(release);
    assert_eq!(
        fate,
        crate::error::ChildFate::Running { id: Some(id) },
        "a front its cgroup kill did not end may be running"
    );
    assert_front_refused_by_its_cgroup_kill(&err, pid);
    handed_back.unreaped();
    let status = handed_back.wait();
    assert!(status.success(), "the front was signalled: {status:?}");
    std::fs::remove_dir(&leaf).unwrap_or_else(|e| panic!("remove the leaf {}: {e}", leaf.display()));
}

/// `err`, a failed password write's, says its front `pid` was refused as `kill` refuses a front
/// whose cgroup kill failed.
#[track_caller]
pub(crate) fn assert_front_refused_by_its_cgroup_kill(err: &crate::error::Error, pid: u32) {
    let text = err.to_string();
    assert!(text.contains("the elevated child could not be terminated"), "{text}");
    assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
    assert!(text.contains("no kill was sent"), "{text}");
    assert!(text.contains("(its cgroup kill failed: "), "{text}");
}

/// A front that has left its leaf is out of the cgroup kill's reach: sent nothing, and refused.
#[skuld::test]
fn cgroup_a_front_that_left_its_leaf_is_unkillable_and_sent_nothing(#[fixture(cgroup)] _group: &Group) {
    let teardowns = record_root_teardowns();
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = child.pid();
    move_out_of_its_leaf(pid);
    assert_unkillable_front(child.kill(), pid);
    assert_unkillable_front(child.kill_tree(), pid);
    assert!(!child.tree_killed.is_set(), "no cgroup kill ran");
    drop(child);
    assert_eq!(teardowns.count(), 0, "the drop must not kill or reap the front");
    drop(stdin);
    assert_reaped_unsignalled(pid);
}

/// An exited front has nothing left to orphan, so its kill is `Ok` even though the signal to it, a
/// zombie that keeps its credentials, is refused.
#[skuld::test]
fn cgroup_kill_of_an_exited_front_that_refuses_signals_is_ok(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_nobody_front();
    let pid = child.pid();
    drop(stdin);
    crate::test_child::wait_until_zombie(pid);
    {
        let _refusing = WithoutKillCap::refusing(pid);
        child.kill().expect("an exited front is killed like any exited child");
        child
            .kill_tree()
            .expect("an exited front is killed like any exited child");
    }
    assert!(child.wait().expect("wait").success());
}

/// A front that a session manager moves out of its leaf between the gate and the `cgroup.kill`
/// write was not killed: the kill answers `Unkillable`, read after the write, and the front is sent
/// nothing.
#[skuld::test]
fn cgroup_a_front_moved_out_during_its_kill_is_unkillable(#[fixture(cgroup)] _group: &Group) {
    let kills: [Kill; 2] = [crate::Child::kill, crate::Child::kill_tree];
    for kill in kills {
        let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
        let pid = child.pid();
        let _moving = crate::containment::cgroup::fault::set_before_kill_write(move || move_out_of_its_leaf(pid));
        assert_refused_by(kill(&child), "left the cgroup before its kill");
        assert_ends_unsignalled(&child, stdin);
    }
}

/// The drop of such a front leaves it running and unreaped, and never waits for it. The front's
/// stdin is closed only by a wait's hook, so a drop that waits ends it and reaps it, which the test
/// sees, rather than hanging.
#[skuld::test]
fn cgroup_drop_of_a_front_moved_out_during_its_kill_leaves_it_unreaped(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = child.pid();
    let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(stdin)));
    let _moving = crate::containment::cgroup::fault::set_before_kill_write(move || move_out_of_its_leaf(pid));
    let _released = crate::child::spawn::fault::set_between_kill_and_wait({
        let stdin = std::rc::Rc::clone(&stdin);
        move || drop(stdin.take())
    });
    let mark = crate::log_capture::mark();
    drop(child);
    let warns = crate::log_capture::records_since_on_current_thread(mark, "is left running and unreaped");
    assert_eq!(warns.len(), 1, "{warns:?}");
    drop(stdin.take().expect("the drop must not wait for the front"));
    assert_reaped_unsignalled(pid);
}

/// `kill_tree` asks the gate once: after the cgroup kill a killed front can read as neither exited
/// nor in its cgroup.
#[skuld::test]
fn cgroup_kill_tree_of_a_front_asks_the_gate_once(#[fixture(cgroup)] _group: &Group) {
    let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let gates = crate::elevation::front::seams::count_kill_gates();
    child.kill_tree().expect("kill_tree is accepted");
    assert_eq!(gates.count(), 1);
}

/// A failed password write's teardown asks the gate once, for the same reason. The handle opts out
/// of the drop, whose own teardown would ask again.
#[skuld::test]
fn cgroup_a_failed_password_write_asks_the_gate_once(#[fixture(cgroup)] _group: &Group) {
    let mut cmd = in_cgroup(cat());
    cmd.kill_on_drop(false);
    let (child, stdin) = spawn_as(cmd, SUDO);
    let release = release_after_cgroup_kill(stdin);
    release.observe(child.pid());
    let gates = crate::elevation::front::seams::count_kill_gates();
    let err = crate::child::spawn::finish_elevated(
        child,
        Err(crate::error::Error::Elevation {
            kind: crate::error::ElevationErrorKind::AuthFailed,
            detail: "forced password-write failure".into(),
        }),
    )
    .expect_err("a failed write fails the spawn");
    let (err, fate) = err.expect_may_have_started_with();
    assert_eq!(
        fate,
        crate::error::ChildFate::Reaped,
        "the cgroup kill ended the front and the teardown reaped it"
    );
    assert!(err.to_string().contains("the elevated child was terminated"), "{err}");
    release.assert_killed();
    assert_eq!(gates.count(), 1);
}

/// How a failed spawn's leaf meets its front (see [`failed_held_front_spawns`]).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeafKill {
    /// The leaf's kill lands on the front.
    Lands,
    /// The leaf's `cgroup.kill` write fails.
    Fails,
    /// The front is moved out of its leaf before the leaf's kill, as pam_systemd moves sudo.
    MissesMovedFront,
    /// The front is moved into a cgroup nested under its leaf, which the leaf's kill reaches, and
    /// `/proc` hides it (`hidepid`).
    LandsNestedHidden,
    /// The leaf's kill lands on the front, whose place is read through `/proc` alone (no
    /// `PIDFD_GET_INFO`): once the leaf is removed, `/proc` names it with ` (deleted)`.
    LandsReadThroughProc,
    /// The front is moved into a live cgroup beside its leaf named as `/proc` prints the removed
    /// leaf, and its place is read through `/proc` alone.
    MissesIntoNamesake,
}

/// A failed front spawn: its error, the front's pid, and the front's stdin, which the test holds
/// so that only a kill ends the front. A teardown's wait on the front releases it first (see
/// `set_between_kill_and_wait`), so a wait on a front no kill reached ends it with status 0 instead
/// of hanging.
pub(crate) struct HeldFailure {
    pub(crate) err: crate::error::Error,
    pub(crate) pid: u32,
    /// The identity the spawn had read when it failed: the attach's, and not the identity check's.
    pub(crate) read_id: Option<crate::identity::ProcessId>,
    pub(crate) stdin: std::rc::Rc<std::cell::RefCell<Option<PipeWriter>>>,
}

/// Spawns of a contained `cat` marked as a `sudo` front, through `spawn`, that fail after their
/// fork: once in the attach, once in the identity check, with the leaf's kill meeting the front
/// as `kill` says.
pub(crate) fn failed_held_front_spawns(
    kill: LeafKill,
    spawn: impl Fn(&mut Command) -> Result<(), crate::error::Error>,
) -> [HeldFailure; 2] {
    use std::cell::RefCell;
    use std::rc::Rc;

    use crate::child::spawn::fault;
    let arms: [fn(bool); 2] = [fault::set_force_attach_failure, fault::set_force_identity_vanished];
    let mut arm = 0;
    arms.map(|force_arm| {
        arm += 1;
        let (reader, writer) = std::io::pipe().expect("pipe");
        let stdin = Rc::new(RefCell::new(Some(writer.into())));
        let mut cmd = in_cgroup(cat());
        cmd.stdin(Stdio::from_file(std::fs::File::from(OwnedFd::from(reader))))
            .expect("stdin");
        cmd.set_elevation_front(crate::elevation::front::front(Some(&SUDO)));
        // Releases the front: a teardown's wait on a front no kill reached ends it with status 0,
        // instead of hanging. The seam is one-shot, so each case gives this to the one guard that
        // arms it.
        let release_front = || {
            let stdin = Rc::clone(&stdin);
            move || drop(stdin.borrow_mut().take())
        };
        // A leaf's kill that lands on the front also releases it, and the front's end is read there:
        // a write that sent nothing, or none, ends the front by itself, and `assert_killed` fails,
        // instead of the teardown waiting for the leaf's drain forever. A kill that misses the front
        // must leave it held.
        let lands = matches!(
            kill,
            LeafKill::Lands | LeafKill::LandsNestedHidden | LeafKill::LandsReadThroughProc
        );
        let released_by_the_leaf = lands.then(|| Rc::new(release_by_cgroup_kill(release_front())));
        let _released = (kill == LeafKill::MissesMovedFront).then(|| fault::set_between_kill_and_wait(release_front()));
        // The spawn has returned from std, so the front has run its placement: it is in its leaf.
        // Both failures come after this point.
        // A namesake front leaves the leaf empty, and an empty leaf is removed without a kill: a
        // filler kept in it makes its kill land, so only the record answers for the front. The
        // filler is released as that kill returns.
        let (filler, filler_release) = if kill == LeafKill::MissesIntoNamesake {
            let (filler, filler_stdin) = spawn_as(cat(), SUDO);
            let release = release_by_cgroup_kill_and_at_wait(move || drop(filler_stdin), release_front());
            release.observe(filler.pid());
            (Some(Rc::new(filler)), Some(release))
        } else {
            (None, None)
        };
        // The front is observed before its identity is read, while the spawn still holds it unreaped.
        let _before_identity = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
            let filler = filler.clone();
            let released = released_by_the_leaf.clone();
            move || {
                let pid = fault::spawn_pid();
                if let Some(released) = &released {
                    released.observe(pid);
                }
                match kill {
                    LeafKill::MissesMovedFront => move_out_of_its_leaf(pid),
                    LeafKill::LandsNestedHidden => {
                        move_under_its_leaf(pid);
                    }
                    LeafKill::MissesIntoNamesake => {
                        let leaf = cgroup_dir_of(pid);
                        let filler = filler.as_ref().expect("a filler for the namesake case").pid();
                        std::fs::write(format!("{leaf}/cgroup.procs"), filler.to_string())
                            .unwrap_or_else(|e| panic!("move the filler into {leaf}: {e}"));
                        move_into_a_namesake_of_its_leaf(pid);
                    }
                    LeafKill::Lands | LeafKill::Fails | LeafKill::LandsReadThroughProc => {}
                }
            }
        });
        let _missing = matches!(kill, LeafKill::LandsReadThroughProc | LeafKill::MissesIntoNamesake)
            .then(crate::containment::cgroup::fault::miss_pidfd_info);
        let _hidden = (kill == LeafKill::LandsNestedHidden).then(crate::containment::cgroup::fault::hide_proc);
        let _failing = (kill == LeafKill::Fails)
            .then(|| crate::containment::cgroup::fault::fail_kill_writes_releasing_at_wait(release_front()));
        force_arm(true);
        let result = spawn(&mut cmd);
        force_arm(false);
        if let Some(released) = &released_by_the_leaf {
            released.assert_killed();
        }
        // The filler kept the leaf busy, so the leaf's removal killed through it: the kill landed.
        if let Some((filler, release)) = filler.as_ref().zip(filler_release.as_ref()) {
            release.assert_killed();
            assert_eq!(
                filler.wait().expect("wait").signal(),
                Some(libc::SIGKILL),
                "the leaf's kill"
            );
        }
        let err = result.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");
        };
        HeldFailure {
            err,
            pid: id.pid(),
            // The attach arm comes first, and fails after the identity was read.
            read_id: (arm == 1).then_some(id),
            stdin,
        }
    })
}

/// Each failure notes its front was killed by its leaf and reaped. The front is gone from the test's
/// reach: the teardown's look or wait reaped it, and records no reap of its own;
/// `failed_held_front_spawns` has already seen the leaf's kill end it. Which of the two reaps it is the
/// kernel's timing; `owned_tests::teardown_look::a_running_front_the_kill_reached_is_waited_for_and_reaped`
/// pins the wait.
#[track_caller]
pub(crate) fn assert_killed_by_the_leaf(failures: &[HeldFailure; 2]) {
    for HeldFailure { err, pid, .. } in failures {
        let text = err.to_string();
        assert_eq!(err.fate(), Some(crate::error::ChildFate::Reaped), "{text}");
        assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
        assert!(text.contains("its cgroup's kill ended it, and it was reaped"), "{text}");
        assert_eq!(
            crate::child::front_kill_tests::reap(*pid),
            None,
            "the teardown reaped front {pid}"
        );
    }
}

/// Each failure notes its front was handed back (`handed_back`: the sync spawn) or left unreaped
/// (the async spawn), and the teardown never waited on it: its stdin is still held. Then ends each
/// front by closing its stdin, reaps it, unsignalled, and removes the leaf a failed kill left behind
/// with it.
#[track_caller]
pub(crate) fn assert_left_running(kill: LeafKill, failures: [HeldFailure; 2], handed_back: bool) {
    for HeldFailure {
        err,
        pid,
        read_id,
        stdin,
    } in failures
    {
        let text = err.to_string();
        assert_eq!(
            err.fate(),
            Some(crate::error::ChildFate::Running { id: read_id }),
            "{text}"
        );
        assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
        let left = if handed_back {
            "handed back to the caller in the error"
        } else {
            "left unreaped"
        };
        assert!(
            text.contains(&format!("the elevated program may be running; {left}")),
            "{text}"
        );
        assert!(
            stdin.borrow().is_some(),
            "the teardown waited on front {pid}, which no kill reached"
        );
        // The front's stdin is held by the test (`stdin`), not by the helper.
        let (_, _, held) = crate::test_child::expect_may_have_started_parts(err, ());
        assert_eq!(!held.is_none(), handed_back, "{text}");
        let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the front's cgroup");
        let path = own
            .lines()
            .find_map(|line| line.strip_prefix("0::"))
            .expect("a cgroup v2 `0::` line")
            .to_owned();
        drop(stdin.borrow_mut().take());
        let status = if held.is_none() {
            crate::child::front_kill_tests::reap(pid).expect("the front was left unreaped")
        } else {
            held.wait()
        };
        assert!(status.success(), "front {pid} was signalled: {status:?}");
        // The cgroup the front was left in, if the test made it or a failed kill left it behind.
        if matches!(kill, LeafKill::Fails | LeafKill::MissesIntoNamesake) {
            let left = format!("/sys/fs/cgroup{path}");
            std::fs::remove_dir(&left).unwrap_or_else(|e| panic!("remove {left}: {e}"));
        }
    }
}

/// A failed spawn's teardown drops a contained front's leaf first, whose kill ends it, then looks at
/// it, waits for it through its pidfd if it is still dying, reaps it and says so, on the error it
/// would have returned anyway. The front's stdin stays open, so only the kill ends it.
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_contained_front_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
    let failures = failed_held_front_spawns(LeafKill::Lands, |cmd| cmd.spawn().map(drop));
    assert_killed_by_the_leaf(&failures);
}

/// A failed spawn's front, its place read through `/proc` alone, is killed by its leaf and reaped:
/// once the leaf is removed `/proc` names it with ` (deleted)`, which the place recorded before the
/// removal answers.
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_front_read_through_proc_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
    let failures = failed_held_front_spawns(LeafKill::LandsReadThroughProc, |cmd| cmd.spawn().map(drop));
    assert_killed_by_the_leaf(&failures);
}

/// A failed spawn whose front was moved into a live cgroup named as `/proc` prints the removed leaf
/// hands it back, running. A filler kept in the leaf makes the leaf's kill land, so nothing but the
/// record tells the front from one the kill reached: before the leaf's removal, with the leaf live,
/// the front read the leaf's path with ` (deleted)` after it, so it was recorded outside, and the
/// record answers once the leaf is gone.
#[skuld::test]
fn cgroup_a_failed_spawn_hands_back_a_front_in_a_namesake_of_its_leaf(#[fixture(cgroup)] _group: &Group) {
    let kill = LeafKill::MissesIntoNamesake;
    assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)), true);
}

/// A failed spawn whose leaf's kill fails hands back its front, running: in its leaf, but reached by
/// nothing, so it is not waited for.
#[skuld::test]
fn cgroup_a_failed_spawn_whose_leaf_kill_fails_hands_back_the_front(#[fixture(cgroup)] _group: &Group) {
    let kill = LeafKill::Fails;
    assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)), true);
}

/// A failed spawn whose front was moved out of its leaf hands it back, running: the leaf's kill did
/// not reach it, so it is not waited for.
#[skuld::test]
fn cgroup_a_failed_spawn_hands_back_a_front_moved_out_of_its_leaf(#[fixture(cgroup)] _group: &Group) {
    let kill = LeafKill::MissesMovedFront;
    assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)), true);
}

/// A contained front that outlives the grace is killed through its cgroup alone. Its `cat` ignores
/// `SIGTERM`, so the escalation runs.
#[skuld::test]
fn cgroup_graceful_shutdown_of_a_front_escalates_through_the_cgroup(#[fixture(cgroup)] _group: &Group) {
    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(in_cgroup(cmd), SUDO);
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    // Released once the escalation is over, before the reap inside the call: a kill that sent
    // nothing lets the front end by itself, and the status below fails, instead of the reap hanging.
    let _release = crate::graceful_hooks::release_at(crate::graceful_hooks::HookPoint::BeforeReap, stdin);
    let status = child
        .graceful_shutdown(std::time::Duration::ZERO)
        .expect("the cgroup kill ends the front");
    assert!(child.tree_killed.is_set(), "the escalation must go through the cgroup");
    assert_eq!(status.signal(), Some(libc::SIGKILL));
}

/// A contained front's escalation whose cgroup kill fails is refused as `Unkillable`, naming the
/// failure, and sends the front nothing. Its `cat` ignores `SIGTERM`, so the escalation runs.
#[skuld::test]
fn cgroup_a_failed_escalation_of_a_front_is_unkillable(#[fixture(cgroup)] _group: &Group) {
    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(in_cgroup(cmd), SUDO);
    let mut ready = [0u8; 6];
    child
        .stdout()
        .expect("stdout pipe")
        .read_exact(&mut ready)
        .expect("read `ready`");
    // Released at the wait that follows the escalation, which a swallowed failure would reach: the
    // front then ends by itself, and the refusal below fails, instead of the wait hanging.
    let release = crate::graceful_hooks::release_at(crate::graceful_hooks::HookPoint::BeforeReap, stdin);
    {
        let _failing = crate::containment::cgroup::fault::fail_kill_writes();
        assert_refused_by(
            child.graceful_shutdown(std::time::Duration::ZERO),
            "its cgroup kill failed",
        );
    }
    // Closes the front's stdin: it ends unsignalled.
    drop(release);
    let status = child.wait().expect("wait");
    assert!(status.success(), "the front was signalled: {status:?}");
}

/// A front that exits, and that another thread's `wait` reaps, between the kill gate's read of
/// whether it runs and its read of its cgroup, has exited: `kill` is `Ok`, and sends nothing. The
/// hook between the reads closes the front's stdin, then lets the waiter reap it.
#[skuld::test]
fn cgroup_a_front_reaped_by_a_concurrent_wait_inside_the_gate_has_exited(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
    let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
    let fired = std::rc::Rc::new(std::cell::Cell::new(false));
    std::thread::scope(|scope| {
        let child = &child;
        scope.spawn(move || {
            if go_rx.recv().is_ok() {
                reaped_tx
                    .send(child.wait().map_err(|e| e.to_string()))
                    .expect("report the reap");
            }
        });
        let _between = crate::elevation::front::seams::set_between_gate_reads({
            let fired = std::rc::Rc::clone(&fired);
            move || {
                fired.set(true);
                drop(stdin);
                go_tx.send(()).expect("start the waiter");
                let status = reaped_rx.recv().expect("the waiter reaps").expect("wait");
                assert!(status.success(), "the front ended on its stdin: {status:?}");
            }
        });
        let sent = crate::send_log::Capture::start();
        child.kill().expect("a front that exited is not refused");
        assert_eq!(sent.entries(), [], "nothing is signalled to a reaped front");
        drop(sent);
    });
    assert!(fired.get(), "the hook between the gate's reads ran");
}

/// A front its cgroup kill ended, and that another thread's `wait` reaped before its cgroup is
/// read, was reached: `kill` is `Ok`. The hook after the kill's write lets the waiter reap it.
#[skuld::test]
fn cgroup_a_front_reaped_by_a_concurrent_wait_after_its_kill_was_reached(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
    let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
    let fired = std::rc::Rc::new(std::cell::Cell::new(false));
    std::thread::scope(|scope| {
        let child = &child;
        scope.spawn(move || {
            if go_rx.recv().is_ok() {
                reaped_tx
                    .send(child.wait().map_err(|e| e.to_string()))
                    .expect("report the reap");
            }
        });
        // The check's first read finds the front running, whether or not the kill has ended it by
        // then, so the hook below always runs between the check's reads.
        let _running = crate::elevation::front::seams::read_front_running_at_the_first_reach_read();
        let _between = crate::elevation::front::seams::set_between_reach_reads({
            let fired = std::rc::Rc::clone(&fired);
            move || {
                fired.set(true);
                // The kill was written, so the front dies of it; one the kill missed exits 0 here.
                drop(stdin);
                go_tx.send(()).expect("start the waiter");
                let status = reaped_rx.recv().expect("the waiter reaps").expect("wait");
                assert_eq!(status.signal(), Some(libc::SIGKILL), "the cgroup kill ended the front");
            }
        });
        child
            .kill()
            .expect("a front its kill ended is reached, whoever reaped it");
    });
    assert!(fired.get(), "the hook between the check's reads ran");
}

/// The leaf `child` is contained in.
fn leaf_of(child: &crate::Child) -> &crate::containment::cgroup::CgroupLeaf {
    match &child.attached {
        crate::containment::Attached::Cgroup(leaf) => leaf,
        other => panic!("expected a cgroup leaf, got {other:?}"),
    }
}

/// A front killed through its leaf stays in it, by its pidfd's cgroup id, until it is freed: as a
/// zombie too, and with `/proc` unreadable (`hidepid`).
#[skuld::test]
fn cgroup_a_killed_front_is_placed_in_its_leaf_by_its_pidfd(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = child.pid();
    let release = release_after_cgroup_kill(stdin);
    release.observe(pid);
    child
        .attached
        .hard_kill(&crate::containment::GroupRoot::none())
        .into_result()
        .expect("cgroup.kill");
    release.assert_killed();
    crate::test_child::wait_until_zombie(pid);
    let hidden = crate::containment::cgroup::fault::hide_proc();
    let names = leaf_of(&child).names(pid, child.proc.pidfd());
    drop(hidden);
    assert!(
        names.expect("the pidfd read needs no /proc"),
        "a killed front stays in its leaf"
    );
}

/// Without `PIDFD_GET_INFO` (before 6.13) the place is read through `/proc`, with the same answers.
#[skuld::test]
fn cgroup_without_pidfd_info_a_front_is_placed_through_proc(#[fixture(cgroup)] _group: &Group) {
    let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
    let (killed, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = killed.pid();
    let release = release_after_cgroup_kill(stdin);
    release.observe(pid);
    killed
        .attached
        .hard_kill(&crate::containment::GroupRoot::none())
        .into_result()
        .expect("cgroup.kill");
    release.assert_killed();
    crate::test_child::wait_until_zombie(pid);
    assert!(leaf_of(&killed)
        .names(pid, killed.proc.pidfd())
        .expect("/proc is readable here"));
    let (moved, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
    move_out_of_its_leaf(moved.pid());
    assert!(!leaf_of(&moved)
        .names(moved.pid(), moved.proc.pidfd())
        .expect("/proc is readable here"));
}

/// A front moved out of its leaf is outside it, by its pidfd's cgroup id.
#[skuld::test]
fn cgroup_a_moved_front_is_placed_outside_its_leaf_by_its_pidfd(#[fixture(cgroup)] _group: &Group) {
    let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = child.pid();
    move_out_of_its_leaf(pid);
    let hidden = crate::containment::cgroup::fault::hide_proc();
    let names = leaf_of(&child).names(pid, child.proc.pidfd());
    drop(hidden);
    assert!(
        !names.expect("the pidfd read needs no /proc"),
        "a moved front is outside its leaf"
    );
}

/// A front moved into a cgroup nested under its leaf is in the leaf's subtree: by the walk of the
/// leaf's descendants with `PIDFD_GET_INFO`, whatever `/proc` hides; without it by its path, which a
/// hidden `/proc` does not give (such a host refuses the spawn, see `front_placement`).
#[skuld::test]
fn cgroup_a_front_under_its_leaf_is_placed_by_the_walk(#[fixture(cgroup)] _group: &Group) {
    let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
    let pid = child.pid();
    move_under_its_leaf(pid);
    let names = || leaf_of(&child).names(pid, child.proc.pidfd());
    assert!(names().expect("/proc is readable here"));
    {
        let _hidden = crate::containment::cgroup::fault::hide_proc();
        assert!(names().expect("the walk needs no /proc"), "found by the walk");
        let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
        names().expect_err("a hidden path places nothing");
    }
    // The child's drop kills the leaf, then removes `a/b`, `a` and the leaf.
}

/// A front in a cgroup nested under its leaf, on a host whose `/proc` hides it: its kill goes
/// through the leaf, which reaches it, and is `Ok`, and the front dies of it.
#[skuld::test]
fn cgroup_a_front_nested_under_its_leaf_is_killed_under_hidepid(#[fixture(cgroup)] _group: &Group) {
    let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
    move_under_its_leaf(child.pid());
    {
        let _hidden = crate::containment::cgroup::fault::hide_proc();
        child.kill().expect("the leaf's kill reaches a front nested under it");
    }
    // Closed first: a front nothing killed then exits 0, and the assertion fails.
    drop(stdin);
    let status = child.wait().expect("wait");
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "the front dies of its leaf's kill"
    );
}

/// A failed spawn whose front is nested under its leaf, on a host whose `/proc` hides it: the
/// leaf's kill reaches it, and its sweep removes the nested cgroups before the teardown asks, so the
/// sweep's record places it; the teardown waits for it and reaps it.
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_front_nested_under_its_leaf_under_hidepid(#[fixture(cgroup)] _group: &Group) {
    let failures = failed_held_front_spawns(LeafKill::LandsNestedHidden, |cmd| cmd.spawn().map(drop));
    assert_killed_by_the_leaf(&failures);
}

/// A front in a cgroup under its leaf behind a mount, which the walk cannot list: its place is
/// read through `/proc` instead, and its kill, which reaches it, is `Ok`. The spawning thread has
/// its own mount namespace, the mount's, in which the spawn holds the leaf; the mount is gone with
/// the thread.
#[skuld::test]
fn cgroup_a_front_behind_a_mount_under_its_leaf_is_placed_through_proc(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::dir_walk_tests::{enter_private_mount_ns, TmpfsOver};
    std::thread::scope(|scope| {
        scope
            .spawn(|| {
                enter_private_mount_ns();
                let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
                let nested = std::path::PathBuf::from(move_under_its_leaf(child.pid()));
                let mounted_on = nested.parent().expect("`a`, under the leaf");
                let killed = {
                    let _mounted = TmpfsOver::new(mounted_on);
                    child.kill()
                };
                killed.expect("a front /proc places under its leaf was reached");
                // Closed first: a front nothing killed then exits 0, and the assertion fails.
                drop(stdin);
                let status = child.wait().expect("wait");
                assert_eq!(
                    status.signal(),
                    Some(libc::SIGKILL),
                    "the front dies of its leaf's kill"
                );
            })
            .join()
            .expect("the spawning thread");
    });
}

/// Where a front is when its leaf records its place, before the leaf's removal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RecordCase {
    /// In a live cgroup beside the leaf named as `/proc` prints the removed leaf.
    Namesake,
    /// In the leaf itself, which the leaf's drop kills.
    Leaf,
    /// In the namesake, with the read of whether the leaf is live failing (`EMFILE`).
    NamesakeLivenessUnread,
    /// In the leaf, killed through it, and the leaf removed by someone else before its drop, so the
    /// front's zombie reads the leaf's path with ` (deleted)` after it.
    LeafRemovedFirst,
}

/// A leaf records its watched front's place just before its removal: outside for a front in a
/// live namesake of the removed leaf, read while the leaf is live; inside for a front in the leaf.
/// Nothing is recorded where the path is undecidable: the leaf's liveness cannot be read, or the
/// leaf is already gone.
#[skuld::test]
fn cgroup_a_leaf_records_its_fronts_place_before_its_removal(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::dir_walk_tests::Scratch;
    crate::log_capture::install();
    let scratch = Scratch::new("record");
    let cgroup_of = |path: &std::path::Path| {
        format!(
            "/{}",
            path.strip_prefix("/sys/fs/cgroup")
                .expect("under the cgroup root")
                .display()
        )
    };
    for (n, case) in [
        RecordCase::Namesake,
        RecordCase::Leaf,
        RecordCase::NamesakeLivenessUnread,
        RecordCase::LeafRemovedFirst,
    ]
    .into_iter()
    .enumerate()
    {
        let leaf_path = scratch.make(&format!("leaf-{n}"));
        let mut leaf = crate::containment::cgroup::test_support::entered_leaf_at(leaf_path.clone());
        leaf.set_cgroup_path_for_test(cgroup_of(&leaf_path));
        let placed = leaf.placed_for_test();
        let (front, stdin) = spawn_as(cat(), SUDO);
        let pid = front.pid();
        leaf.watch_front(pid);
        // A front in the leaf is released as the leaf's drop kills it; see [`KillRelease`].
        let (stdin, release) = if case == RecordCase::Leaf {
            let release = release_after_cgroup_kill(stdin);
            release.observe(pid);
            (None, Some(release))
        } else {
            (Some(stdin), None)
        };
        let namesake = leaf_path.with_file_name(format!("leaf-{n} (deleted)"));
        let in_leaf = matches!(case, RecordCase::Leaf | RecordCase::LeafRemovedFirst);
        if in_leaf {
            std::fs::write(leaf_path.join("cgroup.procs"), pid.to_string()).expect("move the front into the leaf");
        } else {
            std::fs::create_dir(&namesake).expect("make the namesake");
            std::fs::write(namesake.join("cgroup.procs"), pid.to_string()).expect("move the front into the namesake");
        }
        if case == RecordCase::LeafRemovedFirst {
            std::fs::write(leaf_path.join("cgroup.kill"), "1").expect("kill through the leaf");
            // `rmdir` needs `populated 0`, which a waitable zombie does not imply: wait on the
            // leaf's own drain watch (inotify on `cgroup.events`, no timeout) for it.
            assert_eq!(
                leaf.wait_drained(None).expect("wait for the leaf to drain"),
                crate::containment::TreeDrain::AllMembersExited
            );
            std::fs::remove_dir(&leaf_path).expect("remove the drained leaf, as a cgroup manager may");
        }
        let unread = (case == RecordCase::NamesakeLivenessUnread)
            .then(|| crate::containment::cgroup::fault::fail_liveness_read(libc::EMFILE));
        let mark = crate::log_capture::mark();
        // The leaf's drop kills what is in it, and removes it.
        drop(leaf);
        drop(unread);
        if let Some(release) = &release {
            release.assert_killed();
        }
        // An undecided path is the leaf's own path with ` (deleted)` after it, left unrecorded:
        // that, and no other failure of the read, is what leaves no record.
        let unrecorded =
            crate::log_capture::records_since_on_current_thread(mark, "before its leaf's removal cannot be read");
        if matches!(case, RecordCase::NamesakeLivenessUnread | RecordCase::LeafRemovedFirst) {
            assert!(
                unrecorded
                    .iter()
                    .any(|(_, text)| text.contains("is either the removed leaf or a live cgroup of that name")),
                "{case:?}: {unrecorded:?}"
            );
        }
        let expected = match case {
            RecordCase::Namesake => Some(false),
            RecordCase::Leaf => Some(true),
            RecordCase::NamesakeLivenessUnread | RecordCase::LeafRemovedFirst => None,
        };
        assert_eq!(placed.of(pid), expected, "{case:?}");
        drop(stdin);
        let status = front.wait().expect("wait");
        assert_eq!(
            status.signal(),
            in_leaf.then_some(libc::SIGKILL),
            "{case:?}: {status:?}"
        );
        if !in_leaf {
            std::fs::remove_dir(&namesake).expect("remove the namesake");
        }
    }
}

/// Spawns `cmd`, marked as an elevation-derived `sudo` front, through `spawn`, and returns its
/// result with the pid it forked, if it reached its attach.
pub(crate) fn spawn_front_noting_fork<T>(
    mut cmd: Command,
    spawn: impl FnOnce(&mut Command) -> Result<T, crate::error::Error>,
) -> (Result<T, crate::error::Error>, Option<u32>) {
    use crate::child::spawn::fault::{set_at, spawn_pid, SpawnPoint};
    cmd.set_elevation_front(crate::elevation::front::front(Some(&SUDO)));
    let pid = std::rc::Rc::new(std::cell::Cell::new(None));
    let _seen = set_at(SpawnPoint::BeforeAttach, {
        let pid = std::rc::Rc::clone(&pid);
        move || pid.set(Some(spawn_pid()))
    });
    let result = spawn(&mut cmd);
    (result, pid.get())
}

/// `result` is the refusal of a host that cannot place a front, naming `hidepid`, and nothing was
/// forked for it: no front exists to kill, wait for or leave.
#[track_caller]
pub(crate) fn assert_refused_unforked<T: std::fmt::Debug>(result: Result<T, crate::error::Error>, forked: Option<u32>) {
    assert_refused_unforked_naming(result, forked, "hidepid");
}

/// [`assert_refused_unforked`], for a refusal whose detail names `cause`.
#[track_caller]
pub(crate) fn assert_refused_unforked_naming<T: std::fmt::Debug>(
    result: Result<T, crate::error::Error>,
    forked: Option<u32>,
    cause: &str,
) {
    match result {
        Err(crate::error::Error::Unsupported { detail, .. }) => {
            assert!(detail.contains(cause), "{detail}");
            assert!(detail.contains("before anything is spawned"), "{detail}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
    assert_eq!(forked, None, "a refused spawn forks nothing");
}

/// Before 6.13 a host whose `/proc` hides a process this one may not trace cannot place a front
/// after a cgroup kill, so an elevated, cgroup-contained spawn is refused there before anything is
/// forked: whatever a kill on drop, a failing `cgroup.kill` or a front moved out would do to a
/// front, there is none.
#[skuld::test]
fn cgroup_an_unplaceable_front_is_refused_before_its_fork(#[fixture(cgroup)] _group: &Group) {
    let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
    let _hidden = crate::containment::cgroup::fault::hide_proc();
    let _failing = crate::containment::cgroup::fault::fail_kill_writes();
    let mut cmd = in_cgroup(cat());
    cmd.kill_on_drop(true);
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn().map(drop));
    assert_refused_unforked(result, forked);
}

/// A host whose leaves give no cgroup id (`name_to_handle_at` answers `ENOSYS` on a kernel without
/// `CONFIG_FHANDLE`) cannot place a front after a cgroup kill: an elevated, cgroup-contained spawn
/// is refused before anything is forked.
#[skuld::test]
fn cgroup_a_front_whose_leaf_gives_no_id_is_refused_before_its_fork(#[fixture(cgroup)] _group: &Group) {
    let _no_id = crate::containment::cgroup::fault::fail_cgroup_id(libc::ENOSYS);
    let mut cmd = in_cgroup(cat());
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn().map(drop));
    assert_refused_unforked_naming(result, forked, "name_to_handle_at");
}

/// The refusal is decided before the fork with fds 0 and 1 closed too, where std's spawn returns
/// before the child's `exec`. Runs in a process of its own: closing 0 and 1 is process-wide.
#[skuld::test]
fn cgroup_an_unplaceable_front_is_refused_before_its_fork_with_fds_0_and_1_closed(#[fixture(cgroup)] _group: &Group) {
    use crate::test_own_process::{own_process, test_path};
    use crate::test_spawn::spawn;
    use crate::test_stdio::RestoreStdio;

    let Some(done) = own_process(
        test_path!(cgroup_an_unplaceable_front_is_refused_before_its_fork_with_fds_0_and_1_closed),
        spawn,
    ) else {
        return;
    };
    let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
    let _hidden = crate::containment::cgroup::fault::hide_proc();
    let mut cmd = in_cgroup(cat());
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    let restore = RestoreStdio::close(&done, &[0, 1]);
    let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn().map(drop));
    drop(restore);
    assert_refused_unforked(result, forked);
}

/// A host whose `/proc` shows a process this one may not trace can place a front without
/// `PIDFD_GET_INFO`: the spawn goes on. The cgroup group declares the precondition: the lane runs
/// as root, whose `CAP_SYS_PTRACE` reads a non-dumpable child's cgroup through any `/proc`, even a
/// `hidepid` one.
#[skuld::test]
fn cgroup_a_front_placeable_through_proc_is_not_refused(#[fixture(cgroup)] _group: &Group) {
    let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
    let mut cmd = in_cgroup(cat());
    cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
    let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn());
    let mut child = result.expect("a front /proc shows is placeable");
    assert!(forked.is_some());
    // Released as the kill returns; see [`KillRelease`].
    let release = release_after_cgroup_kill(child.stdin().expect("stdin pipe"));
    release.observe(child.pid());
    drop(child);
    release.assert_killed();
}

/// A `cat` front spawned for a cgroup leaf that does not take it (its placement write is made to
/// fail, so the attach falls back to its process group), with its stdin a pipe the caller owns.
pub(crate) fn front_its_leaf_did_not_take() -> (Command, PipeWriter) {
    let (reader, writer) = std::io::pipe().expect("pipe");
    let mut cmd = in_cgroup(cat());
    cmd.stdin(Stdio::from_file(std::fs::File::from(OwnedFd::from(reader))))
        .expect("stdin");
    cmd.set_elevation_front(crate::elevation::front::front(Some(&SUDO)));
    crate::containment::cgroup::fault::set_force_placement_write_result(0);
    (cmd, writer.into())
}

/// Spawns `cmd`, a front, through `spawn` with its identity check failing (`Gone`), and returns the
/// error with the child's pid and the front it handed back, if it did, with `release` (the front's
/// stdin). The front is still running, and no identity was read for it.
pub(crate) fn fail_the_identity_check<R>(
    cmd: &mut Command,
    spawn: impl FnOnce(&mut Command) -> Result<(), crate::error::Error>,
    release: R,
) -> (crate::error::Error, u32, crate::test_child::HandedBack<R>) {
    use crate::child::spawn::fault;
    fault::set_force_identity_vanished(true);
    let result = spawn(cmd);
    fault::set_force_identity_vanished(false);
    let (err, fate, handed_back) = crate::test_child::expect_may_have_started_parts(
        result.expect_err("the forced identity failure fails the spawn"),
        release,
    );
    assert_eq!(fate, crate::error::ChildFate::Running { id: None }, "{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");
    };
    (err, id.pid(), handed_back)
}

/// `err` notes that the front `pid` is handed back (`handed_back` holds it: the sync spawn) or left
/// unreaped (it holds none: the async spawn), and releasing the front then ends it unsignalled.
#[track_caller]
pub(crate) fn assert_left_unsignalled<R>(
    err: &crate::error::Error,
    pid: u32,
    handed_back: crate::test_child::HandedBack<R>,
) {
    let text = err.to_string();
    assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
    let left = if handed_back.is_none() {
        "left unreaped"
    } else {
        "handed back to the caller in the error"
    };
    assert!(
        text.contains(&format!("the elevated program may be running; {left}")),
        "{text}"
    );
    if handed_back.is_none() {
        drop(handed_back);
        assert_reaped_unsignalled(pid);
    } else {
        let status = handed_back.wait();
        assert!(status.success(), "the front was signalled: {status:?}");
    }
}

/// A front whose leaf did not take it is uncontained: a failed identity check sends it nothing,
/// hands it back, and says so.
#[skuld::test]
fn cgroup_a_front_its_leaf_did_not_take_is_handed_back_by_a_failed_identity_check(#[fixture(cgroup)] _group: &Group) {
    let (mut cmd, stdin) = front_its_leaf_did_not_take();
    let (err, pid, handed_back) = fail_the_identity_check(&mut cmd, |cmd| cmd.spawn().map(drop), stdin);
    assert!(!handed_back.is_none(), "a sync spawn hands the front back");
    assert_left_unsignalled(&err, pid, handed_back);
}

/// A front spawn that cannot capture its leaf's subtree (the cgroup id read fails) says so at
/// `debug`, with the cause: a failed spawn's teardown could not place the front. Mutant: "the
/// error is dropped".
#[skuld::test]
fn cgroup_a_front_spawn_that_cannot_read_its_leaf_subtree_says_why(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (child, stdin) = {
        let _failing = crate::containment::cgroup::fault::fail_subtree(libc::EIO);
        spawn_as(in_cgroup(cat()), SUDO)
    };
    let logs = crate::log_capture::records_since_on_current_thread(mark, "leaf subtree cannot be read");
    assert_eq!(logs.len(), 1, "{logs:?}");
    assert_eq!(logs[0].0, log::Level::Debug);
    assert!(logs[0].1.contains("Input/output error"), "{logs:?}");
    drop(stdin);
    drop(child);
}

/// A failed spawn's settled verdict for a child its leaf did not take says why at `debug`, with
/// the leaf's diagnosis. Mutant: "the diagnosis is dropped".
#[skuld::test]
fn cgroup_a_failed_spawn_says_why_its_leaf_did_not_take_the_child(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let (mut cmd, stdin) = front_its_leaf_did_not_take();
    let mark = crate::log_capture::mark();
    let (err, pid, handed_back) = fail_the_identity_check(&mut cmd, |cmd| cmd.spawn().map(drop), stdin);
    let logs = crate::log_capture::records_since_on_current_thread(mark, "not placed in its leaf");
    assert_eq!(logs.len(), 1, "{logs:?}");
    assert_eq!(logs[0].0, log::Level::Debug);
    assert!(
        logs[0].1.contains(&format!("child {pid} is not in the leaf cgroup")),
        "{logs:?}"
    );
    assert_left_unsignalled(&err, pid, handed_back);
}