use crate::child::spawn::failure::{expect_may_have_started_with, expect_not_started};
use crate::child::spawn::fault;
use crate::error::{ChildFate, Error};
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
use crate::tokio::Command;
fn teardown_blocker() -> (Command, fault::TeardownBlocker) {
let fault::TeardownBlockerParts {
argv,
stdin,
stdout,
guard,
} = fault::teardown_blocker_parts();
let mut cmd = Command::new();
cmd.args(argv);
cmd.stdin(stdin).expect("set stdin pipe");
if let Some(stdout) = stdout {
cmd.stdout(stdout).expect("set stdout");
}
(cmd, guard)
}
#[cfg(target_os = "linux")]
fn blocker() -> Command {
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::test_child::leaked_writer_stdin())
.expect("set stdin pipe");
cmd
}
#[skuld::test]
async fn identity_failure_reaps_the_spawned_child() {
fault::set_force_identity_vanished(true);
let (mut cmd, teardown) = teardown_blocker();
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
err.expect("forced identity-vanish must make spawn return Err"),
);
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the teardown killed and reaped the child"
);
assert!(
matches!(err, Error::Io(_)),
"identity-vanish surfaces as an Io error, got {err:?}"
);
fault::assert_child_reaped(fault::take_captured().expect("seam captured the child's identity"));
teardown.assert_killed();
}
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn attach_failure_reaps_the_spawned_child() {
fault::set_force_attach_failure(true);
let (mut cmd, teardown) = teardown_blocker();
let err = cmd.spawn().err();
fault::set_force_attach_failure(false);
let (err, fate) = expect_may_have_started_with(err.expect("forced attach failure must make spawn return Err"));
assert_eq!(fate, ChildFate::Reaped, "the teardown killed and reaped the child");
assert!(
matches!(err, Error::Containment { .. }),
"a real attach failure surfaces as Error::Containment, got {err:?}"
);
fault::assert_child_reaped(fault::take_captured().expect("seam captured the child's identity"));
teardown.assert_killed();
}
#[cfg(unix)]
#[skuld::test]
async fn a_bare_exact_name_loads_the_file_in_the_childs_cwd_not_one_on_path() {
use crate::test_child::{cwd_and_path_tools, CWD_TOOL_EXIT};
let (cwd, on_path) = cwd_and_path_tools();
let mut c = Command::new();
c.raw_executable("tool")
.args(["tool"])
.current_dir(cwd.path())
.env("PATH", on_path.path());
let status = c.spawn().expect("spawn").wait().await.expect("wait");
assert_eq!(status.code(), Some(CWD_TOOL_EXIT));
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_a_post_fork_tokio_failure_leaves_no_live_child_in_a_leaked_leaf(#[fixture(cgroup)] _group: &Group) {
let mut cmd = blocker();
cmd.contain();
let (_err, fate) = {
let _failing = fault::fail_tokio_spawns_after_fork();
expect_may_have_started_with(cmd.spawn().expect_err("the forced failure must fail the spawn"))
};
assert_eq!(fate, ChildFate::Reaped, "killed and reaped through its pidfd");
let pid = fault::take_forgotten_pid().expect("the seam dropped a child");
let leaf = fault::take_forgotten_leaf().expect("the dropped spawn was contained in a leaf");
let pidfd = fault::take_forgotten_pidfd().expect("the seam took a pidfd for the child");
assert!(reaped_through(&pidfd), "the child {pid} must be reaped");
if leaf.exists() {
let events = std::fs::read_to_string(leaf.join("cgroup.events")).expect("read cgroup.events");
assert!(
events.lines().any(|line| line == "populated 0"),
"{} still holds a process",
leaf.display()
);
std::fs::remove_dir(&leaf).expect("remove the drained leaf");
}
}
#[skuld::test]
fn a_failed_teardown_kill_in_the_async_spawn_asserts_all_but_eperm() {
use crate::stdio::Stdio;
use std::io::ErrorKind;
for (kind, asserted) in [(ErrorKind::PermissionDenied, false), (ErrorKind::Other, true)] {
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let releases = crate::tokio::child::fault::count_backend_drops();
let reaps = fault::record_teardown_reaps();
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
runtime.block_on(async {
let mut cmd = crate::tokio::Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(Stdio::pipe_in()).unwrap().stdout(Stdio::null()).unwrap();
let force: fn(bool) = if cfg!(target_os = "macos") {
fault::set_force_identity_vanished
} else {
fault::set_force_attach_failure
};
force(true);
fault::set_force_kill_failure_leaving_child_alive_as("cosca-async-kill-fail-5d2c", kind);
let err = cmd.spawn().err();
force(false);
err
})
}));
assert_eq!(
fault::take_force_kill_failure(),
None,
"{kind:?}: the kill failure must be consumed"
);
assert_eq!(
outcome.is_err(),
asserted && cfg!(debug_assertions),
"{kind:?}: the debug_assert fires in exactly the builds that keep it, and never for EPERM"
);
if let Ok(err) = outcome {
err.expect("the forced arm must fail the spawn");
}
assert_eq!(
releases.get(),
usize::from(!cfg!(target_os = "linux")),
"{kind:?}: the refused-kill arm releases the child to tokio exactly when there is no pidfd"
);
#[cfg(target_os = "linux")]
assert_eq!(
reaps.recorded().len(),
1,
"{kind:?}: the refused-kill arm must have reaped the child through its pidfd"
);
drop(reaps);
let captured = fault::take_captured().expect("seam captured the child's identity");
drive_until_reaped(&runtime, &captured);
fault::assert_child_reaped(captured);
}
}
fn drive_until_reaped(
runtime: &::tokio::runtime::Runtime,
captured: &crate::identity::Resolved<crate::identity::ProcessId>,
) {
let crate::identity::Resolved::Found(id) = captured else {
panic!("the seam must capture a resolved identity, got {captured:?}");
};
#[cfg(unix)]
let pending = || id.exists() == crate::identity::Existence::Present;
#[cfg(windows)]
let pending = || id.is_alive() != crate::identity::Liveness::Dead;
while pending() {
runtime.block_on(::tokio::task::yield_now());
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_post_fork_tokio_failure_without_a_leaf_says_the_child_may_be_unreachable() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let mut cmd = blocker();
cmd.contain_with(crate::ContainMode::TreeWalk);
let mark = crate::log_capture::mark();
let (_err, fate) = {
let _failing = fault::fail_tokio_spawns_after_fork();
expect_may_have_started_with(cmd.spawn().expect_err("the forced failure must fail the spawn"))
};
assert_eq!(fate, ChildFate::Reaped, "killed and reaped through its pidfd");
let pid = fault::take_forgotten_pid().expect("the seam dropped a child");
assert!(
crate::log_capture::records_since(mark, "nothing can reach it")
.iter()
.zip(crate::log_capture::levels_since(mark, "nothing can reach it"))
.any(|(_, level)| level == log::Level::Warn),
"the failure must say the child may be left running"
);
let pidfd = fault::take_forgotten_pidfd().expect("the seam took a pidfd for the child");
assert!(reaped_through(&pidfd), "the child {pid} must be reaped");
}
#[skuld::test]
fn the_unreachable_child_warning_is_every_time() {
use crate::containment::AbandonedChild;
crate::log_capture::install();
let error = || Error::Io(std::io::Error::other("cosca-abandoned-warn-probe-6f21"));
let marker = "cosca-abandoned-warn-probe-6f21";
for child in [AbandonedChild::MaybeUnreachable, AbandonedChild::MaybeUnreaped] {
let mark = crate::log_capture::mark();
super::warn_for_abandoned(child, &error());
super::warn_for_abandoned(child, &error());
assert_eq!(
crate::log_capture::levels_since(mark, marker),
[log::Level::Warn, log::Level::Warn]
);
}
}
#[skuld::test]
fn ended_abandoned_child_logs_nothing() {
use crate::containment::AbandonedChild;
crate::log_capture::install();
let error = Error::Io(std::io::Error::other("cosca-abandoned-ended-probe-3a17"));
let marker = "cosca-abandoned-ended-probe-3a17";
let mark = crate::log_capture::mark();
super::warn_for_abandoned(AbandonedChild::Ended, &error);
assert_eq!(crate::log_capture::levels_since(mark, marker), Vec::<log::Level>::new());
}
#[cfg(target_os = "linux")]
fn warned_for(mark: usize, pid: u32, marker: &str) -> bool {
let spawn = format!("for child {pid})");
crate::log_capture::records_since(mark, marker)
.iter()
.zip(crate::log_capture::levels_since(mark, marker))
.any(|(record, level)| record.contains(&spawn) && level == log::Level::Warn)
}
#[cfg(target_os = "linux")]
fn reaped_through(pidfd: &std::os::fd::OwnedFd) -> bool {
use std::os::fd::AsFd;
use rustix::process::{waitid, WaitId, WaitIdOptions};
matches!(
waitid(
WaitId::PidFd(pidfd.as_fd()),
WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
),
Err(rustix::io::Errno::CHILD)
)
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_a_post_fork_tokio_failure_warns_only_for_a_child_out_of_reach(#[fixture(cgroup)] _group: &Group) {
crate::tokio::test_runtime::assert_current_thread();
use crate::containment::cgroup::fault as cgroup_fault;
crate::log_capture::install();
for (placed, refuses) in [(true, false), (false, false), (false, true)] {
let mut cmd = blocker();
cmd.contain();
let mark = crate::log_capture::mark();
cgroup_fault::set_force_child_pidfd_failure(true);
if !placed {
cgroup_fault::set_force_placement_write_result(0);
}
let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
if refuses {
cgroup_fault::set_force_child_kill_denied(true);
cgroup_fault::set_background_reap_notifier(reaped_tx);
}
fault::set_force_post_fork_failure(true);
assert!(cmd.spawn().is_err(), "the forced failure must fail the spawn");
cgroup_fault::set_force_child_pidfd_failure(false);
let _ = cgroup_fault::take_force_placement_write_result();
let pid = fault::take_forgotten_pid().expect("the seam dropped a child");
let pidfd = fault::take_forgotten_pidfd().expect("the seam took a pidfd for the child");
let _ = fault::take_forgotten_leaf();
let case = format!("placed: {placed}, refuses the kill: {refuses}");
assert_eq!(
warned_for(mark, pid, "nothing can reach it"),
refuses,
"{case}: the warning must fire exactly when the child is out of reach"
);
if refuses {
assert!(!reaped_through(&pidfd), "{case}: the child is still running");
rustix::process::pidfd_send_signal(&pidfd, rustix::process::Signal::KILL).expect("kill the child");
reaped_rx.recv().expect("the background reaper must reap it");
} else {
assert!(
cgroup_fault::take_reaped_orphans().contains(&(pid, Some(libc::SIGKILL))),
"{case}: the child must be killed by its pid"
);
}
assert!(reaped_through(&pidfd), "{case}: the child must be reaped");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_an_identity_failure_leaves_the_child_to_tokio(#[fixture(cgroup)] _group: &Group) {
let _ = crate::containment::cgroup::fault::take_reaped_orphans();
fault::set_force_identity_vanished(true);
let (mut cmd, teardown) = teardown_blocker();
cmd.contain();
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
err.expect("forced identity-vanish must make spawn return Err");
assert_eq!(
crate::containment::cgroup::fault::take_reaped_orphans(),
Vec::new(),
"the leaf must not reap a child tokio owns"
);
fault::assert_child_reaped(fault::take_captured().expect("seam captured the child's identity"));
teardown.assert_killed();
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_tokio_identity_failure_settles_the_leaf_verdict_before_the_kill(#[fixture(cgroup)] _group: &Group) {
use std::cell::Cell;
use std::rc::Rc;
use crate::send_log::Capture;
use crate::signal::Sig;
let (mut cmd, teardown) = teardown_blocker();
cmd.contain();
let capture = Rc::new(Capture::start());
let sends_at_settle = Rc::new(Cell::new(None));
let _hook = crate::containment::cgroup::fault::set_on_take_placement({
let (capture, sends_at_settle) = (Rc::clone(&capture), Rc::clone(&sends_at_settle));
move || sends_at_settle.set(Some(capture.entries().len()))
});
fault::set_force_identity_vanished(true);
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
err.expect("a vanished identity must fail the spawn");
let Some(crate::identity::Resolved::Found(child)) = fault::take_captured() else {
panic!("the seam must capture the child's identity");
};
assert_eq!(
sends_at_settle.get(),
Some(0),
"the verdict must be settled, and before anything is sent to the child"
);
assert!(
capture
.entries()
.iter()
.any(|&(pid, sig, _)| pid == child.pid() && sig == Sig::Kill),
"the child must be killed after the verdict: {:?}",
capture.entries()
);
teardown.assert_killed();
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_an_identity_failure_whose_kill_is_refused_leaves_the_child_to_tokio(#[fixture(cgroup)] _group: &Group) {
let _ = crate::containment::cgroup::fault::take_reaped_orphans();
fault::set_force_identity_vanished(true);
fault::set_force_kill_failure_leaving_child_alive_as(
"cosca-identity-eperm-4c19",
std::io::ErrorKind::PermissionDenied,
);
let mut cmd = blocker();
cmd.contain();
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
err.expect("forced identity-vanish must make spawn return Err");
assert_eq!(
fault::take_force_kill_failure(),
None,
"the kill failure must be consumed"
);
let _ = fault::take_captured();
assert_eq!(
crate::containment::cgroup::fault::take_reaped_orphans(),
Vec::new(),
"the leaf must not reap a child tokio owns"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_abandoned_spawn_writes_nothing_into_the_childs_stdio(#[fixture(cgroup)] _group: &Group) {
use std::io::{Read, Seek, Write};
use std::os::fd::{AsFd, AsRawFd};
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
use crate::test_stdio::RestoreStdio;
let Some(done) = own_process(
test_path!(cgroup_an_abandoned_spawn_writes_nothing_into_the_childs_stdio),
spawn,
) else {
return;
};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let mut file = tempfile::tempfile().expect("tempfile");
let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
runtime.block_on(async {
let mut cmd = blocker();
for slot in [1, 2] {
cmd.fd(
slot,
crate::stdio::Stdio::from_file(file.try_clone().expect("clone the file")),
)
.expect("wire the slot to the file");
}
cmd.contain();
let restore = RestoreStdio::close(&done, &[1, 2]);
crate::containment::cgroup::fault::set_hook_gate(gate_read.as_raw_fd());
fault::set_force_post_fork_failure(true);
let spawned = cmd.spawn();
let _ = crate::containment::cgroup::fault::take_hook_gate();
drop(restore);
gate_write.write_all(b"x").expect("release the child");
assert!(spawned.is_err(), "the forced failure must fail the spawn");
let pidfd = fault::take_forgotten_pidfd().expect("the seam took a pidfd for the child");
let pid = fault::take_forgotten_pid().expect("the seam dropped a child");
let _ = fault::take_forgotten_leaf();
let status = loop {
match rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED,
) {
Err(rustix::io::Errno::INTR) => continue,
other => break other.expect("reap the child").expect("it exited"),
}
};
assert!(
warned_for(mark, pid, "left unreaped"),
"the spawn must say its child may be left unreaped"
);
assert_eq!(
status.exit_status(),
Some(crate::containment::cgroup::ABANDONED_EXIT),
"the abandoned child must exit from its hook"
);
});
let mut written = Vec::new();
file.rewind().expect("rewind the file");
file.read_to_end(&mut written).expect("read the file");
assert!(
!written.windows(4).any(|w| w == b"NOEX"),
"std's error record reached the child's stdio: {written:?}"
);
}
#[cfg(target_os = "linux")]
fn opted_out_blocker(stdin: crate::stdio::Stdio) -> crate::command::Command {
let mut cmd = crate::command::Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin pipe");
cmd.kill_on_drop(false);
cmd
}
#[cfg(target_os = "linux")]
fn opted_out_teardown_blocker() -> (crate::command::Command, fault::TeardownBlocker) {
let fault::TeardownBlockerParts {
argv,
stdin,
stdout: _,
guard,
} = fault::teardown_blocker_parts();
let mut cmd = crate::command::Command::new();
cmd.args(argv);
cmd.stdin(stdin).expect("set stdin pipe");
cmd.kill_on_drop(false);
(cmd, guard)
}
#[cfg(target_os = "linux")]
fn attach_entered_leaf(leaf_path: &std::path::Path) {
std::fs::create_dir(leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::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]
async fn kill_on_drop_false_disarms_the_leaf_only_when_the_spawn_commits() {
for commit in [false, true] {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-async-commit-leaf");
attach_entered_leaf(&leaf_path);
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = opted_out_blocker(stdin);
let mut child = super::spawn_uncommitted(&mut cmd).expect("spawn");
if commit {
child.commit_kill_on_drop();
}
child.kill().expect("end the stand-in root");
drop(writer);
let status = child.wait().await.expect("reap the stand-in root");
assert_eq!(
std::os::unix::process::ExitStatusExt::signal(&status),
Some(libc::SIGKILL),
"the stand-in root must die of the kill, got {status:?}"
);
drop(child);
let expected: &[u8] = if commit { b"" } else { b"1" };
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
expected,
"committed: {commit}"
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_password_write_kills_the_contained_tree() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-async-password-leaf");
attach_entered_leaf(&leaf_path);
let (mut cmd, teardown) = opted_out_teardown_blocker();
let mut child = super::spawn_uncommitted(&mut cmd).expect("spawn");
child.detach();
crate::containment::cgroup::fault::record_leaf_steps();
let mark = crate::log_capture::mark();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
assert!(
matches!(
err,
Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
..
}
),
"got {err:?}"
);
let steps = crate::containment::cgroup::fault::take_leaf_steps();
assert_eq!(
steps.first().map(String::as_str),
Some("kill"),
"the failed spawn must kill its tree through the leaf, got {steps:?}"
);
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
crate::containment::cgroup::KILL_PAYLOAD,
"the failed spawn must kill its tree through the leaf"
);
assert_eq!(
crate::log_capture::levels_since(mark, &crate::child::spawn::teardown_warn_marker(&leaf_path)),
Vec::<log::Level>::new(),
"a successful tree kill must not warn"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_password_write_removes_the_leaf_once_the_tree_drains() {
crate::tokio::test_runtime::assert_current_thread();
use crate::containment::cgroup::fault as leaf_fault;
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
crate::log_capture::install();
let name = "cosca-async-password-drains-leaf";
let fake = FakeLeaf::new(name, true);
let (path, events) = (fake.leaf.clone(), fake.events.clone());
leaf_fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&path, &events));
let (blocking, wait_reached) = std::sync::mpsc::channel();
leaf_fault::set_drain_blocking_notifier(blocking);
let members = fake.events.clone();
let exiting = std::thread::spawn(move || {
if wait_reached.recv().is_ok() {
FakeLeaf::set_populated(&members, false);
}
});
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::Attached::Cgroup(entered_leaf_at(fake.leaf.clone())),
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = opted_out_teardown_blocker();
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let mark = crate::log_capture::mark();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
leaf_fault::take_drain_blocking_notifier();
exiting.join().expect("the exiting thread");
leaf_fault::take_rmdir_hook();
assert!(matches!(err, Error::Elevation { .. }), "got {err:?}");
assert!(
!fake.leaf.exists(),
"the drained leaf must be removed by the handle's drop"
);
assert_eq!(
crate::log_capture::levels_since(mark, name),
Vec::<log::Level>::new(),
"a leaf that was removed must not be warned about"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_password_write_warns_when_the_tree_kill_fails() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-async-password-kill-fail-leaf");
attach_entered_leaf(&leaf_path);
let (mut cmd, teardown) = opted_out_teardown_blocker();
let mut child = super::spawn_uncommitted(&mut cmd).expect("spawn");
child.detach();
std::fs::remove_file(leaf_path.join("cgroup.kill")).expect("remove the fixture's cgroup.kill file");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill a directory");
let mark = crate::log_capture::mark();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
assert!(
matches!(
err,
Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
..
}
),
"got {err:?}"
);
let marker = crate::child::spawn::teardown_warn_marker(&leaf_path);
assert_eq!(
crate::log_capture::levels_since(mark, &marker),
[log::Level::Warn],
"a forced tree-kill failure must be logged at warn"
);
let errno_text = std::io::Error::from_raw_os_error(libc::EISDIR).to_string();
let records = crate::log_capture::records_since(mark, &marker);
assert!(
records[0].contains(&errno_text),
"the warning must name the OS reason the write failed, got {records:?}"
);
}
#[cfg(target_os = "linux")]
fn reaped(pid: u32) -> bool {
let mut status = 0;
let r = unsafe { libc::waitpid(pid as i32, &mut status, libc::WNOHANG) };
r == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD)
}
#[cfg(target_os = "linux")]
fn failed_write() -> Result<(), Error> {
Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
})
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_password_write_kills_and_reaps_a_delegated_root() {
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::Delegated,
attached: crate::containment::Attached::Delegated,
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = opted_out_teardown_blocker();
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let pid = child.id().pid();
let err = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
let (err, fate) = err;
assert_eq!(fate, crate::error::ChildFate::Reaped, "killed and reaped");
teardown.assert_killed();
let reaped = reaped(pid);
if !reaped {
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
}
assert!(reaped, "the root must be killed and reaped, got {err:?}");
assert!(err.to_string().contains("was terminated"), "got {err:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_password_write_reaps_the_root_when_the_tree_kill_fails() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-unkillable-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill unwritable");
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::Attached::Cgroup(crate::containment::cgroup::test_support::entered_leaf_at(
leaf_path.clone(),
)),
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = opted_out_teardown_blocker();
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let pid = child.id().pid();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
assert!(reaped(pid), "the root was killed, so it must be reaped, got {err:?}");
let detail = err.to_string();
assert!(detail.contains("was terminated"), "the root was killed, got {detail}");
assert!(
detail.contains("its contained tree could not be killed"),
"the tree's failure is reported, got {detail}"
);
}
#[cfg(unix)]
#[skuld::test]
async fn finish_elevated_after_a_foreign_reap_sends_no_killpg_to_a_process_group() {
crate::tokio::test_runtime::assert_current_thread();
let recorder = crate::containment::unix::fault::record_kill_group();
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin pipe");
cmd.contain_with(crate::ContainMode::Session);
let child = cmd.spawn().expect("spawn");
assert!(
child.carries_recyclable_pgid(),
"the test needs a number-named group kill"
);
let pid = child.id().pid();
drop(writer);
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 err = super::finish_elevated(
child,
Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("the spawn fails")
.expect_may_have_started_with();
let (err, fate) = err;
assert_eq!(fate, crate::error::ChildFate::Gone, "reaped by someone else");
let Error::Elevation { detail, .. } = err else {
panic!("expected an Elevation error, got {err:?}");
};
assert_eq!(
recorder.killed(),
Vec::<i32>::new(),
"a reaped root's group number may name another group: no killpg ({detail})"
);
assert!(detail.contains("process group"), "{detail}");
assert!(detail.contains("already reaped"), "{detail}");
}
#[skuld::test]
async fn a_refused_stdio_setup_did_not_start_the_program() {
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdout(crate::stdio::Stdio::merge(crate::stdio::Fd::STDERR))
.expect("stdout");
cmd.stderr(crate::stdio::Stdio::merge(crate::stdio::Fd::STDOUT))
.expect("stderr");
let err = expect_not_started(cmd.spawn().expect_err("a merge into a merge is refused"));
assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
}
#[skuld::test]
async fn a_failed_exec_may_have_started_the_program() {
let mut cmd = Command::new();
cmd.args(["cosca-no-such-program-142"]);
let (err, fate) = expect_may_have_started_with(cmd.spawn().expect_err("a missing program fails the spawn"));
let expected = if cfg!(target_os = "linux") {
ChildFate::Gone
} else {
ChildFate::Running { id: None }
};
assert_eq!(fate, expected);
assert!(
matches!(err, Error::Io(ref e) if e.kind() == std::io::ErrorKind::NotFound),
"{err:?}"
);
}
#[cfg(unix)]
#[skuld::test]
async fn run_to_completion_failures_after_the_spawn_may_have_started() {
let mut cmd = Command::new();
cmd.args(["printf", "\\377"]);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
cmd.read().await.expect_err("invalid UTF-8 fails `read`"),
);
assert_eq!(fate, crate::error::ChildFate::Reaped, "`read` collected the exit");
assert!(
matches!(err, Error::Io(ref e) if e.kind() == std::io::ErrorKind::InvalidData),
"{err:?}"
);
}
#[skuld::test]
fn a_spawn_outside_a_runtime_did_not_start_the_program() {
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
expect_not_started(cmd.spawn().expect_err("no runtime, no spawn"));
}
#[skuld::test]
async fn a_command_with_no_program_did_not_start() {
let err = expect_not_started(Command::new().spawn().expect_err("no program, no spawn"));
assert!(matches!(err, Error::Io(_)), "{err:?}");
}
#[cfg(unix)]
#[skuld::test]
async fn an_elevation_refused_for_its_shape_did_not_start() {
let mut cmd = Command::new();
cmd.args(["/bin/sh", "-c", "true"]).elevate();
cmd.fd(3, crate::stdio::Stdio::null()).expect("fd 3");
let err = expect_not_started(cmd.spawn().expect_err("fd >= 3 is refused under elevation"));
assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_handshake_that_cannot_open_did_not_start() {
let _armed = crate::child::spawn::pidfd_handshake::fault::fail_done_fd(rustix::io::Errno::MFILE);
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
let err = expect_not_started(cmd.spawn().expect_err("a failed open fails the spawn"));
assert!(
matches!(err, Error::Io(ref e) if e.to_string() == format!("eventfd: {}", std::io::Error::from_raw_os_error(libc::EMFILE))),
"{err:?}"
);
}
#[cfg(windows)]
#[skuld::test]
async fn a_refused_creation_flag_did_not_start_the_program() {
let mut cmd = Command::new();
cmd.args(["cmd", "/C", "exit 0"])
.contain()
.creation_flags(windows::Win32::System::Threading::CREATE_SUSPENDED.0);
let err = expect_not_started(cmd.spawn().expect_err("a reserved bit must be refused"));
assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
}
#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn an_abandoned_child_nothing_reaches_may_be_running() {
use crate::containment::AbandonedChild;
assert_eq!(
super::abandoned_fate(AbandonedChild::MaybeUnreachable),
ChildFate::Running { id: None }
);
}
#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn an_abandoned_child_only_a_linux_leaf_can_report_asserts() {
use crate::containment::AbandonedChild;
for abandoned in [AbandonedChild::Ended, AbandonedChild::MaybeUnreaped] {
let outcome = std::panic::catch_unwind(|| super::abandoned_fate(abandoned));
if cfg!(debug_assertions) {
assert!(outcome.is_err(), "{abandoned:?} must assert");
} else {
assert_eq!(outcome.expect("no assertion in release"), ChildFate::Unknown);
}
}
}
#[cfg(not(target_os = "linux"))]
#[skuld::test]
async fn a_tokio_spawn_failing_after_the_fork_leaves_the_child_running_and_says_so() {
crate::tokio::test_runtime::assert_current_thread();
#[cfg(unix)]
let (stdin, writer) = crate::test_child::held_writer_stdin();
#[cfg(not(unix))]
let stdin = crate::test_child::leaked_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
let error = {
let _failing = fault::fail_tokio_spawns_after_fork();
cmd.spawn().expect_err("the forced failure fails the spawn")
};
let (_error, fate) = expect_may_have_started_with(error);
assert_eq!(fate, ChildFate::Running { id: None });
let pid = fault::take_forgotten_pid().expect("the seam forked a child");
#[cfg(unix)]
{
drop(writer);
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,
"the forgotten child is still ours to collect"
);
}
#[cfg(not(unix))]
let _ = pid;
}
#[skuld::test]
fn a_front_the_leaf_found_is_answered_by_what_became_of_it() {
use crate::child::spawn::FrontFate;
assert_eq!(super::front_child_fate(FrontFate::Reaped), ChildFate::Reaped);
assert_eq!(
super::front_child_fate(FrontFate::LeftUnreaped),
ChildFate::Running { id: None }
);
assert_eq!(super::front_child_fate(FrontFate::Unplaced), ChildFate::Unknown);
assert_eq!(super::front_child_fate(FrontFate::Unaccounted), ChildFate::Unknown);
}