cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Linux: the drop and a failed elevated spawn's cleanup, for a process group whose root is reaped.
//! On 6.9+ the root's pidfd names the group exactly, whoever reaped the root, so they decide as
//! `kill_tree` does (`group_exact_tests`); below 6.9 nothing goes out by the number of a group whose
//! root another reaper took, while a root this handle's wait saw exit is a zombie that pins it, so
//! its group is killed by the number.

use crate::child::group_exact_tests::root_with_a_member;
use crate::send_log::{assert_group_signalled_first_through_the_pidfd, Capture};
use crate::test_child::reaped_elsewhere::{kill_own_child, reap_behind, session_cat};
use crate::test_groups::{pidfd_group_signal, stray_signal, Group};

/// Who reaps the root.
#[derive(Debug, Clone, Copy)]
enum Reap {
    /// This handle's own `wait`.
    Own,
    /// Another reaper in the process, behind the handle's back.
    Foreign,
}

/// The teardown under test.
#[derive(Debug, Clone, Copy)]
enum Teardown {
    Drop,
    FinishElevated,
}

/// Kills `child`'s root alone, by the test's own `SIGKILL`, and has `reap` reap it.
fn reap_root(child: &crate::Child, reap: Reap) {
    kill_own_child(child.pid());
    match reap {
        Reap::Own => {
            child.wait().expect("this handle reaps the root");
        }
        Reap::Foreign => reap_behind(child.pid()),
    }
}

/// Runs `teardown` on `child`: the error's detail for a cleanup, `None` for a drop.
fn tear_down(child: crate::Child, teardown: Teardown) -> Option<String> {
    match teardown {
        Teardown::Drop => {
            drop(child);
            None
        }
        Teardown::FinishElevated => {
            let error = crate::error::Error::from(
                crate::child::spawn::finish_elevated(
                    child,
                    Err(crate::error::Error::Io(std::io::Error::other("no password"))),
                )
                .expect_err("the password write failed"),
            );
            let detail = crate::test_child::detail_of(&error);
            let (_, _fate) = crate::child::spawn::failure::expect_may_have_started_with(error);
            Some(detail)
        }
    }
}

/// 6.9+: a reaped root whose group still has a member: the teardown kills the group through the
/// root's pidfd.
fn kills_the_group_left_behind(reap: Reap, teardown: Teardown) {
    let (child, member) = root_with_a_member();
    reap_root(&child, reap);
    let capture = Capture::start();
    tear_down(child, teardown);
    let steps = capture.group_steps();
    assert_group_signalled_first_through_the_pidfd(&steps, libc::SIGKILL);
    member.assert_killed();
}

/// Below 6.9 a root reaped by someone else names no group: nothing goes out by its number, and its
/// member lives on.
fn below_6_9_sends_nothing_to_the_group(reap: Reap, teardown: Teardown) {
    let (child, member) = root_with_a_member();
    reap_root(&child, reap);
    let old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    let refused = crate::containment::unix::fault::refuse_group_sends();
    let groups = crate::containment::unix::fault::record_kill_group();
    let capture = Capture::start();
    tear_down(child, teardown);
    let steps = capture.group_steps();
    drop((old_kernel, refused));
    assert_eq!(groups.killed(), Vec::<i32>::new(), "no kill of the group by its number");
    assert_eq!(steps, [], "nothing was sent to the group");
    member.assert_survived();
}

/// Below 6.9 a root this handle's wait saw exit is still a zombie that pins its group's number: the
/// teardown kills the group by that number, and its member dies.
///
/// Mutant: a wait consumes the zombie, so the number is unproven and nothing is sent.
fn below_6_9_kills_the_group_of_a_waited_root_by_its_number(teardown: Teardown) {
    let (child, member) = root_with_a_member();
    reap_root(&child, Reap::Own);
    let old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    let capture = Capture::start();
    tear_down(child, teardown);
    let steps = capture.group_steps();
    drop(old_kernel);
    assert!(
        steps.contains(&crate::send_log::GroupStep::Group(
            crate::send_log::Route::Number,
            libc::SIGKILL
        )),
        "the group was killed by its number: {steps:?}"
    );
    member.assert_killed();
}

/// 6.9+: a reaped root whose group has no member left has no tree left behind: the teardown sends
/// nothing and reports no skipped kill.
fn sends_nothing_to_an_empty_group_and_reports_no_skip(reap: Reap, teardown: Teardown) {
    crate::log_capture::install();
    let child = session_cat().spawn().expect("spawn");
    reap_root(&child, reap);
    let mark = crate::log_capture::mark();
    let capture = Capture::start();
    let detail = tear_down(child, teardown);
    let steps = capture.group_steps();
    assert_eq!(steps, [], "nothing was sent");
    if let Some(detail) = detail {
        assert!(!detail.contains("tree was not killed"), "{detail}");
    }
    let warns = crate::log_capture::warns_since(mark, "");
    assert_eq!(warns, Vec::<String>::new(), "nothing was left behind");
}

#[skuld::test]
fn a_drop_after_its_own_wait_kills_the_group_left_behind(#[fixture(pidfd_group_signal)] _group: &Group) {
    kills_the_group_left_behind(Reap::Own, Teardown::Drop);
}

#[skuld::test]
fn a_drop_after_a_foreign_reap_kills_the_group_left_behind(#[fixture(pidfd_group_signal)] _group: &Group) {
    kills_the_group_left_behind(Reap::Foreign, Teardown::Drop);
}

#[skuld::test]
fn a_failed_elevated_spawns_cleanup_after_its_own_wait_kills_the_group_left_behind(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    kills_the_group_left_behind(Reap::Own, Teardown::FinishElevated);
}

#[skuld::test]
fn a_failed_elevated_spawns_cleanup_after_a_foreign_reap_kills_the_group_left_behind(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    kills_the_group_left_behind(Reap::Foreign, Teardown::FinishElevated);
}

#[skuld::test]
fn a_drop_after_its_own_wait_below_6_9_kills_the_group_by_its_number() {
    below_6_9_kills_the_group_of_a_waited_root_by_its_number(Teardown::Drop);
}

#[skuld::test]
fn a_drop_after_a_foreign_reap_below_6_9_sends_nothing_to_the_group() {
    below_6_9_sends_nothing_to_the_group(Reap::Foreign, Teardown::Drop);
}

#[skuld::test]
fn a_failed_elevated_spawns_cleanup_after_its_own_wait_below_6_9_kills_the_group_by_its_number() {
    below_6_9_kills_the_group_of_a_waited_root_by_its_number(Teardown::FinishElevated);
}

#[skuld::test]
fn a_failed_elevated_spawns_cleanup_after_a_foreign_reap_below_6_9_sends_nothing_to_the_group() {
    below_6_9_sends_nothing_to_the_group(Reap::Foreign, Teardown::FinishElevated);
}

#[skuld::test]
fn a_drop_after_a_foreign_reap_sends_nothing_to_an_empty_group_and_does_not_warn(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    sends_nothing_to_an_empty_group_and_reports_no_skip(Reap::Foreign, Teardown::Drop);
}

#[skuld::test]
fn a_failed_elevated_spawns_cleanup_after_a_foreign_reap_reports_no_skip_for_an_empty_group(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    sends_nothing_to_an_empty_group_and_reports_no_skip(Reap::Foreign, Teardown::FinishElevated);
}

/// 6.9+: a root whose handle cannot say whether it was reaped still names its group exactly through
/// its pidfd, so the drop kills the group as usual. Mutant: "only a reaped root's group is decided
/// by the pidfd".
#[skuld::test]
fn a_drop_of_a_root_its_handle_cannot_read_kills_its_group_through_the_pidfd(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    let (mut child, member) = root_with_a_member();
    let _released = member.release_root_when_a_teardown_waits();
    let capture = Capture::start();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
    drop(child);
    fake.assert_peeks_exhausted();
    let steps = capture.group_steps();
    assert_group_signalled_first_through_the_pidfd(&steps, libc::SIGKILL);
    member.assert_killed();
}

/// 6.9+: a root whose handle cannot say whether it was reaped, whose group has no member, may have
/// left the group alive, so the drop still skips the group and says so. Mutant: "the drop takes an
/// unanswered root for a reaped one".
#[skuld::test]
fn a_drop_of_a_root_its_handle_cannot_read_with_no_member_left_still_skips_the_group(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    use crate::identity::Resolved;
    crate::log_capture::install();
    let mut child = session_cat().spawn().expect("spawn");
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    reap_root(&child, Reap::Foreign);
    let mark = crate::log_capture::mark();
    let capture = Capture::start();
    let fake = child.proc.script_over(|f| {
        f.peeks([Err(std::io::Error::other("forced peek failure"))])
            .number_reads([(Resolved::Found(id), crate::identity::UnknownCause::default())])
    });
    drop(child);
    fake.assert_peeks_exhausted();
    fake.assert_number_reads_exhausted();
    let steps = capture.group_steps();
    assert_eq!(steps, [], "nothing was sent to the group");
    let skips = crate::log_capture::records_since_on_current_thread(mark, "so it does not kill its process group");
    assert_eq!(skips.len(), 1, "{skips:?}");
}

/// 6.9+: a root whose handle cannot say whether it was reaped, but whose number reads as no process
/// and whose pidfd shows its group has no member, is reaped: the teardown sends nothing, does not
/// warn of a skipped kill, and the tree counts as killed. The one look that shows the reap decides
/// the kill and words the report. Mutant: "the kill decides on the handle's raw `Unknown`, the report
/// on the reap the number showed".
fn an_unreadable_handle_with_a_gone_number_and_an_empty_group_is_reaped(teardown: Teardown) {
    use crate::identity::Resolved;
    crate::log_capture::install();
    let mut child = session_cat().spawn().expect("spawn");
    reap_root(&child, Reap::Foreign);
    let mark = crate::log_capture::mark();
    let capture = Capture::start();
    let fake = child.proc.script_over(|f| {
        f.peeks([Err(std::io::Error::other("forced peek failure"))])
            .number_reads([(Resolved::Gone, crate::identity::UnknownCause::default())])
    });
    let detail = match teardown {
        Teardown::Drop => {
            let torn = child.tear_down(
                crate::containment::dispatch::TeardownCaller::FailedRun,
                crate::child::owned::teardown::Disposition::Leave,
            );
            assert!(torn.fate.not_running(), "{:?}", torn.fate);
            assert!(child.tree.is_killed(), "an emptied group is a killed tree");
            None
        }
        Teardown::FinishElevated => tear_down(child, teardown),
    };
    fake.assert_peeks_exhausted();
    fake.assert_number_reads_exhausted();
    assert_eq!(capture.group_steps(), [], "nothing was sent to the group");
    if let Some(detail) = detail {
        assert!(!detail.contains("tree was not killed"), "{detail}");
    }
    let warns = crate::log_capture::warns_since(mark, "");
    assert_eq!(warns, Vec::<String>::new(), "nothing was left behind");
}

#[skuld::test]
fn a_teardown_of_an_unreadable_handle_with_a_gone_number_and_an_empty_group_does_not_warn(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    an_unreadable_handle_with_a_gone_number_and_an_empty_group_is_reaped(Teardown::Drop);
}

#[skuld::test]
fn a_failed_elevated_spawns_cleanup_of_an_unreadable_handle_with_a_gone_number_and_an_empty_group_does_not_warn(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    an_unreadable_handle_with_a_gone_number_and_an_empty_group_is_reaped(Teardown::FinishElevated);
}

/// 6.9+: a drop that finds, listed by its group's number, a process the root's pidfd shows is not a
/// member sends it nothing and does not warn. Mutant: "a group with no member left leaves the
/// listed process unassessable".
#[skuld::test]
fn a_drop_leaves_alone_a_group_that_took_the_number_of_its_emptied_group(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    use crate::child::group_exact_tests::EmptiedGroup;
    crate::log_capture::install();
    let (child, armed) = EmptiedGroup::new().arm();
    let root = child.pid();
    let mark = crate::log_capture::mark();
    let capture = Capture::start();
    drop(child);
    let sent = capture.by_identity();
    armed.finish();
    assert!(
        sent.iter().all(|&(pid, _)| pid == root),
        "nothing was resent to a member: {sent:?}"
    );
    let warns = crate::log_capture::warns_since(mark, "");
    assert_eq!(warns, Vec::<String>::new(), "the tree is gone");
}