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
//! The shared decisions of [`super::tree_call`], driven directly: [`PidfdShutdown`]'s outcomes
//! (Linux), and [`root_number`] over every input it reads.
//!
//! [`PidfdShutdown`]: crate::child::PidfdShutdown

use super::{root_number, RootNumber};
use crate::containment::Attached;
use crate::identity::{ProcessId, Resolved};
use crate::signal::RootState;
#[cfg(target_os = "linux")]
use crate::test_groups::{pidfd_group_signal, Group};

/// A pgid no test process holds: the decisions only name it in their text.
const PGID: i32 = 999_999;

// PidfdShutdown -----

#[cfg(target_os = "linux")]
mod pidfd_shutdown {
    use std::cell::RefCell;

    use super::PGID;
    use crate::child::{PidfdShutdown, TreeCall};
    use crate::containment::dispatch::TreeSignal;
    use crate::containment::{Attached, TreeKilled};
    use crate::elevation::front::Gate;
    use crate::error::Error;
    use crate::log_capture::warns_since;
    use crate::signal::Sent;
    use crate::test_child::reaped_elsewhere::{ROOT_KILLED_BY_PIDFD, ROOT_TERMED_BY_PIDFD};

    const WHY: &str = "the root's own handle could not say";

    fn graceful_call<'a>(attached: &'a Attached, killed: &'a TreeKilled) -> TreeCall<'a> {
        TreeCall {
            attached,
            pid: PGID as u32,
            signal: TreeSignal::Term,
            op: "graceful_shutdown_tree",
            earlier: None,
            killed,
        }
    }

    fn unkillable(what: &str) -> Error {
        Error::Elevation {
            kind: crate::error::ElevationErrorKind::Unkillable,
            detail: what.into(),
        }
    }

    /// One run: `term` answers the `SIGTERM`, `exited` the grace (`None`: the grace is not asked),
    /// `kill_gate` and `kill` the escalation. Returns the error, what was sent, and the warns.
    fn run(
        gate: Gate,
        term: Result<Sent, Error>,
        exited: Option<Result<bool, &'static str>>,
        kill_gate: Gate,
        kill: Result<Sent, Error>,
    ) -> (Error, Vec<&'static str>, Vec<String>) {
        crate::log_capture::install();
        let attached = Attached::ProcessGroup(PGID);
        let killed = TreeKilled::default();
        let call = graceful_call(&attached, &killed);
        let sent = RefCell::new(Vec::new());
        let mark = crate::log_capture::mark();
        let shutdown = match PidfdShutdown::start(gate, || {
            sent.borrow_mut().push("term");
            term
        }) {
            Ok(shutdown) => shutdown,
            Err(e) => return (e, sent.into_inner(), warns_since(mark, "")),
        };
        // A grace the row does not answer reads as an exit, so a wrongly waited one shows in `sent`.
        let waited = shutdown.needs_grace().then(|| {
            sent.borrow_mut().push("grace");
            exited.unwrap_or(Ok(true))
        });
        let err = shutdown.finish(
            &call,
            WHY,
            waited,
            || kill_gate,
            || {
                sent.borrow_mut().push("kill");
                kill
            },
        );
        (err, sent.into_inner(), warns_since(mark, ""))
    }

    /// Mutant: `start` ignores a closed gate.
    #[skuld::test]
    fn a_front_the_sigterm_may_not_reach_is_refused_with_nothing_sent() {
        let (err, sent, warns) = run(
            Gate::Closed(unkillable("osascript")),
            Ok(Sent::Delivered),
            Some(Ok(true)),
            Gate::Open,
            Ok(Sent::Delivered),
        );
        assert!(
            matches!(&err, Error::Elevation { detail, .. } if detail == "osascript"),
            "{err:?}"
        );
        assert_eq!(sent, Vec::<&str>::new());
        assert_eq!(warns, Vec::<String>::new());
    }

    /// Mutant: a failed grace wait read as an exit (no kill).
    #[skuld::test]
    fn a_failed_grace_wait_kills_the_root_at_once() {
        crate::log_capture::install();
        let mark = crate::log_capture::mark();
        let (err, sent, warns) = run(
            Gate::Open,
            Ok(Sent::Delivered),
            Some(Err("forced wait failure")),
            Gate::Open,
            Ok(Sent::Delivered),
        );
        assert!(matches!(err, Error::Unassessable { .. }), "{err:?}");
        assert_eq!(sent, ["term", "grace", "kill"]);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(warns[0].contains(ROOT_KILLED_BY_PIDFD), "{warns:?}");
        let debug = crate::log_capture::records_since_on_current_thread(mark, "grace wait failed");
        assert_eq!(debug.len(), 1, "{debug:?}");
        assert_eq!(debug[0].0, log::Level::Debug, "{debug:?}");
        assert!(debug[0].1.contains("forced wait failure"), "{debug:?}");
    }

    /// Mutant: the escalation ignores a closed kill gate.
    #[skuld::test]
    fn a_front_the_kill_may_not_reach_is_refused_after_the_grace() {
        let (err, sent, warns) = run(
            Gate::Open,
            Ok(Sent::Delivered),
            Some(Ok(false)),
            Gate::Closed(unkillable("sudo")),
            Ok(Sent::Delivered),
        );
        assert!(
            matches!(&err, Error::Elevation { detail, .. } if detail == "sudo"),
            "{err:?}"
        );
        assert_eq!(sent, ["term", "grace"]);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(
            warns[0].contains("then the kill of the root through its pidfd failed"),
            "{warns:?}"
        );
    }

    /// Mutant: the grace waited, or the kill sent, after a failed `SIGTERM`.
    #[skuld::test]
    fn a_failed_sigterm_waits_no_grace_and_is_the_error() {
        let (err, sent, warns) = run(
            Gate::Open,
            Err(Error::Io(std::io::Error::other("forced term failure"))),
            None,
            Gate::Open,
            Ok(Sent::Delivered),
        );
        assert!(
            matches!(&err, Error::Io(e) if e.to_string() == "forced term failure"),
            "{err:?}"
        );
        assert_eq!(sent, ["term"]);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(
            warns[0].contains("sent nothing: the SIGTERM to the root through its pidfd failed (forced term failure)"),
            "{warns:?}"
        );
    }

    /// A `SIGTERM` that finds the root gone, or a handle that no longer reaches it (a tokio backend
    /// forgotten unproven holds no pidfd), waits no grace and sends no kill.
    ///
    /// Mutant: the grace waited for anything but a delivered `SIGTERM`.
    #[skuld::test]
    fn a_sigterm_that_reached_nothing_waits_no_grace() {
        for (term, says) in [
            (Sent::Gone, "sent nothing: the root's pidfd shows it is gone"),
            (Sent::Unverified, "sent nothing: the root's handle no longer reaches it"),
        ] {
            let (err, sent, warns) = run(Gate::Open, Ok(term), None, Gate::Open, Ok(Sent::Delivered));
            assert!(matches!(err, Error::Unassessable { .. }), "{says}: {err:?}");
            assert_eq!(sent, ["term"], "{says}");
            assert_eq!(warns.len(), 1, "{says}: {warns:?}");
            assert!(warns[0].contains(says), "{warns:?}");
            assert!(!warns[0].contains(ROOT_TERMED_BY_PIDFD), "{warns:?}");
        }
    }

    /// Mutant: a kill that found the root gone reported as a kill.
    #[skuld::test]
    fn a_kill_that_finds_the_root_gone_says_so() {
        let (err, sent, warns) = run(
            Gate::Open,
            Ok(Sent::Delivered),
            Some(Ok(false)),
            Gate::Open,
            Ok(Sent::Gone),
        );
        assert!(matches!(err, Error::Unassessable { .. }), "{err:?}");
        assert_eq!(sent, ["term", "grace", "kill"]);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(
            warns[0].contains("its pidfd showed it gone after the grace"),
            "{warns:?}"
        );
        assert!(!warns[0].contains(ROOT_KILLED_BY_PIDFD), "{warns:?}");
    }
}

// root_number -----

/// What `root_number` answered, in a comparable shape.
#[derive(Debug, PartialEq, Eq)]
enum Answer {
    Trusted,
    Empty,
    #[cfg(target_os = "macos")]
    Untrusted,
    #[cfg(target_os = "macos")]
    NoWalk,
    /// `MayNameAnother`, with `exact_root` and a phrase its `why` contains.
    MayNameAnother(bool, &'static str),
}

/// The state a row hands `root_number`, built fresh per call (`RootState` holds an `io::Error`).
#[derive(Debug, Clone, Copy)]
enum State {
    Unreaped,
    Reaped,
    Unknown,
    #[cfg(target_os = "macos")]
    Unpinned,
}

fn answer(attached: &Attached, state: State, own: bool, read: Resolved<ProcessId>) -> (Answer, bool) {
    let _read = crate::child::fault::force_root_reads(read);
    let looked = std::cell::Cell::new(false);
    let number = root_number(attached, PGID as u32, || {
        looked.set(true);
        match state {
            State::Unreaped => RootState::Unreaped,
            State::Reaped => RootState::Reaped { own },
            State::Unknown => RootState::Unknown(std::io::Error::other("forced")),
            #[cfg(target_os = "macos")]
            State::Unpinned => RootState::Unpinned,
        }
    });
    let answer = match number {
        RootNumber::Trusted => Answer::Trusted,
        RootNumber::Empty => Answer::Empty,
        #[cfg(target_os = "macos")]
        RootNumber::Untrusted(_) => Answer::Untrusted,
        #[cfg(target_os = "macos")]
        RootNumber::NoWalk => Answer::NoWalk,
        #[cfg(target_os = "linux")]
        RootNumber::GroupGone => panic!("only a tree call's look through the root's pidfd answers GroupGone"),
        RootNumber::MayNameAnother { why, exact_root } => {
            let phrase = ["could not be read", "was reaped elsewhere", "could not say whether it"]
                .into_iter()
                .find(|phrase| why.contains(phrase))
                .unwrap_or_else(|| panic!("an unexpected reason: {why}"));
            Answer::MayNameAnother(exact_root, phrase)
        }
    };
    (answer, looked.get())
}

/// `root_number` over every state, own-reap flag and identity read, for a process group (which
/// reaches its tree through the root's number) and a `TreeWalk` (which checks for itself). The
/// identity read matters only after this handle's own reap.
///
/// Mutants: any one arm of `root_number` answering another row's value; the look taken for a
/// mechanism that does not need it (off macOS).
#[skuld::test]
fn root_number_answers_each_state_own_reap_and_identity_read() {
    let other = || ProcessId::from_parts_for_test(PGID as u32, crate::identity::Key::for_test(1));
    let reads = || [Resolved::Gone, Resolved::Found(other()), Resolved::Unknown];
    let group = Attached::ProcessGroup(PGID);
    // macOS trusts no number its root's handle cannot vouch for, before the mechanism matters.
    #[cfg(target_os = "macos")]
    let unknown_answer = Answer::Untrusted;
    #[cfg(not(target_os = "macos"))]
    let unknown_answer = Answer::MayNameAnother(cfg!(target_os = "linux"), "could not say whether it");
    for own in [false, true] {
        for (i, read) in reads().into_iter().enumerate() {
            let case = format!("own: {own}, read #{i}");
            assert_eq!(
                answer(&group, State::Unreaped, own, read),
                (Answer::Trusted, true),
                "unreaped, {case}"
            );
        }
        for (i, read) in reads().into_iter().enumerate() {
            let case = format!("own: {own}, read #{i}");
            assert_eq!(
                answer(&group, State::Unknown, own, read).0,
                unknown_answer,
                "unknown, {case}"
            );
        }
    }
    for read in reads() {
        assert_eq!(
            answer(&group, State::Reaped, false, read).0,
            Answer::MayNameAnother(false, "was reaped elsewhere"),
            "reaped elsewhere"
        );
    }
    // This handle's own reap: the pid names nothing (the group's id while a member survives), names
    // another process (so the group is empty), or cannot be read.
    let [gone, found, unknown] = reads();
    assert_eq!(
        answer(&group, State::Reaped, true, gone).0,
        Answer::Trusted,
        "own reap, gone"
    );
    assert_eq!(
        answer(&group, State::Reaped, true, found).0,
        Answer::Empty,
        "own reap, found"
    );
    assert_eq!(
        answer(&group, State::Reaped, true, unknown).0,
        Answer::MayNameAnother(false, "could not be read"),
        "own reap, unreadable"
    );

    // A `TreeWalk` checks for itself.
    let walk = Attached::TreeWalk(other());
    for state in [State::Unreaped, State::Reaped, State::Unknown] {
        for own in [false, true] {
            for read in reads() {
                let (answer, looked) = answer(&walk, state, own, read);
                #[cfg(not(target_os = "macos"))]
                assert_eq!((answer, looked), (Answer::Trusted, false), "{state:?}, own: {own}");
                #[cfg(target_os = "macos")]
                {
                    let expected = match state {
                        State::Unknown => Answer::Untrusted,
                        _ => Answer::Trusted,
                    };
                    assert_eq!((answer, looked), (expected, true), "{state:?}, own: {own}");
                }
            }
        }
    }
}

/// macOS: an `Unpinned` root is `Untrusted` for a `TreeWalk` and a process group alike, whatever
/// the own-reap flag and the identity read.
///
/// Mutant: `Unpinned` left out of the macOS answer that comes before the mechanism is asked.
#[cfg(target_os = "macos")]
#[skuld::test]
fn root_number_answers_an_unpinned_root_untrusted() {
    let other = || ProcessId::from_parts_for_test(PGID as u32, crate::identity::Key::for_test(1));
    for (name, attached) in [
        ("tree walk", Attached::TreeWalk(other())),
        ("group", Attached::ProcessGroup(PGID)),
    ] {
        for own in [false, true] {
            for read in [Resolved::Gone, Resolved::Found(other()), Resolved::Unknown] {
                assert_eq!(
                    answer(&attached, State::Unpinned, own, read),
                    (Answer::Untrusted, true),
                    "{name}, own: {own}"
                );
            }
        }
    }
}

// group_number_holds -----

/// A send by the group's number is allowed only while the root is unreaped, or after this handle's
/// own reap with its pid naming no process. Mutant: "a root reaped elsewhere, or one its handle
/// cannot answer for, passes the check".
#[skuld::test]
fn group_number_holds_only_for_an_unreaped_root_or_a_free_number_after_its_own_reap() {
    use super::group_number_holds;
    let own = std::process::id();
    assert_eq!(group_number_holds(own, RootState::Unreaped), Ok(()));
    let refused = [
        (RootState::Reaped { own: false }, "reaped elsewhere"),
        (
            RootState::Unknown(std::io::Error::other("a failed peek")),
            "a failed peek",
        ),
        (RootState::Unpinned, "not pinned"),
        // This process holds its own pid, so the number names another process than the root.
        (RootState::Reaped { own: true }, "another process holds"),
    ];
    for (state, why) in refused {
        let label = format!("{state:?}");
        let err = group_number_holds(own, state).expect_err(&label);
        assert!(err.contains(why), "{label}: {err}");
    }
}

/// `group_number_holds` reads `own` from the state: a reap by someone else refuses whatever the
/// pid's identity read says, and an own reap is decided by that read. Mutant: "`own` is ignored".
#[skuld::test]
fn group_number_holds_reads_own_from_the_state() {
    use super::group_number_holds;
    let other = || ProcessId::from_parts_for_test(PGID as u32, crate::identity::Key::for_test(1));
    let reads = || [Resolved::Gone, Resolved::Found(other()), Resolved::Unknown];
    for read in reads() {
        let _read = crate::child::fault::force_root_reads(read);
        let err = group_number_holds(PGID as u32, RootState::Reaped { own: false }).expect_err("reaped elsewhere");
        assert!(err.contains("reaped elsewhere"), "{err}");
    }
    let _gone = crate::child::fault::force_root_reads(Resolved::Gone);
    assert_eq!(group_number_holds(PGID as u32, RootState::Reaped { own: true }), Ok(()));
    drop(_gone);
    let _found = crate::child::fault::force_root_reads(Resolved::Found(other()));
    let err = group_number_holds(PGID as u32, RootState::Reaped { own: true }).expect_err("another process holds");
    assert!(err.contains("another process holds"), "{err}");
    drop(_found);
    let _unknown = crate::child::fault::force_root_reads(Resolved::Unknown);
    let err = group_number_holds(PGID as u32, RootState::Reaped { own: true }).expect_err("unreadable");
    assert!(err.contains("could not be read"), "{err}");
}

// through_the_pidfd -----

/// Linux 6.9+: a reaped root's group with no member left has no tree to signal, but a root its
/// handle cannot answer for may have left its group alive, so it keeps the reason it may name
/// another process. Mutant: "a group with no member left is gone whatever the root's state".
#[cfg(target_os = "linux")]
#[skuld::test]
fn through_the_pidfd_keeps_a_root_its_handle_cannot_answer_for(#[fixture(pidfd_group_signal)] _group: &Group) {
    use std::os::fd::AsFd as _;
    use std::os::unix::process::CommandExt as _;
    let mut lone = crate::test_spawn::spawn(std::process::Command::new("true").process_group(0)).expect("spawn");
    let pidfd = crate::containment::cgroup::test_support::pidfd_of(lone.id());
    lone.wait().expect("reap it");
    let passes = || Ok(());
    let group = crate::containment::GroupRoot::new(Some(pidfd.as_fd()), &passes);
    let attached = Attached::ProcessGroup(PGID);
    let decide = |exact_root| {
        super::through_the_pidfd(
            &attached,
            RootNumber::MayNameAnother {
                why: "forced".to_owned(),
                exact_root,
            },
            &group,
        )
    };
    assert!(matches!(decide(false), RootNumber::GroupGone));
    assert!(matches!(
        decide(true),
        RootNumber::MayNameAnother { exact_root: true, .. }
    ));
}