use std::cell::{Cell, RefCell};
use crate::test_child::Console;
use std::io::Read as _;
use crate::{PipeReader, PipeWriter};
use std::os::fd::{AsFd as _, OwnedFd};
use std::os::unix::process::ExitStatusExt as _;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::child::front_kill_tests::{
assert_ends_unsignalled, assert_reaped_unsignalled, assert_refused_by, assert_unkillable_front, cat, spawn_as,
};
use crate::child::owned::seams::record_root_teardowns;
use crate::command::Command;
use crate::elevation::{Backend, ElevatedVia};
use crate::os_process::fake::ReapAnswer;
use crate::test_groups::{cgroup, Group};
use crate::{ContainMode, Containment, Stdio};
pub(crate) const SUDO: ElevatedVia = ElevatedVia::Wrapped(Backend::Sudo);
type Kill = fn(&crate::Child) -> Result<(), crate::error::Error>;
pub(crate) fn in_cgroup(mut cmd: Command) -> Command {
cmd.contain_with(ContainMode::Strongest);
cmd
}
pub(crate) fn nobody_cat() -> Command {
let mut cmd = crate::test_child::command(Console::Hidden);
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}"),
}
}
}
fn end_signal(pidfd: &OwnedFd) -> Option<i32> {
loop {
match rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOWAIT,
) {
Ok(Some(status)) => return status.terminating_signal(),
Ok(None) => unreachable!("a blocking waitid returns a status"),
Err(rustix::io::Errno::INTR) => {}
Err(e) => panic!("waitid on the pidfd of a child nothing has reaped: {e}"),
}
}
}
type EndedBy = (u32, Option<i32>);
type Released = (bool, Vec<EndedBy>);
type Once = Box<dyn FnOnce()>;
#[must_use = "dropping this disarms the release"]
pub(crate) struct KillRelease {
_after_write: crate::oneshot_hook::Armed,
_before_drain: crate::oneshot_hook::Armed,
_before_wait: crate::oneshot_hook::Armed,
observed: Rc<RefCell<Vec<(u32, OwnedFd)>>>,
ended: Rc<RefCell<Option<Released>>>,
}
pub(crate) fn release_after_cgroup_kill(held: impl Sized + 'static) -> KillRelease {
release_by_cgroup_kill(move || drop(held))
}
pub(crate) fn release_by_cgroup_kill(release: impl FnOnce() + 'static) -> KillRelease {
release_by_cgroup_kill_and_at_wait(release, || {})
}
pub(crate) fn release_by_cgroup_kill_and_at_wait(
release: impl FnOnce() + 'static,
at_wait: impl FnOnce() + 'static,
) -> KillRelease {
let observed: Rc<RefCell<Vec<(u32, OwnedFd)>>> = Rc::default();
let ended = Rc::new(RefCell::new(None));
let release: Rc<Cell<Option<Once>>> = Rc::new(Cell::new(Some(Box::new(release))));
let fire: Rc<dyn Fn(bool)> = {
let (observed, ended) = (Rc::clone(&observed), Rc::clone(&ended));
Rc::new(move |by_write| {
let Some(release) = release.take() else {
return;
};
release();
let how = observed
.borrow()
.iter()
.map(|(pid, pidfd)| (*pid, end_signal(pidfd)))
.collect();
*ended.borrow_mut() = Some((by_write, how));
})
};
let after_write = crate::containment::cgroup::fault::set_after_kill_write({
let fire = Rc::clone(&fire);
move || fire(true)
});
let before_drain = crate::containment::cgroup::fault::set_before_drain_block({
let fire = Rc::clone(&fire);
move || fire(false)
});
let before_wait = crate::child::spawn::fault::set_between_kill_and_wait({
let fire = Rc::clone(&fire);
move || {
at_wait();
fire(false);
}
});
KillRelease {
_after_write: after_write,
_before_drain: before_drain,
_before_wait: before_wait,
observed,
ended,
}
}
impl KillRelease {
pub(crate) fn observe(&self, pid: u32) {
self.observed.borrow_mut().push((pid, pidfd_of(pid)));
}
#[track_caller]
pub(crate) fn assert_killed(&self) {
let ended = self.ended.borrow();
let (by_write, ended) = ended
.as_ref()
.expect("the teardown released its holder, at the cgroup kill or before its drain wait");
assert!(*by_write, "cgroup.kill was written before the teardown's waits");
for (pid, signal) in ended {
assert_eq!(
*signal,
Some(libc::SIGKILL),
"pid {pid} must die of the cgroup kill, not exit by itself once released"
);
}
}
}
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);
let sent = crate::send_log::Capture::start();
child.kill().expect("the cgroup kill reaches the program");
assert_eq!(sent.entries(), [], "nothing is signalled after it");
drop(sent);
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);
let sent = crate::send_log::Capture::start();
child.kill_tree().expect("the cgroup kill reaches the program");
assert_eq!(sent.entries(), [], "nothing is signalled after it");
drop(sent);
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 pid = child.pid();
let pidfd = pidfd_of(pid);
let release = release_after_cgroup_kill(stdin);
release.observe(pid);
let mark = crate::log_capture::mark();
drop(child);
release.assert_killed();
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 said = crate::log_capture::records_since_on_current_thread(mark, "Child::drop");
assert_said_reaped_at_debug(&said, pid, "a front the cgroup killed is not left behind");
}
#[track_caller]
fn assert_said_reaped_at_debug(said: &[(log::Level, String)], pid: u32, what: &str) {
let reaped = format!("Child::drop: elevation front pid {pid}: reaped it");
let reaped_after_the_kill = format!("{reaped} after the kill");
assert!(
said.iter().all(|(level, _)| *level >= log::Level::Debug),
"{what}: a record above debug: {said:?}"
);
let reaps: Vec<_> = said
.iter()
.filter(|(_, text)| *text == reaped || *text == reaped_after_the_kill)
.collect();
assert_eq!(reaps.len(), 1, "{what}: the reap is said once: {said:?}");
}
#[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.pid();
let mark = crate::log_capture::mark();
let stdin = Rc::new(std::cell::Cell::new(Some(stdin)));
{
let _failing = crate::containment::cgroup::fault::fail_kill_writes_releasing_on_unwritten_kill({
let stdin = Rc::clone(&stdin);
move || drop(stdin.take())
});
drop(child);
}
let stdin = stdin.take().expect("released only before a failure");
let warns = crate::log_capture::warns_since(mark, "Child::drop");
assert_eq!(warns.len(), 1, "one warn for the one event: {warns:?}");
assert!(
warns[0].contains("contained-tree teardown did not fully succeed") && warns[0].contains("elevation front pid"),
"the failed kill and the front are in it: {warns:?}"
);
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) const FRONT_WITH_MEMBER_SH: &str = "{ cat <&2 2>&- && echo eof; } & echo $!; exec cat";
pub(crate) struct FrontWithMember {
pub(crate) child: crate::Child,
pub(crate) stdin: PipeWriter,
pub(crate) member_stdin: PipeWriter,
pub(crate) member: OwnedFd,
pub(crate) stdout: PipeReader,
}
pub(crate) fn spawn_front_with_member() -> FrontWithMember {
let (member_reader, member_stdin) = std::io::pipe().expect("pipe");
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["sh", "-c", FRONT_WITH_MEMBER_SH]);
cmd.stdout(Stdio::pipe_out()).expect("stdout pipe");
cmd.stderr(Stdio::from_file(std::fs::File::from(OwnedFd::from(member_reader))))
.expect("stderr");
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 member's pid");
FrontWithMember {
child,
stdin,
member_stdin: member_stdin.into(),
member: pidfd_of(member),
stdout,
}
}
#[track_caller]
pub(crate) fn assert_nothing_ended_by_itself(rest: &[u8]) {
assert!(
rest.is_empty(),
"a member ended by itself, so the kill did not reach it: {}",
String::from_utf8_lossy(rest)
);
}
pub(crate) fn wait_until_exited(pidfd: &OwnedFd) {
let mut fds = [rustix::event::PollFd::from_borrowed_fd(
pidfd.as_fd(),
rustix::event::PollFlags::IN,
)];
crate::wait::poll_ready(&mut fds).expect("poll the pidfd");
}
#[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 FrontWithMember {
mut child,
stdin,
member_stdin,
member,
mut stdout,
} = spawn_front_with_member();
let front = pidfd_of(child.pid());
let pid = child.pid();
let release = release_after_cgroup_kill((stdin, member_stdin));
release.observe(pid);
let awaited = Arc::new(AtomicBool::new(false));
crate::containment::cgroup::fault::record_leaf_steps();
child.proc.script_over(|fake| fake).on_look({
let awaited = Arc::clone(&awaited);
move |_| {
if crate::containment::cgroup::fault::peek_leaf_steps()
.iter()
.any(|step| step == "kill")
{
crate::test_child::wait_until_zombie(pid);
awaited.store(true, Ordering::SeqCst);
}
}
});
let mark = crate::log_capture::mark();
{
let _fault = fault();
drop(child);
}
let steps = crate::containment::cgroup::fault::take_leaf_steps();
release.assert_killed();
assert!(
awaited.load(Ordering::SeqCst),
"some look came after the leaf's kill was written, and awaited the front's end"
);
let said =
crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
assert_said_reaped_at_debug(&said, pid, "a front reaped with its status needs no warn");
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);
let mut rest = Vec::new();
stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
assert_nothing_ended_by_itself(&rest);
}
#[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_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) {
use crate::containment::cgroup::fault;
crate::log_capture::install();
let FrontWithMember {
mut child,
stdin,
member_stdin,
member,
mut stdout,
} = spawn_front_with_member();
let pid = child.pid();
let front = pidfd_of(pid);
let release = release_after_cgroup_kill((stdin, member_stdin));
release.observe(pid);
let unreadable = Arc::new(std::sync::Mutex::new(None));
fault::record_leaf_steps();
child
.proc
.script_over(|fake| fake.reaps([ReapAnswer::Running]))
.on_look({
let unreadable = Arc::clone(&unreadable);
move |_| {
if fault::peek_leaf_steps().iter().any(|step| step == "kill") {
drop(unreadable.lock().expect("lock").take());
}
}
});
let mark = crate::log_capture::mark();
{
let _arming = fault::set_before_kill_write({
let unreadable = Arc::clone(&unreadable);
move || *unreadable.lock().expect("lock") = Some(fault::fail_pidfd_info())
});
let _running = crate::elevation::front::seams::read_front_running_at_every_reach_read();
drop(child);
}
fault::take_leaf_steps();
release.assert_killed();
let said =
crate::log_capture::records_since_on_current_thread(mark, &format!("Child::drop: elevation front pid {pid}"));
assert_said_reaped_at_debug(&said, pid, "a front reaped with its status needs no warn");
assert!(reaped(&front), "the drop reaps the front");
wait_until_exited(&member);
let mut rest = Vec::new();
stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
assert_nothing_ended_by_itself(&rest);
}
#[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 FrontWithMember {
mut child,
stdin,
member_stdin,
member,
mut stdout,
} = spawn_front_with_member();
let pid = child.pid();
let release = release_after_cgroup_kill((stdin, member_stdin));
release.observe(pid);
child.proc.script_over(|fake| fake.reaps([ReapAnswer::Running]));
let mark = crate::log_capture::mark();
{
let _unreadable = crate::containment::cgroup::fault::fail_pidfd_info();
drop(child);
}
release.assert_killed();
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);
wait_until_exited(&member);
let mut rest = Vec::new();
stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
assert_nothing_ended_by_itself(&rest);
}
#[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 FrontWithMember {
child,
stdin,
member_stdin,
member,
mut stdout,
} = spawn_front_with_member();
let pid = child.pid();
move_out_of_its_leaf(pid);
let stdin = Rc::new(std::cell::Cell::new(Some(stdin)));
let release = release_by_cgroup_kill_and_at_wait(move || drop(member_stdin), {
let stdin = 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:?}");
release.assert_killed();
wait_until_exited(&member);
drop(stdin.take().expect("the drop must not wait for the front"));
assert_reaped_unsignalled(pid);
let mut rest = Vec::new();
stdout.read_to_end(&mut rest).expect("every member of the tree is gone");
assert_nothing_ended_by_itself(&rest);
}
#[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.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.pid());
let release = release_after_cgroup_kill(stdin);
release.observe(child.pid());
let mark = crate::log_capture::mark();
{
let _refusing = WithoutKillCap::refusing(child.pid());
drop(child);
}
release.assert_killed();
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.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().expect(crate::test_child::IDENTITY_READ);
let pid = id.pid();
let leaf = leaf_of(&child).path().to_path_buf();
let stdin = Rc::new(std::cell::Cell::new(Some(stdin)));
let err = {
let _failing = crate::containment::cgroup::fault::fail_kill_writes_releasing_on_unwritten_kill({
let stdin = Rc::clone(&stdin);
move || drop(stdin.take())
});
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 release = stdin.take().expect("the teardown must not release the front");
let (err, fate, handed_back) = err.expect_may_have_started_parts(release);
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);
handed_back.unreaped();
let status = handed_back.wait();
assert!(status.success(), "the front was signalled: {status:?}");
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.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.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.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.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("kill_tree is accepted");
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 release = release_after_cgroup_kill(stdin);
release.observe(child.pid());
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}");
release.assert_killed();
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.into())));
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 release_front = || {
let stdin = Rc::clone(&stdin);
move || drop(stdin.borrow_mut().take())
};
let lands = matches!(
kill,
LeafKill::Lands | LeafKill::LandsNestedHidden | LeafKill::LandsReadThroughProc
);
let released_by_the_leaf = lands.then(|| Rc::new(release_by_cgroup_kill(release_front())));
let _released = (kill == LeafKill::MissesMovedFront).then(|| fault::set_between_kill_and_wait(release_front()));
let (filler, filler_release) = if kill == LeafKill::MissesIntoNamesake {
let (filler, filler_stdin) = spawn_as(cat(), SUDO);
let release = release_by_cgroup_kill_and_at_wait(move || drop(filler_stdin), release_front());
release.observe(filler.pid());
(Some(Rc::new(filler)), Some(release))
} else {
(None, None)
};
let _before_identity = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
let filler = filler.clone();
let released = released_by_the_leaf.clone();
move || {
let pid = fault::spawn_pid();
if let Some(released) = &released {
released.observe(pid);
}
match kill {
LeafKill::MissesMovedFront => move_out_of_its_leaf(pid),
LeafKill::LandsNestedHidden => {
move_under_its_leaf(pid);
}
LeafKill::MissesIntoNamesake => {
let leaf = cgroup_dir_of(pid);
let filler = filler.as_ref().expect("a filler for the namesake case").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 => {}
}
}
});
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_releasing_at_wait(release_front()));
force_arm(true);
let result = spawn(&mut cmd);
force_arm(false);
if let Some(released) = &released_by_the_leaf {
released.assert_killed();
}
if let Some((filler, release)) = filler.as_ref().zip(filler_release.as_ref()) {
release.assert_killed();
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]) {
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}");
assert_eq!(
crate::child::front_kill_tests::reap(*pid),
None,
"the teardown reaped front {pid}"
);
}
}
#[track_caller]
pub(crate) fn assert_left_running(kill: LeafKill, failures: [HeldFailure; 2], handed_back: bool) {
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}");
let left = if handed_back {
"handed back to the caller in the error"
} else {
"left unreaped"
};
assert!(
text.contains(&format!("the elevated program may be running; {left}")),
"{text}"
);
assert!(
stdin.borrow().is_some(),
"the teardown waited on front {pid}, which no kill reached"
);
let (_, _, held) = crate::test_child::expect_may_have_started_parts(err, ());
assert_eq!(!held.is_none(), handed_back, "{text}");
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 = if held.is_none() {
crate::child::front_kill_tests::reap(pid).expect("the front was left unreaped")
} else {
held.wait()
};
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 failures = failed_held_front_spawns(LeafKill::Lands, |cmd| cmd.spawn().map(drop));
assert_killed_by_the_leaf(&failures);
}
#[skuld::test]
fn cgroup_a_failed_spawn_kills_a_front_read_through_proc_and_reaps_it(#[fixture(cgroup)] _group: &Group) {
let failures = failed_held_front_spawns(LeafKill::LandsReadThroughProc, |cmd| cmd.spawn().map(drop));
assert_killed_by_the_leaf(&failures);
}
#[skuld::test]
fn cgroup_a_failed_spawn_hands_back_a_front_in_a_namesake_of_its_leaf(#[fixture(cgroup)] _group: &Group) {
let kill = LeafKill::MissesIntoNamesake;
assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)), true);
}
#[skuld::test]
fn cgroup_a_failed_spawn_whose_leaf_kill_fails_hands_back_the_front(#[fixture(cgroup)] _group: &Group) {
let kill = LeafKill::Fails;
assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)), true);
}
#[skuld::test]
fn cgroup_a_failed_spawn_hands_back_a_front_moved_out_of_its_leaf(#[fixture(cgroup)] _group: &Group) {
let kill = LeafKill::MissesMovedFront;
assert_left_running(kill, failed_held_front_spawns(kill, |cmd| cmd.spawn().map(drop)), true);
}
#[skuld::test]
fn cgroup_graceful_shutdown_of_a_front_escalates_through_the_cgroup(#[fixture(cgroup)] _group: &Group) {
let mut cmd = crate::test_child::command(Console::Hidden);
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 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 = crate::test_child::command(Console::Hidden);
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:?}");
}
});
let sent = crate::send_log::Capture::start();
child.kill().expect("a front that exited is not refused");
assert_eq!(sent.entries(), [], "nothing is signalled to a reaped front");
drop(sent);
});
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.pid();
let release = release_after_cgroup_kill(stdin);
release.observe(pid);
child
.attached
.hard_kill(&crate::containment::GroupRoot::none())
.into_result()
.expect("cgroup.kill");
release.assert_killed();
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.pid();
let release = release_after_cgroup_kill(stdin);
release.observe(pid);
killed
.attached
.hard_kill(&crate::containment::GroupRoot::none())
.into_result()
.expect("cgroup.kill");
release.assert_killed();
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.pid());
assert!(!leaf_of(&moved)
.names(moved.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.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.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.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 failures = failed_held_front_spawns(LeafKill::LandsNestedHidden, |cmd| cmd.spawn().map(drop));
assert_killed_by_the_leaf(&failures);
}
#[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.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.pid();
leaf.watch_front(pid);
let (stdin, release) = if case == RecordCase::Leaf {
let release = release_after_cgroup_kill(stdin);
release.observe(pid);
(None, Some(release))
} else {
(Some(stdin), None)
};
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);
if let Some(release) = &release {
release.assert_killed();
}
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());
let mut child = result.expect("a front /proc shows is placeable");
assert!(forked.is_some());
let release = release_after_cgroup_kill(child.stdin().expect("stdin pipe"));
release.observe(child.pid());
drop(child);
release.assert_killed();
}
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.into())
}
pub(crate) fn fail_the_identity_check<R>(
cmd: &mut Command,
spawn: impl FnOnce(&mut Command) -> Result<(), crate::error::Error>,
release: R,
) -> (crate::error::Error, u32, crate::test_child::HandedBack<R>) {
use crate::child::spawn::fault;
fault::set_force_identity_vanished(true);
let result = spawn(cmd);
fault::set_force_identity_vanished(false);
let (err, fate, handed_back) = crate::test_child::expect_may_have_started_parts(
result.expect_err("the forced identity failure fails the spawn"),
release,
);
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(), handed_back)
}
#[track_caller]
pub(crate) fn assert_left_unsignalled<R>(
err: &crate::error::Error,
pid: u32,
handed_back: crate::test_child::HandedBack<R>,
) {
let text = err.to_string();
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
let left = if handed_back.is_none() {
"left unreaped"
} else {
"handed back to the caller in the error"
};
assert!(
text.contains(&format!("the elevated program may be running; {left}")),
"{text}"
);
if handed_back.is_none() {
drop(handed_back);
assert_reaped_unsignalled(pid);
} else {
let status = handed_back.wait();
assert!(status.success(), "the front was signalled: {status:?}");
}
}
#[skuld::test]
fn cgroup_a_front_its_leaf_did_not_take_is_handed_back_by_a_failed_identity_check(#[fixture(cgroup)] _group: &Group) {
let (mut cmd, stdin) = front_its_leaf_did_not_take();
let (err, pid, handed_back) = fail_the_identity_check(&mut cmd, |cmd| cmd.spawn().map(drop), stdin);
assert!(!handed_back.is_none(), "a sync spawn hands the front back");
assert_left_unsignalled(&err, pid, handed_back);
}
#[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, handed_back) = fail_the_identity_check(&mut cmd, |cmd| cmd.spawn().map(drop), stdin);
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, handed_back);
}