use std::io::{PipeWriter, Read as _};
use std::os::fd::{AsFd as _, OwnedFd};
use std::os::unix::process::ExitStatusExt as _;
use crate::child::fault::record_root_teardowns;
use crate::child::front_kill_tests::{
assert_ends_unsignalled, assert_reaped_unsignalled, assert_refused_by, assert_unkillable_front, cat, spawn_as,
};
use crate::command::Command;
use crate::elevation::{Backend, ElevatedVia};
use crate::test_groups::{cgroup, Group};
use crate::{ContainMode, Containment, Stdio};
const SUDO: ElevatedVia = ElevatedVia::Wrapped(Backend::Sudo);
type Kill = fn(&crate::Child) -> Result<(), crate::error::Error>;
fn in_cgroup(mut cmd: Command) -> Command {
cmd.contain_with(ContainMode::Strongest);
cmd
}
pub(crate) fn nobody_cat() -> Command {
let mut cmd = Command::new();
cmd.args([
"setpriv",
"--reuid=65534",
"--regid=65534",
"--clear-groups",
"sh",
"-c",
"echo ready; exec cat",
]);
cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
in_cgroup(cmd)
}
fn spawn_nobody_front() -> (crate::Child, PipeWriter) {
let (mut child, stdin) = spawn_as(nobody_cat(), SUDO);
assert_eq!(child.containment(), Containment::CgroupV2);
let mut ready = [0u8; 6];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut ready)
.expect("read `ready`");
assert_eq!(&ready, b"ready\n");
(child, stdin)
}
#[must_use = "the capability returns as soon as the guard is dropped"]
pub(crate) struct WithoutKillCap(rustix::thread::CapabilitySets);
impl WithoutKillCap {
pub(crate) fn refusing(pid: u32) -> WithoutKillCap {
use rustix::thread::{capabilities, set_capabilities, CapabilitySet};
let saved = capabilities(None).expect("capget");
assert!(
saved.effective.contains(CapabilitySet::KILL),
"the cgroup lane runs as root, with CAP_KILL: {saved:?}"
);
let mut without = saved;
without.effective.remove(CapabilitySet::KILL);
set_capabilities(None, without).expect("capset without CAP_KILL");
let guard = WithoutKillCap(saved);
let target = rustix::process::Pid::from_raw(pid as i32).expect("a positive pid");
assert_eq!(
rustix::process::test_kill_process(target),
Err(rustix::io::Errno::PERM),
"the front {pid} must refuse this thread's signal"
);
guard
}
}
impl Drop for WithoutKillCap {
fn drop(&mut self) {
rustix::thread::set_capabilities(None, self.0).expect("capset to restore CAP_KILL");
}
}
pub(crate) fn pidfd_of(pid: u32) -> OwnedFd {
let pid = rustix::process::Pid::from_raw(pid as i32).expect("a positive pid");
rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).expect("pidfd_open")
}
pub(crate) fn reaped(pidfd: &OwnedFd) -> bool {
loop {
match rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED
| rustix::process::WaitIdOptions::NOHANG
| rustix::process::WaitIdOptions::NOWAIT,
) {
Ok(_) => return false,
Err(rustix::io::Errno::CHILD) => return true,
Err(rustix::io::Errno::INTR) => {}
Err(e) => panic!("waitid on a pidfd: {e}"),
}
}
}
pub(crate) fn move_out_of_its_leaf(pid: u32) {
let own = std::fs::read_to_string("/proc/self/cgroup").expect("read /proc/self/cgroup");
let path = own
.lines()
.find_map(|line| line.strip_prefix("0::"))
.expect("a cgroup v2 `0::` line");
let procs = format!("/sys/fs/cgroup{path}/cgroup.procs");
std::fs::write(&procs, pid.to_string()).unwrap_or_else(|e| panic!("move {pid} into {procs}: {e}"));
}
pub(crate) fn cgroup_dir_of(pid: u32) -> String {
let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the cgroup");
let path = own
.lines()
.find_map(|line| line.strip_prefix("0::"))
.expect("a cgroup v2 `0::` line");
format!("/sys/fs/cgroup{path}")
}
pub(crate) fn move_into_a_namesake_of_its_leaf(pid: u32) {
let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the front's cgroup");
let leaf = own
.lines()
.find_map(|line| line.strip_prefix("0::"))
.expect("a cgroup v2 `0::` line");
let namesake = format!("/sys/fs/cgroup{leaf} (deleted)");
std::fs::create_dir(&namesake).unwrap_or_else(|e| panic!("make {namesake}: {e}"));
std::fs::write(format!("{namesake}/cgroup.procs"), pid.to_string())
.unwrap_or_else(|e| panic!("move {pid} into {namesake}: {e}"));
}
pub(crate) fn move_under_its_leaf(pid: u32) -> String {
let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the front's cgroup");
let leaf = own
.lines()
.find_map(|line| line.strip_prefix("0::"))
.expect("a cgroup v2 `0::` line");
let nested = format!("/sys/fs/cgroup{leaf}/a/b");
std::fs::create_dir_all(&nested).unwrap_or_else(|e| panic!("make {nested}: {e}"));
std::fs::write(format!("{nested}/cgroup.procs"), pid.to_string())
.unwrap_or_else(|e| panic!("move {pid} into {nested}: {e}"));
nested
}
#[skuld::test]
fn cgroup_kill_of_a_front_goes_through_the_cgroup_alone(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
assert_eq!(child.containment(), Containment::CgroupV2);
crate::wait::exit_only::seams::signals_sent();
child.kill().expect("the cgroup kill reaches the program");
assert_eq!(
crate::wait::exit_only::seams::signals_sent(),
0,
"nothing is signalled after it"
);
assert!(child.tree_killed.is_set(), "the kill must go through the cgroup");
drop(stdin);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}
#[skuld::test]
fn cgroup_kill_tree_of_a_front_goes_through_the_cgroup_alone(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
crate::wait::exit_only::seams::signals_sent();
child.kill_tree().expect("the cgroup kill reaches the program");
assert_eq!(
crate::wait::exit_only::seams::signals_sent(),
0,
"nothing is signalled after it"
);
assert!(child.tree_killed.is_set());
drop(stdin);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}
#[skuld::test]
fn cgroup_drop_of_a_front_kills_it_through_the_cgroup_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let teardowns = record_root_teardowns();
let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pidfd = pidfd_of(child.id().pid());
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(teardowns.count(), 0, "the drop sends the front no kill of its own");
assert!(reaped(&pidfd), "the drop reaps the front its cgroup kill ended");
let warns = crate::log_capture::records_since_on_current_thread(mark, "Child::drop");
assert_eq!(warns, [], "a front the cgroup killed is not left behind");
}
#[skuld::test]
fn cgroup_a_failed_kill_of_a_front_leaves_the_front_alone(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
{
let _failing = crate::containment::cgroup::fault::fail_kill_writes();
crate::child::front_kill_tests::assert_refused_by(child.kill(), "its cgroup kill failed");
crate::child::front_kill_tests::assert_refused_by(child.kill_tree(), "its cgroup kill failed");
}
assert_ends_unsignalled(&child, stdin);
}
#[skuld::test]
fn cgroup_a_failed_drop_kill_of_a_front_leaves_the_front_alone(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let teardowns = record_root_teardowns();
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let crate::containment::Attached::Cgroup(leaf) = &child.attached else {
panic!("expected a cgroup leaf, got {:?}", child.attached);
};
let leaf = leaf.path().to_path_buf();
let pid = child.id().pid();
{
let _failing = crate::containment::cgroup::fault::fail_kill_writes();
drop(child);
}
assert_eq!(teardowns.count(), 0, "the drop must not kill or reap the front");
drop(stdin);
assert_reaped_unsignalled(pid);
std::fs::remove_dir(&leaf).unwrap_or_else(|e| panic!("remove the leaf {}: {e}", leaf.display()));
}
pub(crate) fn spawn_front_with_member() -> (crate::Child, PipeWriter, OwnedFd) {
let mut cmd = Command::new();
cmd.args(["sh", "-c", "sleep 1000 & echo $!; exec cat"]);
cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
let (mut child, stdin) = spawn_as(in_cgroup(cmd), SUDO);
let mut line = Vec::new();
let mut stdout = child.stdout().expect("stdout pipe");
let mut byte = [0u8; 1];
while stdout.read_exact(&mut byte).is_ok() && byte[0] != b'\n' {
line.push(byte[0]);
}
let member: u32 = String::from_utf8(line)
.expect("utf8")
.trim()
.parse()
.expect("the sleep's pid");
(child, stdin, pidfd_of(member))
}
pub(crate) fn wait_until_exited(pidfd: &OwnedFd) {
let mut fds = [rustix::event::PollFd::from_borrowed_fd(
pidfd.as_fd(),
rustix::event::PollFlags::IN,
)];
while rustix::event::poll(&mut fds, None) == Err(rustix::io::Errno::INTR) {}
}
#[track_caller]
fn assert_drop_kills_the_leaf_and_reaps_the_front(fault: impl FnOnce() -> Box<dyn std::any::Any>) {
crate::log_capture::install();
let (child, stdin, member) = spawn_front_with_member();
let front = pidfd_of(child.id().pid());
let pid = child.id().pid();
let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(stdin)));
let _look = crate::child::fault::set_before_front_look({
let stdin = std::rc::Rc::clone(&stdin);
move || {
drop(stdin.take());
crate::test_child::wait_until_zombie(pid);
}
});
crate::containment::cgroup::fault::record_leaf_steps();
let mark = crate::log_capture::mark();
{
let _fault = fault();
drop(child);
}
let steps = crate::containment::cgroup::fault::take_leaf_steps();
let said =
crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
assert_eq!(said.len(), 1, "{said:?}");
assert_eq!(said[0].0, log::Level::Debug, "{said:?}");
assert!(
said[0].1.contains("killed through its cgroup and reaped (signal: 9"),
"{said:?}"
);
assert!(reaped(&front), "the drop reaps the front its leaf's kill ended");
assert!(steps.iter().any(|s| s == "kill"), "{steps:?}");
wait_until_exited(&member);
}
#[skuld::test]
fn cgroup_a_drop_whose_placement_read_fails_kills_the_leaf_and_reaps_the_front(#[fixture(cgroup)] _group: &Group) {
assert_drop_kills_the_leaf_and_reaps_the_front(|| Box::new(crate::containment::cgroup::fault::fail_pidfd_info()));
}
#[skuld::test]
fn cgroup_a_drop_whose_first_cgroup_kill_fails_kills_the_leaf_and_reaps_the_front(#[fixture(cgroup)] _group: &Group) {
assert_drop_kills_the_leaf_and_reaps_the_front(|| {
Box::new(crate::containment::cgroup::fault::fail_next_kill_write())
});
}
#[skuld::test]
fn cgroup_a_drop_whose_post_kill_read_fails_reaps_the_front_the_kill_ended(#[fixture(cgroup)] _group: &Group) {
assert_drop_kills_the_leaf_and_reaps_the_front(|| {
let unreadable = std::rc::Rc::new(std::cell::RefCell::new(None));
let arming = crate::containment::cgroup::fault::set_before_kill_write({
let unreadable = std::rc::Rc::clone(&unreadable);
move || *unreadable.borrow_mut() = Some(crate::containment::cgroup::fault::fail_pidfd_info())
});
let running = crate::elevation::front::seams::read_front_running_at_every_reach_read();
Box::new((arming, running, unreadable))
});
}
#[skuld::test]
fn cgroup_a_drop_places_a_front_that_reads_as_running_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (child, _stdin, member) = spawn_front_with_member();
let pid = child.id().pid();
let front = pidfd_of(pid);
let _old_kernel = crate::child::fault::read_front_as_running_at_the_look();
let mark = crate::log_capture::mark();
{
let _first_write_fails = crate::containment::cgroup::fault::fail_next_kill_write();
drop(child);
}
let said =
crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
assert_eq!(said.len(), 1, "{said:?}");
assert_eq!(said[0].0, log::Level::Debug, "{said:?}");
assert!(
said[0].1.contains("killed through its cgroup and reaped (signal: 9"),
"{said:?}"
);
assert!(reaped(&front), "the drop reaps the front");
wait_until_exited(&member);
}
#[skuld::test]
fn cgroup_a_drop_that_cannot_place_a_front_does_not_call_it_running(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (child, _stdin, _member) = spawn_front_with_member();
let pid = child.id().pid();
let _old_kernel = crate::child::fault::read_front_as_running_at_the_look();
let mark = crate::log_capture::mark();
{
let _unreadable = crate::containment::cgroup::fault::fail_pidfd_info();
drop(child);
}
let said =
crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
assert_eq!(said.len(), 1, "{said:?}");
assert_eq!(said[0].0, log::Level::Warn, "{said:?}");
assert!(said[0].1.contains("cannot be read"), "{said:?}");
assert!(!said[0].1.contains("left running"), "{said:?}");
crate::child::front_kill_tests::reap(pid);
}
#[skuld::test]
fn cgroup_drop_of_a_front_outside_its_leaf_leaves_it_running_and_kills_the_rest(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (child, stdin, member) = spawn_front_with_member();
let pid = child.id().pid();
move_out_of_its_leaf(pid);
let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(stdin)));
let _released = crate::child::spawn::fault::set_between_kill_and_wait({
let stdin = std::rc::Rc::clone(&stdin);
move || drop(stdin.take())
});
crate::containment::cgroup::fault::record_leaf_steps();
let mark = crate::log_capture::mark();
drop(child);
let steps = crate::containment::cgroup::fault::take_leaf_steps();
let said =
crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
assert_eq!(said.len(), 1, "{said:?}");
assert_eq!(said[0].0, log::Level::Warn);
assert!(said[0].1.contains("is left running and unreaped"), "{said:?}");
assert!(steps.iter().any(|s| s == "kill"), "the leaf was killed: {steps:?}");
wait_until_exited(&member);
drop(stdin.take().expect("the drop must not wait for the front"));
assert_reaped_unsignalled(pid);
}
#[skuld::test]
fn cgroup_kill_of_a_front_that_refuses_signals_is_ok(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_nobody_front();
{
let _refusing = WithoutKillCap::refusing(child.id().pid());
child.kill().expect("the cgroup kill ends the front");
child.kill_tree().expect("the cgroup kill ends the front");
}
drop(stdin);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}
#[skuld::test]
fn cgroup_drop_of_a_front_that_refuses_signals_reaps_it(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (child, _stdin) = spawn_nobody_front();
let pidfd = pidfd_of(child.id().pid());
let mark = crate::log_capture::mark();
{
let _refusing = WithoutKillCap::refusing(child.id().pid());
drop(child);
}
assert!(reaped(&pidfd), "the drop reaps the front its cgroup kill ended");
let warns = crate::log_capture::records_since_on_current_thread(mark, "could not be terminated");
assert_eq!(warns, [], "nothing was refused");
}
#[skuld::test]
fn cgroup_a_failed_password_write_terminates_a_front_that_refuses_signals(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_nobody_front();
let pid = child.id().pid();
let _refusing = WithoutKillCap::refusing(pid);
let reaps = crate::child::spawn::fault::record_teardown_reaps();
let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(stdin)));
let _released = crate::child::spawn::fault::set_between_kill_and_wait({
let stdin = std::rc::Rc::clone(&stdin);
move || drop(stdin.take())
});
let err = crate::child::spawn::finish_elevated(
child,
Err(crate::error::Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn");
let (err, fate) = err.expect_may_have_started_with();
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the cgroup kill ended the front and the teardown reaped it"
);
let rendered = err.to_string();
assert!(rendered.contains("the elevated child was terminated"), "{rendered}");
let (_, status) = reaps
.recorded()
.into_iter()
.find(|(reaped, _)| *reaped == pid)
.expect("the teardown reaped the front");
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"the front ended by the cgroup kill"
);
}
#[skuld::test]
fn cgroup_a_failed_password_write_whose_cgroup_kill_fails_refuses_as_kill_does(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let id = child.id();
let pid = id.pid();
let leaf = leaf_of(&child).path().to_path_buf();
let err = {
let _failing = crate::containment::cgroup::fault::fail_kill_writes();
crate::child::spawn::finish_elevated(
child,
Err(crate::error::Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn")
};
let (err, fate) = err.expect_may_have_started_with();
assert_eq!(
fate,
crate::error::ChildFate::Running { id: Some(id) },
"a front its cgroup kill did not end may be running"
);
assert_front_refused_by_its_cgroup_kill(&err, pid);
drop(stdin);
assert_reaped_unsignalled(pid);
std::fs::remove_dir(&leaf).unwrap_or_else(|e| panic!("remove the leaf {}: {e}", leaf.display()));
}
#[track_caller]
pub(crate) fn assert_front_refused_by_its_cgroup_kill(err: &crate::error::Error, pid: u32) {
let text = err.to_string();
assert!(text.contains("the elevated child could not be terminated"), "{text}");
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(text.contains("no kill was sent"), "{text}");
assert!(text.contains("(its cgroup kill failed: "), "{text}");
}
#[skuld::test]
fn cgroup_a_front_that_left_its_leaf_is_unkillable_and_sent_nothing(#[fixture(cgroup)] _group: &Group) {
let teardowns = record_root_teardowns();
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = child.id().pid();
move_out_of_its_leaf(pid);
assert_unkillable_front(child.kill(), pid);
assert_unkillable_front(child.kill_tree(), pid);
assert!(!child.tree_killed.is_set(), "no cgroup kill ran");
drop(child);
assert_eq!(teardowns.count(), 0, "the drop must not kill or reap the front");
drop(stdin);
assert_reaped_unsignalled(pid);
}
#[skuld::test]
fn cgroup_kill_of_an_exited_front_that_refuses_signals_is_ok(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_nobody_front();
let pid = child.id().pid();
drop(stdin);
crate::test_child::wait_until_zombie(pid);
{
let _refusing = WithoutKillCap::refusing(pid);
child.kill().expect("an exited front is killed like any exited child");
child
.kill_tree()
.expect("an exited front is killed like any exited child");
}
assert!(child.wait().expect("wait").success());
}
#[skuld::test]
fn cgroup_a_front_moved_out_during_its_kill_is_unkillable(#[fixture(cgroup)] _group: &Group) {
let kills: [Kill; 2] = [crate::Child::kill, crate::Child::kill_tree];
for kill in kills {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = child.id().pid();
let _moving = crate::containment::cgroup::fault::set_before_kill_write(move || move_out_of_its_leaf(pid));
assert_refused_by(kill(&child), "left the cgroup before its kill");
assert_ends_unsignalled(&child, stdin);
}
}
#[skuld::test]
fn cgroup_drop_of_a_front_moved_out_during_its_kill_leaves_it_unreaped(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = child.id().pid();
let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(stdin)));
let _moving = crate::containment::cgroup::fault::set_before_kill_write(move || move_out_of_its_leaf(pid));
let _released = crate::child::spawn::fault::set_between_kill_and_wait({
let stdin = std::rc::Rc::clone(&stdin);
move || drop(stdin.take())
});
let mark = crate::log_capture::mark();
drop(child);
let warns = crate::log_capture::records_since_on_current_thread(mark, "is left running and unreaped");
assert_eq!(warns.len(), 1, "{warns:?}");
drop(stdin.take().expect("the drop must not wait for the front"));
assert_reaped_unsignalled(pid);
}
#[skuld::test]
fn cgroup_kill_tree_of_a_front_asks_the_gate_once(#[fixture(cgroup)] _group: &Group) {
let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
let gates = crate::elevation::front::seams::count_kill_gates();
child.kill_tree().expect("the cgroup kill reaches the front");
assert_eq!(gates.count(), 1);
}
#[skuld::test]
fn cgroup_a_failed_password_write_asks_the_gate_once(#[fixture(cgroup)] _group: &Group) {
let mut cmd = in_cgroup(cat());
cmd.kill_on_drop(false);
let (child, _stdin) = spawn_as(cmd, SUDO);
let gates = crate::elevation::front::seams::count_kill_gates();
let err = crate::child::spawn::finish_elevated(
child,
Err(crate::error::Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn");
let (err, fate) = err.expect_may_have_started_with();
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the cgroup kill ended the front and the teardown reaped it"
);
assert!(err.to_string().contains("the elevated child was terminated"), "{err}");
assert_eq!(gates.count(), 1);
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeafKill {
Lands,
Fails,
MissesMovedFront,
LandsNestedHidden,
LandsReadThroughProc,
MissesIntoNamesake,
}
pub(crate) struct HeldFailure {
pub(crate) err: crate::error::Error,
pub(crate) pid: u32,
pub(crate) read_id: Option<crate::identity::ProcessId>,
pub(crate) stdin: std::rc::Rc<std::cell::RefCell<Option<PipeWriter>>>,
}
pub(crate) fn failed_held_front_spawns(
kill: LeafKill,
spawn: impl Fn(&mut Command) -> Result<(), crate::error::Error>,
) -> [HeldFailure; 2] {
use std::cell::RefCell;
use std::rc::Rc;
use crate::child::spawn::fault;
let arms: [fn(bool); 2] = [fault::set_force_attach_failure, fault::set_force_identity_vanished];
let mut arm = 0;
arms.map(|force_arm| {
arm += 1;
let (reader, writer) = std::io::pipe().expect("pipe");
let stdin = Rc::new(RefCell::new(Some(writer)));
let mut cmd = in_cgroup(cat());
cmd.stdin(Stdio::from_file(std::fs::File::from(OwnedFd::from(reader))))
.expect("stdin");
cmd.set_elevation_front(crate::elevation::front::front(Some(&SUDO)));
let _released = fault::set_between_kill_and_wait({
let stdin = Rc::clone(&stdin);
move || drop(stdin.borrow_mut().take())
});
let (filler, filler_stdin) = if kill == LeafKill::MissesIntoNamesake {
let (filler, stdin) = spawn_as(cat(), SUDO);
(Some(Rc::new(filler)), Some(stdin))
} else {
(None, None)
};
let _moved = match kill {
LeafKill::MissesMovedFront => Some(fault::set_at(fault::SpawnPoint::BeforeIdentity, || {
move_out_of_its_leaf(fault::spawn_pid())
})),
LeafKill::LandsNestedHidden => Some(fault::set_at(fault::SpawnPoint::BeforeIdentity, || {
move_under_its_leaf(fault::spawn_pid());
})),
LeafKill::MissesIntoNamesake => {
let filler = filler.clone();
Some(fault::set_at(fault::SpawnPoint::BeforeIdentity, move || {
let pid = fault::spawn_pid();
let leaf = cgroup_dir_of(pid);
let filler = filler.as_ref().expect("a filler for the namesake case").id().pid();
std::fs::write(format!("{leaf}/cgroup.procs"), filler.to_string())
.unwrap_or_else(|e| panic!("move the filler into {leaf}: {e}"));
move_into_a_namesake_of_its_leaf(pid);
}))
}
LeafKill::Lands | LeafKill::Fails | LeafKill::LandsReadThroughProc => None,
};
let _missing = matches!(kill, LeafKill::LandsReadThroughProc | LeafKill::MissesIntoNamesake)
.then(crate::containment::cgroup::fault::miss_pidfd_info);
let _hidden = (kill == LeafKill::LandsNestedHidden).then(crate::containment::cgroup::fault::hide_proc);
let _failing = (kill == LeafKill::Fails).then(crate::containment::cgroup::fault::fail_kill_writes);
force_arm(true);
let result = spawn(&mut cmd);
force_arm(false);
if let Some((filler, stdin)) = filler.as_ref().zip(filler_stdin) {
drop(stdin);
assert_eq!(
filler.wait().expect("wait").signal(),
Some(libc::SIGKILL),
"the leaf's kill"
);
}
let err = result.expect_err("the forced arm fails the spawn");
let crate::identity::Resolved::Found(id) = fault::take_captured().expect("the seam captured the child") else {
panic!("the seam must capture a resolved identity");
};
HeldFailure {
err,
pid: id.pid(),
read_id: (arm == 1).then_some(id),
stdin,
}
})
}
#[track_caller]
pub(crate) fn assert_killed_by_the_leaf(
failures: &[HeldFailure; 2],
reaps: &crate::child::spawn::fault::TeardownReaps,
) {
let recorded = reaps.recorded();
for HeldFailure { err, pid, .. } in failures {
let text = err.to_string();
assert_eq!(err.fate(), Some(crate::error::ChildFate::Reaped), "{text}");
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(text.contains("its cgroup's kill ended it, and it was reaped"), "{text}");
let status = recorded
.iter()
.find_map(|(reaped, status)| (reaped == pid).then_some(*status))
.unwrap_or_else(|| panic!("the teardown waited for front {pid}: {recorded:?}"));
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"front {pid} ended by its leaf's kill"
);
}
}
#[track_caller]
pub(crate) fn assert_left_running(kill: LeafKill, failures: [HeldFailure; 2]) {
for HeldFailure {
err,
pid,
read_id,
stdin,
} in failures
{
let text = err.to_string();
assert_eq!(
err.fate(),
Some(crate::error::ChildFate::Running { id: read_id }),
"{text}"
);
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(
text.contains("the elevated program may be running; it is left unreaped"),
"{text}"
);
assert!(
stdin.borrow().is_some(),
"the teardown waited on front {pid}, which no kill reached"
);
let own = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).expect("read the front's cgroup");
let path = own
.lines()
.find_map(|line| line.strip_prefix("0::"))
.expect("a cgroup v2 `0::` line")
.to_owned();
drop(stdin.borrow_mut().take());
let status = crate::child::front_kill_tests::reap(pid).expect("the front was left unreaped");
assert!(status.success(), "front {pid} was signalled: {status:?}");
if matches!(kill, LeafKill::Fails | LeafKill::MissesIntoNamesake) {
let left = format!("/sys/fs/cgroup{path}");
std::fs::remove_dir(&left).unwrap_or_else(|e| panic!("remove {left}: {e}"));
}
}
}
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_contained_front_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
let _running = crate::child::spawn::fault::see_fronts_running();
let reaps = crate::child::spawn::fault::record_teardown_reaps();
let failures = failed_held_front_spawns(LeafKill::Lands, |cmd| cmd.spawn().map(drop));
assert_killed_by_the_leaf(&failures, &reaps);
}
#[skuld::test]
fn cgroup_a_failed_spawn_reaps_a_front_its_leaf_made_a_zombie_without_waiting(#[fixture(cgroup)] _group: &Group) {
let _zombie = crate::child::spawn::fault::exit_fronts_before_teardown();
crate::containment::cgroup::fault::record_leaf_steps();
let reaps = crate::child::spawn::fault::record_teardown_reaps();
let failures = failed_held_front_spawns(LeafKill::Lands, |cmd| cmd.spawn().map(drop));
for HeldFailure { err, pid, .. } in &failures {
let text = err.to_string();
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(text.contains("and it was reaped"), "{text}");
assert_eq!(
crate::child::front_kill_tests::reap(*pid),
None,
"the teardown's read reaped front {pid}"
);
}
assert_eq!(reaps.recorded(), [], "the zombie was reaped by the read, not by a wait");
}
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_front_read_through_proc_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
let _running = crate::child::spawn::fault::see_fronts_running();
let reaps = crate::child::spawn::fault::record_teardown_reaps();
let failures = failed_held_front_spawns(LeafKill::LandsReadThroughProc, |cmd| cmd.spawn().map(drop));
assert_killed_by_the_leaf(&failures, &reaps);
}
#[skuld::test]
fn cgroup_a_failed_spawn_leaves_a_front_in_a_namesake_of_its_leaf_running(#[fixture(cgroup)] _group: &Group) {
let kill = LeafKill::MissesIntoNamesake;
assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)));
}
#[skuld::test]
fn cgroup_a_failed_spawn_whose_leaf_kill_fails_leaves_the_front_running(#[fixture(cgroup)] _group: &Group) {
let kill = LeafKill::Fails;
assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)));
}
#[skuld::test]
fn cgroup_a_failed_spawn_leaves_a_front_moved_out_of_its_leaf_running(#[fixture(cgroup)] _group: &Group) {
let kill = LeafKill::MissesMovedFront;
assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)));
}
#[skuld::test]
fn cgroup_graceful_shutdown_of_a_front_escalates_through_the_cgroup(#[fixture(cgroup)] _group: &Group) {
let mut cmd = Command::new();
cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
let (mut child, _stdin) = spawn_as(in_cgroup(cmd), SUDO);
let mut ready = [0u8; 6];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut ready)
.expect("read `ready`");
let status = child
.graceful_shutdown(std::time::Duration::ZERO)
.expect("the cgroup kill ends the front");
assert!(child.tree_killed.is_set(), "the escalation must go through the cgroup");
assert_eq!(status.signal(), Some(libc::SIGKILL));
}
#[skuld::test]
fn cgroup_a_failed_escalation_of_a_front_is_unkillable(#[fixture(cgroup)] _group: &Group) {
let mut cmd = Command::new();
cmd.args(["sh", "-c", "trap '' TERM; echo ready; exec cat"]);
cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
let (mut child, stdin) = spawn_as(in_cgroup(cmd), SUDO);
let mut ready = [0u8; 6];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut ready)
.expect("read `ready`");
let release = crate::graceful_hooks::release_at(crate::graceful_hooks::HookPoint::BeforeReap, stdin);
{
let _failing = crate::containment::cgroup::fault::fail_kill_writes();
assert_refused_by(
child.graceful_shutdown(std::time::Duration::ZERO),
"its cgroup kill failed",
);
}
drop(release);
let status = child.wait().expect("wait");
assert!(status.success(), "the front was signalled: {status:?}");
}
#[skuld::test]
fn cgroup_a_front_reaped_by_a_concurrent_wait_inside_the_gate_has_exited(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
let fired = std::rc::Rc::new(std::cell::Cell::new(false));
std::thread::scope(|scope| {
let child = &child;
scope.spawn(move || {
if go_rx.recv().is_ok() {
reaped_tx
.send(child.wait().map_err(|e| e.to_string()))
.expect("report the reap");
}
});
let _between = crate::elevation::front::seams::set_between_gate_reads({
let fired = std::rc::Rc::clone(&fired);
move || {
fired.set(true);
drop(stdin);
go_tx.send(()).expect("start the waiter");
let status = reaped_rx.recv().expect("the waiter reaps").expect("wait");
assert!(status.success(), "the front ended on its stdin: {status:?}");
}
});
crate::wait::exit_only::seams::signals_sent();
child.kill().expect("a front that exited is not refused");
assert_eq!(
crate::wait::exit_only::seams::signals_sent(),
0,
"nothing is signalled to a reaped front"
);
});
assert!(fired.get(), "the hook between the gate's reads ran");
}
#[skuld::test]
fn cgroup_a_front_reaped_by_a_concurrent_wait_after_its_kill_was_reached(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
let fired = std::rc::Rc::new(std::cell::Cell::new(false));
std::thread::scope(|scope| {
let child = &child;
scope.spawn(move || {
if go_rx.recv().is_ok() {
reaped_tx
.send(child.wait().map_err(|e| e.to_string()))
.expect("report the reap");
}
});
let _running = crate::elevation::front::seams::read_front_running_at_the_first_reach_read();
let _between = crate::elevation::front::seams::set_between_reach_reads({
let fired = std::rc::Rc::clone(&fired);
move || {
fired.set(true);
drop(stdin);
go_tx.send(()).expect("start the waiter");
let status = reaped_rx.recv().expect("the waiter reaps").expect("wait");
assert_eq!(status.signal(), Some(libc::SIGKILL), "the cgroup kill ended the front");
}
});
child
.kill()
.expect("a front its kill ended is reached, whoever reaped it");
});
assert!(fired.get(), "the hook between the check's reads ran");
}
fn leaf_of(child: &crate::Child) -> &crate::containment::cgroup::CgroupLeaf {
match &child.attached {
crate::containment::Attached::Cgroup(leaf) => leaf,
other => panic!("expected a cgroup leaf, got {other:?}"),
}
}
#[skuld::test]
fn cgroup_a_killed_front_is_placed_in_its_leaf_by_its_pidfd(#[fixture(cgroup)] _group: &Group) {
let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = child.id().pid();
child.attached.hard_kill().expect("cgroup.kill");
crate::test_child::wait_until_zombie(pid);
let hidden = crate::containment::cgroup::fault::hide_proc();
let names = leaf_of(&child).names(pid, child.proc.pidfd());
drop(hidden);
assert!(
names.expect("the pidfd read needs no /proc"),
"a killed front stays in its leaf"
);
}
#[skuld::test]
fn cgroup_without_pidfd_info_a_front_is_placed_through_proc(#[fixture(cgroup)] _group: &Group) {
let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
let (killed, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = killed.id().pid();
killed.attached.hard_kill().expect("cgroup.kill");
crate::test_child::wait_until_zombie(pid);
assert!(leaf_of(&killed)
.names(pid, killed.proc.pidfd())
.expect("/proc is readable here"));
let (moved, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
move_out_of_its_leaf(moved.id().pid());
assert!(!leaf_of(&moved)
.names(moved.id().pid(), moved.proc.pidfd())
.expect("/proc is readable here"));
}
#[skuld::test]
fn cgroup_a_moved_front_is_placed_outside_its_leaf_by_its_pidfd(#[fixture(cgroup)] _group: &Group) {
let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = child.id().pid();
move_out_of_its_leaf(pid);
let hidden = crate::containment::cgroup::fault::hide_proc();
let names = leaf_of(&child).names(pid, child.proc.pidfd());
drop(hidden);
assert!(
!names.expect("the pidfd read needs no /proc"),
"a moved front is outside its leaf"
);
}
#[skuld::test]
fn cgroup_a_front_under_its_leaf_is_placed_by_the_walk(#[fixture(cgroup)] _group: &Group) {
let (child, _stdin) = spawn_as(in_cgroup(cat()), SUDO);
let pid = child.id().pid();
move_under_its_leaf(pid);
let names = || leaf_of(&child).names(pid, child.proc.pidfd());
assert!(names().expect("/proc is readable here"));
{
let _hidden = crate::containment::cgroup::fault::hide_proc();
assert!(names().expect("the walk needs no /proc"), "found by the walk");
let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
names().expect_err("a hidden path places nothing");
}
}
#[skuld::test]
fn cgroup_a_front_nested_under_its_leaf_is_killed_under_hidepid(#[fixture(cgroup)] _group: &Group) {
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
move_under_its_leaf(child.id().pid());
{
let _hidden = crate::containment::cgroup::fault::hide_proc();
child.kill().expect("the leaf's kill reaches a front nested under it");
}
drop(stdin);
let status = child.wait().expect("wait");
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"the front dies of its leaf's kill"
);
}
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_front_nested_under_its_leaf_under_hidepid(#[fixture(cgroup)] _group: &Group) {
let _running = crate::child::spawn::fault::see_fronts_running();
let reaps = crate::child::spawn::fault::record_teardown_reaps();
let failures = failed_held_front_spawns(LeafKill::LandsNestedHidden, |cmd| cmd.spawn().map(drop));
assert_killed_by_the_leaf(&failures, &reaps);
}
#[skuld::test]
fn cgroup_a_front_behind_a_mount_under_its_leaf_is_placed_through_proc(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::dir_walk_tests::{enter_private_mount_ns, TmpfsOver};
std::thread::scope(|scope| {
scope
.spawn(|| {
enter_private_mount_ns();
let (child, stdin) = spawn_as(in_cgroup(cat()), SUDO);
let nested = std::path::PathBuf::from(move_under_its_leaf(child.id().pid()));
let mounted_on = nested.parent().expect("`a`, under the leaf");
let killed = {
let _mounted = TmpfsOver::new(mounted_on);
child.kill()
};
killed.expect("a front /proc places under its leaf was reached");
drop(stdin);
let status = child.wait().expect("wait");
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"the front dies of its leaf's kill"
);
})
.join()
.expect("the spawning thread");
});
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RecordCase {
Namesake,
Leaf,
NamesakeLivenessUnread,
LeafRemovedFirst,
}
#[skuld::test]
fn cgroup_a_leaf_records_its_fronts_place_before_its_removal(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::dir_walk_tests::Scratch;
crate::log_capture::install();
let scratch = Scratch::new("record");
let cgroup_of = |path: &std::path::Path| {
format!(
"/{}",
path.strip_prefix("/sys/fs/cgroup")
.expect("under the cgroup root")
.display()
)
};
for (n, case) in [
RecordCase::Namesake,
RecordCase::Leaf,
RecordCase::NamesakeLivenessUnread,
RecordCase::LeafRemovedFirst,
]
.into_iter()
.enumerate()
{
let leaf_path = scratch.make(&format!("leaf-{n}"));
let mut leaf = crate::containment::cgroup::test_support::entered_leaf_at(leaf_path.clone());
leaf.set_cgroup_path_for_test(cgroup_of(&leaf_path));
let placed = leaf.placed_for_test();
let (front, stdin) = spawn_as(cat(), SUDO);
let pid = front.id().pid();
leaf.watch_front(pid);
let namesake = leaf_path.with_file_name(format!("leaf-{n} (deleted)"));
let in_leaf = matches!(case, RecordCase::Leaf | RecordCase::LeafRemovedFirst);
if in_leaf {
std::fs::write(leaf_path.join("cgroup.procs"), pid.to_string()).expect("move the front into the leaf");
} else {
std::fs::create_dir(&namesake).expect("make the namesake");
std::fs::write(namesake.join("cgroup.procs"), pid.to_string()).expect("move the front into the namesake");
}
if case == RecordCase::LeafRemovedFirst {
std::fs::write(leaf_path.join("cgroup.kill"), "1").expect("kill through the leaf");
assert_eq!(
leaf.wait_drained(None).expect("wait for the leaf to drain"),
crate::containment::TreeDrain::AllMembersExited
);
std::fs::remove_dir(&leaf_path).expect("remove the drained leaf, as a cgroup manager may");
}
let unread = (case == RecordCase::NamesakeLivenessUnread)
.then(|| crate::containment::cgroup::fault::fail_liveness_read(libc::EMFILE));
let mark = crate::log_capture::mark();
drop(leaf);
drop(unread);
let unrecorded =
crate::log_capture::records_since_on_current_thread(mark, "before its leaf's removal cannot be read");
if matches!(case, RecordCase::NamesakeLivenessUnread | RecordCase::LeafRemovedFirst) {
assert!(
unrecorded
.iter()
.any(|(_, text)| text.contains("is either the removed leaf or a live cgroup of that name")),
"{case:?}: {unrecorded:?}"
);
}
let expected = match case {
RecordCase::Namesake => Some(false),
RecordCase::Leaf => Some(true),
RecordCase::NamesakeLivenessUnread | RecordCase::LeafRemovedFirst => None,
};
assert_eq!(placed.of(pid), expected, "{case:?}");
drop(stdin);
let status = front.wait().expect("wait");
assert_eq!(
status.signal(),
in_leaf.then_some(libc::SIGKILL),
"{case:?}: {status:?}"
);
if !in_leaf {
std::fs::remove_dir(&namesake).expect("remove the namesake");
}
}
}
pub(crate) fn spawn_front_noting_fork<T>(
mut cmd: Command,
spawn: impl FnOnce(&mut Command) -> Result<T, crate::error::Error>,
) -> (Result<T, crate::error::Error>, Option<u32>) {
use crate::child::spawn::fault::{set_at, spawn_pid, SpawnPoint};
cmd.set_elevation_front(crate::elevation::front::front(Some(&SUDO)));
let pid = std::rc::Rc::new(std::cell::Cell::new(None));
let _seen = set_at(SpawnPoint::BeforeAttach, {
let pid = std::rc::Rc::clone(&pid);
move || pid.set(Some(spawn_pid()))
});
let result = spawn(&mut cmd);
(result, pid.get())
}
#[track_caller]
pub(crate) fn assert_refused_unforked<T: std::fmt::Debug>(result: Result<T, crate::error::Error>, forked: Option<u32>) {
assert_refused_unforked_naming(result, forked, "hidepid");
}
#[track_caller]
pub(crate) fn assert_refused_unforked_naming<T: std::fmt::Debug>(
result: Result<T, crate::error::Error>,
forked: Option<u32>,
cause: &str,
) {
match result {
Err(crate::error::Error::Unsupported { detail, .. }) => {
assert!(detail.contains(cause), "{detail}");
assert!(detail.contains("before anything is spawned"), "{detail}");
}
other => panic!("expected Unsupported, got {other:?}"),
}
assert_eq!(forked, None, "a refused spawn forks nothing");
}
#[skuld::test]
fn cgroup_an_unplaceable_front_is_refused_before_its_fork(#[fixture(cgroup)] _group: &Group) {
let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
let _hidden = crate::containment::cgroup::fault::hide_proc();
let _failing = crate::containment::cgroup::fault::fail_kill_writes();
let mut cmd = in_cgroup(cat());
cmd.kill_on_drop(true);
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn().map(drop));
assert_refused_unforked(result, forked);
}
#[skuld::test]
fn cgroup_a_front_whose_leaf_gives_no_id_is_refused_before_its_fork(#[fixture(cgroup)] _group: &Group) {
let _no_id = crate::containment::cgroup::fault::fail_cgroup_id(libc::ENOSYS);
let mut cmd = in_cgroup(cat());
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn().map(drop));
assert_refused_unforked_naming(result, forked, "name_to_handle_at");
}
#[skuld::test]
fn cgroup_an_unplaceable_front_is_refused_before_its_fork_with_fds_0_and_1_closed(#[fixture(cgroup)] _group: &Group) {
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_unplaceable_front_is_refused_before_its_fork_with_fds_0_and_1_closed),
spawn,
) else {
return;
};
let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
let _hidden = crate::containment::cgroup::fault::hide_proc();
let mut cmd = in_cgroup(cat());
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
let restore = RestoreStdio::close(&done, &[0, 1]);
let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn().map(drop));
drop(restore);
assert_refused_unforked(result, forked);
}
#[skuld::test]
fn cgroup_a_front_placeable_through_proc_is_not_refused(#[fixture(cgroup)] _group: &Group) {
let _missing = crate::containment::cgroup::fault::miss_pidfd_info();
let mut cmd = in_cgroup(cat());
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
let (result, forked) = spawn_front_noting_fork(cmd, |cmd| cmd.spawn());
result.expect("a front /proc shows is placeable");
assert!(forked.is_some());
}
pub(crate) fn front_its_leaf_did_not_take() -> (Command, PipeWriter) {
let (reader, writer) = std::io::pipe().expect("pipe");
let mut cmd = in_cgroup(cat());
cmd.stdin(Stdio::from_file(std::fs::File::from(OwnedFd::from(reader))))
.expect("stdin");
cmd.set_elevation_front(crate::elevation::front::front(Some(&SUDO)));
crate::containment::cgroup::fault::set_force_placement_write_result(0);
(cmd, writer)
}
pub(crate) fn fail_the_identity_check(
cmd: &mut Command,
spawn: impl FnOnce(&mut Command) -> Result<(), crate::error::Error>,
) -> (crate::error::Error, u32) {
use crate::child::spawn::fault;
fault::set_force_identity_vanished(true);
let result = spawn(cmd);
fault::set_force_identity_vanished(false);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
result.expect_err("the forced identity failure fails the spawn"),
);
assert_eq!(fate, crate::error::ChildFate::Running { id: None }, "{err:?}");
let crate::identity::Resolved::Found(id) = fault::take_captured().expect("the seam captured the child") else {
panic!("the seam must capture a resolved identity");
};
(err, id.pid())
}
#[track_caller]
pub(crate) fn assert_left_unsignalled(err: &crate::error::Error, pid: u32, stdin: PipeWriter) {
let text = err.to_string();
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(
text.contains("the elevated program may be running; it is left unreaped"),
"{text}"
);
drop(stdin);
assert_reaped_unsignalled(pid);
}
#[skuld::test]
fn cgroup_a_front_its_leaf_did_not_take_is_left_by_a_failed_identity_check(#[fixture(cgroup)] _group: &Group) {
let (mut cmd, stdin) = front_its_leaf_did_not_take();
let (err, pid) = fail_the_identity_check(&mut cmd, |cmd| cmd.spawn().map(drop));
assert_left_unsignalled(&err, pid, stdin);
}
#[skuld::test]
fn cgroup_a_front_spawn_that_cannot_read_its_leaf_subtree_says_why(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (child, stdin) = {
let _failing = crate::containment::cgroup::fault::fail_subtree(libc::EIO);
spawn_as(in_cgroup(cat()), SUDO)
};
let logs = crate::log_capture::records_since_on_current_thread(mark, "leaf subtree cannot be read");
assert_eq!(logs.len(), 1, "{logs:?}");
assert_eq!(logs[0].0, log::Level::Debug);
assert!(logs[0].1.contains("Input/output error"), "{logs:?}");
drop(stdin);
drop(child);
}
#[skuld::test]
fn cgroup_a_failed_spawn_says_why_its_leaf_did_not_take_the_child(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (mut cmd, stdin) = front_its_leaf_did_not_take();
let mark = crate::log_capture::mark();
let (err, pid) = fail_the_identity_check(&mut cmd, |cmd| cmd.spawn().map(drop));
let logs = crate::log_capture::records_since_on_current_thread(mark, "not placed in its leaf");
assert_eq!(logs.len(), 1, "{logs:?}");
assert_eq!(logs[0].0, log::Level::Debug);
assert!(
logs[0].1.contains(&format!("child {pid} is not in the leaf cgroup")),
"{logs:?}"
);
assert_left_unsignalled(&err, pid, stdin);
}