cosca 0.6.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
use std::cell::Cell;
use std::io;

use super::{front, kill_gate, terminate_gate, Gate};
use crate::elevation::{Backend, ElevatedVia};
use crate::error::{ElevationErrorKind, Error};

const PID: u32 = 4242;

const FRONTS: [(ElevatedVia, &str); 3] = [
    (ElevatedVia::Wrapped(Backend::Sudo), "sudo"),
    (ElevatedVia::Wrapped(Backend::Doas), "doas"),
    (ElevatedVia::MacosOsascript, "osascript"),
];

const NOT_FRONTS: [Option<ElevatedVia>; 4] = [
    None,
    Some(ElevatedVia::Wrapped(Backend::Pkexec)),
    Some(ElevatedVia::WindowsUac),
    Some(ElevatedVia::AlreadyElevated),
];

/// `answers` in turn, one per call; the last is repeated once they run out.
fn in_turn(answers: Vec<io::Result<bool>>) -> impl Fn() -> io::Result<bool> {
    let answers: Vec<_> = answers
        .into_iter()
        .map(|a| a.map_err(|e| (e.kind(), e.to_string())))
        .collect();
    let next = Cell::new(0);
    move || {
        let i = next.get().min(answers.len() - 1);
        next.set(next.get() + 1);
        answers[i].clone().map_err(|(kind, text)| io::Error::new(kind, text))
    }
}

/// What a gate asked, in order: `r` for `running`, `c` for `in_cgroup`.
fn kill_gate_asking(
    via: Option<&ElevatedVia>,
    running: io::Result<bool>,
    in_cgroup: io::Result<bool>,
) -> (Gate, String) {
    kill_gate_asking_in_turn(via, vec![running], in_cgroup)
}

/// [`kill_gate_asking`], with `running` answering in turn.
fn kill_gate_asking_in_turn(
    via: Option<&ElevatedVia>,
    running: Vec<io::Result<bool>>,
    in_cgroup: io::Result<bool>,
) -> (Gate, String) {
    let asked = Cell::new(String::new());
    let note = |c: char| {
        let mut s = asked.take();
        s.push(c);
        asked.set(s);
    };
    let running = in_turn(running);
    let g = kill_gate(
        front(via),
        PID,
        || {
            note('r');
            running()
        },
        || {
            note('c');
            in_cgroup
        },
    );
    (g, asked.take())
}

fn refusal_detail(g: Gate) -> String {
    match g {
        Gate::Closed(Error::Elevation {
            kind: ElevationErrorKind::Unkillable,
            detail,
        }) => detail,
        other => panic!("expected a closed gate with Unkillable, got {other:?}"),
    }
}

#[skuld::test]
fn a_live_front_outside_a_cgroup_is_closed_with_unkillable_naming_it() {
    for (via, name) in FRONTS {
        let (g, asked) = kill_gate_asking(Some(&via), Ok(true), Ok(false));
        assert_eq!(asked, "rcr", "{via:?}");
        let detail = refusal_detail(g);
        assert!(detail.contains(&format!("pid {PID} is")), "{detail}");
        assert!(detail.contains(name), "{detail}");
        assert!(detail.contains("no kill was sent"), "{detail}");
        assert_eq!(
            detail.contains("direct exec"),
            name != "osascript",
            "only a wrapper may track the program itself: {detail}"
        );
    }
}

/// A front that has left its cgroup (pam_systemd moving sudo into a session scope) is outside it.
#[skuld::test]
fn a_live_front_that_left_its_cgroup_is_closed() {
    let (g, _) = kill_gate_asking(Some(&ElevatedVia::Wrapped(Backend::Sudo)), Ok(true), Ok(false));
    refusal_detail(g);
}

/// An exited front has nothing left to orphan, and its cgroup is not asked about.
#[skuld::test]
fn an_exited_front_is_exited() {
    for (via, _) in FRONTS {
        let (g, asked) = kill_gate_asking(Some(&via), Ok(false), Ok(true));
        assert_eq!(asked, "r", "{via:?}");
        assert!(matches!(g, Gate::Exited), "{via:?}: {g:?}");
    }
}

/// A cgroup kill reaches a member whatever its credentials, so a live front in one, or one whose
/// state cannot be read, is killed through it.
#[skuld::test]
fn a_live_front_in_its_cgroup_is_killed_through_the_cgroup_only() {
    for (via, _) in FRONTS {
        for running in [Ok(true), Err(io::Error::other("peek refused"))] {
            let (g, asked) = kill_gate_asking(Some(&via), running, Ok(true));
            assert_eq!(asked, "rc", "{via:?}");
            assert!(matches!(g, Gate::CgroupOnly), "{via:?}: {g:?}");
        }
    }
}

/// A front whose state or membership cannot be read is closed, and says why.
#[skuld::test]
fn a_front_whose_state_cannot_be_read_is_closed_and_says_why() {
    let sudo = ElevatedVia::Wrapped(Backend::Sudo);
    let (g, _) = kill_gate_asking(Some(&sudo), Err(io::Error::other("peek refused")), Ok(false));
    assert!(refusal_detail(g).contains("could not be read: peek refused"));
    let (g, _) = kill_gate_asking(Some(&sudo), Ok(true), Err(io::Error::other("procs refused")));
    assert!(refusal_detail(g).contains("could not be read: procs refused"));
}

/// The tracked process is the program itself, or there is no elevation: signalled like any child,
/// with nothing read.
#[skuld::test]
fn a_child_that_is_not_a_front_is_open_whatever_its_containment() {
    for via in &NOT_FRONTS {
        for in_cgroup in [false, true] {
            let (g, asked) = kill_gate_asking(via.as_ref(), Ok(true), Ok(in_cgroup));
            assert_eq!(asked, "", "{via:?}");
            assert!(matches!(g, Gate::Open), "{via:?}: {g:?}");
            let g = terminate_gate(front(via.as_ref()), PID, || panic!("not asked"));
            assert!(matches!(g, Gate::Open), "{via:?}: {g:?}");
        }
    }
}

/// sudo and doas relay `SIGTERM` to the program: never gated.
#[skuld::test]
fn a_sigterm_to_a_relaying_front_is_open() {
    for via in [ElevatedVia::Wrapped(Backend::Sudo), ElevatedVia::Wrapped(Backend::Doas)] {
        let g = terminate_gate(front(Some(&via)), PID, || panic!("not asked"));
        assert!(matches!(g, Gate::Open), "{via:?}: {g:?}");
    }
}

/// A `SIGTERM` would end osascript and orphan the program: refused while osascript runs, sent once
/// it has exited.
#[skuld::test]
fn a_sigterm_to_a_live_osascript_is_closed() {
    let osascript = ElevatedVia::MacosOsascript;
    let detail = refusal_detail(terminate_gate(front(Some(&osascript)), PID, || Ok(true)));
    assert!(detail.contains(&format!("pid {PID} is osascript")), "{detail}");
    assert!(detail.contains("no SIGTERM was sent"), "{detail}");
    let detail = refusal_detail(terminate_gate(front(Some(&osascript)), PID, || {
        Err(io::Error::other("peek refused"))
    }));
    assert!(detail.contains("peek refused"), "{detail}");
    assert!(matches!(
        terminate_gate(front(Some(&osascript)), PID, || Ok(false)),
        Gate::Open
    ));
}

/// What `cgroup_kill_reached` asked, in order (`e`xited, `u`nder the leaf), and its answer.
fn reached_asking(exited: io::Result<bool>, under_leaf: io::Result<bool>) -> (Result<(), Error>, String) {
    reached_asking_in_turn(vec![exited], under_leaf)
}

/// [`reached_asking`], with `exited` answering in turn.
fn reached_asking_in_turn(exited: Vec<io::Result<bool>>, under_leaf: io::Result<bool>) -> (Result<(), Error>, String) {
    let asked = Cell::new(String::new());
    let note = |c: char| {
        let mut s = asked.take();
        s.push(c);
        asked.set(s);
    };
    let exited = in_turn(exited);
    let r = super::cgroup_kill_reached(
        front(Some(&ElevatedVia::Wrapped(Backend::Sudo))),
        PID,
        || {
            note('e');
            exited()
        },
        || {
            note('u');
            under_leaf
        },
    );
    (r, asked.take())
}

/// A front exited, or in its leaf after the write, was there for the kill.
#[skuld::test]
fn a_front_in_its_leaf_after_the_kill_was_reached() {
    let (r, asked) = reached_asking(Ok(true), Ok(false));
    assert!(r.is_ok() && asked == "e", "{r:?} {asked}");
    let (r, asked) = reached_asking(Ok(false), Ok(true));
    assert!(r.is_ok() && asked == "eu", "{r:?} {asked}");
}

/// A front neither exited nor in its leaf left it before the kill: refused, and named.
#[skuld::test]
fn a_front_outside_its_leaf_after_the_kill_was_not_reached() {
    let (r, _) = reached_asking(Ok(false), Ok(false));
    let detail = refusal_detail(Gate::Closed(r.expect_err("not reached")));
    assert!(detail.contains("left the cgroup before its kill"), "{detail}");
}

/// A front whose place cannot be read is not shown reached: refused, with every reason.
#[skuld::test]
fn a_front_whose_place_after_the_kill_cannot_be_read_is_refused() {
    let (r, _) = reached_asking(Err(io::Error::other("peek refused")), Err(io::Error::other("hidepid")));
    let detail = refusal_detail(Gate::Closed(r.expect_err("not shown reached")));
    assert!(detail.contains("nothing shows the cgroup kill reached it"), "{detail}");
    assert!(
        detail.contains("peek refused") && detail.contains("hidepid"),
        "{detail}"
    );
}

/// A front that exits, and is reaped by another thread's `wait`, between the gate's two reads has
/// no cgroup left to read: the gate reads it again, finds it exited, and kills nothing.
#[skuld::test]
fn a_front_reaped_between_the_gates_reads_has_exited() {
    let sudo = ElevatedVia::Wrapped(Backend::Sudo);
    let reaped = || Err(io::Error::other("ESRCH: reaped"));
    let (g, asked) = kill_gate_asking_in_turn(Some(&sudo), vec![Ok(true), Ok(false)], reaped());
    assert!(matches!(g, Gate::Exited), "{g:?}");
    assert_eq!(asked, "rcr");
    let (g, _) = kill_gate_asking_in_turn(Some(&sudo), vec![Ok(true), Ok(true)], reaped());
    refusal_detail(g);
}

/// A front its cgroup kill ended, reaped by another thread's `wait` before its cgroup is read,
/// was reached: the check reads its exit again.
#[skuld::test]
fn a_front_reaped_before_its_cgroup_is_read_was_reached() {
    let reaped = || Err(io::Error::other("ESRCH: reaped"));
    let (r, asked) = reached_asking_in_turn(vec![Ok(false), Ok(true)], reaped());
    assert!(r.is_ok(), "{r:?}");
    assert_eq!(asked, "eue");
    let (r, _) = reached_asking_in_turn(vec![Ok(false), Ok(false)], reaped());
    r.expect_err("still running, unplaced");
}

/// A reach check of a child that is no front is a contract violation. Mutant: "debug_assert
/// removed".
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "only a front's cgroup kill is checked")]
fn a_reach_check_with_no_front_asserts() {
    drop(super::cgroup_kill_reached(None, PID, || Ok(true), || Ok(true)));
}

/// In release the same check fails closed, like its siblings: nothing shows the kill reached a
/// front it does not know. Mutant: "`None` answers `Ok(())`".
#[cfg(not(debug_assertions))]
#[skuld::test]
fn a_reach_check_with_no_front_fails_closed_in_release() {
    let r = super::cgroup_kill_reached(None, PID, || Ok(true), || Ok(true));
    let Err(Error::Containment { detail }) = r else {
        panic!("expected a refusal, got {r:?}");
    };
    assert!(detail.contains(&format!("pid {PID}")), "{detail}");
}