cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! The tree walk over `pidfs` ids (and, at the end, `ticks` ids), on a [`FakeKernel`] that states
//! the table. A process's identity
//! (its pidfd's inode) and the start time its `stat` shows are different numbers here, so a wrapper
//! that hands the filter one for the other fails.
//!
//! Rows run on every Linux that has `pidfd_open`; none needs pidfs.

use std::os::fd::OwnedFd;

use rustix::io::Errno;
use rustix::process::Pid;

use crate::error::Error;
use crate::identity::{FakeKernel, HostKernel, Kernel, Key, ProcessId};
use crate::test_child::{blocker_with, StdChild};
use crate::Recursive;

const ROOT: u32 = 4242;
const CHILD: u32 = 4243;
/// The inodes and start times: the child's inode is below the root's start time, and the root
/// started before the child.
const ROOT_INO: u64 = 900;
const CHILD_INO: u64 = 5;
const ROOT_START: u64 = 1_000;
const CHILD_START: u64 = 2_000;

fn stand_in() -> OwnedFd {
    OwnedFd::from(std::fs::File::open("/dev/null").expect("/dev/null opens"))
}

/// `pid`'s `stat`, with parent `ppid` and start time `start`.
fn stat(pid: u32, ppid: u32, start: u64) -> Vec<u8> {
    format!("{pid} (x) S {ppid} {ppid} 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 {start} 0 0").into_bytes()
}

fn root() -> ProcessId {
    ProcessId::from_parts_for_test(ROOT, Key::Pidfs(ROOT_INO))
}

fn child() -> ProcessId {
    ProcessId::from_parts_for_test(CHILD, Key::Pidfs(CHILD_INO))
}

/// A kernel in which `ROOT` has inode `ROOT_INO` and `CHILD` (its child) has `CHILD_INO`, each
/// showing its start time, and which lists those two pids and no other: a walk through it reaches no
/// host process, whichever host pids those numbers are.
fn table() -> FakeKernel<'static> {
    FakeKernel::over(&HostKernel)
        .same_view()
        .on_pids(Ok(&[ROOT, CHILD]))
        .on_pidfd_open(ROOT, Ok(stand_in()))
        .on_pidfs_ino(ROOT, Ok(Some(ROOT_INO)))
        .on_pidfd_open(CHILD, Ok(stand_in()))
        .on_pidfs_ino(CHILD, Ok(Some(CHILD_INO)))
        .on_read(&format!("{ROOT}/stat"), Ok(&stat(ROOT, 1, ROOT_START)))
        .on_read(&format!("{CHILD}/stat"), Ok(&stat(CHILD, ROOT, CHILD_START)))
}

/// The snapshot: the root has a row, as a live root does.
const EDGES: [(u32, u32); 2] = [(ROOT, 1), (CHILD, ROOT)];

/// The members of the walk from `root`, whole subtree. Empty, not an error, for a root that is
/// gone; an error for one that cannot be read.
pub(super) fn descendants(kernel: &dyn Kernel, root: ProcessId, edges: &[(u32, u32)]) -> Result<Vec<ProcessId>, Error> {
    Ok(super::walk_from(kernel, root, edges, Recursive::Yes)?
        .unwrap_or_default()
        .members)
}

/// [`descendants`], one level.
pub(super) fn children_of(
    kernel: &dyn Kernel,
    parent: ProcessId,
    edges: &[(u32, u32)],
) -> Result<Vec<ProcessId>, Error> {
    Ok(super::walk_from(kernel, parent, edges, Recursive::No)?
        .unwrap_or_default()
        .members)
}

/// The resolver hands the filter the child's identity (its inode), and no bound for its children: a
/// Linux walk orders by nothing. Mutants: "the id carries the start time"; "the resolver hands out
/// the start time as a bound".
#[skuld::test]
fn resolve_or_drop_hands_out_a_pidfs_id_and_no_bound() {
    assert_eq!(
        super::resolve_or_drop(&table(), CHILD, root(), None).expect("the child reads"),
        Some((child(), None))
    );
}

#[skuld::test]
fn descendants_and_children_of_keep_the_child_of_a_pidfs_root() {
    assert_eq!(
        descendants(&table(), root(), &EDGES).expect("a readable root"),
        vec![child()]
    );
    assert_eq!(
        children_of(&table(), root(), &EDGES).expect("a readable root"),
        vec![child()]
    );
}

/// A child that started before the root, whose `ppid` names the root while the root holds its pid,
/// is the root's child: the `ppid` read after the root was proved is what counts, and no order of
/// start times is asked. Mutant: "a Linux walk drops a candidate that started before its parent".
#[skuld::test]
fn a_child_that_started_before_a_pidfs_root_is_still_its_child() {
    let kernel = table().on_read(&format!("{CHILD}/stat"), Ok(&stat(CHILD, ROOT, ROOT_START - 500)));
    assert_eq!(descendants(&kernel, root(), &EDGES).unwrap(), vec![child()]);
    assert_eq!(children_of(&kernel, root(), &EDGES).unwrap(), vec![child()]);
}

/// A child whose `stat` names the root but shows no start time is a member, and the walk is
/// complete: no start time is read, so none is missing. Mutant: "a Linux read requires a start time"
/// (the child is unassessed, and `children` errs).
#[skuld::test]
fn a_pidfs_child_whose_stat_shows_no_start_time_is_a_member_of_a_complete_walk() {
    let kernel = table().on_read(&format!("{CHILD}/stat"), Ok(format!("{CHILD} (x) S {ROOT}").as_bytes()));
    for depth in [Recursive::Yes, Recursive::No] {
        let walk = super::walk_from(&kernel, root(), &EDGES, depth)
            .unwrap()
            .expect("the root is live");
        assert_eq!(walk.members, vec![child()], "{depth:?}");
        assert!(walk.unassessed.is_empty(), "{:?}", walk.unassessed);
    }
}

/// A `ticks` root whose `stat`, which proves it, is gone has nothing to walk, and that is not an
/// error.
#[skuld::test]
fn the_walk_of_a_ticks_root_whose_stat_is_gone_is_empty() {
    let kernel = ticks_table(ROOT_START)
        .on_read(&format!("{ROOT}/stat"), Err(libc::ENOENT))
        .on_signal_probe(Pid::from_raw(ROOT as i32).unwrap(), Err(Errno::SRCH));
    assert!(descendants(&kernel, ticks_root(), &EDGES).unwrap().is_empty());
    assert!(children_of(&kernel, ticks_root(), &EDGES).unwrap().is_empty());
}

/// A `ticks` root whose `stat` cannot be read (`hidepid`) is an error, never an empty walk: an
/// empty one would let a caller kill the root and leave its descendants running.
#[skuld::test]
fn the_walk_of_a_ticks_root_whose_stat_cannot_be_read_is_unassessable() {
    let kernel = ticks_table(ROOT_START)
        .on_read(&format!("{ROOT}/stat"), Err(libc::EACCES))
        .on_signal_probe(Pid::from_raw(ROOT as i32).unwrap(), Ok(()));
    for result in [
        descendants(&kernel, ticks_root(), &EDGES),
        children_of(&kernel, ticks_root(), &EDGES),
    ] {
        match result {
            Err(Error::Unassessable { detail, .. }) => {
                assert!(
                    detail.contains(&format!("pid {ROOT} exists but could not be queried")),
                    "{detail}"
                );
            }
            other => panic!("expected Unassessable, got {other:?}"),
        }
    }
}

// The accepted parent is proved again after its child's read =====

const GRAND: u32 = 4244;
const GRAND_INO: u64 = 7;
const GRAND_START: u64 = 3_000;

/// [`table`], and `GRAND` (a child of `CHILD`) with inode `GRAND_INO`.
fn table_with_a_grandchild() -> FakeKernel<'static> {
    table()
        .on_pidfd_open(GRAND, Ok(stand_in()))
        .on_pidfs_ino(GRAND, Ok(Some(GRAND_INO)))
        .on_read(&format!("{GRAND}/stat"), Ok(&stat(GRAND, CHILD, GRAND_START)))
}

const EDGES_WITH_A_GRANDCHILD: [(u32, u32); 3] = [(ROOT, 1), (CHILD, ROOT), (GRAND, CHILD)];

/// The child's `ppid` names the root's number, and only the root's number: after the child's read
/// the number may belong to a process that reaped the root and took it. So the root is proved again
/// then, and a number that opens to another inode is not the root. Mutant: "the parent is not
/// proved again".
#[skuld::test]
fn a_child_read_after_its_parents_number_changed_hands_is_dropped() {
    // A kernel per walk: the row waits for a read of the child's `stat`, which a walk makes.
    let kernel = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Ok(Some(ROOT_INO + 1)));
    assert!(descendants(&kernel(), root(), &EDGES).unwrap().is_empty());
    assert!(children_of(&kernel(), root(), &EDGES).unwrap().is_empty());
}

/// The same for a parent that the walk accepted itself, deeper down. Mutant: "only the root is
/// proved again".
#[skuld::test]
fn a_grandchild_read_after_its_accepted_parents_number_changed_hands_is_dropped() {
    let kernel =
        table_with_a_grandchild().on_pidfs_ino_after_read(CHILD, &format!("{GRAND}/stat"), Ok(Some(CHILD_INO + 1)));
    assert_eq!(
        descendants(&kernel, root(), &EDGES_WITH_A_GRANDCHILD).unwrap(),
        vec![child()]
    );
    let kept = descendants(&table_with_a_grandchild(), root(), &EDGES_WITH_A_GRANDCHILD).unwrap();
    assert_eq!(
        kept.len(),
        2,
        "with the parent still holding its number the grandchild is kept"
    );
}

/// The parent-order rule is off here ([`ORDER_AFTER_PARENT`](crate::identity::ORDER_AFTER_PARENT)):
/// `GRAND` started after the root but before its listed parent `CHILD`, and is kept. Mutant:
/// `ORDER_AFTER_PARENT` is true off Windows.
#[skuld::test]
fn a_grandchild_that_started_before_its_listed_parent_is_kept_off_windows() {
    let kernel = table_with_a_grandchild().on_read(
        &format!("{GRAND}/stat"),
        Ok(&stat(GRAND, CHILD, (ROOT_START + CHILD_START) / 2)),
    );
    let grand = ProcessId::from_parts_for_test(GRAND, Key::Pidfs(GRAND_INO));
    assert_eq!(
        descendants(&kernel, root(), &EDGES_WITH_A_GRANDCHILD).unwrap(),
        vec![child(), grand]
    );
}

/// A parent whose proof cannot be made (here: its pidfd's inode cannot be read) verifies nothing, so
/// the child is dropped like a pid the walk cannot query, not walked.
#[skuld::test]
fn a_child_whose_parent_cannot_be_proved_again_is_dropped() {
    let kernel = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Err(Errno::BADF));
    assert!(descendants(&kernel(), root(), &EDGES).unwrap().is_empty());
    assert!(children_of(&kernel(), root(), &EDGES).unwrap().is_empty());
}

/// That child is not a gone one: the walk lists it as unassessed, with the parent's proof as the
/// reason, in both filters. A child whose pid is gone is listed in neither. Mutants: "an `Unknown`
/// read is dropped as `Gone`"; "a gone read is counted".
#[skuld::test]
fn a_child_whose_parent_cannot_be_proved_again_is_unassessed_and_a_gone_child_is_not() {
    let unproved = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Err(Errno::BADF));
    let walk = |kernel: &FakeKernel, depth| {
        super::walk_from(kernel, root(), &EDGES, depth)
            .unwrap()
            .expect("the root is live")
    };
    let found = walk(&unproved(), Recursive::Yes);
    let [(pid, Error::Unassessable { detail, .. })] = &found.unassessed[..] else {
        panic!("expected one Unassessable entry, got {:?}", found.unassessed);
    };
    assert_eq!(*pid, CHILD);
    assert!(
        detail.contains(&format!("ppid {ROOT} identity could not be read")),
        "{detail}"
    );
    assert!(found.members.is_empty());
    let children = walk(&unproved(), Recursive::No);
    assert_eq!(children.unassessed.len(), 1, "{:?}", children.unassessed);

    let gone = table()
        .on_pidfd_open(CHILD, Err(Errno::SRCH))
        .on_read(&format!("{CHILD}/stat"), Err(libc::ENOENT));
    for depth in [Recursive::Yes, Recursive::No] {
        let found = walk(&gone, depth);
        assert!(found.members.is_empty() && found.unassessed.is_empty(), "{found:?}");
    }
}

/// The error for that child names the parent whose proof failed and the child it dropped. The walk
/// and `children`' list of a walk (`ProcessId::children` is a query) log nothing; the warn of a
/// caller with no error to return ([`super::warn_unassessed`]) says it once. Mutants: "the error
/// names the parent alone"; "the walk or `children` warns".
#[skuld::test]
fn a_child_whose_parent_cannot_be_proved_is_reported_by_an_error_naming_both() {
    crate::log_capture::install();
    let kernel = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Err(Errno::BADF));
    let names_both = |detail: &str| {
        detail.contains(&format!("ppid {ROOT} identity could not be read")) && detail.contains(&format!("pid {CHILD}"))
    };
    let mark = crate::log_capture::mark();
    for depth in [Recursive::No, Recursive::Yes] {
        let walked = super::walk_from(&kernel(), root(), &EDGES, depth)
            .expect("the root reads")
            .expect("the root is live");
        let [(_, Error::Unassessable { detail, .. })] = &walked.unassessed[..] else {
            panic!(
                "{depth:?}: expected one Unassessable entry, got {:?}",
                walked.unassessed
            );
        };
        // The entry is the cause, which names the parent and the candidate whose read it left unanswered.
        assert!(
            detail.contains(&format!("ppid {ROOT} identity could not be read"))
                && detail.contains(&format!("reading pid {CHILD}")),
            "{depth:?}: {detail}"
        );
        let err = walked.complete_members().expect_err("the list would be short");
        let Error::Unassessable { detail, .. } = &err else {
            panic!("{depth:?}: expected Unassessable, got {err:?}");
        };
        assert!(names_both(detail), "{depth:?}: {detail}");
    }
    assert_eq!(
        crate::log_capture::records_since_on_current_thread(mark, ""),
        [],
        "a query logs nothing"
    );

    let walked = super::walk_from(&kernel(), root(), &EDGES, Recursive::Yes)
        .expect("the root reads")
        .expect("the root is live");
    let mark = crate::log_capture::mark();
    super::warn_unassessed(&walked.unassessed);
    let warned = crate::log_capture::records_since_on_current_thread(mark, "");
    assert_eq!(warned.len(), 1, "{warned:?}");
    assert_eq!(warned[0].0, log::Level::Warn);
    assert!(names_both(&warned[0].1), "{warned:?}");
}

/// On a host whose pidfds have no inode the proof is the ticks compare: the root's `stat` shows the
/// ticks the id has, or another process's.
fn ticks_table(root_start_now: u64) -> FakeKernel<'static> {
    FakeKernel::over(&HostKernel)
        .same_view()
        .on_pidfd_open(CHILD, Ok(stand_in()))
        .on_pidfs_ino(CHILD, Ok(None))
        .on_read(&format!("{ROOT}/stat"), Ok(&stat(ROOT, 1, root_start_now)))
        .on_read(&format!("{CHILD}/stat"), Ok(&stat(CHILD, ROOT, CHILD_START)))
}

fn ticks_root() -> ProcessId {
    ProcessId::from_parts_for_test(ROOT, Key::Ticks(ROOT_START))
}

/// Mutant: "the parent is not proved again" (ticks).
#[skuld::test]
fn on_a_ticks_host_a_child_is_kept_only_while_its_parent_shows_its_ticks() {
    let kept = ticks_table(ROOT_START);
    assert_eq!(descendants(&kept, ticks_root(), &EDGES).unwrap().len(), 1);
    assert_eq!(children_of(&kept, ticks_root(), &EDGES).unwrap().len(), 1);

    let changed_hands = ticks_table(ROOT_START + 1);
    assert!(descendants(&changed_hands, ticks_root(), &EDGES).unwrap().is_empty());
    assert!(children_of(&changed_hands, ticks_root(), &EDGES).unwrap().is_empty());
}

// The root's proof is the anchor =====

/// A kernel in which another process holds `ROOT`'s pid when the walk proves it.
fn root_changed_hands() -> FakeKernel<'static> {
    table().on_pidfs_ino(ROOT, Ok(Some(ROOT_INO + 1)))
}

/// A kernel in which `ROOT`'s pid cannot be proved.
fn root_proof_fails() -> FakeKernel<'static> {
    table().on_pidfs_ino(ROOT, Err(Errno::BADF))
}

/// A root whose pid another process holds when the walk proves it walks nothing, from every entry
/// point: the answer is the proof's. Mutants: "the walk goes on after a `Gone` proof" (`hard_kill`
/// and `terminate` record a walk, as they do once the root is proved); "the root is signalled".
#[skuld::test]
fn a_root_whose_proof_finds_another_process_walks_nothing() {
    let sends = crate::send_log::Capture::start();
    let walks = super::fault::record_walks();
    assert!(
        matches!(
            super::hard_kill(
                &root_changed_hands(),
                root(),
                &super::ByIdentity::new(&root_changed_hands(), root())
            )
            .outcome(),
            crate::containment::dispatch::TreeKillOutcome::NoRoot(..)
        ),
        "a gone root has no tree to walk"
    );
    let termed = super::terminate(
        &root_changed_hands(),
        root(),
        &super::ByIdentity::new(&root_changed_hands(), root()),
    );
    assert!(
        matches!(termed, Ok(super::Terminated::RootExited(_))),
        "a gone root sends nothing"
    );
    for recursive in [Recursive::No, Recursive::Yes] {
        let children = root().children_with(&root_changed_hands(), recursive);
        assert_eq!(children.expect("a gone root is Ok"), vec![], "{recursive:?}");
    }
    assert_eq!(walks.walked(), Vec::<u32>::new(), "no walk began");
    assert!(sends.by_identity().is_empty(), "{:?}", sends.by_identity());
}

/// A root whose proof cannot be made is an error from every entry point, never an empty walk:
/// an empty one would let a caller kill the root and leave its descendants running. Mutants: "an
/// `Unknown` proof is an empty walk"; "the root is signalled"; "the walk begins before the root is
/// proved" (`hard_kill` and `terminate` record a walk).
#[skuld::test]
fn a_root_whose_proof_cannot_be_made_is_unassessable_and_signals_nothing() {
    let sends = crate::send_log::Capture::start();
    let walks = super::fault::record_walks();
    let results = [
        super::hard_kill(
            &root_proof_fails(),
            root(),
            &super::ByIdentity::new(&root_proof_fails(), root()),
        )
        .outcome()
        .into_result()
        .map_err(crate::containment::dispatch::Unkilled::into_error),
        super::terminate(
            &root_proof_fails(),
            root(),
            &super::ByIdentity::new(&root_proof_fails(), root()),
        )
        .map(drop),
        root().children_with(&root_proof_fails(), Recursive::No).map(|_| ()),
        root().children_with(&root_proof_fails(), Recursive::Yes).map(|_| ()),
    ];
    for result in results {
        match result {
            Err(Error::Unassessable { detail, .. }) => {
                assert!(detail.contains(&format!("pid {ROOT}")), "{detail}");
            }
            other => panic!("expected Unassessable, got {other:?}"),
        }
    }
    assert_eq!(walks.walked(), Vec::<u32>::new(), "no walk began");
    assert!(sends.by_identity().is_empty(), "{:?}", sends.by_identity());
}

// The kill goes through the proved pidfd =====

const KILLED_INO: u64 = 77;

/// A `cat` that lives until its stdin closes, its pidfd, and a kernel in which that pid is `KILLED_INO`.
/// The child is the pidfd's real target, so a signal sent through it is observable.
fn live_child_in_a_table() -> (StdChild, ProcessId, FakeKernel<'static>) {
    let child = blocker_with(|cat| {
        cat.stdout(std::process::Stdio::null());
    });
    let pid = child.id();
    let kernel = FakeKernel::over(&HostKernel)
        .on_pidfd_open(pid, Ok(crate::child::front_cgroup_tests::pidfd_of(pid)))
        .on_pidfs_ino(pid, Ok(Some(KILLED_INO)));
    (
        child,
        ProcessId::from_parts_for_test(pid, Key::Pidfs(KILLED_INO)),
        kernel,
    )
}

/// Linux sends through the pidfd the identity was proved on, never by the pid's number, which could
/// name another process the instant after the proof. Mutant: "send `kill(2)` by number after the
/// proof": no send through a pidfd is recorded.
#[skuld::test]
fn a_kill_by_identity_is_sent_through_the_proved_pidfd() {
    use nix::sys::signal::Signal;
    use std::os::unix::process::ExitStatusExt as _;
    let (mut child, id, kernel) = live_child_in_a_table();
    let sends = crate::send_log::Capture::start();
    let outcome = super::kill_by_identity(&kernel, id, Signal::SIGTERM);
    assert!(matches!(outcome, super::KillOutcome::Terminated), "{outcome:?}");
    assert_eq!(
        sends.entries(),
        [(id.pid(), crate::signal::Sig::Term, crate::send_log::Via::Pidfd)]
    );
    assert_eq!(
        child.wait().expect("the child exits").signal(),
        Some(libc::SIGTERM),
        "the signal reached the process the pidfd names"
    );
}

/// A process that was reaped after the proof is gone: the pidfd answers `ESRCH`. Mutant: "`ESRCH` is
/// not attempted".
#[skuld::test]
fn a_kill_by_identity_of_a_process_reaped_after_the_proof_is_already_gone() {
    let (mut child, id, kernel) = live_child_in_a_table();
    drop(child.stdin.take());
    child.wait().expect("the child exits at EOF");
    let outcome = super::kill_by_identity(&kernel, id, nix::sys::signal::Signal::SIGTERM);
    assert!(matches!(outcome, super::KillOutcome::AlreadyGone), "{outcome:?}");
}