From 39ec21a7d74b2452496b240e1bbc06eb2cfa2e64 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:23:29 -0600 Subject: [PATCH 1/3] fix(id): bound directory mail command runtime --- pkgs/id/src/directory_mail.rs | 82 ++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 7 deletions(-) diff --git a/pkgs/id/src/directory_mail.rs b/pkgs/id/src/directory_mail.rs index 9eb8ade993..5ddf5981a7 100644 --- a/pkgs/id/src/directory_mail.rs +++ b/pkgs/id/src/directory_mail.rs @@ -11,7 +11,8 @@ use std::io::{BufRead, BufReader, Write as _}; use std::net::{SocketAddr, TcpStream}; use std::path::PathBuf; use std::process::{Command, Stdio}; -use std::time::Duration; +use std::thread; +use std::time::{Duration, Instant}; use anyhow::{Context as _, Result, bail, ensure}; use rand::RngExt as _; @@ -36,7 +37,7 @@ pub trait MailSink: Debug + Send + Sync { /// # Errors /// /// Fails if the message could not be written or the program did not - /// finish successfully. + /// finish successfully before its deadline. fn send(&self, mail: &Mail) -> Result<()>; } @@ -90,10 +91,8 @@ impl CommandSink { pub const fn new(program: PathBuf, args: Vec) -> Self { Self { program, args } } -} -impl MailSink for CommandSink { - fn send(&self, mail: &Mail) -> Result<()> { + fn send_with_timeout(&self, mail: &Mail, timeout: Duration) -> Result<()> { let mut child = Command::new(&self.program) .args(&self.args) .env("ID_MAIL_TO", &mail.to) @@ -104,7 +103,38 @@ impl MailSink for CommandSink { .stderr(Stdio::null()) .spawn() .with_context(|| format!("run {}", self.program.display()))?; - let status = child.wait().context("wait for mail program")?; + let started = Instant::now(); + let status = loop { + if let Some(status) = child.try_wait().context("wait for mail program")? { + if started.elapsed() >= timeout { + bail!("mail program timed out after {timeout:?}"); + } + break status; + } + + let remaining = timeout.saturating_sub(started.elapsed()); + if remaining.is_zero() { + if let Err(kill_error) = child.kill() { + let reaper = thread::Builder::new() + .name("id-mail-reaper".to_owned()) + .spawn(move || { + let _ = child.wait(); + }); + if let Err(reaper_error) = reaper { + bail!( + "mail program timed out after {timeout:?}; failed to kill child: {kill_error}; failed to start reaper: {reaper_error}" + ); + } + bail!( + "mail program timed out after {timeout:?}; failed to kill child: {kill_error}; reaping in background" + ); + } + child.wait().context("reap timed-out mail program")?; + bail!("mail program timed out after {timeout:?}"); + } + + thread::sleep(Duration::from_millis(10).min(remaining)); + }; if !status.success() { bail!("mail program exited with {status}"); } @@ -112,6 +142,16 @@ impl MailSink for CommandSink { } } +// Keep the configurable program on the same 10-second failure budget as the +// loopback SMTP sink; its child must not pin a directory request indefinitely. +const COMMAND_TIMEOUT: Duration = Duration::from_secs(10); + +impl MailSink for CommandSink { + fn send(&self, mail: &Mail) -> Result<()> { + self.send_with_timeout(mail, COMMAND_TIMEOUT) + } +} + const RELAY_TIMEOUT: Duration = Duration::from_secs(10); /// Hands mail to an SMTP relay on this machine, with plain SMTP and no login. @@ -321,11 +361,39 @@ mod tests { assert!(sink.send(&sample()).is_err()); } + #[test] + fn a_command_that_exceeds_its_deadline_is_killed_and_reaped() { + let sink = CommandSink::new( + PathBuf::from("/bin/sh"), + vec!["-c".to_owned(), "exec sleep 30".to_owned()], + ); + let started = Instant::now(); + let error = sink + .send_with_timeout(&sample(), Duration::from_millis(50)) + .unwrap_err(); + assert!(error.to_string().contains("mail program timed out")); + assert!( + started.elapsed() < Duration::from_secs(5), + "timed-out command took {:?}", + started.elapsed() + ); + } + + #[test] + fn a_slow_finite_command_completes_before_its_deadline() { + let sink = CommandSink::new( + PathBuf::from("/bin/sh"), + vec!["-c".to_owned(), "exec sleep 0.05".to_owned()], + ); + sink.send_with_timeout(&sample(), Duration::from_secs(2)) + .unwrap(); + } + /// A relay that records every line it is sent, refusing the recipient if asked. fn fake_relay(refuse_recipient: bool) -> (SocketAddr, JoinHandle>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); - let handle = std::thread::spawn(move || { + let handle = thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut writer = stream; From db70193b23a84b4ecee7f252e66e8cc809c40e85 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 17:05:42 -0600 Subject: [PATCH 2/3] fix(id): kill the mail command tree on timeout; observed exit always wins (#1788) Codex P2 (PR #4031): child.kill() terminated only a wrapper script, leaving descendants such as the shipped cloudflare-mail.sh curl running after a reported timeout. The command now spawns as a process-group leader (unix) and the timeout path SIGKILLs the whole group via kill_child_tree, falling back to child.kill(). New regression test: a wrapper that backgrounds sleep 30 and waits - after the timeout error the descendant is gone. Codex P2 (PR #4031): the poll loop replaced an observed successful exit with a timeout when the finish was first seen after the deadline. The elapsed check on an observed status is deleted: try_wait success now always breaks with the real status, and the deadline applies only while the child is still running. Also merges current main, which brings the #4044 idset test-compile fix - directory_mail tests now run: 11 passed, 0 failed on the laptop. --- pkgs/id/src/directory_mail.rs | 89 +++++++++++++++++++++++++++++++---- 1 file changed, 81 insertions(+), 8 deletions(-) diff --git a/pkgs/id/src/directory_mail.rs b/pkgs/id/src/directory_mail.rs index 5ddf5981a7..cf46bda330 100644 --- a/pkgs/id/src/directory_mail.rs +++ b/pkgs/id/src/directory_mail.rs @@ -77,6 +77,24 @@ impl MailSink for OutboxSink { } } +/// Terminate a timed-out mail command. On Unix the child was spawned as a +/// process-group leader, so SIGKILL the whole group to take any wrapper +/// script's descendants with it; fall back to killing just the child when +/// the group signal fails (e.g. the group is already gone). +fn kill_child_tree(child: &mut std::process::Child) -> std::io::Result<()> { + #[cfg(unix)] + { + #[allow(clippy::cast_possible_wrap)] + let pgid = child.id() as libc::pid_t; + // SAFETY: killpg only delivers a signal; the pgid is our own child's + // pid, and no memory is accessed. + if unsafe { libc::killpg(pgid, libc::SIGKILL) } == 0 { + return Ok(()); + } + } + child.kill() +} + /// Runs a program once per message, with the message in environment /// variables. No shell is involved, so an address cannot inject a command. #[derive(Clone, Debug)] @@ -93,28 +111,38 @@ impl CommandSink { } fn send_with_timeout(&self, mail: &Mail, timeout: Duration) -> Result<()> { - let mut child = Command::new(&self.program) + let mut command = Command::new(&self.program); + command .args(&self.args) .env("ID_MAIL_TO", &mail.to) .env("ID_MAIL_SUBJECT", &mail.subject) .env("ID_MAIL_BODY", &mail.body) .stdin(Stdio::null()) .stdout(Stdio::null()) - .stderr(Stdio::null()) + .stderr(Stdio::null()); + // The child leads its own process group so a timeout can terminate + // the whole tree: a wrapper script's descendants (e.g. a stalled + // curl in the shipped cloudflare-mail.sh) must not outlive the + // failure this function reports. + #[cfg(unix)] + { + use std::os::unix::process::CommandExt as _; + command.process_group(0); + } + let mut child = command .spawn() .with_context(|| format!("run {}", self.program.display()))?; let started = Instant::now(); let status = loop { + // An observed exit always wins: a command that finished before + // the deadline is a success even if the finish is only seen on + // the first poll after the deadline has passed. if let Some(status) = child.try_wait().context("wait for mail program")? { - if started.elapsed() >= timeout { - bail!("mail program timed out after {timeout:?}"); - } break status; } - let remaining = timeout.saturating_sub(started.elapsed()); - if remaining.is_zero() { - if let Err(kill_error) = child.kill() { + if started.elapsed() >= timeout { + if let Err(kill_error) = kill_child_tree(&mut child) { let reaper = thread::Builder::new() .name("id-mail-reaper".to_owned()) .spawn(move || { @@ -133,6 +161,7 @@ impl CommandSink { bail!("mail program timed out after {timeout:?}"); } + let remaining = timeout.saturating_sub(started.elapsed()); thread::sleep(Duration::from_millis(10).min(remaining)); }; if !status.success() { @@ -379,6 +408,50 @@ mod tests { ); } + #[cfg(unix)] + #[test] + fn a_timed_out_wrapper_script_takes_its_descendants_with_it() { + // The shipped mail program is a wrapper script (cloudflare-mail.sh) + // that waits on descendants such as curl. Killing only the wrapper + // on timeout would leave them running after the failure is reported, + // so the sink spawns the command as a process-group leader and + // SIGKILLs the whole group. + let dir = scratch("wrapper"); + let pid_file = dir.join("child.pid"); + let script = format!("sleep 30 & echo $! > {}; wait", pid_file.display()); + let sink = CommandSink::new(PathBuf::from("/bin/sh"), vec!["-c".to_owned(), script]); + let started = Instant::now(); + let error = sink + .send_with_timeout(&sample(), Duration::from_millis(500)) + .unwrap_err(); + assert!(error.to_string().contains("mail program timed out")); + assert!( + started.elapsed() < Duration::from_secs(5), + "timed-out wrapper took {:?}", + started.elapsed() + ); + let child_pid: i32 = std::fs::read_to_string(&pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + // The descendant may take a moment to be reaped after SIGKILL. + let deadline = Instant::now() + Duration::from_secs(2); + loop { + // SAFETY: signal 0 only probes for the process's existence. + let alive = unsafe { libc::kill(child_pid, 0) } == 0; + if !alive { + break; + } + assert!( + Instant::now() < deadline, + "descendant {child_pid} survived the wrapper's timeout kill" + ); + thread::sleep(Duration::from_millis(20)); + } + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn a_slow_finite_command_completes_before_its_deadline() { let sink = CommandSink::new( From 86f21f9f45f533fccd3345363dbb26d718f9063c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 17:17:37 -0600 Subject: [PATCH 3/3] test(id): zombie-aware descendant probe for the mail timeout test (#1788) Codex P2 (PR #4031 re-review): signal 0 succeeds for a zombie, so in a container whose PID 1 does not reap orphans the descendant check would fail after 2s even though the group kill worked. The probe now treats a Linux /proc state of Z as terminated. --- pkgs/id/src/directory_mail.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/pkgs/id/src/directory_mail.rs b/pkgs/id/src/directory_mail.rs index cf46bda330..708c03ed35 100644 --- a/pkgs/id/src/directory_mail.rs +++ b/pkgs/id/src/directory_mail.rs @@ -436,13 +436,29 @@ mod tests { .parse() .unwrap(); // The descendant may take a moment to be reaped after SIGKILL. - let deadline = Instant::now() + Duration::from_secs(2); - loop { + let running = |pid: i32| { // SAFETY: signal 0 only probes for the process's existence. - let alive = unsafe { libc::kill(child_pid, 0) } == 0; - if !alive { - break; + if unsafe { libc::kill(pid, 0) } != 0 { + return false; + } + // A zombie is terminated, not running — but it still answers + // signal 0, and in a container whose PID 1 does not reap + // orphans it would look alive forever. Linux exposes the + // state in /proc; other hosts' init reaps orphans promptly. + #[cfg(target_os = "linux")] + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) + && let Some(state) = stat + .rsplit(')') + .next() + .and_then(|rest| rest.trim_start().chars().next()) + && state == 'Z' + { + return false; } + true + }; + let deadline = Instant::now() + Duration::from_secs(2); + while running(child_pid) { assert!( Instant::now() < deadline, "descendant {child_pid} survived the wrapper's timeout kill"