#![cfg(all(target_os = "linux", feature = "uds"))]
use std::ffi::CString;
use std::fs::{self, File, OpenOptions};
use std::io::Write as _;
use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::fs::PermissionsExt as _;
use std::os::unix::net::{UnixListener, UnixStream};
use std::os::unix::process::ExitStatusExt as _;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use trusty_common::linux_lifecycle::{
DaemonDescriptor, KernelDelivery, LifecycleError, PinnedProcess, ProcessTable, Signal,
SignalDelivery, StopOutcome, StoppedSignal, restart, restart_pid, restart_pid_with,
restart_with, restart_with_table, start, start_with_table, stop, stop_pid, stop_pid_with,
stop_with, stop_with_table,
};
const ROLE_DAEMON: &str = "tc-lc-role=daemon";
const ROLE_RUNNER: &str = "tc-lc-role=runner";
const ROLE_BRIDGE: &str = "tc-lc-role=bridge";
const SOCKET_ENV: &str = "TC_LC_SOCKET";
const BAD_NAME_FLAG: &str = "bad-name";
const BAD_NAME: &[u8] = b"lc-\xff\xfe-bad";
const DAEMON: &str = "lc-daemon";
const OTHER: &str = "lc-other";
const LINGER_MS: u64 = 3_500;
const SERVE_BOUND: Duration = Duration::from_secs(20);
const FIXTURE_LIFETIME: Duration = Duration::from_secs(120);
const WATCH_TICK: Duration = Duration::from_millis(100);
const SPAWN_SETTLE: Duration = Duration::from_millis(500);
#[test]
fn child_entry() {
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == ROLE_DAEMON || a == ROLE_BRIDGE) {
daemon_main(&args);
}
if args.iter().any(|a| a == ROLE_RUNNER) {
runner_main(&args);
}
}
fn arg<'a>(args: &'a [String], key: &str) -> Option<&'a str> {
args.iter()
.find_map(|a| a.strip_prefix(key)?.strip_prefix('='))
}
static TERM: AtomicBool = AtomicBool::new(false);
extern "C" fn on_term(_: libc::c_int) {
TERM.store(true, Ordering::SeqCst);
}
fn append(path: &str, line: &str) {
let mut f = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.expect("open marker");
writeln!(f, "{line}").expect("write marker");
}
fn arm_watchdog(dir: PathBuf) {
std::thread::spawn(move || {
let deadline = Instant::now() + FIXTURE_LIFETIME;
while Instant::now() < deadline && fs::symlink_metadata(&dir).is_ok() {
std::thread::sleep(WATCH_TICK);
}
std::process::exit(3);
});
}
fn forked_watch(dir: &CString) -> ! {
let ticks = FIXTURE_LIFETIME.as_millis() / WATCH_TICK.as_millis();
let tick = libc::timespec {
tv_sec: 0,
tv_nsec: WATCH_TICK.as_nanos() as libc::c_long,
};
for _ in 0..ticks {
unsafe {
if libc::access(dir.as_ptr(), libc::F_OK) != 0 {
break;
}
libc::nanosleep(&tick, std::ptr::null_mut());
}
}
unsafe { libc::_exit(3) }
}
fn daemon_main(args: &[String]) -> ! {
let mode = arg(args, "mode").unwrap_or("serve");
let socket = arg(args, "socket")
.map(PathBuf::from)
.or_else(|| std::env::var_os(SOCKET_ENV).map(PathBuf::from))
.expect("socket arg or env");
let watch_dir = socket.parent().expect("socket dir").to_path_buf();
arm_watchdog(watch_dir.clone());
if args.iter().any(|a| a == "undumpable") {
let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) };
assert_eq!(rc, 0, "prctl(PR_SET_DUMPABLE)");
}
if args.iter().any(|a| a == BAD_NAME_FLAG) {
fs::write("/proc/self/comm", BAD_NAME).expect("set comm");
}
let marker = arg(args, "marker");
if let Some(m) = marker {
append(m, &std::process::id().to_string());
}
let _lock = arg(args, "lock").map(|p| {
let f = File::create(p).expect("create lock");
f.lock().expect("take lock");
f
});
if mode == "exit-now" {
std::process::exit(7);
}
unsafe {
if mode == "ignore-term" {
libc::signal(libc::SIGTERM, libc::SIG_IGN);
} else {
libc::signal(libc::SIGTERM, on_term as *const () as libc::sighandler_t);
}
}
if mode == "never-bind" {
loop {
if TERM.load(Ordering::SeqCst) {
std::process::exit(0);
}
std::thread::sleep(Duration::from_millis(10));
}
}
let watch_c = CString::new(watch_dir.as_os_str().as_bytes()).expect("watch dir C string");
let bind_lock = File::create(format!("{}.lock", socket.display())).expect("bind lock");
bind_lock.lock().expect("take bind lock");
let _ = fs::remove_file(&socket);
let listener = UnixListener::bind(&socket).expect("bind fixture socket");
drop(bind_lock);
listener.set_nonblocking(true).expect("nonblocking");
let mut listener = Some(listener);
if mode == "unlink-socket" || mode == "close-socket" {
if mode == "unlink-socket" {
fs::remove_file(&socket).expect("unlink fixture socket");
} else {
drop(listener.take());
}
if let Some(m) = marker {
append(m, "unserved");
}
}
loop {
if TERM.load(Ordering::SeqCst) {
match mode {
"linger" => {
drop(listener.take());
if let Some(m) = marker {
append(m, "closed");
}
std::thread::sleep(Duration::from_millis(LINGER_MS));
std::process::exit(0);
}
"fork-lock-holder" => {
drop(listener.take());
let _ = fs::remove_file(&socket);
let holder = unsafe { libc::fork() };
if holder == 0 {
forked_watch(&watch_c);
}
if let Some(m) = marker {
append(m, &format!("holder={holder}"));
}
std::process::exit(0);
}
_ => {
let _ = fs::remove_file(&socket);
std::process::exit(0);
}
}
}
if let Some(l) = &listener {
while let Ok((conn, _)) = l.accept() {
drop(conn);
}
}
std::thread::sleep(Duration::from_millis(5));
}
}
fn deny_pidfd_open() {
let stmt = |code: u32, k: u32| libc::sock_filter {
code: code as u16,
jt: 0,
jf: 0,
k,
};
let filter = [
stmt(libc::BPF_LD | libc::BPF_W | libc::BPF_ABS, 0),
libc::sock_filter {
code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
jt: 0,
jf: 1,
k: libc::SYS_pidfd_open as u32,
},
stmt(
libc::BPF_RET | libc::BPF_K,
libc::SECCOMP_RET_ERRNO | libc::ENOSYS as u32,
),
stmt(libc::BPF_RET | libc::BPF_K, libc::SECCOMP_RET_ALLOW),
];
let prog = libc::sock_fprog {
len: filter.len() as u16,
filter: filter.as_ptr().cast_mut(),
};
unsafe {
assert_eq!(libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), 0);
assert_eq!(
libc::prctl(
libc::PR_SET_SECCOMP,
libc::SECCOMP_MODE_FILTER as libc::c_ulong,
&raw const prog,
),
0,
"seccomp filter"
);
}
}
fn children_of_self() -> Vec<u32> {
let me = std::process::id();
let Ok(dir) = fs::read_dir("/proc") else {
return Vec::new();
};
dir.flatten()
.filter_map(|e| e.file_name().to_str()?.parse::<u32>().ok())
.filter(|&pid| {
fs::read_to_string(format!("/proc/{pid}/stat"))
.ok()
.and_then(|s| {
let rest = s.rsplit_once(')')?.1;
rest.split_whitespace().nth(1)?.parse::<u32>().ok()
})
== Some(me)
})
.collect()
}
fn runner_main(args: &[String]) -> ! {
if args.iter().any(|a| a == "no-pidfd") {
deny_pidfd_open();
}
let socket = PathBuf::from(arg(args, "socket").expect("socket"));
let marker = PathBuf::from(arg(args, "marker").expect("marker"));
let out = arg(args, "out").expect("out");
let mut desc = DaemonDescriptor::with_install_dir(
DAEMON,
arg(args, "install").expect("install"),
&socket,
StoppedSignal::SocketRefuses,
)
.expect("descriptor");
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
set_instance(&mut desc, &socket);
desc.env_passthrough = arg(args, "allow").map(str::to_string).into_iter().collect();
desc.ready_timeout = SERVE_BOUND;
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
if args.iter().any(|a| a == "emfile") {
let fillers = exhaust_fds();
let stopped = rt.block_on(stop(&desc));
drop(fillers);
fs::write(out, format!("{stopped:?}")).expect("write out");
std::process::exit(0);
}
match rt.block_on(start(&desc)) {
Ok(outcome) => {
fs::write(out, outcome.pid.to_string()).expect("write out");
std::process::exit(0);
}
Err(e) => {
let children: Vec<String> = children_of_self().iter().map(u32::to_string).collect();
fs::write(out, format!("error: {e}\nchildren={}", children.join(",")))
.expect("write out");
std::process::exit(1);
}
}
}
fn exhaust_fds() -> Vec<File> {
let mut lim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
unsafe {
assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut lim), 0);
lim.rlim_cur = lim.rlim_cur.min(128);
assert_eq!(libc::setrlimit(libc::RLIMIT_NOFILE, &raw const lim), 0);
}
let mut files = Vec::new();
loop {
match File::open("/dev/null") {
Ok(f) => files.push(f),
Err(e) if e.raw_os_error() == Some(libc::EMFILE) => break,
Err(e) => panic!("filling the fd table: {e}"),
}
}
files.pop().expect("at least one filler");
files
}
fn daemon_args(mode: &str, extra: &[String]) -> Vec<String> {
role_args(ROLE_DAEMON, mode, extra)
}
fn set_instance(desc: &mut DaemonDescriptor, socket: &Path) {
desc.socket = socket.to_path_buf();
desc.liveness_args = vec![ROLE_DAEMON.to_string()];
desc.instance_env.retain(|(name, _)| name != SOCKET_ENV);
desc.instance_env
.push((SOCKET_ENV.to_string(), Some(socket.as_os_str().to_owned())));
}
fn role_args(role: &str, mode: &str, extra: &[String]) -> Vec<String> {
let mut args = vec![
"--exact".to_string(),
"child_entry".to_string(),
"-q".to_string(),
role.to_string(),
format!("mode={mode}"),
];
args.extend_from_slice(extra);
args
}
struct Fixture {
_install_dir: tempfile::TempDir,
_work_dir: tempfile::TempDir,
install: PathBuf,
work: PathBuf,
socket: PathBuf,
}
impl Fixture {
fn new() -> Self {
let exe = std::env::current_exe().expect("current_exe");
let exe_dir = exe.parent().expect("exe dir");
let install_dir = tempfile::Builder::new()
.prefix("lc-install")
.tempdir_in(exe_dir)
.expect("install dir");
for name in [DAEMON, OTHER] {
fs::hard_link(&exe, install_dir.path().join(name)).expect("hard link fixture");
}
let work_dir = tempfile::tempdir().expect("work dir");
let install = fs::canonicalize(install_dir.path()).expect("canonical install");
let work = work_dir.path().to_path_buf();
let socket = work.join("d.sock");
Self {
_install_dir: install_dir,
_work_dir: work_dir,
install,
work,
socket,
}
}
fn descriptor(&self, signal: StoppedSignal) -> DaemonDescriptor {
self.descriptor_at(signal, &self.socket)
}
fn descriptor_at(&self, signal: StoppedSignal, socket: &Path) -> DaemonDescriptor {
let mut desc = DaemonDescriptor::with_install_dir(DAEMON, &self.install, socket, signal)
.expect("descriptor");
desc.stop_grace = Duration::from_secs(30);
desc.kill_wait = Duration::from_secs(5);
desc.ready_timeout = SERVE_BOUND;
set_instance(&mut desc, socket);
desc
}
fn instance_socket(&self, name: &str) -> PathBuf {
let dir = self.path(name);
fs::create_dir(&dir).expect("instance dir");
dir.join("d.sock")
}
fn path(&self, name: &str) -> PathBuf {
self.work.join(name)
}
fn spawn(&self, binary: &str, mode: &str, extra: &[String]) -> Running {
self.spawn_at(binary, mode, &self.socket, extra)
}
fn spawn_at(&self, binary: &str, mode: &str, socket: &Path, extra: &[String]) -> Running {
let running = self.launch(binary, mode, socket, extra);
assert!(wait_serving(socket), "fixture never served");
running
}
fn launch(&self, binary: &str, mode: &str, socket: &Path, extra: &[String]) -> Running {
self.launch_as(ROLE_DAEMON, binary, mode, socket, extra)
}
fn launch_as(
&self,
role: &str,
binary: &str,
mode: &str,
socket: &Path,
extra: &[String],
) -> Running {
let child = Command::new(self.install.join(binary))
.args(role_args(role, mode, extra))
.env(SOCKET_ENV, socket)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn fixture");
Running { child }
}
fn reap_reported(&self, marker: &Path) -> Vec<Reap> {
lines(marker)
.iter()
.filter_map(|l| l.parse().ok())
.map(|pid| Reap::arm(pid, &self.install))
.collect()
}
}
struct Running {
child: Child,
}
impl Running {
fn pid(&self) -> u32 {
self.child.id()
}
}
impl Drop for Running {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn wait_serving(socket: &Path) -> bool {
wait_for(|| UnixStream::connect(socket).is_ok())
}
fn wait_for(mut cond: impl FnMut() -> bool) -> bool {
let deadline = Instant::now() + SERVE_BOUND;
while Instant::now() < deadline {
if cond() {
return true;
}
std::thread::sleep(Duration::from_millis(10));
}
false
}
fn lock_held(lock: &Path) -> bool {
File::open(lock).is_ok_and(|f| matches!(f.try_lock(), Err(fs::TryLockError::WouldBlock)))
}
fn is_alive(pid: u32) -> bool {
let Ok(stat) = fs::read(format!("/proc/{pid}/stat")) else {
return false;
};
let close = stat.iter().rposition(|b| *b == b')');
let state = close.and_then(|i| stat[i + 1..].iter().find(|b| !b.is_ascii_whitespace()));
!matches!(state, None | Some(b'Z' | b'X'))
}
fn kill_pid(pid: u32) {
unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
}
struct Reap(Option<OwnedFd>);
impl Reap {
fn arm(pid: u32, install: &Path) -> Self {
let rc = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::pid_t, 0) };
if rc < 0 {
return Self(None);
}
let fd = unsafe { OwnedFd::from_raw_fd(rc as i32) };
let ours =
fs::read_link(format!("/proc/{pid}/exe")).is_ok_and(|exe| exe.starts_with(install));
Self(ours.then_some(fd))
}
fn disarm(&mut self) {
self.0 = None;
}
}
impl Drop for Reap {
fn drop(&mut self) {
if let Some(fd) = &self.0 {
unsafe {
libc::syscall(
libc::SYS_pidfd_send_signal,
fd.as_raw_fd(),
libc::SIGKILL,
std::ptr::null::<libc::siginfo_t>(),
0,
);
}
}
}
}
struct ModeGuard(PathBuf);
impl ModeGuard {
fn lock(dir: &Path) -> Self {
fs::set_permissions(dir, fs::Permissions::from_mode(0o000)).expect("chmod 000");
Self(dir.to_path_buf())
}
}
impl Drop for ModeGuard {
fn drop(&mut self) {
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o755));
}
}
fn lines(path: &Path) -> Vec<String> {
fs::read_to_string(path)
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect()
}
struct Recording {
kill_takes: bool,
sent: Mutex<Vec<Signal>>,
}
impl Recording {
fn new(kill_takes: bool) -> Self {
Self {
kill_takes,
sent: Mutex::new(Vec::new()),
}
}
fn sent(&self) -> Vec<Signal> {
self.sent.lock().expect("sent lock").clone()
}
}
impl SignalDelivery for Recording {
fn deliver(&self, target: &PinnedProcess, signal: Signal) -> std::io::Result<()> {
self.sent.lock().expect("sent lock").push(signal);
if signal == Signal::Kill && !self.kill_takes {
return Ok(());
}
target.send_signal(signal)
}
}
#[tokio::test]
async fn stop_returns_not_running_when_socket_is_absent() {
let fx = Fixture::new();
let rec = Recording::new(true);
let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
assert_eq!(out.expect("stop"), StopOutcome::NotRunning);
assert!(rec.sent().is_empty(), "no signal may be sent");
}
#[tokio::test]
async fn stop_returns_not_running_when_socket_refuses_connections() {
let fx = Fixture::new();
drop(UnixListener::bind(&fx.socket).expect("bind"));
assert!(fx.socket.exists(), "stale socket file must remain");
assert!(
wait_for(|| UnixStream::connect(&fx.socket)
.is_err_and(|e| e.kind() == std::io::ErrorKind::ConnectionRefused)),
"fixture precondition: the stale socket refuses"
);
let rec = Recording::new(true);
let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
assert_eq!(out.expect("stop"), StopOutcome::NotRunning);
assert!(rec.sent().is_empty(), "no signal may be sent");
}
#[tokio::test]
async fn stop_returns_stopped_promptly_after_a_clean_exit() {
let fx = Fixture::new();
let mut d = fx.spawn(DAEMON, "serve", &[]);
let rec = Recording::new(true);
let t0 = Instant::now();
let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
let elapsed = t0.elapsed();
let pid = d.pid();
assert_eq!(
out.expect("stop"),
StopOutcome::Stopped { pid, forced: false }
);
assert!(
d.child.try_wait().expect("try_wait").is_some(),
"pid must have exited"
);
assert!(elapsed < Duration::from_secs(10), "stop took {elapsed:?}");
assert_eq!(rec.sent(), vec![Signal::Term]);
}
#[tokio::test]
async fn stop_waits_for_pid_exit_not_socket_close() {
let fx = Fixture::new();
let marker = fx.path("marker");
let mut d = fx.spawn(DAEMON, "linger", &[format!("marker={}", marker.display())]);
let t0 = Instant::now();
let out = stop(&fx.descriptor(StoppedSignal::SocketRefuses)).await;
let elapsed = t0.elapsed();
let pid = d.pid();
assert_eq!(
out.expect("stop"),
StopOutcome::Stopped { pid, forced: false }
);
assert!(
d.child.try_wait().expect("try_wait").is_some(),
"pid must have exited"
);
assert!(
elapsed >= Duration::from_millis(LINGER_MS),
"returned after {elapsed:?}, before the pid exited"
);
assert!(
lines(&marker).iter().any(|l| l == "closed"),
"socket closed first"
);
}
#[tokio::test]
async fn stop_sends_sigkill_to_a_process_that_ignores_sigterm() {
let fx = Fixture::new();
let mut d = fx.spawn(DAEMON, "ignore-term", &[]);
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.stop_grace = Duration::from_millis(300);
let rec = Recording::new(true);
let out = stop_with(&desc, &rec).await;
let pid = d.pid();
assert_eq!(
out.expect("stop"),
StopOutcome::Stopped { pid, forced: true }
);
let status = d
.child
.try_wait()
.expect("try_wait")
.expect("pid must have exited");
assert_eq!(status.signal(), Some(libc::SIGKILL));
assert_eq!(rec.sent(), vec![Signal::Term, Signal::Kill]);
}
#[tokio::test]
async fn stop_reports_a_survivor_when_sigkill_does_not_take() {
let fx = Fixture::new();
let d = fx.spawn(DAEMON, "ignore-term", &[]);
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.stop_grace = Duration::from_millis(200);
desc.kill_wait = Duration::from_millis(300);
let rec = Recording::new(false);
match stop_with(&desc, &rec).await {
Err(LifecycleError::Survivor { pid }) => assert_eq!(pid, d.pid()),
other => panic!("expected Survivor, got {other:?}"),
}
assert!(is_alive(d.pid()), "the survivor is still running");
assert_eq!(rec.sent(), vec![Signal::Term, Signal::Kill]);
}
#[tokio::test]
async fn stop_refuses_to_signal_a_process_with_another_name() {
let fx = Fixture::new();
let d = fx.spawn(OTHER, "serve", &[]);
let rec = Recording::new(true);
match stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await {
Err(LifecycleError::IdentityMismatch {
pid,
expected,
found,
}) => {
assert_eq!(
(pid, expected.as_str(), found.as_str()),
(d.pid(), DAEMON, OTHER)
);
}
other => panic!("expected IdentityMismatch, got {other:?}"),
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(d.pid()), "the other process is untouched");
}
#[tokio::test]
async fn stop_with_lock_signal_is_not_stopped_while_another_process_holds_the_lock() {
let fx = Fixture::new();
let lock = fx.path("daemon.lock");
let marker = fx.path("marker");
let mut d = fx.spawn(
DAEMON,
"fork-lock-holder",
&[
format!("lock={}", lock.display()),
format!("marker={}", marker.display()),
],
);
let mut desc = fx.descriptor(StoppedSignal::LockFree(lock.clone()));
desc.kill_wait = Duration::from_secs(1);
let out = stop(&desc).await;
let holder: u32 = lines(&marker)
.iter()
.find_map(|l| l.strip_prefix("holder=")?.parse().ok())
.expect("holder pid");
let holder_alive = is_alive(holder);
kill_pid(holder);
match out {
Err(LifecycleError::StoppedSignalNotReached { pid, .. }) => assert_eq!(pid, d.pid()),
other => panic!("expected StoppedSignalNotReached, got {other:?}"),
}
assert!(
d.child.try_wait().expect("try_wait").is_some(),
"the daemon pid exited"
);
assert!(holder_alive, "the lock holder was alive during stop");
let deadline = Instant::now() + SERVE_BOUND;
while is_alive(holder) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(stop(&desc).await.expect("stop"), StopOutcome::NotRunning);
}
#[tokio::test]
async fn stop_with_lock_signal_returns_stopped_once_the_lock_is_released() {
let fx = Fixture::new();
let lock = fx.path("daemon.lock");
let d = fx.spawn(DAEMON, "serve", &[format!("lock={}", lock.display())]);
let desc = fx.descriptor(StoppedSignal::LockFree(lock.clone()));
let pid = d.pid();
assert_eq!(
stop(&desc).await.expect("stop"),
StopOutcome::Stopped { pid, forced: false }
);
let probe = File::open(&lock).expect("lock file");
assert!(probe.try_lock().is_ok(), "the flock is free after Stopped");
}
#[tokio::test]
async fn start_from_another_process_spawns_the_install_dir_binary_and_it_outlives_the_caller() {
let fx = Fixture::new();
let decoy_dir = fx.path("decoy");
fs::create_dir(&decoy_dir).expect("decoy dir");
let decoy_ran = fx.path("decoy-ran");
let decoy = decoy_dir.join(DAEMON);
fs::write(
&decoy,
format!("#!/bin/sh\ntouch '{}'\n", decoy_ran.display()),
)
.expect("decoy");
fs::set_permissions(&decoy, fs::Permissions::from_mode(0o755)).expect("chmod decoy");
let path = format!(
"{}:{}",
decoy_dir.display(),
std::env::var("PATH").unwrap_or_default()
);
let out = fx.path("out");
let marker = fx.path("marker");
let status = Command::new(std::env::current_exe().expect("current_exe"))
.args(["--exact", "child_entry", "-q", ROLE_RUNNER])
.arg(format!("install={}", fx.install.display()))
.arg(format!("socket={}", fx.socket.display()))
.arg(format!("marker={}", marker.display()))
.arg(format!("out={}", out.display()))
.env("PATH", path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("run runner");
let mut reaps = fx.reap_reported(&marker);
let report = fs::read_to_string(&out).unwrap_or_default();
assert!(status.success(), "runner failed: {report}");
let pid: u32 = report.trim().parse().expect("runner pid");
assert_eq!(
lines(&marker),
vec![pid.to_string()],
"one daemon, reported"
);
assert!(is_alive(pid), "the daemon outlived the runner");
assert!(UnixStream::connect(&fx.socket).is_ok(), "and still serves");
let exe = fs::read_link(format!("/proc/{pid}/exe")).expect("exe link");
assert_eq!(exe, fx.install.join(DAEMON));
assert!(!decoy_ran.exists(), "the PATH decoy must never run");
let desc = fx.descriptor(StoppedSignal::SocketRefuses);
assert_eq!(
stop(&desc).await.expect("cleanup stop"),
StopOutcome::Stopped { pid, forced: false }
);
reaps.iter_mut().for_each(Reap::disarm);
}
#[tokio::test]
async fn start_errors_when_the_socket_never_serves() {
let fx = Fixture::new();
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("never-bind", &[format!("marker={}", marker.display())]);
desc.ready_timeout = Duration::from_secs(1);
let out = start(&desc).await;
let _reaps = fx.reap_reported(&marker);
let (pid, err) = match out {
Err(e @ LifecycleError::NotReady { pid, .. }) => (pid, e),
other => panic!("expected NotReady, got {other:?}"),
};
assert_eq!(lines(&marker), vec![pid.to_string()], "the child ran");
assert!(!is_alive(pid), "the unready child must be gone: {err}");
assert!(
!Path::new(&format!("/proc/{pid}")).exists(),
"and reaped, not a zombie"
);
assert!(err.to_string().contains("killed and reaped"), "{err}");
}
#[test]
fn start_kills_the_child_when_its_pidfd_cannot_be_opened() {
let fx = Fixture::new();
let marker = fx.path("marker");
let out = fx.path("out");
let status = Command::new(std::env::current_exe().expect("current_exe"))
.args(["--exact", "child_entry", "-q", ROLE_RUNNER, "no-pidfd"])
.arg(format!("install={}", fx.install.display()))
.arg(format!("socket={}", fx.socket.display()))
.arg(format!("marker={}", marker.display()))
.arg(format!("out={}", out.display()))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("run runner");
let report = fs::read_to_string(&out).unwrap_or_default();
let children: Vec<u32> = report
.lines()
.find_map(|l| l.strip_prefix("children="))
.unwrap_or_default()
.split(',')
.filter_map(|p| p.parse().ok())
.collect();
let _reaps: Vec<Reap> = children
.iter()
.map(|&pid| Reap::arm(pid, &fx.install))
.chain(fx.reap_reported(&marker))
.collect();
assert!(
!status.success(),
"start must fail without a pidfd: {report}"
);
assert!(report.contains("pidfd"), "the pidfd arm was hit: {report}");
assert!(
children.is_empty(),
"start left children {children:?} behind: {report}"
);
for pid in lines(&marker).iter().filter_map(|l| l.parse::<u32>().ok()) {
assert!(!is_alive(pid), "spawned pid {pid} still runs: {report}");
}
}
#[tokio::test]
async fn start_errors_when_the_child_exits_at_boot() {
let fx = Fixture::new();
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("exit-now", &[]);
desc.ready_timeout = Duration::from_secs(30);
let t0 = Instant::now();
let out = start(&desc).await;
assert!(
matches!(out, Err(LifecycleError::ChildExited { .. })),
"expected ChildExited, got {out:?}"
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"reported as a death, not a timeout"
);
}
#[tokio::test]
async fn restart_starts_a_daemon_that_is_not_running() {
let fx = Fixture::new();
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let out = restart(&desc).await;
let mut reaps = fx.reap_reported(&marker);
let out = out.expect("restart");
assert_eq!(out.stop, StopOutcome::NotRunning);
let pid = out.start.pid;
assert_eq!(
lines(&marker),
vec![pid.to_string()],
"one daemon, reported"
);
assert!(
UnixStream::connect(&fx.socket).is_ok(),
"the new daemon serves"
);
let exe = fs::read_link(format!("/proc/{pid}/exe")).expect("exe link");
assert_eq!(exe, fx.install.join(DAEMON));
assert_eq!(
stop(&desc).await.expect("cleanup stop"),
StopOutcome::Stopped { pid, forced: false }
);
reaps.iter_mut().for_each(Reap::disarm);
}
#[tokio::test]
async fn restart_does_not_start_when_stop_reports_a_survivor() {
let fx = Fixture::new();
let marker = fx.path("marker");
let marker_arg = format!("marker={}", marker.display());
let d = fx.spawn(DAEMON, "ignore-term", std::slice::from_ref(&marker_arg));
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[marker_arg]);
desc.stop_grace = Duration::from_millis(200);
desc.kill_wait = Duration::from_millis(300);
match restart_with(&desc, &Recording::new(false)).await {
Err(LifecycleError::Survivor { pid }) => assert_eq!(pid, d.pid()),
other => panic!("expected Survivor, got {other:?}"),
}
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
assert_eq!(
lines(&marker),
vec![d.pid().to_string()],
"no second process"
);
assert!(is_alive(d.pid()));
}
#[tokio::test]
async fn stop_and_restart_refuse_when_the_lock_is_held_without_a_socket() {
let fx = Fixture::new();
let lock = fx.path("daemon.lock");
let marker = fx.path("marker");
let marker_arg = format!("marker={}", marker.display());
let holder = fx.launch(
DAEMON,
"never-bind",
&fx.socket,
&[format!("lock={}", lock.display()), marker_arg.clone()],
);
assert!(
wait_for(|| lock_held(&lock)),
"the holder never took the lock"
);
let mut desc = fx.descriptor(StoppedSignal::LockFree(lock.clone()));
desc.spawn_args = daemon_args("serve", &[marker_arg]);
let rec = Recording::new(true);
let stopped = stop_with(&desc, &rec).await;
let restarted = restart_with(&desc, &rec).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
assert!(
matches!(&stopped, Err(LifecycleError::Unidentified { lock: l, .. }) if *l == lock),
"stop: expected Unidentified, got {stopped:?}"
);
assert!(
matches!(restarted, Err(LifecycleError::Unidentified { .. })),
"restart: expected Unidentified, got {restarted:?}"
);
assert!(rec.sent().is_empty(), "no signal may be sent");
assert_eq!(
lines(&marker),
vec![holder.pid().to_string()],
"restart spawned nothing"
);
assert!(is_alive(holder.pid()), "the holder is untouched");
}
#[tokio::test]
async fn start_refuses_a_socket_that_already_serves_and_spawns_no_second_daemon() {
let fx = Fixture::new();
let marker = fx.path("marker");
let marker_arg = format!("marker={}", marker.display());
let d = fx.spawn(DAEMON, "serve", std::slice::from_ref(&marker_arg));
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[marker_arg]);
let out = start(&desc).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
assert_eq!(
lines(&marker),
vec![d.pid().to_string()],
"exactly one daemon process (start returned {out:?})"
);
match out {
Err(LifecycleError::AlreadyRunning { pid, .. }) => assert_eq!(pid, Some(d.pid())),
other => panic!("expected AlreadyRunning, got {other:?}"),
}
assert!(is_alive(d.pid()), "the running daemon is untouched");
}
#[tokio::test]
async fn stop_refuses_to_signal_a_process_whose_executable_cannot_be_read() {
let fx = Fixture::new();
let d = fx.launch_as(
ROLE_BRIDGE,
DAEMON,
"serve",
&fx.socket,
&["undumpable".to_string()],
);
assert!(wait_serving(&fx.socket), "fixture never served");
assert!(
fs::read_link(format!("/proc/{}/exe", d.pid())).is_err(),
"fixture precondition: the exe link is unreadable (not running as root)"
);
let rec = Recording::new(true);
match stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await {
Err(LifecycleError::IdentityUnreadable { pid, .. }) => assert_eq!(pid, d.pid()),
other => panic!("expected IdentityUnreadable, got {other:?}"),
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(d.pid()), "the process stays alive");
}
#[tokio::test]
async fn stop_and_restart_stop_short_when_the_socket_cannot_be_probed() {
let fx = Fixture::new();
let dir = fx.path("locked");
fs::create_dir(&dir).expect("socket dir");
let socket = dir.join("d.sock");
let marker = fx.path("marker");
let marker_arg = format!("marker={}", marker.display());
let d = fx.spawn_at(DAEMON, "serve", &socket, std::slice::from_ref(&marker_arg));
let mut desc = fx.descriptor_at(StoppedSignal::SocketRefuses, &socket);
desc.spawn_args = daemon_args("serve", &[marker_arg]);
let guard = ModeGuard::lock(&dir);
let probe = UnixStream::connect(&socket).map(drop);
assert!(
matches!(&probe, Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
"fixture precondition: connect is refused with EACCES, got {probe:?}"
);
let rec = Recording::new(true);
let stopped = stop_with(&desc, &rec).await;
let restarted = restart_with(&desc, &rec).await;
std::thread::sleep(SPAWN_SETTLE);
drop(guard);
let _reaps = fx.reap_reported(&marker);
for (call, out) in [
("stop", stopped.map(|o| format!("{o:?}"))),
("restart", restarted.map(|o| format!("{o:?}"))),
] {
assert!(
matches!(&out, Err(LifecycleError::ProbeInconclusive { socket: s }) if *s == socket),
"{call}: expected ProbeInconclusive, got {out:?}"
);
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert_eq!(
lines(&marker),
vec![d.pid().to_string()],
"restart spawned nothing"
);
assert!(is_alive(d.pid()), "the daemon is untouched");
}
fn pid_lines(marker: &Path) -> Vec<String> {
lines(marker)
.into_iter()
.filter(|l| l.parse::<u32>().is_ok())
.collect()
}
#[tokio::test]
async fn stop_start_and_restart_refuse_while_a_daemon_runs_without_its_socket() {
for mode in ["unlink-socket", "close-socket"] {
let fx = Fixture::new();
let marker = fx.path("marker");
let marker_arg = format!("marker={}", marker.display());
let d = fx.launch(DAEMON, mode, &fx.socket, std::slice::from_ref(&marker_arg));
assert!(
wait_for(|| lines(&marker).iter().any(|l| l == "unserved")),
"{mode}: the fixture never dropped its socket"
);
assert!(
UnixStream::connect(&fx.socket).is_err(),
"{mode}: fixture precondition: the socket does not serve"
);
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[marker_arg]);
let rec = Recording::new(true);
let stopped = stop_with(&desc, &rec).await;
let restarted = restart_with(&desc, &rec).await;
let started = start(&desc).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
assert_eq!(
pid_lines(&marker),
vec![d.pid().to_string()],
"{mode}: a second daemon was spawned (stop: {stopped:?}, restart: {restarted:?})"
);
for (call, out) in [
("stop", stopped.map(|o| format!("{o:?}"))),
("restart", restarted.map(|o| format!("{o:?}"))),
("start", started.map(|o| format!("{o:?}"))),
] {
assert!(
matches!(&out, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [d.pid()]),
"{mode}: {call}: expected RunningUnserved naming pid {}, got {out:?}",
d.pid()
);
}
assert!(rec.sent().is_empty(), "{mode}: no signal may be sent");
assert!(is_alive(d.pid()), "{mode}: the daemon is untouched");
}
}
#[tokio::test]
async fn stop_ignores_an_unrelated_process_whose_name_is_not_utf8() {
let fx = Fixture::new();
let marker = fx.path("marker");
let other = fx.launch(
OTHER,
"never-bind",
&fx.instance_socket("other"),
&[format!("marker={}", marker.display()), BAD_NAME_FLAG.into()],
);
assert!(
wait_for(|| !pid_lines(&marker).is_empty()),
"the fixture never started"
);
let status = fs::read(format!("/proc/{}/status", other.pid())).expect("read status");
assert!(
std::str::from_utf8(&status).is_err(),
"the fixture's status must hold its non-UTF-8 name"
);
let rec = Recording::new(true);
let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
assert_eq!(
out.expect("a non-UTF-8 name on an unrelated process must not fail the scan"),
StopOutcome::NotRunning
);
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(other.pid()), "the unrelated process is untouched");
}
#[tokio::test]
async fn stop_returns_not_running_while_only_a_bridge_of_the_same_binary_runs() {
let fx = Fixture::new();
let marker = fx.path("marker");
let bridge = fx.launch_as(
ROLE_BRIDGE,
DAEMON,
"never-bind",
&fx.socket,
&[format!("marker={}", marker.display())],
);
assert!(
wait_for(|| !pid_lines(&marker).is_empty()),
"the bridge never started"
);
let rec = Recording::new(true);
let out = stop_with(&fx.descriptor(StoppedSignal::SocketRefuses), &rec).await;
assert_eq!(
out.expect("a bridge alone is not the daemon"),
StopOutcome::NotRunning
);
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(bridge.pid()), "the bridge is untouched");
}
#[test]
fn start_runs_the_daemon_in_its_working_dir_with_only_the_allowed_environment() {
let fx = Fixture::new();
let checkout = fx.path("checkout");
fs::create_dir(&checkout).expect("checkout dir");
fs::write(checkout.join(".env.local"), "TC_LC_FROM_DOTENV=1\n").expect(".env.local");
let checkout = fs::canonicalize(&checkout).expect("canonical checkout");
let out = fx.path("out");
let marker = fx.path("marker");
let status = Command::new(std::env::current_exe().expect("current_exe"))
.args([
"--exact",
"child_entry",
"-q",
ROLE_RUNNER,
"allow=TC_LC_ALLOWED",
])
.arg(format!("install={}", fx.install.display()))
.arg(format!("socket={}", fx.socket.display()))
.arg(format!("marker={}", marker.display()))
.arg(format!("out={}", out.display()))
.current_dir(&checkout)
.env("TC_LC_SENTINEL", "leaked")
.env("TC_LC_ALLOWED", "kept")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("run runner");
let _reaps = fx.reap_reported(&marker);
let report = fs::read_to_string(&out).unwrap_or_default();
assert!(status.success(), "runner failed: {report}");
let pid: u32 = report.trim().parse().expect("runner pid");
let cwd = fs::read_link(format!("/proc/{pid}/cwd")).expect("daemon cwd");
let environ = fs::read(format!("/proc/{pid}/environ")).expect("daemon environ");
let vars: Vec<String> = environ
.split(|b| *b == 0)
.map(|v| String::from_utf8_lossy(v).into_owned())
.collect();
let names: Vec<&str> = vars.iter().filter_map(|v| v.split('=').next()).collect();
assert_ne!(cwd, checkout, "the daemon runs in the caller's cwd");
assert_eq!(cwd, Path::new("/"), "the default working_dir is /");
assert!(
!names.contains(&"TC_LC_SENTINEL"),
"the caller's sentinel reached the daemon; its names: {names:?}"
);
assert!(
vars.iter().any(|v| v == "TC_LC_ALLOWED=kept"),
"the allowlisted variable is missing; names: {names:?}"
);
if let Some(home) = std::env::var_os("HOME") {
let want = format!("HOME={}", home.to_string_lossy());
assert!(
vars.contains(&want),
"the base HOME is missing; names: {names:?}"
);
}
}
fn cmdline(pid: u32) -> Vec<u8> {
fs::read(format!("/proc/{pid}/cmdline")).expect("cmdline")
}
struct Siblings {
fx: Fixture,
marker: PathBuf,
extra: Vec<String>,
sock_a: PathBuf,
sock_b: PathBuf,
}
impl Siblings {
fn new() -> Self {
let fx = Fixture::new();
let marker = fx.path("marker");
let extra = vec![format!("marker={}", marker.display())];
let (sock_a, sock_b) = (fx.instance_socket("a"), fx.instance_socket("b"));
Self {
fx,
marker,
extra,
sock_a,
sock_b,
}
}
fn run(&self, socket: &Path) -> Running {
self.fx.spawn_at(DAEMON, "serve", socket, &self.extra)
}
fn desc_a(&self) -> DaemonDescriptor {
let mut desc = self
.fx
.descriptor_at(StoppedSignal::SocketRefuses, &self.sock_a);
desc.spawn_args = daemon_args("serve", &self.extra);
desc
}
fn assert_b_untouched(&self, b: &Running) {
assert!(is_alive(b.pid()), "sibling B was stopped");
assert!(UnixStream::connect(&self.sock_b).is_ok(), "B still serves");
}
}
#[tokio::test]
async fn restart_of_one_instance_leaves_a_sibling_with_the_same_argv_serving() {
let s = Siblings::new();
let a = s.run(&s.sock_a);
let b = s.run(&s.sock_b);
assert_eq!(
cmdline(a.pid()),
cmdline(b.pid()),
"precondition: same argv"
);
let desc = s.desc_a();
let out = restart(&desc).await;
let _reaps = s.fx.reap_reported(&s.marker);
let out = out.expect("restart of A beside sibling B");
assert_eq!(
out.stop,
StopOutcome::Stopped {
pid: a.pid(),
forced: false
}
);
let new = out.start.pid;
assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves again");
assert_eq!(cmdline(new), cmdline(b.pid()), "the new A has B's argv");
s.assert_b_untouched(&b);
assert_eq!(
stop(&desc).await.expect("cleanup stop"),
StopOutcome::Stopped {
pid: new,
forced: false
}
);
s.assert_b_untouched(&b);
}
#[tokio::test]
async fn start_and_restart_start_a_stopped_instance_while_a_sibling_runs() {
let s = Siblings::new();
let b = s.run(&s.sock_b);
let desc = s.desc_a();
let started = start(&desc).await;
let mut reaps = s.fx.reap_reported(&s.marker);
let pid = started.expect("start of A beside sibling B").pid;
assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves");
assert_eq!(cmdline(pid), cmdline(b.pid()), "A has B's argv");
assert_eq!(
stop(&desc).await.expect("stop A"),
StopOutcome::Stopped { pid, forced: false }
);
s.assert_b_untouched(&b);
let restarted = restart(&desc).await;
reaps.extend(s.fx.reap_reported(&s.marker));
let restarted = restarted.expect("restart of a stopped A beside B");
assert_eq!(restarted.stop, StopOutcome::NotRunning);
assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves again");
assert_eq!(
stop(&desc).await.expect("cleanup stop"),
StopOutcome::Stopped {
pid: restarted.start.pid,
forced: false
}
);
s.assert_b_untouched(&b);
}
#[tokio::test]
async fn stop_and_start_fail_closed_when_a_matching_process_hides_its_environment() {
let fx = Fixture::new();
let marker = fx.path("marker");
let marker_arg = format!("marker={}", marker.display());
let hidden = fx.launch(
OTHER,
"never-bind",
&fx.socket,
&[marker_arg.clone(), "undumpable".to_string()],
);
assert!(
wait_for(|| !pid_lines(&marker).is_empty()),
"the fixture never started"
);
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.binary = OTHER.to_string();
desc.spawn_args = daemon_args("serve", &[marker_arg]);
let rec = Recording::new(true);
let stopped = stop_with(&desc, &rec).await;
let started = start(&desc).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
for (call, out) in [
("stop", stopped.map(|o| format!("{o:?}"))),
("start", started.map(|o| format!("{o:?}"))),
] {
assert!(
matches!(&out, Err(LifecycleError::InstanceUnreadable { pid, .. }) if *pid == hidden.pid()),
"{call}: expected InstanceUnreadable naming pid {}, got {out:?}",
hidden.pid()
);
}
assert_eq!(
pid_lines(&marker),
vec![hidden.pid().to_string()],
"start spawned a second process"
);
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(hidden.pid()), "the process is untouched");
}
const FAKE_PID: u32 = 4_194_401;
fn euid() -> u32 {
unsafe { libc::geteuid() }
}
fn fake_proc_entry(root: &Path, pid: u32, uid: u32, desc: &DaemonDescriptor, readable: bool) {
let dir = root.join(pid.to_string());
fs::create_dir_all(&dir).expect("fake entry dir");
let status = format!("Name:\tlc\nState:\tS (sleeping)\nUid:\t{uid}\t{uid}\t{uid}\t{uid}\n");
fs::write(dir.join("status"), status).expect("fake status");
let mut cmdline = desc.program().as_os_str().as_bytes().to_vec();
for arg in &desc.liveness_args {
cmdline.push(0);
cmdline.extend_from_slice(arg.as_bytes());
}
cmdline.push(0);
fs::write(dir.join("cmdline"), cmdline).expect("fake cmdline");
std::os::unix::fs::symlink(desc.program(), dir.join("exe")).expect("fake exe link");
let mut environ = Vec::new();
for (name, value) in &desc.instance_env {
if let Some(value) = value {
environ.extend_from_slice(format!("{name}=").as_bytes());
environ.extend_from_slice(value.as_bytes());
environ.push(0);
}
}
let path = dir.join("environ");
fs::write(&path, environ).expect("fake environ");
if !readable {
fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).expect("chmod 000");
}
}
#[tokio::test]
async fn a_foreign_uid_entry_in_the_process_table_is_skipped_by_stop_start_and_restart() {
let fx = Fixture::new();
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let mine = fx.path("mine-proc");
fake_proc_entry(&mine, FAKE_PID, euid(), &desc, true);
let foreign = fx.path("foreign-proc");
let other_uid = euid().wrapping_add(1);
fake_proc_entry(&foreign, FAKE_PID, other_uid, &desc, true);
fake_proc_entry(&foreign, FAKE_PID + 1, other_uid, &desc, false);
let table = ProcessTable::at(&foreign);
let rec = Recording::new(true);
let control = stop_with_table(&desc, &rec, &ProcessTable::at(&mine)).await;
let stopped = stop_with_table(&desc, &rec, &table).await;
let started = start_with_table(&desc, &table).await;
let restarted = restart_with_table(&desc, &KernelDelivery, &table).await;
let mut reaps = fx.reap_reported(&marker);
assert!(
matches!(&control, Err(LifecycleError::RunningUnserved { pids, .. }) if pids == &[FAKE_PID]),
"the same entry under this uid is this instance: {control:?}"
);
assert_eq!(stopped.expect("stop"), StopOutcome::NotRunning);
let first = started.expect("start").pid;
let restarted = restarted.expect("restart");
assert_eq!(
restarted.stop,
StopOutcome::Stopped {
pid: first,
forced: false
}
);
let second = restarted.start.pid;
assert_eq!(
stop_with_table(&desc, &KernelDelivery, &table)
.await
.expect("cleanup stop"),
StopOutcome::Stopped {
pid: second,
forced: false
}
);
assert!(rec.sent().is_empty(), "no signal may be sent");
reaps.iter_mut().for_each(Reap::disarm);
}
#[tokio::test]
async fn a_same_uid_entry_with_an_unreadable_environment_in_the_process_table_fails_closed() {
let fx = Fixture::new();
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let proc = fx.path("proc");
fake_proc_entry(&proc, FAKE_PID, euid(), &desc, false);
let table = ProcessTable::at(&proc);
let rec = Recording::new(true);
let stopped = stop_with_table(&desc, &rec, &table).await;
let started = start_with_table(&desc, &table).await;
let restarted = restart_with_table(&desc, &rec, &table).await;
let unlisted = stop_with_table(&desc, &rec, &ProcessTable::at(fx.path("absent"))).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
for (call, out) in [
("stop", stopped.map(|o| format!("{o:?}"))),
("start", started.map(|o| format!("{o:?}"))),
("restart", restarted.map(|o| format!("{o:?}"))),
] {
assert!(
matches!(&out, Err(LifecycleError::InstanceUnreadable { pid, source, .. })
if *pid == FAKE_PID && source.kind() == std::io::ErrorKind::PermissionDenied),
"{call}: expected InstanceUnreadable naming pid {FAKE_PID}, got {out:?}"
);
}
assert!(
matches!(&unlisted, Err(LifecycleError::Io { .. })),
"an unlistable table must fail closed: {unlisted:?}"
);
assert!(lines(&marker).is_empty(), "a daemon was spawned");
assert!(rec.sent().is_empty(), "no signal may be sent");
}
#[test]
fn stop_fails_closed_when_the_scan_cannot_open_proc_files() {
let fx = Fixture::new();
let out = fx.path("out");
let status = Command::new(std::env::current_exe().expect("current_exe"))
.args(["--exact", "child_entry", "-q", ROLE_RUNNER, "emfile"])
.arg(format!("install={}", fx.install.display()))
.arg(format!("socket={}", fx.socket.display()))
.arg(format!("marker={}", fx.path("marker").display()))
.arg(format!("out={}", out.display()))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("run runner");
let report = fs::read_to_string(&out).unwrap_or_default();
assert!(status.success(), "runner failed: {report}");
assert!(
report.starts_with("Err(Io") && report.contains("/status"),
"expected an Io error on a status read, got {report}"
);
}
const DIR_FLAG: &str = "lc-dir";
struct PathSiblings {
fx: Fixture,
marker: PathBuf,
extra: Vec<String>,
sock_a: PathBuf,
sock_b: PathBuf,
}
impl PathSiblings {
fn new() -> Self {
let fx = Fixture::new();
let marker = fx.path("marker");
let extra = vec![format!("marker={}", marker.display())];
let (sock_a, sock_b) = (fx.instance_socket("a"), fx.instance_socket("b"));
Self {
fx,
marker,
extra,
sock_a,
sock_b,
}
}
fn dir(socket: &Path) -> PathBuf {
socket.parent().expect("instance dir").to_path_buf()
}
fn sibling(&self) -> Running {
let mut extra = self.extra.clone();
extra.extend([
format!("socket={}", self.sock_b.display()),
DIR_FLAG.to_string(),
Self::dir(&self.sock_b).display().to_string(),
]);
let running = self.fx.launch(DAEMON, "serve", &self.sock_a, &extra);
assert!(wait_serving(&self.sock_b), "the sibling never served");
running
}
fn desc_a(&self, opt_in: bool) -> DaemonDescriptor {
let mut desc = self
.fx
.descriptor_at(StoppedSignal::SocketRefuses, &self.sock_a);
desc.spawn_args = daemon_args("serve", &self.extra);
if opt_in {
desc.instance_path_args = vec![(DIR_FLAG.to_string(), Self::dir(&self.sock_a))];
}
desc
}
fn assert_sibling_untouched(&self, sibling: &Running) {
assert!(is_alive(sibling.pid()), "the sibling was stopped");
assert!(
UnixStream::connect(&self.sock_b).is_ok(),
"the sibling still serves"
);
}
}
fn launch_unserved(fx: &Fixture, socket: &Path, name: &str, extra: &[String]) -> Running {
let marker = fx.path(name);
let mut args = vec![format!("marker={}", marker.display())];
args.extend_from_slice(extra);
let running = fx.launch(DAEMON, "never-bind", socket, &args);
assert!(
wait_for(|| !pid_lines(&marker).is_empty()),
"{name}: the fixture never started"
);
running
}
#[tokio::test]
async fn stop_tells_a_sibling_from_this_instance_by_its_path_flag() {
let s = PathSiblings::new();
let sibling = s.sibling();
let rec = Recording::new(true);
let residual = stop_with(&s.desc_a(false), &rec).await;
let told_apart = stop_with(&s.desc_a(true), &rec).await;
let own_dir = format!("{DIR_FLAG}={}", PathSiblings::dir(&s.sock_a).display());
let own = launch_unserved(&s.fx, &s.sock_a, "own-marker", &[own_dir]);
let refused = stop_with(&s.desc_a(true), &rec).await;
assert!(
matches!(&residual, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [sibling.pid()]),
"precondition: without the opt-in the sibling reads as A, got {residual:?}"
);
assert_eq!(told_apart.expect("stop A"), StopOutcome::NotRunning);
assert!(
matches!(&refused, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [own.pid()]),
"a process naming A's own dir is A, got {refused:?}"
);
assert!(rec.sent().is_empty(), "no signal may be sent");
s.assert_sibling_untouched(&sibling);
}
#[tokio::test]
async fn restart_refuses_before_any_signal_when_another_process_is_this_instance() {
let s = PathSiblings::new();
let a = s.fx.spawn_at(DAEMON, "serve", &s.sock_a, &s.extra);
let sibling = s.sibling();
let rec = Recording::new(true);
let blocked = restart_with(&s.desc_a(false), &rec).await;
std::thread::sleep(SPAWN_SETTLE);
match &blocked {
Err(LifecycleError::RestartBlocked {
serving, others, ..
}) => {
assert_eq!(*serving, [a.pid()]);
assert_eq!(*others, [sibling.pid()]);
}
other => panic!("expected RestartBlocked, got {other:?}"),
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(a.pid()), "A was stopped");
assert!(UnixStream::connect(&s.sock_a).is_ok(), "A still serves");
assert_eq!(pid_lines(&s.marker).len(), 2, "nothing was spawned");
let out = restart(&s.desc_a(true)).await;
let _reaps = s.fx.reap_reported(&s.marker);
let out = out.expect("restart of A beside the told-apart sibling");
assert_eq!(
out.stop,
StopOutcome::Stopped {
pid: a.pid(),
forced: false
}
);
assert!(UnixStream::connect(&s.sock_a).is_ok(), "A serves again");
s.assert_sibling_untouched(&sibling);
assert_eq!(
stop(&s.desc_a(true)).await.expect("cleanup stop"),
StopOutcome::Stopped {
pid: out.start.pid,
forced: false
}
);
}
#[tokio::test]
async fn stop_pid_stops_a_daemon_whose_socket_bind_failed() {
let fx = Fixture::new();
let mut d = launch_unserved(&fx, &fx.socket, "marker", &[]);
let desc = fx.descriptor(StoppedSignal::SocketRefuses);
let rec = Recording::new(true);
let by_socket = stop_with(&desc, &rec).await;
assert!(
matches!(&by_socket, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [d.pid()]),
"precondition: the socket path cannot reach it, got {by_socket:?}"
);
let pid = d.pid();
assert_eq!(
stop_pid_with(&desc, pid, &rec).await.expect("stop by pid"),
StopOutcome::Stopped { pid, forced: false }
);
assert_eq!(rec.sent(), vec![Signal::Term]);
assert!(
d.child.try_wait().expect("try_wait").is_some(),
"pid must have exited"
);
}
#[tokio::test]
async fn stop_pid_refuses_a_pid_that_is_not_this_instance() {
let fx = Fixture::new();
let own_dir = fx.path("own");
fs::create_dir(&own_dir).expect("own dir");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.instance_path_args = vec![(DIR_FLAG.to_string(), own_dir)];
desc.spawn_args = daemon_args(
"serve",
&[format!("marker={}", fx.path("spawned").display())],
);
let other_sock = fx.instance_socket("b");
let other = fx.launch(OTHER, "never-bind", &fx.socket, &[]);
let bridge = fx.launch_as(ROLE_BRIDGE, DAEMON, "never-bind", &fx.socket, &[]);
let env_sibling = launch_unserved(&fx, &other_sock, "env-marker", &[]);
let path_sibling = launch_unserved(
&fx,
&fx.socket,
"path-marker",
&[
DIR_FLAG.to_string(),
PathSiblings::dir(&other_sock).display().to_string(),
],
);
for pid in [other.pid(), bridge.pid()] {
assert!(
wait_for(|| fs::read_link(format!("/proc/{pid}/exe"))
.is_ok_and(|e| e.starts_with(&fx.install))),
"fixture {pid} never ran"
);
}
let rec = Recording::new(true);
match stop_pid_with(&desc, other.pid(), &rec).await {
Err(LifecycleError::IdentityMismatch { pid, found, .. }) => {
assert_eq!((pid, found.as_str()), (other.pid(), OTHER));
}
out => panic!("another binary: expected IdentityMismatch, got {out:?}"),
}
for (what, pid) in [
("a bridge", bridge.pid()),
("an env sibling", env_sibling.pid()),
("a path sibling", path_sibling.pid()),
] {
let stopped = stop_pid_with(&desc, pid, &rec).await;
let restarted = restart_pid_with(&desc, pid, &rec).await;
for (call, out) in [
("stop_pid", stopped.map(|o| format!("{o:?}"))),
("restart_pid", restarted.map(|o| format!("{o:?}"))),
] {
assert!(
matches!(&out, Err(LifecycleError::NotThisInstance { pid: p, .. }) if *p == pid),
"{what}: {call}: expected NotThisInstance, got {out:?}"
);
}
}
std::thread::sleep(SPAWN_SETTLE);
assert!(lines(&fx.path("spawned")).is_empty(), "restart_pid spawned");
assert!(rec.sent().is_empty(), "no signal may be sent");
for pid in [
other.pid(),
bridge.pid(),
env_sibling.pid(),
path_sibling.pid(),
] {
assert!(is_alive(pid), "pid {pid} is untouched");
}
}
#[tokio::test]
async fn stop_pid_of_a_pid_that_is_gone_answers_as_stop_does() {
let fx = Fixture::new();
let mut gone = fx.launch(DAEMON, "exit-now", &fx.socket, &[]);
gone.child.wait().expect("reap the exited fixture");
let stale = gone.pid();
let desc = fx.descriptor(StoppedSignal::SocketRefuses);
let rec = Recording::new(true);
assert_eq!(
stop_pid_with(&desc, stale, &rec)
.await
.expect("nothing runs"),
StopOutcome::NotRunning
);
let d = launch_unserved(&fx, &fx.socket, "marker", &[]);
let out = stop_pid_with(&desc, stale, &rec).await;
assert!(
matches!(&out, Err(LifecycleError::RunningUnserved { pids, .. }) if *pids == [d.pid()]),
"expected RunningUnserved naming pid {}, got {out:?}",
d.pid()
);
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(d.pid()), "the daemon is untouched");
}
#[tokio::test]
async fn restart_pid_restarts_a_daemon_whose_socket_bind_failed() {
let fx = Fixture::new();
let d = launch_unserved(&fx, &fx.socket, "old-marker", &[]);
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let out = restart_pid(&desc, d.pid()).await;
let mut reaps = fx.reap_reported(&marker);
let out = out.expect("restart by pid");
assert_eq!(
out.stop,
StopOutcome::Stopped {
pid: d.pid(),
forced: false
}
);
let new = out.start.pid;
assert_eq!(pid_lines(&marker), vec![new.to_string()], "one new daemon");
assert!(UnixStream::connect(&fx.socket).is_ok(), "it serves");
assert!(!is_alive(d.pid()), "the old daemon is gone");
assert_eq!(
stop_pid(&desc, new).await.expect("cleanup stop"),
StopOutcome::Stopped {
pid: new,
forced: false
}
);
reaps.iter_mut().for_each(Reap::disarm);
}
#[tokio::test]
async fn restart_pid_refuses_before_any_signal_when_another_process_is_this_instance() {
let fx = Fixture::new();
let d = launch_unserved(&fx, &fx.socket, "d-marker", &[]);
let twin = launch_unserved(&fx, &fx.socket, "twin-marker", &[]);
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let rec = Recording::new(true);
let out = restart_pid_with(&desc, d.pid(), &rec).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
match &out {
Err(LifecycleError::RestartBlocked {
serving, others, ..
}) => {
assert_eq!(*serving, [d.pid()]);
assert_eq!(*others, [twin.pid()]);
}
other => panic!("expected RestartBlocked, got {other:?}"),
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(lines(&marker).is_empty(), "nothing was spawned");
assert!(is_alive(d.pid()) && is_alive(twin.pid()), "both untouched");
}
#[tokio::test]
async fn stop_pid_reports_a_survivor_and_restart_pid_starts_nothing() {
let fx = Fixture::new();
let d = fx.spawn(DAEMON, "ignore-term", &[]);
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
desc.stop_grace = Duration::from_millis(200);
desc.kill_wait = Duration::from_millis(300);
let stopped = stop_pid_with(&desc, d.pid(), &Recording::new(false)).await;
let restarted = restart_pid_with(&desc, d.pid(), &Recording::new(false)).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
for (call, out) in [
("stop_pid", stopped.map(|o| format!("{o:?}"))),
("restart_pid", restarted.map(|o| format!("{o:?}"))),
] {
assert!(
matches!(&out, Err(LifecycleError::Survivor { pid }) if *pid == d.pid()),
"{call}: expected Survivor, got {out:?}"
);
}
assert!(lines(&marker).is_empty(), "nothing was spawned");
assert!(is_alive(d.pid()), "the survivor still runs");
}
#[tokio::test]
async fn stop_pid_and_restart_pid_refuse_an_undecided_instance_before_any_signal() {
let fx = Fixture::new();
let own_dir = fx.path("own");
fs::create_dir(&own_dir).expect("own dir");
let spawned = fx.path("spawned");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.instance_path_args = vec![(DIR_FLAG.to_string(), own_dir)];
desc.spawn_args = daemon_args("serve", &[format!("marker={}", spawned.display())]);
let mut no_liveness = fx.descriptor(StoppedSignal::SocketRefuses);
no_liveness.liveness_args.clear();
no_liveness.spawn_args = desc.spawn_args.clone();
let flag = |value: &str| vec![DIR_FLAG.to_string(), value.to_string()];
let missing = fx.path("missing").display().to_string();
let relative = launch_unserved(&fx, &fx.socket, "rel-marker", &flag("own"));
let unresolvable = launch_unserved(&fx, &fx.socket, "abs-marker", &flag(&missing));
let no_value = launch_unserved(&fx, &fx.socket, "none-marker", &[DIR_FLAG.to_string()]);
let plain = launch_unserved(&fx, &fx.socket, "plain-marker", &[]);
let rec = Recording::new(true);
let mut results = Vec::new();
for (what, d, pid, undecided) in [
("a relative value", &desc, relative.pid(), true),
("an unresolvable value", &desc, unresolvable.pid(), true),
("no value", &desc, no_value.pid(), true),
("empty liveness_args", &no_liveness, plain.pid(), false),
] {
let stopped = stop_pid_with(d, pid, &rec).await.map(|o| format!("{o:?}"));
let restarted = restart_pid_with(d, pid, &rec)
.await
.map(|o| format!("{o:?}"));
results.push((what, pid, undecided, stopped, restarted));
}
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&spawned);
for (what, pid, undecided, stopped, restarted) in results {
for (call, out) in [("stop_pid", stopped), ("restart_pid", restarted)] {
let refused = match &out {
Err(LifecycleError::InstanceUndecided { pid: p, flag, .. }) => {
undecided && *p == pid && flag == DIR_FLAG
}
Err(LifecycleError::InvalidDescriptor { .. }) => !undecided,
_ => false,
};
assert!(refused, "{what}: {call}: expected a refusal, got {out:?}");
}
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(lines(&spawned).is_empty(), "restart_pid spawned");
for pid in [
relative.pid(),
unresolvable.pid(),
no_value.pid(),
plain.pid(),
] {
assert!(is_alive(pid), "pid {pid} is untouched");
}
}
#[tokio::test]
async fn stop_pid_and_restart_pid_refuse_before_any_signal_when_another_pid_serves_the_socket() {
let fx = Fixture::new();
let p = launch_unserved(&fx, &fx.socket, "p-marker", &[]);
let q = fx.spawn(OTHER, "serve", &[]);
let marker = fx.path("marker");
let mut desc = fx.descriptor(StoppedSignal::SocketRefuses);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let rec = Recording::new(true);
let restarted = restart_pid_with(&desc, p.pid(), &rec).await;
let stopped = stop_pid_with(&desc, p.pid(), &rec).await;
std::thread::sleep(SPAWN_SETTLE);
let _reaps = fx.reap_reported(&marker);
match &restarted {
Err(LifecycleError::RestartBlocked {
serving, others, ..
}) => {
assert_eq!(*serving, [p.pid()]);
assert_eq!(*others, [q.pid()]);
}
other => panic!("restart_pid: expected RestartBlocked, got {other:?}"),
}
assert!(
matches!(&stopped, Err(LifecycleError::ServedByAnother { pid, peer, .. })
if (*pid, *peer) == (p.pid(), q.pid())),
"stop_pid: expected ServedByAnother, got {stopped:?}"
);
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(lines(&marker).is_empty(), "nothing was spawned");
assert!(is_alive(p.pid()) && is_alive(q.pid()), "both untouched");
assert!(UnixStream::connect(&fx.socket).is_ok(), "Q still serves");
}
#[tokio::test]
async fn stop_pid_and_restart_pid_stop_short_when_the_socket_cannot_be_probed() {
let fx = Fixture::new();
let dir = fx.path("locked");
fs::create_dir(&dir).expect("socket dir");
let socket = dir.join("d.sock");
let p = launch_unserved(&fx, &socket, "p-marker", &[]);
let marker = fx.path("marker");
let mut desc = fx.descriptor_at(StoppedSignal::SocketRefuses, &socket);
desc.spawn_args = daemon_args("serve", &[format!("marker={}", marker.display())]);
let guard = ModeGuard::lock(&dir);
let probe = UnixStream::connect(&socket).map(drop);
assert!(
matches!(&probe, Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
"fixture precondition: connect is refused with EACCES, got {probe:?}"
);
let rec = Recording::new(true);
let restarted = restart_pid_with(&desc, p.pid(), &rec)
.await
.map(|o| format!("{o:?}"));
let stopped = stop_pid_with(&desc, p.pid(), &rec)
.await
.map(|o| format!("{o:?}"));
std::thread::sleep(SPAWN_SETTLE);
drop(guard);
let _reaps = fx.reap_reported(&marker);
for (call, out) in [("restart_pid", restarted), ("stop_pid", stopped)] {
assert!(
matches!(&out, Err(LifecycleError::ProbeInconclusive { socket: s }) if *s == socket),
"{call}: expected ProbeInconclusive, got {out:?}"
);
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(lines(&marker).is_empty(), "nothing was spawned");
assert!(is_alive(p.pid()), "the daemon is untouched");
}
#[tokio::test]
async fn restart_and_restart_pid_stop_nothing_when_the_install_binary_is_missing() {
let fx = Fixture::new();
let d = fx.spawn(DAEMON, "serve", &[]);
let desc = fx.descriptor(StoppedSignal::SocketRefuses);
let program = fx.install.join(DAEMON);
fs::remove_file(&program).expect("remove the install binary");
let rec = Recording::new(true);
let restarted = restart_with(&desc, &rec).await.map(|o| format!("{o:?}"));
let by_pid = restart_pid_with(&desc, d.pid(), &rec)
.await
.map(|o| format!("{o:?}"));
for (call, out) in [("restart", restarted), ("restart_pid", by_pid)] {
assert!(
matches!(&out, Err(LifecycleError::BinaryMissing { path }) if *path == program),
"{call}: expected BinaryMissing, got {out:?}"
);
}
assert!(rec.sent().is_empty(), "no signal may be sent");
assert!(is_alive(d.pid()), "the daemon still runs");
assert!(UnixStream::connect(&fx.socket).is_ok(), "it still serves");
}