use super::is_nested;
use crate::test_child::Console;
#[cfg(unix)]
use crate::test_groups::setuid;
#[skuld::test]
fn is_nested_without_marker_is_false() {
assert!(!is_nested(false));
}
#[skuld::test]
fn is_nested_with_marker_is_true() {
assert!(is_nested(true));
}
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_session_selects_setsid() {
use super::{unix_setup_for, UnixSetup};
use crate::containment::ContainMode;
assert_eq!(unix_setup_for(Some(ContainMode::Session)), UnixSetup::Session);
}
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_strongest_selects_process_group() {
use super::{unix_setup_for, UnixSetup};
use crate::containment::ContainMode;
assert_eq!(unix_setup_for(Some(ContainMode::Strongest)), UnixSetup::ProcessGroup);
}
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_treewalk_selects_none() {
use super::{unix_setup_for, UnixSetup};
use crate::containment::ContainMode;
assert_eq!(unix_setup_for(Some(ContainMode::TreeWalk)), UnixSetup::None);
}
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_none_mode_selects_process_group() {
use super::{unix_setup_for, UnixSetup};
assert_eq!(unix_setup_for(None), UnixSetup::ProcessGroup);
}
#[skuld::test]
fn attached_is_actionable() {
use super::Attached;
assert!(!Attached::None.is_actionable()); assert!(!Attached::Delegated.is_actionable());
assert!(Attached::TreeWalk(crate::identity::ProcessId::current()).is_actionable());
#[cfg(unix)]
assert!(Attached::ProcessGroup(0).is_actionable());
#[cfg(target_os = "linux")]
assert!(Attached::Cgroup(crate::containment::cgroup::CgroupLeaf::placeholder_for_test()).is_actionable());
#[cfg(windows)]
assert!(Attached::JobObject(crate::containment::windows::JobHandle::create_empty_for_test()).is_actionable());
}
#[cfg(unix)]
#[skuld::test]
fn attached_needs_root_check() {
use super::Attached;
assert!(!Attached::None.needs_root_check());
assert!(!Attached::Delegated.needs_root_check());
assert!(!Attached::TreeWalk(crate::identity::ProcessId::current()).needs_root_check());
assert!(Attached::ProcessGroup(0).needs_root_check());
#[cfg(target_os = "linux")]
assert!(!Attached::Cgroup(crate::containment::cgroup::CgroupLeaf::placeholder_for_test()).needs_root_check());
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn attached_fd_marker_needs_root_check_with_or_without_a_pgid() {
use std::os::fd::{AsFd, AsRawFd};
use super::Attached;
fn marker_with_pgid(pgid: Option<i32>) -> crate::containment::fdmarker::Marker {
let (read, write) = std::io::pipe().expect("pipe");
let handle = crate::containment::fdmarker::pipe_handle_of(write.as_fd()).expect("handle");
let read_handle = crate::containment::fdmarker::pipe_handle_of(read.as_fd()).expect("read handle");
let prepared = crate::containment::fdmarker::PreparedMarker {
read: std::os::fd::OwnedFd::from(read),
handle,
read_handle,
fd: write.as_fd().as_raw_fd(),
};
crate::containment::fdmarker::Marker::new(
prepared,
crate::containment::fdmarker::fdmarker_tests::inert_root(),
pgid,
)
}
assert!(Attached::FdMarker(marker_with_pgid(Some(1234))).needs_root_check());
assert!(Attached::FdMarker(marker_with_pgid(None)).needs_root_check());
}
#[skuld::test]
fn nested_attach_is_delegated() {
use super::{attach, Attached, Prepared};
use crate::containment::{ContainMode, Containment};
fn spawn_trivial() -> std::process::Child {
#[cfg(unix)]
return crate::test_spawn::spawn(&mut std::process::Command::new("true")).expect("spawn true");
#[cfg(windows)]
return crate::test_spawn::spawn(std::process::Command::new("cmd").args(["/C", "exit"])).expect("spawn cmd");
}
for mode in [ContainMode::Strongest, ContainMode::TreeWalk] {
let mut child = spawn_trivial();
let prepared = Prepared {
mode: Some(mode),
is_root: false, #[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
#[cfg(target_os = "macos")]
marker: None,
#[cfg(windows)]
graceful: crate::containment::windows::mechanism_from_flags(crate::containment::windows::group_flags()),
#[cfg(windows)]
frozen: false,
};
#[cfg(windows)]
let proc_handle = {
use std::os::windows::io::AsRawHandle;
child.as_raw_handle()
};
let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
panic!("the helper child must be readable");
};
let attachment = attach(
#[cfg(unix)]
child.id(),
Ok(id),
#[cfg(target_os = "linux")]
crate::containment::cgroup::test_support::handle_of(
child.id(),
&crate::containment::cgroup::test_support::pidfd_of(child.id()),
),
#[cfg(windows)]
proc_handle,
prepared,
)
.expect("attach nested");
let (containment, attached) = (attachment.containment, attachment.attached);
_ = child.kill();
_ = child.wait();
assert_eq!(
containment,
Containment::Delegated,
"nested member ({mode:?}) must report Containment::Delegated, got {containment:?}"
);
assert!(
matches!(attached, Attached::Delegated),
"nested member ({mode:?}) must be Attached::Delegated, got {attached:?}"
);
}
}
#[skuld::test]
fn sync_kill_tree_backstop_is_load_bearing() {
#[cfg(not(target_os = "macos"))]
use super::super::treewalk::fault;
#[cfg(target_os = "macos")]
use crate::containment::fdmarker::fault;
let mut cmd = crate::test_child::command(Console::Hidden);
#[cfg(unix)]
cmd.args(["cat"]);
#[cfg(windows)]
cmd.args([crate::test_child::windows_more()]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
#[cfg(windows)]
cmd.stdout(crate::Stdio::null()).expect("set stdout null");
cmd.contain_with(crate::ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
fault::set_force_root_kill_noop(true);
let result = child.kill_tree();
assert!(
!fault::armed(),
"seam not consumed — hard_kill did not run on the arming thread"
);
result.expect("kill_tree via backstop");
drop(stdin);
let status = child.wait().expect("reap");
assert!(
!status.success(),
"the handle backstop must be what killed the root, got {status:?}"
);
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_kill_tree_backstop_is_load_bearing() {
#[cfg(not(target_os = "macos"))]
use super::super::treewalk::fault;
#[cfg(target_os = "macos")]
use crate::containment::fdmarker::fault;
let mut cmd = crate::test_child::tokio_command(Console::Hidden);
#[cfg(unix)]
cmd.args(["cat"]);
#[cfg(windows)]
cmd.args([crate::test_child::windows_more()]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
#[cfg(windows)]
cmd.stdout(crate::Stdio::null()).expect("set stdout null");
cmd.contain_with(crate::ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
fault::set_force_root_kill_noop(true);
let result = child.kill_tree();
assert!(
!fault::armed(),
"seam not consumed — hard_kill did not run on the arming thread"
);
result.expect("kill_tree via backstop");
drop(stdin);
let status = child.wait().await.expect("reap");
assert!(
!status.success(),
"the handle backstop must be what killed the root, got {status:?}"
);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn sync_kill_tree_after_an_incomplete_walk_still_runs_the_handle_backstop() {
use super::super::treewalk::fault::{self, LeftBehind};
for left in [LeftBehind::Root, LeftBehind::Descendant, LeftBehind::RootAndDescendant] {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["cat"]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.contain_with(crate::ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
fault::set_force_root_kill_noop(true);
fault::force_incomplete_once(left);
let result = child.kill_tree();
match left {
LeftBehind::Root => result.expect("only the root was left, and the backstop killed it"),
LeftBehind::Descendant | LeftBehind::RootAndDescendant => {
let err = result.expect_err("a descendant was left");
assert!(matches!(err, crate::error::Error::MemberNotKilled { .. }), "{err:?}");
}
}
drop(stdin);
let status = child.wait().expect("reap");
assert!(
!status.success(),
"{left:?}: the handle backstop must be what killed the root, got {status:?}"
);
}
}
#[cfg(all(unix, not(target_os = "macos"), feature = "tokio"))]
#[skuld::test]
async fn async_kill_tree_after_an_incomplete_walk_still_runs_the_handle_backstop() {
use super::super::treewalk::fault::{self, LeftBehind};
for left in [LeftBehind::Root, LeftBehind::Descendant, LeftBehind::RootAndDescendant] {
let mut cmd = crate::test_child::tokio_command(Console::Hidden);
cmd.args(["cat"]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.contain_with(crate::ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
fault::set_force_root_kill_noop(true);
fault::force_incomplete_once(left);
let result = child.kill_tree();
match left {
LeftBehind::Root => result.expect("only the root was left, and the backstop killed it"),
LeftBehind::Descendant | LeftBehind::RootAndDescendant => {
let err = result.expect_err("a descendant was left");
assert!(matches!(err, crate::error::Error::MemberNotKilled { .. }), "{err:?}");
}
}
drop(stdin);
let status = child.wait().await.expect("reap");
assert!(
!status.success(),
"{left:?}: the handle backstop must be what killed the root, got {status:?}"
);
}
}
#[skuld::test]
fn settle_answers_and_marks_by_what_ran_what_was_left_and_the_root_s_end() {
use super::{Attached, SettleOutcome, TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
use crate::error::Error;
let left = |pid| Error::MemberNotKilled {
pid,
source: Box::new(Error::Containment {
detail: "refused".into(),
}),
note: None,
};
let unkilled = |members: &[u32], root: Option<u32>| Unkilled {
members: members.iter().map(|pid| left(*pid)).collect(),
root: root.map(left),
resolved: Vec::new(),
};
let skipped = |holders| TreeKillOutcome::Skipped {
action: "walk".into(),
holders,
};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
type Answer = Result<SettleOutcome, (u32, Vec<u32>)>;
let table: Vec<(TreeKillOutcome, bool, Answer, bool)> = vec![
(TreeKillOutcome::Ran(Ok(())), false, Ok(SettleOutcome::Killed), true),
(skipped(Ok(())), true, Ok(SettleOutcome::Skipped), false),
(skipped(Err(unkilled(&[7], None))), true, Err((7, vec![])), false),
(
TreeKillOutcome::Ran(Err(unkilled(&[], Some(1)))),
false,
Err((1, vec![])),
false,
),
(
TreeKillOutcome::Ran(Err(unkilled(&[], Some(1)))),
true,
Ok(SettleOutcome::Unvouched {
kind: UnvouchedKind::RootSeenRunning,
}),
false,
),
(
TreeKillOutcome::Ran(Err(unkilled(&[2, 3], None))),
true,
Err((2, vec![3])),
false,
),
(
TreeKillOutcome::Ran(Err(unkilled(&[2], Some(1)))),
true,
Err((2, vec![])),
false,
),
(
TreeKillOutcome::Ran(Err(unkilled(&[2], Some(1)))),
false,
Err((2, vec![1])),
false,
),
];
let pid_of = |error: &Error| match error {
Error::MemberNotKilled { pid, .. } => *pid,
other => panic!("expected MemberNotKilled, got {other:?}"),
};
for (outcome, root_ended, want, marked) in table {
let label = format!("{outcome:?}, root_ended {root_ended}");
let killed = TreeKilled::default();
let got = attached.settle(&killed, outcome, root_ended);
let got = got.map_err(|left| (pid_of(&left.first), left.others.iter().map(pid_of).collect::<Vec<_>>()));
assert_eq!(got, want, "{label}");
assert_eq!(killed.is_set(), marked, "{label}");
}
}
#[skuld::test]
fn settle_answers_a_walk_that_was_not_made_with_an_error_and_marks_nothing() {
use super::{Attached, TreeKillOutcome, TreeKilled};
use crate::error::Error;
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
for outcome in [
TreeKillOutcome::NoRoot,
TreeKillOutcome::Unwalked(Error::Unassessable {
detail: "the snapshot could not be taken".into(),
source: None,
}),
] {
let label = format!("{outcome:?}");
let killed = TreeKilled::default();
let left = attached
.settle(&killed, outcome, true)
.expect_err("nothing was killed, whatever became of the root");
assert!(matches!(left.first, Error::Unassessable { .. }), "{label}: {left}");
assert!(left.others.is_empty(), "{label}: {left}");
assert!(!killed.is_set(), "{label}");
}
}
#[skuld::test]
fn settle_answers_a_gone_root_as_killed_once_the_handle_killed_the_tree() {
use super::{Attached, SettleOutcome, TreeKillOutcome, TreeKilled};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), false)
.expect("the tree is killed");
let later = attached
.settle(&killed, TreeKillOutcome::NoRoot, false)
.expect("the tree was killed already");
assert_eq!(later, SettleOutcome::Killed);
}
#[derive(Debug, PartialEq)]
enum Standing {
Never,
Killed,
Left(Vec<u32>),
Unvouched(super::UnvouchedKind),
}
fn standing(killed: &super::TreeKilled) -> Standing {
standing_of(&killed.lock())
}
fn standing_of(state: &super::TreeState) -> Standing {
use crate::containment::treewalk::Left;
match state {
super::TreeState::Never => Standing::Never,
super::TreeState::Killed => Standing::Killed,
super::TreeState::Unvouched(kind) => Standing::Unvouched(*kind),
super::TreeState::Left(held) => {
assert!(!held.is_empty(), "a tree left holds a member");
Standing::Left(
held.iter()
.map(|left| match left {
Left::Resolved(id) => id.pid(),
Left::Unread { pid, .. } => *pid,
})
.collect(),
)
}
}
}
#[skuld::test]
fn next_is_the_one_transition_of_state_and_facts() {
use super::{TreeState, UnvouchedKind};
use crate::containment::treewalk::Left;
let unread = |pid| Left::Unread {
pid,
said: "its identity could not be read".into(),
};
let prev_names = [
"Never",
"Killed",
"Left(7)",
"Unvouched(HeldMembersGone)",
"Unvouched(RootSeenRunning)",
"Unvouched(Earlier)",
];
let prev_at = |at: usize| match at {
0 => TreeState::Never,
1 => TreeState::Killed,
2 => TreeState::Left(vec![unread(7)]),
3 => TreeState::Unvouched(UnvouchedKind::HeldMembersGone),
4 => TreeState::Unvouched(UnvouchedKind::RootSeenRunning),
_ => TreeState::Unvouched(UnvouchedKind::Earlier),
};
type Row = (&'static str, bool, Vec<Left>, bool, bool, [Standing; 6]);
let killed = || Standing::Killed;
let left_8 = || Standing::Left(vec![8]);
let held = || Standing::Unvouched(UnvouchedKind::HeldMembersGone);
let root = || Standing::Unvouched(UnvouchedKind::RootSeenRunning);
let earlier = || Standing::Unvouched(UnvouchedKind::Earlier);
#[rustfmt::skip]
let facts: Vec<Row> = vec![
("walk, nothing left", true, vec![], false, false,
[killed(), killed(), killed(), killed(), killed(), killed()]),
("walk, something running with no identity", true, vec![], true, false,
[earlier(), earlier(), earlier(), earlier(), earlier(), earlier()]),
("walk, the root seen running", true, vec![], true, true,
[root(), root(), root(), root(), root(), root()]),
("no walk, nothing left (skipped kill, gone root, walk not made)", false, vec![], false, false,
[Standing::Never, killed(), held(), held(), root(), earlier()]),
("no walk, something running with no identity", false, vec![], true, false,
[earlier(), earlier(), earlier(), earlier(), earlier(), earlier()]),
("walk, member 8 left", true, vec![unread(8)], true, false,
[left_8(), left_8(), left_8(), left_8(), left_8(), left_8()]),
("walk, member 8 left and the root seen running", true, vec![unread(8)], true, true,
[left_8(), left_8(), left_8(), left_8(), left_8(), left_8()]),
("no walk, member 8 left", false, vec![unread(8)], true, false,
[left_8(), left_8(), left_8(), left_8(), left_8(), left_8()]),
];
for (label, walked, left_now, running, root_seen_running, wants) in facts {
for (at, want) in wants.into_iter().enumerate() {
let got = super::next(&prev_at(at), walked, left_now.clone(), running, root_seen_running);
assert_eq!(standing_of(&got), want, "{} x {label}", prev_names[at]);
}
}
}
fn table_outcomes() -> [(&'static str, super::TreeKillOutcome); 5] {
use super::{TreeKillOutcome, Unkilled};
[
("Ran(Ok)", TreeKillOutcome::Ran(Ok(()))),
(
"Ran(Err member 8)",
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(8)],
root: None,
resolved: Vec::new(),
})),
),
("NoRoot", TreeKillOutcome::NoRoot),
(
"Unwalked",
TreeKillOutcome::Unwalked(crate::error::Error::Unassessable {
detail: "the snapshot failed".into(),
source: None,
}),
),
(
"Skipped",
TreeKillOutcome::Skipped {
action: "walk the process table".into(),
holders: Ok(()),
},
),
]
}
fn tree_left_with(pid: u32, resolved: Vec<crate::identity::ProcessId>) -> super::TreeKilled {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let killed = TreeKilled::default();
Attached::TreeWalk(crate::identity::ProcessId::current())
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(pid)],
root: None,
resolved,
})),
true,
)
.expect_err("a member was left");
killed
}
type Want = (Result<super::SettleOutcome, Vec<String>>, Standing);
fn check_table(
state: &str,
rows: impl Fn(u32) -> [Want; 5],
enter: impl Fn() -> (super::TreeKilled, u32, Box<dyn FnOnce()>),
) {
use super::Attached;
use crate::error::Error;
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let name = |error: &Error| match error {
Error::MemberNotKilled { pid, .. } => format!("pid {pid}"),
Error::Unassessable { .. } => "unassessable".to_owned(),
other => panic!("unexpected error {other:?}"),
};
for (at, (outcome_name, outcome)) in table_outcomes().into_iter().enumerate() {
let (killed, pid, after) = enter();
let (want_answer, want_standing) = rows(pid).into_iter().nth(at).expect("a row per outcome");
let got = attached.settle(&killed, outcome, true).map_err(|left| {
std::iter::once(&left.first)
.chain(&left.others)
.map(name)
.collect::<Vec<_>>()
});
assert_eq!(got, want_answer, "{state} x {outcome_name}: answer");
assert_eq!(standing(&killed), want_standing, "{state} x {outcome_name}: next state");
after();
}
}
fn gone() -> Vec<String> {
vec!["unassessable".to_owned()]
}
fn holding_rows(pid: u32) -> [Want; 5] {
let held = format!("pid {pid}");
let two = vec![held.clone(), "pid 8".to_owned()];
let walk_not_made = vec![held.clone(), "unassessable".to_owned()];
[
(Err(vec![held.clone()]), Standing::Left(vec![pid])),
(Err(two), Standing::Left(vec![pid, 8])),
(Err(vec![held.clone()]), Standing::Left(vec![pid])),
(Err(walk_not_made), Standing::Left(vec![pid])),
(Err(vec![held]), Standing::Left(vec![pid])),
]
}
#[skuld::test]
fn settle_answers_each_outcome_over_a_tree_never_settled_killed_or_left_an_unread_member() {
use super::{
Attached,
SettleOutcome::{Killed, Skipped},
TreeKillOutcome, TreeKilled,
};
let nothing = || -> Box<dyn FnOnce()> { Box::new(|| {}) };
check_table(
"never settled",
|_| {
[
(Ok(Killed), Standing::Killed),
(Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
(Err(gone()), Standing::Never),
(Err(gone()), Standing::Never),
(Ok(Skipped), Standing::Never),
]
},
|| (TreeKilled::default(), 0, nothing()),
);
check_table(
"killed",
|_| {
[
(Ok(Killed), Standing::Killed),
(Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
(Ok(Killed), Standing::Killed),
(Err(gone()), Standing::Killed),
(Ok(Skipped), Standing::Killed),
]
},
|| {
let killed = TreeKilled::default();
Attached::TreeWalk(crate::identity::ProcessId::current())
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
(killed, 0, nothing())
},
);
check_table("left, unread", holding_rows, || {
(tree_left_with(7, Vec::new()), 7, nothing())
});
}
#[skuld::test]
fn settle_answers_each_outcome_over_a_tree_left_a_member_that_can_be_killed() {
use super::{
SettleOutcome::{Killed, Unvouched},
UnvouchedKind,
};
check_table(
"left, killable",
|_| {
[
(Ok(Killed), Standing::Killed),
(Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
(Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
(Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
(
Ok(Unvouched {
kind: UnvouchedKind::HeldMembersGone,
}),
Standing::Unvouched(UnvouchedKind::HeldMembersGone),
),
]
},
|| {
let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
let killed = tree_left_with(id.pid(), vec![id]);
let after: Box<dyn FnOnce()> = Box::new(move || {
drop(stdin);
crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
});
(killed, id.pid(), after)
},
);
}
fn unvouched_tree() -> (super::TreeKilled, Box<dyn FnOnce()>) {
use super::{Attached, TreeKillOutcome};
let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
let killed = tree_left_with(id.pid(), vec![id]);
Attached::TreeWalk(crate::identity::ProcessId::current())
.settle(&killed, TreeKillOutcome::NoRoot, true)
.expect_err("a gone root walked nothing");
assert_eq!(
standing(&killed),
Standing::Unvouched(super::UnvouchedKind::HeldMembersGone)
);
let after: Box<dyn FnOnce()> = Box::new(move || {
drop(stdin);
crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
});
(killed, after)
}
#[skuld::test]
fn settle_answers_each_outcome_over_an_unvouched_tree() {
use super::{
SettleOutcome::{Killed, Unvouched},
UnvouchedKind,
};
check_table(
"unvouched",
|_| {
[
(Ok(Killed), Standing::Killed),
(Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
(Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
(Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
(
Ok(Unvouched {
kind: UnvouchedKind::HeldMembersGone,
}),
Standing::Unvouched(UnvouchedKind::HeldMembersGone),
),
]
},
|| {
let (killed, after) = unvouched_tree();
(killed, 0, after)
},
);
}
#[cfg(unix)]
#[skuld::test]
fn settle_answers_each_outcome_over_a_tree_left_a_member_that_refuses_the_kill(
#[fixture(setuid)] _group: &crate::test_groups::Group,
) {
check_table("left, refusing", holding_rows, || {
let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
let id = child.id().expect(crate::test_child::IDENTITY_READ);
let killed = tree_left_with(id.pid(), vec![id]);
let after: Box<dyn FnOnce()> = Box::new(move || {
drop(stdin);
assert!(child.wait().expect("the helper exits on EOF").success());
});
(killed, id.pid(), after)
});
}
#[skuld::test]
fn a_kill_that_leaves_a_member_after_a_killed_tree_of_a_handle_that_is_not_a_walk_unvouches_it() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
let attached = Attached::None;
let killed = TreeKilled::default();
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
assert_eq!(standing(&killed), Standing::Killed);
let left = attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(8)],
root: None,
resolved: Vec::new(),
})),
true,
)
.expect_err("a member was left");
assert_eq!(pid_left(&left.first), 8);
assert_eq!(standing(&killed), Standing::Unvouched(UnvouchedKind::Earlier));
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
assert_eq!(standing(&killed), Standing::Killed);
let skipped_with_a_member = || TreeKillOutcome::Skipped {
action: "walk".into(),
holders: Err(Unkilled {
members: vec![member_left(9)],
root: None,
resolved: Vec::new(),
}),
};
attached
.settle(&killed, skipped_with_a_member(), true)
.expect_err("a member was left");
assert_eq!(standing(&killed), Standing::Unvouched(UnvouchedKind::Earlier));
let never = TreeKilled::default();
attached
.settle(&never, skipped_with_a_member(), true)
.expect_err("a member was left");
assert_eq!(standing(&never), Standing::Unvouched(UnvouchedKind::Earlier));
}
fn member_left(pid: u32) -> crate::error::Error {
crate::error::Error::MemberNotKilled {
pid,
source: Box::new(crate::error::Error::Unassessable {
detail: "its identity could not be read".into(),
source: None,
}),
note: None,
}
}
fn pid_left(error: &crate::error::Error) -> u32 {
match error {
crate::error::Error::MemberNotKilled { pid, .. } => *pid,
other => panic!("expected MemberNotKilled, got {other:?}"),
}
}
#[skuld::test]
fn a_member_whose_identity_was_never_read_is_reported_again_until_a_kill_shows_it_killed() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
let left = |pids: &[u32]| {
TreeKillOutcome::Ran(Err(Unkilled {
members: pids.iter().copied().map(member_left).collect(),
root: None,
resolved: Vec::new(),
}))
};
let first = attached
.settle(&killed, left(&[7]), true)
.expect_err("a member was left");
assert_eq!(pid_left(&first.first), 7);
let later = attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect_err("a walk that finds nothing does not show the member killed");
assert_eq!((pid_left(&later.first), later.others.len()), (7, 0));
assert!(!killed.is_set());
let named_again = attached
.settle(&killed, left(&[7, 8]), true)
.expect_err("two members are left");
assert_eq!(pid_left(&named_again.first), 7);
assert_eq!(named_again.others.iter().map(pid_left).collect::<Vec<_>>(), [8]);
}
#[skuld::test]
fn a_held_member_is_answered_first_whatever_the_next_kill_found() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let unwalked = || {
TreeKillOutcome::Unwalked(crate::error::Error::Unassessable {
detail: "the snapshot failed".into(),
source: None,
})
};
let skipped = || TreeKillOutcome::Skipped {
action: "walk the process table".into(),
holders: Ok(()),
};
let outcomes: [(&str, &dyn Fn() -> TreeKillOutcome); 3] = [
("NoRoot", &|| TreeKillOutcome::NoRoot),
("Unwalked", &unwalked),
("Skipped", &skipped),
];
for (label, outcome) in outcomes {
let killed = TreeKilled::default();
attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(7)],
root: None,
resolved: Vec::new(),
})),
true,
)
.expect_err("a member was left");
let again = attached
.settle(&killed, outcome(), true)
.expect_err("the member is not shown killed");
assert_eq!(pid_left(&again.first), 7, "{label}: {again}");
assert!(!killed.is_set(), "{label}");
}
}
#[skuld::test]
fn a_gone_root_over_a_marked_tree_still_answers_a_held_member() {
use super::{Attached, SettleOutcome, TreeKillOutcome, TreeKilled, Unkilled};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
assert!(killed.is_set());
attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(7)],
root: None,
resolved: Vec::new(),
})),
true,
)
.expect_err("a later kill left a member");
let again = attached
.settle(&killed, TreeKillOutcome::NoRoot, true)
.expect_err("the member is not shown killed");
assert_eq!(pid_left(&again.first), 7, "{again}");
let nothing_held = TreeKilled::default();
attached
.settle(¬hing_held, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
assert!(matches!(
attached.settle(¬hing_held, TreeKillOutcome::NoRoot, true),
Ok(SettleOutcome::Killed)
));
}
#[skuld::test]
fn only_a_walk_not_made_is_answered_before_the_backstop() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(7)],
root: None,
resolved: Vec::new(),
})),
true,
)
.expect_err("a member was left");
let handed_back = attached.unless_unwalked("kill_tree", &killed, TreeKillOutcome::Ran(Ok(())));
assert!(
matches!(handed_back, Ok(TreeKillOutcome::Ran(Ok(())))),
"a walk made is the backstop's to settle"
);
let Err(failure) = attached.unless_unwalked(
"kill_tree",
&killed,
TreeKillOutcome::Unwalked(crate::error::Error::Unassessable {
detail: "the snapshot failed".into(),
source: None,
}),
) else {
panic!("a walk not made is an error");
};
assert_eq!(pid_left(&failure.error), 7, "{:?}", failure.error);
assert!(!failure.root_ended);
assert!(!killed.is_set());
}
#[skuld::test]
fn a_member_whose_kill_was_refused_is_killed_again_by_identity_and_then_settled() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
let first = attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(id.pid())],
root: None,
resolved: vec![id],
})),
true,
)
.expect_err("the member was left");
assert_eq!(pid_left(&first.first), id.pid());
assert!(!killed.is_set());
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("the retry killed the member by its identity");
assert!(killed.is_set());
drop(stdin);
crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
}
fn gone_root_answers_over_gone_members_each_time(exits_on_its_own: bool) {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(id.pid())],
root: None,
resolved: vec![id],
})),
true,
)
.expect_err("the member was left");
let mut held = Some(stdin);
if exits_on_its_own {
drop(held.take());
blocker.wait().expect("the member exits on its own and is reaped");
}
let texts: Vec<String> = (0..2)
.map(|_| {
let left = attached
.settle(&killed, TreeKillOutcome::NoRoot, true)
.expect_err("a gone root walked nothing");
assert!(left.others.is_empty(), "{left}");
assert_eq!(
standing(&killed),
Standing::Unvouched(super::UnvouchedKind::HeldMembersGone)
);
left.first.to_string()
})
.collect();
if !exits_on_its_own {
drop(held.take());
crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
}
assert_eq!(texts[0], texts[1]);
for text in &texts {
assert!(text.contains("are gone"), "{text}");
assert!(!text.contains("nothing was killed"), "{text}");
assert!(!text.contains("killed again"), "{text}");
}
}
#[skuld::test]
fn a_gone_root_over_members_killed_by_the_settlement_says_they_are_gone_each_time() {
gone_root_answers_over_gone_members_each_time(false);
}
#[skuld::test]
fn a_gone_root_over_a_member_that_exited_on_its_own_says_it_is_gone_each_time() {
gone_root_answers_over_gone_members_each_time(true);
}
#[skuld::test]
fn a_drop_over_an_unvouched_tree_warns_of_what_settle_found() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let skipped = || TreeKillOutcome::Skipped {
action: "walk the process table".into(),
holders: Ok(()),
};
let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
let held_gone = tree_left_with(id.pid(), vec![id]);
let warn = attached
.settle_for_drop(&held_gone, skipped(), true)
.expect("an unvouched tree is warned of");
drop(stdin);
crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
assert!(warn.contains("could not be vouched for"), "{warn}");
assert!(warn.contains("skipped the kill"), "{warn}");
assert!(warn.contains("are gone"), "{warn}");
assert!(!warn.contains("no longer tracked"), "{warn}");
let root_left = || {
TreeKillOutcome::Ran(Err(Unkilled {
members: Vec::new(),
root: Some(member_left(1)),
resolved: Vec::new(),
}))
};
let earlier = TreeKilled::default();
Attached::None
.settle(
&earlier,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(8)],
root: None,
resolved: Vec::new(),
})),
true,
)
.expect_err("a member is running");
let warn = attached
.settle_for_drop(&earlier, skipped(), true)
.expect("an unvouched tree is warned of");
assert!(warn.contains("could not be vouched for"), "{warn}");
assert!(warn.contains("skipped the kill"), "{warn}");
assert!(warn.contains("left something running that it could not name"), "{warn}");
assert!(!warn.contains("earlier kill"), "{warn}");
assert!(!warn.contains("members"), "{warn}");
let root_running = TreeKilled::default();
attached
.settle(&root_running, root_left(), false)
.expect_err("the root is running");
let warn = attached
.settle_for_drop(&root_running, skipped(), true)
.expect("an unvouched tree is warned of");
assert!(warn.contains("found the root running"), "{warn}");
assert!(!warn.contains("had ended"), "{warn}");
assert!(!warn.contains("members"), "{warn}");
let root_only = TreeKilled::default();
attached.settle(&root_only, root_left(), true).expect("the root ended");
for _ in 0..2 {
let warn = attached
.settle_for_drop(&root_only, skipped(), true)
.expect("an unvouched tree is warned of");
assert!(warn.contains("could not be vouched for"), "{warn}");
assert!(warn.contains("found the root running"), "{warn}");
assert!(warn.contains("never looked for"), "{warn}");
assert!(!warn.contains("had ended"), "{warn}");
assert!(!warn.contains("members"), "{warn}");
assert!(!warn.contains("skipped the kill"), "{warn}");
assert!(!warn.contains("earlier kill"), "{warn}");
}
let warn = attached
.settle_for_drop(
&TreeKilled::default(),
TreeKillOutcome::Ran(Err(Unkilled {
members: Vec::new(),
root: Some(member_left(1)),
resolved: Vec::new(),
})),
true,
)
.expect("a walk that left the root is warned of");
assert!(warn.contains("could not be vouched for"), "{warn}");
assert!(warn.contains("found the root running"), "{warn}");
assert!(warn.contains("never looked for"), "{warn}");
assert!(!warn.contains("had ended"), "{warn}");
assert!(!warn.contains("members"), "{warn}");
assert!(!warn.contains("skipped the kill"), "{warn}");
let killed = TreeKilled::default();
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
assert_eq!(attached.settle_for_drop(&killed, skipped(), true), None);
assert_eq!(attached.settle_for_drop(&TreeKilled::default(), skipped(), true), None);
}
#[skuld::test]
fn a_walk_that_saw_the_root_running_unvouches_the_tree_whatever_ended_it_afterwards() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let root_left = || {
TreeKillOutcome::Ran(Err(Unkilled {
members: Vec::new(),
root: Some(member_left(1)),
resolved: Vec::new(),
}))
};
for start in ["never", "killed", "root seen running", "held members gone", "earlier"] {
for root_ended in [false, true] {
let label = format!("{start}, root_ended {root_ended}");
let mut after: Box<dyn FnOnce()> = Box::new(|| {});
let killed = match start {
"held members gone" => {
let (killed, reap) = unvouched_tree();
after = reap;
killed
}
_ => TreeKilled::default(),
};
if matches!(start, "killed") {
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a complete kill");
}
if start == "root seen running" {
attached
.settle(&killed, root_left(), false)
.expect_err("the root is left");
}
if start == "earlier" {
Attached::None
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(8)],
root: None,
resolved: Vec::new(),
})),
true,
)
.expect_err("a member is running");
}
let want_start = match start {
"never" => Standing::Never,
"killed" => Standing::Killed,
"root seen running" => Standing::Unvouched(UnvouchedKind::RootSeenRunning),
"held members gone" => Standing::Unvouched(UnvouchedKind::HeldMembersGone),
_ => Standing::Unvouched(UnvouchedKind::Earlier),
};
assert_eq!(standing(&killed), want_start, "{label}: start");
let answer = attached.settle(&killed, root_left(), root_ended);
match answer {
Ok(outcome) => {
assert!(root_ended, "{label}: the root is running");
assert_eq!(
outcome,
super::SettleOutcome::Unvouched {
kind: super::UnvouchedKind::RootSeenRunning
},
"{label}"
);
}
Err(left) => {
assert!(!root_ended, "{label}: the root ended");
assert_eq!(pid_left(&left.first), 1, "{label}");
}
}
assert_eq!(
standing(&killed),
Standing::Unvouched(UnvouchedKind::RootSeenRunning),
"{label}"
);
let want = "found running";
let mut texts = Vec::new();
for _ in 0..2 {
let gone = attached
.settle(&killed, TreeKillOutcome::NoRoot, true)
.expect_err("a gone root walked nothing");
let text = gone.first.to_string();
assert!(!text.contains("nothing was killed"), "{label}: {gone}");
assert!(!text.contains("members"), "{label}: {gone}");
assert!(text.contains(want), "{label}: {gone}");
assert_eq!(
standing(&killed),
Standing::Unvouched(UnvouchedKind::RootSeenRunning),
"{label}"
);
texts.push(text);
}
assert_eq!(texts[0], texts[1], "{label}");
after();
}
}
}
#[skuld::test]
fn a_member_that_exited_since_it_was_left_stops_failing_the_call() {
use super::{Attached, TreeKillOutcome, TreeKilled, Unkilled};
let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
let attached = Attached::TreeWalk(crate::identity::ProcessId::current());
let killed = TreeKilled::default();
let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
attached
.settle(
&killed,
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member_left(id.pid())],
root: None,
resolved: vec![id],
})),
true,
)
.expect_err("the member was left");
drop(stdin);
blocker.wait().expect("the member exits on its own and is reaped");
attached
.settle(&killed, TreeKillOutcome::Ran(Ok(())), true)
.expect("a member that is gone is not left");
assert!(killed.is_set());
}
#[skuld::test]
fn a_sweeps_report_of_the_other_members_it_left_names_its_call() {
use super::{Attached, SweepFailure, TreeKillOutcome, TreeKilled, Unkilled};
use crate::error::Error;
let member = |pid| Error::MemberNotKilled {
pid,
source: Box::new(Error::Containment {
detail: "refused".into(),
}),
note: None,
};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let failure = SweepFailure::of(
"graceful_shutdown_tree",
&Attached::None,
&TreeKilled::default(),
TreeKillOutcome::Ran(Err(Unkilled {
members: vec![member(1), member(2)],
root: None,
resolved: Vec::new(),
})),
Ok(()),
false,
)
.expect_err("two members were left");
assert!(
matches!(failure.error, Error::MemberNotKilled { pid: 1, .. }),
"{:?}",
failure.error
);
let warned = crate::log_capture::records_since_on_current_thread(mark, "pid 2 was not killed");
assert_eq!(warned.len(), 1, "{warned:?}");
assert!(warned[0].1.starts_with("graceful_shutdown_tree: "), "{warned:?}");
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn marker_wanted_installs_for_every_contained_root_and_nothing_else() {
use crate::containment::fdmarker::marker_wanted;
use crate::containment::ContainMode;
for mode in [ContainMode::Strongest, ContainMode::Session, ContainMode::TreeWalk] {
assert!(
marker_wanted(Some(mode), true, false),
"{mode:?} root installs a marker"
);
assert!(
!marker_wanted(Some(mode), false, false),
"{mode:?} nested inherits, never installs"
);
assert!(
!marker_wanted(Some(mode), true, true),
"{mode:?} elevated root must not install"
);
}
assert!(
!marker_wanted(None, true, false),
"an uncontained spawn installs no marker"
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn attached_fd_marker_is_actionable() {
use std::os::fd::{AsFd, AsRawFd};
use super::Attached;
let (read, write) = std::io::pipe().expect("pipe");
let handle = crate::containment::fdmarker::pipe_handle_of(write.as_fd()).expect("handle");
let read_handle = crate::containment::fdmarker::pipe_handle_of(read.as_fd()).expect("read handle");
let prepared = crate::containment::fdmarker::PreparedMarker {
read: std::os::fd::OwnedFd::from(read),
handle,
read_handle,
fd: write.as_fd().as_raw_fd(),
};
let marker = crate::containment::fdmarker::Marker::new(
prepared,
crate::containment::fdmarker::fdmarker_tests::inert_root(),
None,
);
assert!(Attached::FdMarker(marker).is_actionable());
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn prepare_places_the_marker_above_the_callers_reserved_fds() {
use crate::containment::{ContainMode, ContainRequest, Nesting};
let _lock = crate::child::spawn::spawn_lock();
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = super::prepare(
&mut cmd,
&mut crate::child::spawn::in_child::InChild::default(),
&ContainRequest {
mode: Some(ContainMode::Strongest),
nesting: Nesting::Mark,
},
&crate::command::flags::FlagsRequest::default(),
&[3, 4, 5, 6, 7, 8, 9, 10],
false,
&[],
)
.expect("prepare is infallible off Windows");
let marker = prepared.marker.as_ref().expect("a contained macOS root gets a marker");
assert!(
marker.fd > 10,
"prepare placed the marker on fd {}, which a user mapping would dup2 over",
marker.fd
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_failed_marker_install_leaves_prepare_without_one() {
use crate::containment::fdmarker::fault::{lock_for_log_assertion, set_fault, Fault};
use crate::containment::{ContainMode, ContainRequest, Nesting};
let _serialize = lock_for_log_assertion();
let mut cmd = std::process::Command::new("/usr/bin/true");
set_fault(Some(Fault::Pipe));
let prepared = super::prepare(
&mut cmd,
&mut crate::child::spawn::in_child::InChild::default(),
&ContainRequest {
mode: Some(ContainMode::Strongest),
nesting: Nesting::Mark,
},
&crate::command::flags::FlagsRequest::default(),
&[],
false,
&[],
)
.expect("prepare is infallible off Windows");
assert!(prepared.marker.is_none(), "the forced failure must yield no marker");
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn prepare_installs_no_marker_for_an_elevation_derived_spawn() {
use crate::containment::{ContainMode, ContainRequest, Nesting};
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = super::prepare(
&mut cmd,
&mut crate::child::spawn::in_child::InChild::default(),
&ContainRequest {
mode: Some(ContainMode::Strongest),
nesting: Nesting::Mark,
},
&crate::command::flags::FlagsRequest::default(),
&[],
true,
&[],
)
.expect("prepare is infallible off Windows");
assert!(
prepared.marker.is_none(),
"an elevated spawn must not claim marker containment"
);
}
#[cfg(windows)]
#[skuld::test]
fn spawn_identity_distinguishes_a_denied_pid_from_a_vanished_one() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(spawn_identity_distinguishes_a_denied_pid_from_a_vanished_one),
crate::test_spawn::spawn,
) else {
return;
};
use crate::child::spawn::{resolve_identity_unchecked, spawn_identity_error};
use windows::Win32::System::Threading::PROCESS_SYNCHRONIZE;
let child = crate::identity::windows_fixture::spawn_restricted(&done, PROCESS_SYNCHRONIZE.0);
assert!(child.is_running(), "precondition: the subject must be live");
let (read, cause) = resolve_identity_unchecked(&crate::identity::HostKernel, child.pid());
let denied = spawn_identity_error(read, cause);
assert!(
matches!(denied, crate::error::Error::Unassessable { .. }),
"a pid we may not query must not read as vanished: {denied:?}"
);
let (read, cause) = resolve_identity_unchecked(&crate::identity::HostKernel, 0xFFFF_FFF0);
let absent = spawn_identity_error(read, cause);
assert!(
matches!(&absent, crate::error::Error::Io(e) if e.to_string().contains("reaped by another party")),
"absence must not read as denial: {absent:?}"
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_drained_is_unsupported_without_a_marker() {
use super::Attached;
for attached in [Attached::None, Attached::Delegated] {
let err = attached
.wait_drained(Some(std::time::Instant::now()))
.expect_err("a mechanism with no drain edge must be Unsupported");
assert!(matches!(err, crate::error::Error::Unsupported { .. }), "got {err:?}");
}
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_drained_reports_members_remain_then_all_markers_closed() {
use super::Attached;
use crate::containment::fdmarker::{pipe_handle_of, Marker, PreparedMarker};
use crate::containment::TreeDrain;
use std::os::fd::{AsFd, OwnedFd};
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.executable("/bin/sh").args(["sh", "-c", "exec cat >/dev/null"]);
cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
let mut child = cmd.spawn().expect("spawn /bin/sh");
let marker = child.fd_read_end(3.into()).expect("marker read end");
let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");
let handle = pipe_handle_of(marker.as_fd()).expect("handle");
let prepared = PreparedMarker {
read: OwnedFd::from(marker),
handle,
read_handle: handle,
fd: 3,
};
let attached = Attached::FdMarker(Marker::new(
prepared,
crate::containment::fdmarker::fdmarker_tests::inert_root(),
None,
));
assert_eq!(
attached
.wait_drained(Some(std::time::Instant::now()))
.expect("bounded wait while the holder is alive"),
TreeDrain::MembersRemain
);
drop(stdin); child.wait().expect("reap");
assert_eq!(
attached
.wait_drained(None)
.expect("unbounded wait after the holder exits"),
TreeDrain::AllMarkersClosed
);
}
#[cfg(windows)]
#[skuld::test]
fn uac_elevated_attachment_has_no_in_process_route() {
use super::{Attached, Attachment};
use crate::containment::Containment;
use crate::graceful::GracefulMechanism;
let a = Attachment::uac_elevated();
assert_eq!(a.containment, Containment::None);
assert!(matches!(a.attached, Attached::None), "got {:?}", a.attached);
assert_eq!(a.graceful, GracefulMechanism::Unknown);
}
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
enum ChildReport {
Placed,
WriteFailed,
NotReported,
}
#[cfg(target_os = "linux")]
fn decide(leaf_path: &std::path::Path, report: ChildReport) -> (crate::containment::Containment, super::Attached) {
use crate::containment::cgroup::{place_self_in_cgroup_pre_exec, CgroupLeaf};
let leaf = CgroupLeaf::for_test_at(leaf_path.to_path_buf());
match report {
ChildReport::Placed => unsafe { leaf.placement_slot().report_placed_for_test() },
ChildReport::WriteFailed => {
_ = unsafe { place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
}
ChildReport::NotReported => {}
}
let prepared = super::Prepared {
mode: Some(crate::containment::ContainMode::Strongest),
is_root: true,
cgroup_leaf: Some(leaf),
#[cfg(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
};
super::attach_tree(
std::process::id(),
Ok(crate::identity::ProcessId::current()),
crate::containment::cgroup::test_support::handle_of(
std::process::id(),
&crate::containment::cgroup::test_support::pidfd_of(std::process::id()),
),
prepared,
)
.expect("attach_tree")
}
#[cfg(target_os = "linux")]
fn leaf_listing_another_pid(dir: &std::path::Path) -> std::path::PathBuf {
let leaf_path = dir.join("cosca-decision-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let other = std::process::id().wrapping_add(1);
std::fs::write(leaf_path.join("cgroup.procs"), format!("{other}\n")).expect("write cgroup.procs");
leaf_path
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn a_placed_report_outranks_a_cgroup_procs_that_omits_the_child() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = leaf_listing_another_pid(dir.path());
let (containment, attached) = decide(&leaf_path, ChildReport::Placed);
assert_eq!(containment, crate::containment::Containment::CgroupV2);
let super::Attached::Cgroup(leaf) = &attached else {
panic!("got {attached:?}");
};
assert!(
!leaf.holds_spawn_resources(),
"a live child's leaf must not hold its cgroup.procs fd or report pipe past the verdict"
);
assert!(
!leaf_path.join("cgroup.kill").exists(),
"the leaf owns a live tree; nothing may kill it at spawn time"
);
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn a_placed_report_outranks_an_unreadable_cgroup_procs() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-decision-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf (no cgroup.procs inside)");
let (containment, attached) = decide(&leaf_path, ChildReport::Placed);
assert_eq!(containment, crate::containment::Containment::CgroupV2);
assert!(matches!(attached, super::Attached::Cgroup(_)), "got {attached:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_write_degrades_and_removes_the_leaf() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-decision-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let (containment, attached) = decide(&leaf_path, ChildReport::WriteFailed);
assert_eq!(containment, crate::containment::Containment::ProcessGroup);
assert!(matches!(attached, super::Attached::ProcessGroup(_)), "got {attached:?}");
assert!(!leaf_path.exists(), "the degrade must remove the leaf it created");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_degrade_never_kills_through_the_leaf() {
crate::log_capture::install();
for report in [ChildReport::WriteFailed, ChildReport::NotReported] {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = leaf_listing_another_pid(dir.path());
let mark = crate::log_capture::mark();
let (containment, _attached) = decide(&leaf_path, report);
assert_eq!(containment, crate::containment::Containment::ProcessGroup);
assert!(
!leaf_path.join("cgroup.kill").exists(),
"a degrade wrote cgroup.kill: it would kill a tree cosca had just been asked to contain"
);
let left_behind: Vec<String> = crate::log_capture::records_since(mark, &leaf_path.to_string_lossy())
.into_iter()
.filter(|record| record.contains("was not removed"))
.collect();
assert_eq!(
left_behind.len(),
1,
"the unremoved leaf is reported once: {left_behind:?}"
);
}
}
#[cfg(target_os = "linux")]
fn occupied_leaf_for_test(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
let leaf_path = dir.join(name);
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("stand in for the live tree");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
leaf_path
}
#[cfg(target_os = "linux")]
fn cgroup_attachment_for_test(leaf_path: &std::path::Path) -> super::Attachment {
super::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: super::Attached::Cgroup(crate::containment::cgroup::test_support::entered_leaf_at(
leaf_path.to_path_buf(),
)),
graceful: crate::graceful::GracefulMechanism::Process,
}
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn kill_on_drop_false_disarms_a_cgroup_leaf() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-kill-on-drop-false-leaf");
let attachment = cgroup_attachment_for_test(&leaf_path);
attachment.attached.honor_kill_on_drop(false).expect("disarm");
drop(attachment);
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
b"",
"kill_on_drop(false) opts out of the teardown; a tree it killed anyway is the opposite"
);
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn kill_on_drop_true_leaves_a_cgroup_leaf_armed() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-kill-on-drop-true-leaf");
let attachment = cgroup_attachment_for_test(&leaf_path);
attachment.attached.honor_kill_on_drop(true).expect("nothing to disarm");
drop(attachment);
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
b"1",
"the default is still a kill-on-drop teardown"
);
}
#[cfg(windows)]
mod frozen_attach {
use crate::containment::dispatch::{attach, Attached, Attachment, Prepared};
use crate::containment::windows::fault::{force_next, Step};
use crate::containment::{ContainMode, Containment};
use crate::error::Error;
use crate::test_frozen::{
assert_not_released, limit_flags, raw, release, spawn_suspended_blocker, spawn_suspended_releasable,
InitialThread,
};
use windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
const ERROR_ACCESS_DENIED: u32 = 5;
fn prepared(mode: Option<ContainMode>, is_root: bool, frozen: bool) -> Prepared {
Prepared {
mode,
is_root,
graceful: crate::graceful::GracefulMechanism::None,
frozen,
}
}
fn attach_suspended(child: &std::process::Child, prepared: Prepared) -> Result<Attachment, Error> {
let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
panic!("the suspended child must be readable");
};
attach(Ok(id), raw(child), prepared)
}
fn refused_identity() -> Error {
Error::Unassessable {
detail: "the OS refused to report the spawned child's identity".into(),
source: None,
}
}
#[skuld::test]
fn attach_assigns_a_strongest_roots_job_though_its_identity_could_not_be_read() {
let child = spawn_suspended_blocker();
let prepared = prepared(Some(ContainMode::Strongest), true, false);
let attachment = attach(Err(refused_identity()), raw(&child), prepared).expect("attach");
assert_eq!(attachment.containment, Containment::JobObject);
dispose(child);
drop(attachment);
}
#[skuld::test]
fn attach_fails_a_tree_walk_root_with_the_identity_reads_error() {
let child = spawn_suspended_blocker();
let err = attach(
Err(refused_identity()),
raw(&child),
prepared(Some(ContainMode::TreeWalk), true, false),
)
.err()
.expect("a tree walk without an identity must fail the attach");
assert!(matches!(err, Error::Unassessable { source: None, .. }), "got {err:?}");
dispose(child);
}
fn dispose(mut child: std::process::Child) {
child.kill().expect("kill the test child");
child.wait().expect("reap the test child");
}
#[skuld::test]
fn death_watch_attach_frozen_assigns_a_strongest_roots_job_and_leaves_the_thread_suspended() {
let mut child = spawn_suspended_releasable();
let thread = InitialThread::of(child.id());
let attachment = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, true)).expect("attach");
assert_eq!(attachment.containment, Containment::JobObject);
let Attached::JobObject(job) = &attachment.attached else {
panic!("expected a job, got {:?}", attachment.attached);
};
assert_ne!(
limit_flags(job).0 & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0,
0,
"the job must kill on close: the frozen child never runs, so nothing else ends it"
);
assert_eq!(thread.suspend_count(), 1, "a frozen attach must not resume");
drop(attachment);
release(&mut child, &thread);
assert_not_released("the frozen child", child.wait().expect("reap the frozen child"));
}
#[skuld::test]
fn attach_frozen_fails_when_the_strongest_assignment_fails_instead_of_falling_back_to_treewalk() {
let child = spawn_suspended_blocker();
let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);
let err = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, true))
.err()
.expect("a frozen attach with no job must fail");
assert!(matches!(err, Error::Containment { .. }), "got {err:?}");
dispose(child);
}
#[skuld::test]
fn attach_without_hold_still_resumes_and_still_falls_back_to_treewalk() {
let child = spawn_suspended_blocker();
let thread = InitialThread::of(child.id());
let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);
let attachment = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, false)).expect("attach");
assert_eq!(attachment.containment, Containment::TreeWalk);
assert_eq!(thread.suspend_count(), 0, "the ordinary attach resumes the child");
dispose(child);
}
#[skuld::test]
fn attach_frozen_gives_treewalk_nested_and_uncontained_shapes_no_job_and_leaves_them_suspended() {
let shapes = [
(
"treewalk root",
Some(ContainMode::TreeWalk),
true,
Containment::TreeWalk,
),
(
"nested strongest member",
Some(ContainMode::Strongest),
false,
Containment::Delegated,
),
(
"nested treewalk member",
Some(ContainMode::TreeWalk),
false,
Containment::Delegated,
),
("uncontained", None, false, Containment::None),
];
for (name, mode, is_root, expected) in shapes {
let child = spawn_suspended_blocker();
let thread = InitialThread::of(child.id());
let attachment = attach_suspended(&child, prepared(mode, is_root, true)).expect(name);
assert_eq!(attachment.containment, expected, "{name}");
assert!(
!matches!(attachment.attached, Attached::JobObject(_)),
"{name}: no job of its own"
);
assert_eq!(thread.suspend_count(), 1, "{name}: a frozen attach must not resume");
drop(attachment);
dispose(child);
}
}
}