use std::io::{PipeWriter, Read as _};
use std::os::unix::process::ExitStatusExt as _;
use std::time::Duration;
use crate::child::fault::record_root_teardowns;
use crate::command::Command;
use crate::elevation::{Backend, ElevatedStdio, ElevatedVia, ElevationReport};
use crate::error::{ElevationErrorKind, Error};
use crate::{ContainMode, Containment, Stdio};
pub(crate) fn report(via: ElevatedVia) -> Option<ElevationReport> {
Some(ElevationReport {
via,
stripped_env: Vec::new(),
stdio: ElevatedStdio::Passthrough,
})
}
pub(crate) fn spawn_as(mut cmd: Command, via: ElevatedVia) -> (crate::Child, PipeWriter) {
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
cmd.set_elevation_front(crate::elevation::front::front(Some(&via)));
let mut child = cmd.spawn().expect("spawn");
child.set_elevation(report(via));
let stdin = child.stdin().expect("stdin pipe");
(child, stdin)
}
pub(crate) fn cat() -> Command {
let mut cmd = Command::new();
cmd.args(["cat"]);
cmd
}
#[track_caller]
pub(crate) fn assert_unkillable_front<T: std::fmt::Debug>(r: Result<T, Error>, pid: u32) {
assert_refused_by(r, &format!("pid {pid} is what sudo left"));
}
#[track_caller]
pub(crate) fn assert_refused_by<T: std::fmt::Debug>(r: Result<T, Error>, names: &str) {
match r {
Err(Error::Elevation {
kind: ElevationErrorKind::Unkillable,
detail,
}) => assert!(detail.contains(names), "{detail}"),
other => panic!("expected Unkillable naming {names:?}, got {other:?}"),
}
}
#[track_caller]
pub(crate) fn assert_ends_unsignalled(child: &crate::Child, stdin: PipeWriter) {
drop(stdin);
let status = child.wait().expect("wait");
assert!(status.success(), "the front was signalled: {status:?}");
}
#[skuld::test]
fn kill_of_a_live_front_is_unkillable_and_sends_nothing() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
assert_unkillable_front(child.kill(), child.id().pid());
assert_ends_unsignalled(&child, stdin);
}
#[skuld::test]
fn kill_of_an_exited_front_is_ok() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
drop(stdin);
crate::test_child::wait_until_zombie(child.id().pid());
let refused = crate::signal::seams::refuse_kills();
child.kill().expect("an exited front is killed like any child");
drop(refused);
assert!(child.wait().expect("wait").success());
}
#[skuld::test]
fn kill_of_an_exited_front_returns_any_other_failure() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
drop(stdin);
crate::test_child::wait_until_zombie(child.id().pid());
let failing = crate::signal::seams::fail_kills_with(libc::EINVAL);
match child.kill() {
Err(Error::Io(io)) => assert_eq!(io.kind(), std::io::ErrorKind::InvalidInput, "{io}"),
other => panic!("expected the kill's own failure, got {other:?}"),
}
drop(failing);
assert!(child.wait().expect("wait").success());
}
#[skuld::test]
fn kill_tree_of_an_exited_front_is_ok() {
let mut cmd = cat();
cmd.contain_with(ContainMode::Session);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
drop(stdin);
crate::test_child::wait_until_zombie(child.id().pid());
let refused = crate::signal::seams::refuse_kills();
child
.kill_tree()
.expect("an exited front's tree is killed like any child's");
drop(refused);
assert!(child.wait().expect("wait").success());
}
#[skuld::test]
fn drop_of_an_exited_front_reaps_it_and_warns_of_nothing() {
crate::log_capture::install();
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
let pid = child.id().pid();
drop(stdin);
crate::test_child::wait_until_zombie(pid);
let mark = crate::log_capture::mark();
drop(child);
let warns = crate::log_capture::records_since_on_current_thread(mark, "Child::drop");
assert!(warns.is_empty(), "{warns:?}");
assert_eq!(reap(pid), None, "the drop reaps an exited front");
}
#[skuld::test]
fn kill_reads_the_front_its_spawn_found_not_its_report() {
let mut cmd = cat();
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
let mut child = cmd.spawn().expect("spawn");
child.set_elevation(report(ElevatedVia::Wrapped(Backend::Sudo)));
let stdin = child.stdin().expect("stdin pipe");
child.kill().expect("a child with no front is killed as any child");
drop(stdin);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}
#[skuld::test]
fn kill_of_a_live_doas_front_is_unkillable_and_sends_nothing() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Doas));
assert_refused_by(child.kill(), &format!("pid {} is what doas left", child.id().pid()));
assert_ends_unsignalled(&child, stdin);
}
pub(crate) fn uncontained_cats() -> [Command; 2] {
let mut walked = cat();
walked.contain_with(ContainMode::TreeWalk);
[cat(), walked]
}
#[skuld::test]
fn kill_of_a_live_front_without_a_group_sends_nothing() {
for cmd in uncontained_cats() {
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
assert_unkillable_front(child.kill(), child.id().pid());
assert_ends_unsignalled(&child, stdin);
}
}
#[skuld::test]
fn drop_of_a_live_front_without_a_group_sends_nothing() {
for cmd in uncontained_cats() {
let teardowns = record_root_teardowns();
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let pid = child.id().pid();
drop(child);
assert_eq!(teardowns.count(), 0, "the drop must not kill or reap a live front");
drop(stdin);
assert_reaped_unsignalled(pid);
}
}
#[skuld::test]
fn a_failed_password_write_sends_a_live_front_without_a_group_nothing() {
for cmd in uncontained_cats() {
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let id = child.id();
let pid = id.pid();
let (detail, fate) = failed_password_write_detail(child);
assert_eq!(
fate,
crate::error::ChildFate::Running { id: Some(id) },
"a live front is left"
);
assert!(detail.contains("could not be terminated"), "{detail}");
assert!(detail.contains(&format!("pid {pid} is what sudo left")), "{detail}");
drop(stdin);
assert_reaped_unsignalled(pid);
}
}
pub(crate) fn failed_password_write_detail(child: crate::Child) -> (String, crate::error::ChildFate) {
let (err, fate) = crate::child::spawn::finish_elevated(
child,
Err(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
let Error::Elevation { detail, .. } = err else {
panic!("expected an Elevation error, got {err:?}");
};
(detail, fate)
}
#[skuld::test]
fn graceful_shutdown_of_a_front_that_exits_within_the_grace_returns_its_status() {
let (child, _stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
let status = child
.graceful_shutdown(Duration::from_secs(3600))
.expect("the relayed SIGTERM ends the front");
assert_eq!(status.signal(), Some(libc::SIGTERM));
}
#[skuld::test]
fn graceful_shutdown_of_a_front_that_exits_before_its_escalation() {
use std::cell::RefCell;
use std::rc::Rc;
use crate::child::graceful::fault::{at, HookPoint};
for errno in [libc::EPERM, libc::EINVAL] {
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(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let mut ready = [0u8; 6];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut ready)
.expect("read `ready`");
let pid = child.id().pid();
let failing = Rc::new(RefCell::new(None));
let _hook = at(HookPoint::BeforeEscalation, {
let failing = Rc::clone(&failing);
move || {
drop(stdin);
crate::test_child::wait_until_zombie(pid);
*failing.borrow_mut() = Some(crate::signal::seams::fail_kills_with(errno));
}
});
let result = child.graceful_shutdown(Duration::ZERO);
drop(failing.borrow_mut().take());
if errno == libc::EPERM {
assert!(result.expect("a refused kill of an exited front is Ok").success());
} else {
match result {
Err(Error::Io(io)) => assert_eq!(io.kind(), std::io::ErrorKind::InvalidInput, "{io}"),
other => panic!("expected the kill's own failure, got {other:?}"),
}
assert!(child.wait().expect("wait").success());
}
}
}
#[skuld::test]
fn a_failed_password_write_to_a_front_someone_else_reaped_says_it_had_exited() {
let mut cmd = cat();
cmd.kill_on_drop(false);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let pid = child.id().pid();
drop(stdin);
crate::test_child::wait_until_zombie(pid);
assert!(reap(pid).is_some(), "the test reaps the front itself");
let (detail, fate) = failed_password_write_detail(child);
assert_eq!(fate, crate::error::ChildFate::Gone);
assert!(
detail.contains("the elevated child had already exited, and was reaped by someone else"),
"{detail}"
);
}
#[skuld::test]
fn kill_of_a_pkexec_child_signals_it() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Pkexec));
child.kill().expect("kill");
drop(stdin);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGKILL));
}
#[skuld::test]
fn kill_tree_of_a_live_front_outside_a_cgroup_is_unkillable_and_sends_nothing() {
let mut cmd = cat();
cmd.contain_with(ContainMode::Session);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
assert_ne!(child.containment(), Containment::CgroupV2);
assert_unkillable_front(child.kill_tree(), child.id().pid());
assert_ends_unsignalled(&child, stdin);
}
#[skuld::test]
fn graceful_shutdown_of_a_front_that_outlives_the_grace_is_unkillable() {
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(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let mut ready = [0u8; 6];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut ready)
.expect("read `ready`");
assert_eq!(&ready, b"ready\n");
assert_unkillable_front(child.graceful_shutdown(Duration::ZERO), child.id().pid());
assert_ends_unsignalled(&child, stdin);
}
#[skuld::test]
fn drop_of_a_live_front_leaves_it_running_unreaped_and_warns() {
crate::log_capture::install();
let teardowns = record_root_teardowns();
let mut cmd = cat();
cmd.contain_with(ContainMode::Session);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let pid = child.id().pid();
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(teardowns.count(), 0, "the drop must not kill or reap a live front");
let warns = crate::log_capture::records_since_on_current_thread(mark, "Child::drop");
assert_eq!(warns.len(), 1, "{warns:?}");
assert_eq!(warns[0].0, log::Level::Warn);
assert!(
warns[0].1.contains(&format!("pid {pid} is what sudo left")),
"{warns:?}"
);
drop(stdin);
assert_reaped_unsignalled(pid);
}
#[track_caller]
pub(crate) fn assert_reaped_unsignalled(pid: u32) {
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(
reaped,
pid as libc::pid_t,
"waitpid: {}",
std::io::Error::last_os_error()
);
assert!(
libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
"the front was signalled: raw status {status:#x}"
);
}
#[skuld::test]
fn a_failed_password_write_signals_neither_a_live_front_nor_its_group() {
let groups = crate::containment::unix::fault::record_kill_group();
let mut cmd = cat();
cmd.contain_with(ContainMode::Session);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
let id = child.id();
let pid = id.pid();
let (err, fate) = crate::child::spawn::finish_elevated(
child,
Err(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(
fate,
crate::error::ChildFate::Running { id: Some(id) },
"a live front is left"
);
assert_eq!(
groups.killed(),
Vec::<i32>::new(),
"no group kill of a live front: {err}"
);
let Error::Elevation { detail, .. } = &err else {
panic!("expected an Elevation error, got {err:?}");
};
assert!(detail.contains("could not be terminated"), "{detail}");
assert!(detail.contains(&format!("pid {pid} is what sudo left")), "{detail}");
drop(stdin);
assert_reaped_unsignalled(pid);
}
fn failed_password_write_fate(child: crate::Child) -> crate::error::ChildFate {
crate::child::spawn::finish_elevated(
child,
Err(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with()
.1
}
#[skuld::test]
fn a_failed_password_write_leaves_a_live_front_running_and_names_it() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
let id = child.id();
let fate = failed_password_write_fate(child);
assert_eq!(fate, crate::error::ChildFate::Running { id: Some(id) });
drop(stdin);
assert_reaped_unsignalled(id.pid());
}
#[skuld::test]
fn a_live_front_reaped_elsewhere_after_the_refused_kill_is_gone() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
let pid = child.id().pid();
let _foreign_reap = crate::child::spawn::fault::set_between_kill_and_wait(move || {
drop(stdin);
crate::test_child::wait_until_zombie(pid);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
});
assert_eq!(failed_password_write_fate(child), crate::error::ChildFate::Gone);
}
#[skuld::test]
fn a_failed_password_write_to_a_front_that_had_exited_says_so() {
let mut cmd = cat();
cmd.kill_on_drop(false);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
drop(stdin);
crate::test_child::wait_until_zombie(child.id().pid());
let _refused = crate::signal::seams::refuse_kills();
let gates = crate::elevation::front::seams::count_kill_gates();
let (err, fate) = crate::child::spawn::finish_elevated(
child,
Err(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the non-blocking look reaps the exited front"
);
assert_eq!(gates.count(), 1, "{err}");
let Error::Elevation { detail, .. } = &err else {
panic!("expected an Elevation error, got {err:?}");
};
assert!(detail.contains("the elevated child had already exited"), "{detail}");
assert!(!detail.contains("terminated"), "{detail}");
}
#[skuld::test]
fn a_failed_password_write_whose_exited_front_cannot_be_reaped_says_it_had_exited() {
let mut cmd = cat();
cmd.kill_on_drop(false);
let (child, stdin) = spawn_as(cmd, ElevatedVia::Wrapped(Backend::Sudo));
drop(stdin);
crate::test_child::wait_until_zombie(child.id().pid());
let _refused = crate::signal::seams::refuse_kills();
crate::child::spawn::fault::set_force_reap_failure("forced reap failure");
let (err, fate) = crate::child::spawn::finish_elevated(
child,
Err(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, crate::error::ChildFate::Killed, "the exit was not collected");
let Error::Elevation { detail, .. } = &err else {
panic!("expected an Elevation error, got {err:?}");
};
assert!(
detail.contains("the elevated child had already exited, but could not be reaped"),
"{detail}"
);
assert!(!detail.contains("killed"), "{detail}");
}
#[skuld::test]
fn terminate_of_a_live_osascript_is_unkillable_and_sends_nothing() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::MacosOsascript);
let pid = child.id().pid();
assert_refused_by(child.terminate(), &format!("pid {pid} is osascript"));
assert_ends_unsignalled(&child, stdin);
}
#[skuld::test]
fn graceful_shutdown_of_a_live_osascript_is_unkillable_and_sends_nothing() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::MacosOsascript);
let pid = child.id().pid();
assert_refused_by(
child.graceful_shutdown(Duration::ZERO),
&format!("pid {pid} is osascript"),
);
assert_refused_by(child.kill(), &format!("pid {pid} is osascript"));
assert_ends_unsignalled(&child, stdin);
}
#[skuld::test]
fn terminate_of_a_live_sudo_front_is_sent() {
let (child, stdin) = spawn_as(cat(), ElevatedVia::Wrapped(Backend::Sudo));
child.terminate().expect("sudo relays SIGTERM");
drop(stdin);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGTERM));
}
#[cfg(target_os = "linux")]
pub(crate) fn failed_front_spawns(
contain: Option<ContainMode>,
spawn: impl Fn(&mut Command) -> Result<(), Error>,
) -> [(Error, u32); 2] {
use crate::child::spawn::fault;
let arms: [(fn(bool), bool); 2] = [
(fault::set_force_attach_failure, true),
(fault::set_force_identity_vanished, false),
];
arms.map(|(force_arm, identified)| {
let mut cmd = cat();
cmd.stdin(Stdio::pipe_in()).expect("stdin pipe");
if let Some(mode) = contain {
cmd.contain_with(mode);
}
cmd.set_elevation_front(crate::elevation::front::front(Some(&ElevatedVia::Wrapped(
Backend::Sudo,
))));
force_arm(true);
let err = spawn(&mut cmd);
force_arm(false);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
err.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");
};
let expected = if contain.is_some() {
crate::error::ChildFate::Reaped
} else {
crate::error::ChildFate::Running {
id: identified.then_some(id),
}
};
assert_eq!(fate, expected, "{err}");
(err, id.pid())
})
}
pub(crate) fn reap(pid: u32) -> Option<std::process::ExitStatus> {
let mut raw = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut raw, 0) };
if reaped == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD) {
return None;
}
assert_eq!(
reaped,
pid as libc::pid_t,
"waitpid: {}",
std::io::Error::last_os_error()
);
Some(std::os::unix::process::ExitStatusExt::from_raw(raw))
}
#[cfg(target_os = "linux")]
#[track_caller]
pub(crate) fn assert_noted(failures: &[(Error, u32); 2], fate: &str) {
let [(attach, attach_pid), (identity, identity_pid)] = failures;
assert!(
matches!(attach, Error::Containment { .. }),
"the attach failure keeps its variant: {attach:?}"
);
assert!(
matches!(identity, Error::Io(_)),
"the identity failure keeps its variant: {identity:?}"
);
for (err, pid) in [(attach, attach_pid), (identity, identity_pid)] {
let text = err.to_string();
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(text.contains(fate), "{text}");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_spawn_leaves_an_elevation_front_running_and_says_so() {
let failures = failed_front_spawns(None, |cmd| cmd.spawn().map(drop));
assert_noted(&failures, "the elevated program may be running; it is left unreaped");
for (_, pid) in &failures {
let status = reap(*pid).expect("the front must be left unreaped");
assert!(status.success(), "the teardown signalled the front: {status:?}");
}
}
#[skuld::test]
fn graceful_shutdown_of_a_child_that_is_not_a_front_keeps_its_io_refusal() {
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(cmd, ElevatedVia::Wrapped(Backend::Pkexec));
let mut ready = [0u8; 6];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut ready)
.expect("read `ready`");
{
let _refused = crate::signal::seams::refuse_kills();
match child.graceful_shutdown(Duration::ZERO) {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e}"),
other => panic!("expected the raw Io(PermissionDenied), got {other:?}"),
}
}
assert_ends_unsignalled(&child, stdin);
}
#[cfg(target_os = "macos")]
pub(crate) fn fail_the_attach() -> AttachFails {
crate::child::spawn::fault::set_force_attach_failure(true);
AttachFails
}
#[cfg(target_os = "macos")]
#[must_use = "attaches succeed again as soon as the guard is dropped"]
pub(crate) struct AttachFails;
#[cfg(target_os = "macos")]
impl Drop for AttachFails {
fn drop(&mut self) {
crate::child::spawn::fault::set_force_attach_failure(false);
}
}
#[cfg(target_os = "macos")]
#[track_caller]
pub(crate) fn assert_attach_failure_left_the_front(err: &Error, pid: u32, mark: usize) {
assert!(matches!(err, Error::Containment { .. }), "the variant is kept: {err:?}");
let text = err.to_string();
assert!(text.contains(&format!("pid {pid} is what sudo left")), "{text}");
assert!(text.contains("it is left unreaped"), "{text}");
assert!(
crate::log_capture::contains_since(mark, "attach failed"),
"the warning says the attach failed"
);
assert!(
!crate::log_capture::contains_since(mark, "could not be read"),
"the identity was read, so the log must not say it was not"
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_front_whose_attach_fails_is_left_unreaped_and_noted() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (err, id, fate) = fail_a_front_spawn(|_| {}, fail_the_attach, |cmd| cmd.spawn().map(drop));
assert_eq!(
fate,
crate::error::ChildFate::Running { id: Some(id) },
"the front is left running"
);
assert_attach_failure_left_the_front(&err, id.pid(), mark);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_an_identity_check_that_found_the_front_gone_does_not_claim_it_unreaped() {
let (err, _id, fate) = fail_a_front_spawn(|_| {}, identity_finds_the_front_gone, |cmd| cmd.spawn().map(drop));
assert_eq!(
fate,
crate::error::ChildFate::Gone,
"the check found it reaped by someone else"
);
assert_noted_unaccounted(&err);
}
#[cfg(target_os = "macos")]
pub(crate) fn identity_finds_the_front_gone() -> IdentityFindsGone {
crate::child::spawn::fault::set_force_identity_vanished(true);
IdentityFindsGone
}
#[cfg(target_os = "macos")]
#[must_use = "identity checks succeed again as soon as the guard is dropped"]
pub(crate) struct IdentityFindsGone;
#[cfg(target_os = "macos")]
impl Drop for IdentityFindsGone {
fn drop(&mut self) {
crate::child::spawn::fault::set_force_identity_vanished(false);
}
}
#[cfg(target_os = "macos")]
#[track_caller]
pub(crate) fn assert_noted_unaccounted(err: &Error) {
let text = err.to_string();
assert!(text.contains("what sudo left"), "{text}");
assert!(text.contains("could not be waited on"), "{text}");
assert!(!text.contains("left unreaped"), "{text}");
}
#[skuld::test]
fn an_unverified_childs_fate_follows_its_identity() {
use crate::child::spawn::FrontFate;
use crate::containment::RootIdentity;
assert_eq!(FrontFate::of_unverified(RootIdentity::Gone), FrontFate::Unaccounted);
assert_eq!(FrontFate::of_unverified(RootIdentity::Unknown), FrontFate::LeftUnreaped);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_front_whose_report_read_fails_is_left_and_noted() {
let (err, id, fate) = fail_a_front_spawn(|_| {}, fail_the_report_read, |cmd| cmd.spawn().map(drop));
assert_eq!(
fate,
crate::error::ChildFate::Running { id: None },
"the front is left running"
);
assert_unadopted_front_noted(&err, id.pid());
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_a_front_whose_identity_is_refused_is_left_and_noted() {
let (err, id, fate) = fail_a_front_spawn(|_| {}, refuse_the_identity, |cmd| cmd.spawn().map(drop));
assert_eq!(
fate,
crate::error::ChildFate::Running { id: None },
"the front is left running"
);
assert_unadopted_front_noted(&err, id.pid());
}
#[cfg(target_os = "macos")]
pub(crate) fn fail_the_report_read() -> crate::child::spawn::unique_report::seams::FailedParentRead {
crate::child::spawn::unique_report::seams::fail_parent_read(libc::EIO)
}
#[cfg(target_os = "macos")]
pub(crate) fn refuse_the_identity() -> RefusedIdentity {
crate::child::spawn::fault::set_force_identity_unknown(true);
RefusedIdentity(crate::wait::exit_only::seams::force_peek_once(Err(
std::io::Error::from_raw_os_error(libc::EPERM),
)))
}
#[cfg(target_os = "macos")]
#[must_use = "identity reads succeed again as soon as the guard is dropped"]
pub(crate) struct RefusedIdentity(
#[allow(dead_code, reason = "held for its drop")] crate::wait::exit_only::seams::Forced,
);
#[cfg(target_os = "macos")]
impl Drop for RefusedIdentity {
fn drop(&mut self) {
crate::child::spawn::fault::set_force_identity_unknown(false);
}
}
#[cfg(target_os = "macos")]
pub(crate) fn fail_a_front_spawn<G>(
configure: impl FnOnce(&mut Command),
force: impl FnOnce() -> G,
spawn: impl FnOnce(&mut Command) -> Result<(), Error>,
) -> (Error, crate::identity::ProcessId, crate::error::ChildFate) {
use std::os::fd::OwnedFd;
use crate::child::spawn::fault;
let (reader, writer) = std::io::pipe().expect("pipe");
let mut cmd = cat();
cmd.stdin(Stdio::from_file(std::fs::File::from(OwnedFd::from(reader))))
.expect("stdin");
cmd.set_elevation_front(crate::elevation::front::front(Some(&ElevatedVia::Wrapped(
Backend::Sudo,
))));
configure(&mut cmd);
let err = {
let _forced = force();
spawn(&mut cmd).expect_err("the forced failure fails the spawn")
};
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let crate::identity::Resolved::Found(id) = fault::take_captured().expect("the spawn captured the child") else {
panic!("the spawn must capture a resolved identity");
};
drop(writer);
let status = reap(id.pid()).expect("the front was left unreaped");
assert!(status.success(), "the front was signalled: {status:?}");
(err, id, fate)
}
#[cfg(target_os = "macos")]
#[track_caller]
pub(crate) fn assert_unadopted_front_noted(err: &Error, pid: u32) {
assert!(
matches!(err, Error::Unassessable { .. }),
"the variant is kept: {err:?}"
);
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}"
);
}