use crate::log_capture::warns_since;
use crate::test_child::Console;
#[cfg(target_os = "linux")]
use crate::test_groups::{setuid, Group};
use crate::ContainMode;
fn refused() -> crate::os_process::fake::SignalAnswer {
crate::os_process::fake::failed_signal(libc::EPERM)
}
fn refusal() -> String {
std::io::Error::from_raw_os_error(libc::EPERM).to_string()
}
fn contained_blocker(mode: ContainMode) -> (crate::Child, crate::PipeWriter) {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
cmd.contain_with(mode);
(cmd.spawn().expect("spawn"), writer)
}
fn bare_blocker() -> (crate::Child, crate::PipeWriter) {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
(cmd.spawn().expect("spawn"), writer)
}
fn failed_write() -> Result<(), crate::error::Error> {
Err(crate::error::Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "w".into(),
source: None,
})
}
#[skuld::test]
fn an_unknown_root_with_a_refused_kill_warns_once() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| {
f.peeks([Err(std::io::Error::other("forced peek failure"))])
.signals([refused()])
});
drop(child);
drop(writer);
fake.assert_peeks_exhausted();
assert_eq!(fake.signal_calls(), [crate::signal::Sig::Kill], "the drop's kill");
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0].starts_with("Child::drop:")
&& warns[0].contains("RootState::Unknown")
&& warns[0].contains(&refusal()),
"{warns:?}"
);
}
#[skuld::test]
fn a_roots_reap_is_said_under_the_name_of_the_caller_that_tore_it_down() {
use crate::containment::dispatch::TeardownCaller;
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let pid = child.pid();
let mark = crate::log_capture::mark();
let torn = child.tear_down(
TeardownCaller::FailedRun,
crate::child::owned::teardown::Disposition::Leave,
);
assert_eq!(torn.fate, crate::error::ChildFate::Reaped);
assert_eq!(
crate::log_capture::records_since_on_current_thread(mark, "teardown of child"),
[(
log::Level::Debug,
format!("teardown after a failed run: teardown of child {pid}: reaped it after the kill")
)]
);
drop(writer);
}
#[skuld::test]
fn finish_elevated_with_an_unknown_root_and_a_failed_reap_warns_once() {
crate::log_capture::install();
let _recorder = crate::containment::unix::fault::record_kill_group();
let (mut child, writer) = contained_blocker(ContainMode::Session);
let pid = child.pid();
let _released = crate::child::spawn::fault::set_between_kill_and_wait(move || {
drop(writer);
crate::test_child::assert_zombie_sigkilled("the root", pid);
});
let mark = crate::log_capture::mark();
let fake = child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
crate::child::spawn::fault::set_force_reap_failure("cosca-unknown-reap-9d1c");
let err = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
fake.assert_peeks_exhausted();
assert!(
crate::child::spawn::fault::take_force_reap_failure().is_none(),
"the cleanup consumed the forced failure"
);
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?} ({err:?})");
assert!(
warns[0].starts_with("finish_elevated:")
&& warns[0].contains("RootState::Unknown")
&& warns[0].contains(&format!("the elevated child pid {pid}: the wait failed")),
"{warns:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_reports_a_walk_that_left_only_the_root_as_unvouched_once() {
use crate::containment::treewalk::fault::LeftBehind;
crate::log_capture::install();
for (left, failed) in [(LeftBehind::Root, false), (LeftBehind::Descendant, true)] {
let (child, writer) = crate::test_child::held_treewalk_blocker_leaving(left);
let mark = crate::log_capture::mark();
let drop_looks = crate::graceful_hooks::watch_for_a_second_look();
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let cleanup = matches!(&error, crate::error::Error::MayHaveStarted { cleanup: Some(_), .. });
assert_eq!(cleanup, failed, "{left:?}: {error:?}");
if failed {
let cleanup = crate::test_child::cleanup_of(&error);
assert!(
matches!(&**cleanup.first(), crate::error::Error::MembersLeft { .. }),
"{left:?}: {cleanup:?}"
);
}
let detail = crate::test_child::detail_of(&error);
let (_, fate, _) = crate::test_child::expect_may_have_started_parts(error, writer);
assert!(fate.not_running(), "{left:?}: {fate:?}");
assert_eq!(drop_looks.seen(), failed, "{left:?}: armed only over a failed kill");
assert!(detail.starts_with("the elevated child"), "{left:?}: {detail}");
assert!(
!detail.contains("its contained tree could not be killed"),
"{left:?}: {detail}"
);
assert_eq!(
detail.contains("could not be vouched for"),
!failed,
"{left:?}: {detail}"
);
let warns = warns_since(mark, "");
let finish_elevated: Vec<_> = warns
.iter()
.filter(|warn| warn.starts_with("finish_elevated:"))
.collect();
assert_eq!(finish_elevated.len(), 1, "{left:?}: {warns:?}");
let unvouched = warns
.iter()
.filter(|warn| warn.contains("could not be vouched for"))
.count();
assert_eq!(unvouched, usize::from(!failed), "{left:?}: {warns:?}");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_makes_no_early_tree_kill_over_an_unvouched_tree_when_it_hands_the_root_back() {
use crate::containment::treewalk::fault::LeftBehind;
crate::log_capture::install();
let (mut child, writer) = crate::test_child::held_treewalk_blocker_leaving(LeftBehind::Root);
let teardowns = crate::child::owned::seams::record_root_teardowns();
let mark = crate::log_capture::mark();
let drop_looks = crate::graceful_hooks::watch_for_a_second_look();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered)])
.reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let detail = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);
assert!(detail.contains("could not be vouched for"), "{detail}");
assert!(
!detail.contains("made early") && !detail.contains("failed too"),
"{detail}"
);
assert!(!drop_looks.seen(), "the handle is disarmed");
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
let warns = warns_since(mark, "");
let unvouched = warns
.iter()
.filter(|warn| warn.contains("could not be vouched for"))
.count();
assert_eq!(unvouched, 1, "{warns:?}");
assert!(
warns
.iter()
.all(|warn| !warn.contains("made early") && !warn.contains("failed too")),
"{warns:?}"
);
handed_back.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_names_the_root_the_first_walk_saw_running_when_the_early_tree_kill_finds_it_gone() {
use crate::containment::treewalk::fault::LeftBehind;
crate::log_capture::install();
let (mut child, writer) = crate::test_child::held_treewalk_blocker_leaving(LeftBehind::Root);
let teardowns = crate::child::owned::seams::record_root_teardowns();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered), refused()])
.reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
});
let pid = child.pid();
let _reaped = crate::child::spawn::fault::set_between_kill_and_wait(move || {
let killed = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
assert_eq!(killed, 0, "{}", std::io::Error::last_os_error());
crate::test_child::wait_until_zombie(pid);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let cleanup = crate::test_child::cleanup_of(&error);
let detail = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);
assert!(
detail.starts_with("the elevated child could not be terminated"),
"{detail}"
);
assert!(
!detail.contains("its contained tree could not be killed") && !detail.contains("failed too"),
"{detail}"
);
let found = "the root an earlier walk found running is gone";
assert!(!detail.contains(found), "{detail}");
assert!(
cleanup
.iter()
.any(|failure| crate::error::said(&**failure).contains(found)),
"the early tree kill's answer: {cleanup:?}"
);
assert!(!detail.contains("left something running"), "{detail}");
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
let warns = warns_since(mark, "");
let tree: Vec<_> = warns
.iter()
.filter(|warn| warn.starts_with("finish_elevated:"))
.collect();
assert_eq!(tree.len(), 1, "{warns:?}");
assert!(tree[0].contains(found), "{warns:?}");
drop(handed_back);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_reports_an_early_tree_kill_that_ends_unvouched_after_a_member_refused_the_first_kill(
#[fixture(setuid)] _group: &Group,
) {
use crate::containment::treewalk::fault::{force_incomplete_once, LeftBehind};
crate::log_capture::install();
let (mut child, writer) = crate::test_privilege::root_over_setuid_blockers(1, |cmd| {
cmd.contain_with(ContainMode::TreeWalk);
});
let pid = child.pid();
let member: u32 = std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children"))
.expect("the root lists its children")
.trim()
.parse()
.expect("the root has the one child");
let teardowns = crate::child::owned::seams::record_root_teardowns();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered)])
.reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
});
let _released = crate::child::spawn::fault::set_between_kill_and_wait(move || {
drop(writer);
while std::path::Path::new(&format!("/proc/{member}")).exists() {
std::thread::yield_now();
}
force_incomplete_once(LeftBehind::Root);
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let detail = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, ());
assert!(!detail.contains("its contained tree could not be killed"), "{detail}");
assert!(
detail.contains("; on the drop's tree kill, made early, ") && detail.contains("could not be vouched for"),
"the early tree kill's answer: {detail}"
);
assert!(!detail.contains("failed too"), "{detail}");
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
let warns = warns_since(mark, "");
let tree: Vec<_> = warns
.iter()
.filter(|warn| warn.starts_with("finish_elevated:"))
.collect();
assert_eq!(tree.len(), 1, "{warns:?}");
assert!(
tree[0].contains("; on the drop's tree kill, made early, ") && tree[0].contains("could not be vouched for"),
"{warns:?}"
);
handed_back.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_walk_that_left_only_the_root_is_settled_by_a_root_someone_else_reaped() {
use crate::containment::treewalk::fault::LeftBehind;
crate::log_capture::install();
let (mut child, writer) = crate::test_child::held_treewalk_blocker_leaving(LeftBehind::Root);
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered), refused()]).reaps([
crate::os_process::fake::ReapAnswer::Foreign(crate::os_process::child::Foreign::Gone),
])
});
let torn = child.tear_down(
crate::containment::dispatch::TeardownCaller::FailedRun,
crate::child::owned::teardown::Disposition::Leave,
);
child.kill_on_drop = false;
assert_eq!(torn.fate, crate::error::ChildFate::Gone);
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains("could not be vouched for"), "{warns:?}");
assert!(!warns[0].contains("members"), "{warns:?}");
assert!(!child.tree.is_killed(), "the walk saw the root running");
drop(writer);
}
#[skuld::test]
fn finish_elevated_hands_back_a_root_whose_kill_was_refused() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let teardowns = crate::child::owned::seams::record_root_teardowns();
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| f.signals([refused()]));
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);
assert!(matches!(fate, crate::error::ChildFate::Running { .. }), "{fate:?}");
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
assert_eq!(fake.signal_calls().len(), 1, "the cleanup's kill alone");
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains(&refusal()), "{warns:?}");
let status = handed_back.wait();
assert!(status.success(), "the root exits on EOF: {status:?}");
}
#[skuld::test]
fn finish_elevated_hands_back_a_root_whose_kill_was_refused_and_look_failed() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let teardowns = crate::child::owned::seams::record_root_teardowns();
child.proc.script_over(|f| {
f.signals([refused()])
.reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);
assert_eq!(fate, crate::error::ChildFate::Unknown);
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
let status = handed_back.wait();
assert!(status.success(), "the root exits on EOF: {status:?}");
}
#[skuld::test]
fn finish_elevated_names_the_failure_of_the_look_after_a_refused_kill() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([refused()])
.reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let cleanup = crate::test_child::cleanup_of(&error);
let said = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);
let failed_look = std::io::Error::from(std::io::ErrorKind::Other).to_string();
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0].contains(&format!("the wait failed: {}", crate::error::io_said(&failed_look))),
"{warns:?}"
);
assert!(said.contains("the wait failed"), "{said}");
assert!(!said.contains(&failed_look) && !said.contains(&refusal()), "{said}");
let codes: Vec<_> = cleanup
.iter()
.map(|failure| crate::error::first_os_code(&**failure))
.collect();
assert_eq!(codes, [Some(libc::EPERM), None], "{cleanup:?}");
assert!(
matches!(&**cleanup.iter().nth(1).expect("the failed look"), crate::error::Error::Io(e) if e.kind() == std::io::ErrorKind::Other),
"{cleanup:?}"
);
handed_back.wait();
}
#[skuld::test]
fn finish_elevated_hands_back_nothing_when_the_root_was_reaped_elsewhere_after_the_kill() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let teardowns = crate::child::owned::seams::record_root_teardowns();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered)])
.reaps([crate::os_process::fake::ReapAnswer::Foreign(
crate::os_process::child::Foreign::Gone,
)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(failure.into(), writer);
assert_eq!(fate, crate::error::ChildFate::Killed);
assert!(handed_back.is_none(), "a root reaped elsewhere is not handed back");
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
}
#[skuld::test]
fn finish_elevated_logs_a_root_reaped_elsewhere_after_the_kill_at_debug() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered)])
.reaps([crate::os_process::fake::ReapAnswer::Foreign(
crate::os_process::child::Foreign::Gone,
)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let (_, _, handed_back) = crate::test_child::expect_may_have_started_parts(failure.into(), writer);
assert!(handed_back.is_none());
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
let debug = crate::log_capture::records_since_on_current_thread(mark, "reaped by someone else");
assert!(
debug.len() == 1 && debug[0].0 == log::Level::Debug,
"one debug record names the foreign reap: {debug:?}"
);
}
#[skuld::test]
fn finish_elevated_keeps_the_refusal_when_the_look_finds_the_root_reaped_elsewhere() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([refused()])
.reaps([crate::os_process::fake::ReapAnswer::Foreign(
crate::os_process::child::Foreign::Gone,
)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let cleanup = crate::test_child::cleanup_of(&error);
let detail = crate::test_child::detail_of(&error);
let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, writer);
assert_eq!(fate, crate::error::ChildFate::Gone);
assert!(handed_back.is_none());
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
assert!(
detail.contains("could not be terminated: reaped by someone else"),
"{detail}"
);
assert_eq!(
crate::error::first_os_code(&**cleanup.first()),
Some(libc::EPERM),
"{cleanup:?}"
);
let debug = crate::log_capture::records_since_on_current_thread(mark, "reaped by someone else");
assert!(
debug.len() == 1 && debug[0].0 == log::Level::Debug && debug[0].1.contains(&refusal()),
"{debug:?}"
);
}
#[skuld::test]
fn finish_elevated_keeps_the_refusal_when_the_look_finds_launchd_holding_the_root() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([refused()])
.reaps([crate::os_process::fake::ReapAnswer::Foreign(
crate::os_process::child::Foreign::Orphaned,
)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let cleanup = crate::test_child::cleanup_of(&error);
let detail = crate::test_child::detail_of(&error);
let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, writer);
assert_eq!(fate, crate::error::ChildFate::Gone);
assert!(handed_back.is_none());
assert_eq!(
crate::error::first_os_code(&**cleanup.first()),
Some(libc::EPERM),
"{cleanup:?}"
);
let clause = "could not be terminated: not ours to reap (launchd";
let reported = format!(
"could not be terminated ({}): not ours to reap (launchd",
crate::error::io_said(refusal())
);
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains(&reported), "{warns:?}");
assert!(detail.contains(clause), "{detail}");
}
#[skuld::test]
fn finish_elevated_names_the_root_when_launchd_holds_it_after_a_delivered_kill() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let pid = child.pid();
let mark = crate::log_capture::mark();
child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered)])
.reaps([crate::os_process::fake::ReapAnswer::Foreign(
crate::os_process::child::Foreign::Orphaned,
)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let detail = crate::test_child::detail_of(&error);
let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, writer);
assert_eq!(fate, crate::error::ChildFate::Killed);
assert!(handed_back.is_none());
let clause = format!("the elevated child pid {pid}: not ours to reap (launchd");
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains(&clause), "{warns:?}");
assert!(detail.contains(&clause), "{detail}");
}
#[skuld::test]
fn finish_elevated_hands_back_a_root_whose_reap_failed_after_a_delivered_kill() {
crate::log_capture::install();
let (mut child, writer) = bare_blocker();
let teardowns = crate::child::owned::seams::record_root_teardowns();
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| {
f.signals([Ok(crate::signal::Sent::Delivered)])
.reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);
assert_eq!(fate, crate::error::ChildFate::Killed);
assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
assert_eq!(fake.signal_calls().len(), 1, "the cleanup's kill alone");
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0].contains("the elevated child pid")
&& warns[0].contains(": the wait failed: ")
&& warns[0].ends_with("handed back to the caller in the error"),
"{warns:?}"
);
let status = handed_back.wait();
assert!(status.success(), "the root exits on EOF: {status:?}");
}
#[cfg(target_os = "linux")]
fn child_in_a_leaf_whose_kill_fails() -> (
crate::Child,
crate::PipeWriter,
std::path::PathBuf,
std::path::PathBuf,
tempfile::TempDir,
) {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-retry-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
let kill_file = leaf_path.join("cgroup.kill");
std::fs::create_dir(&kill_file).expect("make cgroup.kill a directory");
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
let mut child = crate::child::spawn::spawn_uncommitted(&mut cmd, crate::child::spawn::policy::SpawnPolicy::SYNC)
.expect("spawn");
child.tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(
crate::containment::cgroup::test_support::entered_leaf_at(leaf_path.clone()),
));
child.tree.disarm().expect("disarm");
(child, writer, leaf_path, kill_file, dir)
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_retry_that_only_repeats_the_cleanups_warn_is_debug() {
use crate::child::spawn::fault;
crate::log_capture::install();
let (child, writer, leaf_path, _kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
let reaps = fault::record_teardown_reaps();
let _hook = fault::set_between_kill_and_wait(move || drop(writer));
let mark = crate::log_capture::mark();
let err = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
drop(err);
reaps.assert_killed();
let marker = crate::child::spawn::teardown_warn_marker(&leaf_path);
assert_eq!(
crate::log_capture::levels_since(mark, &marker),
[log::Level::Warn],
"the cleanup's warn is the only one"
);
let drop_records = crate::log_capture::records_since_on_current_thread(mark, "Child::drop:");
assert!(
drop_records
.iter()
.any(|(level, text)| *level == log::Level::Debug && text.contains("contained-tree teardown")),
"the drop made its tree kill and said so at debug: {drop_records:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_tree_kill_is_followed_by_the_drops_own_tree_kill() {
use crate::child::spawn::fault;
crate::log_capture::install();
let (child, writer, leaf_path, kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
let reaps = fault::record_teardown_reaps();
let healed = kill_file.clone();
let _hook = fault::set_between_kill_and_wait(move || {
std::fs::remove_dir(&healed).expect("remove the directory");
std::fs::write(&healed, b"").expect("create cgroup.kill");
drop(writer);
});
let mark = crate::log_capture::mark();
let err = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
assert_eq!(
std::fs::read(&kill_file).expect("read cgroup.kill"),
crate::containment::cgroup::KILL_PAYLOAD,
"the handle's drop must make its tree kill ({err:?})"
);
assert_eq!(
crate::log_capture::levels_since(mark, &crate::child::spawn::teardown_warn_marker(&leaf_path)),
[log::Level::Warn],
"the failed kill is reported once, and the drop's tree kill adds nothing"
);
reaps.assert_killed();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_drops_tree_kill_is_made_early_when_a_failed_one_precedes_a_handed_back_root() {
use crate::child::spawn::fault;
crate::log_capture::install();
let (mut child, writer, _leaf_path, kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
child.proc.script_over(|f| f.signals([refused()]));
let healed = kill_file.clone();
let _hook = fault::set_between_kill_and_wait(move || {
std::fs::remove_dir(&healed).expect("remove the directory");
std::fs::write(&healed, b"").expect("create cgroup.kill");
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);
assert!(matches!(fate, crate::error::ChildFate::Running { .. }), "{fate:?}");
assert_eq!(
std::fs::read(&kill_file).expect("read cgroup.kill"),
crate::containment::cgroup::KILL_PAYLOAD,
"the cleanup must make the drop's tree kill"
);
handed_back.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_tree_kill_that_worked_when_made_early_is_reported_as_such_not_as_a_failure() {
use crate::child::spawn::fault;
crate::log_capture::install();
let (mut child, writer, leaf_path, kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
child.proc.script_over(|f| f.signals([refused()]));
let healed = kill_file.clone();
let _hook = fault::set_between_kill_and_wait(move || {
std::fs::remove_dir(&healed).expect("remove the directory");
std::fs::write(&healed, b"").expect("create cgroup.kill");
});
let mark = crate::log_capture::mark();
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let detail = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);
let first = std::io::Error::from_raw_os_error(libc::EISDIR).to_string();
let warns = warns_since(mark, "");
let warn = warns
.iter()
.find(|warn| warn.contains(&leaf_path.display().to_string()))
.unwrap_or_else(|| panic!("no warn names the tree: {warns:?}"));
assert!(
warn.contains("needed the drop's tree kill, made early") && warn.contains(&first),
"the warn says the early tree kill was needed, after: {first}: {warn}"
);
assert!(
!warn.contains(crate::child::spawn::TREE_TEARDOWN_WARN),
"the tree was killed: {warn}"
);
assert!(
detail.starts_with("the elevated child could not be terminated") && !detail.contains("could not be killed"),
"the error blames no tree: {detail}"
);
handed_back.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_tree_kill_that_failed_when_made_early_too_names_both_failures() {
crate::log_capture::install();
let (mut child, writer, leaf_path, _kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
child.proc.script_over(|f| f.signals([refused()]));
let _first = crate::containment::cgroup::fault::fail_next_kill_write();
let mark = crate::log_capture::mark();
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let cleanup = crate::test_child::cleanup_of(&error);
let detail = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);
let first = std::io::Error::from_raw_os_error(libc::EIO).to_string();
let early = std::io::Error::from_raw_os_error(libc::EISDIR).to_string();
let warns = warns_since(mark, "");
let warn = warns
.iter()
.find(|warn| warn.contains(&leaf_path.display().to_string()))
.unwrap_or_else(|| panic!("no warn names the tree: {warns:?}"));
let report = format!(
"the drop's tree kill, made early, failed too (process containment failed: the kernel refused the \
write of {}/cgroup.kill: {})",
leaf_path.display(),
crate::error::io_said(&early)
);
assert!(
detail.starts_with("the elevated child could not be terminated"),
"{detail}"
);
assert!(
!detail.contains("failed too") && !detail.contains("its contained tree could not be killed"),
"{detail}"
);
assert!(
!detail.contains(&first) && !detail.contains(&early),
"a failure is in the text: {detail}"
);
let codes: Vec<_> = cleanup
.iter()
.map(|failure| crate::error::first_os_code(&**failure))
.collect();
assert_eq!(
codes,
[Some(libc::EIO), Some(libc::EPERM), Some(libc::EISDIR)],
"the first tree kill's failure, the root's refusal, the early one's: {cleanup:?}"
);
assert!(warn.contains(&first), "the first failure: {warn}");
assert!(warn.contains(&report), "the early kill's Report: {warn}");
handed_back.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_skipped_tree_kill_keeps_its_note_when_the_root_is_handed_back() {
let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
crate::log_capture::install();
let (mut child, writer) = contained_blocker(ContainMode::Session);
child.proc.script_over(|f| {
f.peeks([Err(std::io::Error::other("forced peek failure"))])
.signals([refused()])
});
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let detail = crate::test_child::detail_of(&error);
let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);
assert!(
detail.contains("its contained tree was not killed"),
"nothing killed the tree: {detail}"
);
handed_back.wait();
}
#[skuld::test]
fn finish_elevated_leaves_the_handle_armed_after_a_skipped_tree_kill() {
#[cfg(target_os = "linux")]
let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
crate::log_capture::install();
let (mut child, writer) = contained_blocker(ContainMode::Session);
child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
let mark = crate::log_capture::mark();
let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
let error = crate::error::Error::from(failure);
let detail = crate::test_child::detail_of(&error);
let (_, _, _) = crate::test_child::expect_may_have_started_parts(error, writer);
assert!(
detail.contains("its contained tree was not killed"),
"nothing killed the tree: {detail}"
);
let drops = crate::log_capture::records_since_on_current_thread(mark, "Child::drop:");
assert!(!drops.is_empty(), "the handle was disarmed by a kill that did not run");
}
#[skuld::test]
fn a_teardown_that_skipped_the_tree_kill_does_not_mark_the_tree_killed() {
#[cfg(target_os = "linux")]
let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
crate::log_capture::install();
let (mut child, writer) = contained_blocker(ContainMode::Session);
child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
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(), "a skipped kill does not mark the tree killed");
drop(writer);
}
#[skuld::test]
fn a_handle_that_could_not_say_is_logged_when_the_number_shows_the_reap() {
crate::log_capture::install();
let (mut child, _writer) = contained_blocker(ContainMode::Session);
let mark = crate::log_capture::mark();
let _number = crate::child::fault::force_next_root_read(crate::identity::Resolved::Gone);
let fake = child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("handle doubt 6e2"))]));
let view = crate::containment::DropView::read(
crate::containment::dispatch::TeardownCaller::FailedRun,
child.pid(),
child.id,
|| child.proc.state(),
&child.tree,
);
fake.assert_peeks_exhausted();
assert!(
matches!(view.root, crate::signal::RootState::Reaped { .. }),
"{:?}",
view.root
);
let records = crate::log_capture::records_since_on_current_thread(mark, "handle doubt 6e2");
assert_eq!(records.len(), 1, "{records:?}");
assert!(
records[0].0 == log::Level::Debug && records[0].1.starts_with("teardown after a failed run:"),
"{records:?}"
);
}
#[skuld::test]
fn the_look_a_kill_decides_on_is_the_one_the_report_is_worded_from() {
let (mut child, _writer) = contained_blocker(ContainMode::Session);
let _number = crate::child::fault::force_next_root_read(crate::identity::Resolved::Gone);
let fake = child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("handle doubt 7a1"))]));
let view = crate::containment::DropView::read(
crate::containment::dispatch::TeardownCaller::Drop,
child.pid(),
child.id,
|| child.proc.state(),
&child.tree,
);
fake.assert_peeks_exhausted();
assert!(view.leaves_root_alone());
assert!(
matches!(view.look(), crate::signal::RootState::Reaped { .. }),
"{:?}",
view.look()
);
}
#[cfg(debug_assertions)] #[skuld::test]
fn asking_why_a_trusted_root_is_untrusted_is_a_contract_breach() {
let view = crate::containment::DropView {
caller: crate::containment::dispatch::TeardownCaller::Drop,
root_pid: 1,
root: crate::signal::RootState::Unreaped,
tree_killed: false,
};
let asked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| view.why_number_untrusted()));
assert!(asked.is_err(), "a trusted root has no untrusted number to explain");
}