Skip to main content

bounded_command/
lib.rs

1//! Deadline- and allocation-bounded subprocess execution.
2//!
3//! Privileged components use small command-line clients at a few platform
4//! boundaries; this wrapper keeps a wedged client, a compromised daemon or an
5//! inherited pipe in a descendant from pinning or exhausting its caller.
6
7use std::ffi::OsStr;
8use std::io::{Read, Write as _};
9#[cfg(unix)]
10use std::os::unix::process::CommandExt as _;
11use std::process::{Child, Command, ExitStatus, Stdio};
12use std::sync::Arc;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::mpsc::{Receiver, SyncSender, TryRecvError};
15use std::time::Duration;
16
17use thiserror::Error;
18use zeroize::Zeroizing;
19
20#[cfg(unix)]
21mod child_wait;
22/// The `Command` helpers domains share: `which`, `run` and bounded capture with one error
23/// vocabulary. Native only: the page's build links this crate through the UI's speech engine,
24/// and a browser page has no subprocesses to look up or start.
25#[cfg(not(target_arch = "wasm32"))]
26pub mod command;
27#[cfg(unix)]
28pub use child_wait::{WakeFd, Wakeup, wait_child_or};
29
30/// Start `command`'s child as the leader of its own process tree, so
31/// [`kill_tree`] also reaches every descendant it starts. On Unix this is a
32/// new process group named after the child's pid.
33pub fn own_process_tree(command: &mut Command) -> &mut Command {
34    #[cfg(unix)]
35    command.process_group(0);
36    command
37}
38
39/// Start `command`'s child without a console window of its own. On Windows a
40/// console program otherwise opens one; elsewhere this changes nothing.
41pub fn without_console_window(command: &mut Command) -> &mut Command {
42    #[cfg(windows)]
43    {
44        use std::os::windows::process::CommandExt as _;
45        command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
46    }
47    command
48}
49
50/// Kill a child started with [`own_process_tree`] together with its
51/// descendants, and the child itself as a fallback. The caller still reaps it.
52pub fn kill_tree(child: &mut Child) {
53    #[cfg(unix)]
54    if let Ok(pid) = i32::try_from(child.id())
55        && let Some(group) = pid.checked_neg()
56    {
57        // SAFETY: the child was placed in its own pid-named process group; a
58        // negative pid targets exactly that group.
59        unsafe { libc::kill(group, libc::SIGKILL) };
60    }
61    let _ = child.kill();
62}
63
64/// Stop a child started with [`own_process_tree`] and reap it. With a
65/// non-zero `grace`, the tree is first asked to exit (`SIGTERM` on Unix) and
66/// gets that long to do so: until the child and, on Unix, every process left
67/// in its group are gone. Whatever remains is then killed with [`kill_tree`].
68pub fn terminate_tree(child: &mut Child, grace: Duration) {
69    #[cfg(unix)]
70    if !grace.is_zero()
71        && let Ok(pid) = i32::try_from(child.id())
72        && let Some(group) = pid.checked_neg()
73    {
74        // SAFETY: the child was placed in its own pid-named process group; a
75        // negative pid targets exactly that group.
76        unsafe { libc::kill(group, libc::SIGTERM) };
77        // A grace past what the clock can name waits for the tree, as a timeout does.
78        let deadline = tilo_clock::now().checked_add(grace);
79        while deadline.is_none_or(|deadline| tilo_clock::now() < deadline) {
80            // The leader exiting is not enough: a worker it started may still
81            // be winding down in the group. Signal 0 only probes for one.
82            // SAFETY: as above; signal 0 delivers nothing.
83            if child.try_wait().ok().flatten().is_some()
84                && unsafe { libc::kill(group, 0) } != 0
85                && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
86            {
87                return;
88            }
89            std::thread::sleep(Duration::from_millis(20));
90        }
91    }
92    #[cfg(not(unix))]
93    let _ = grace;
94    kill_tree(child);
95    let _ = child.wait();
96}
97
98/// Wait up to `timeout` for `child` to exit, and reap it. `None` when it is
99/// still running at the deadline; it is left running. On Unix this sleeps in
100/// [`wait_child_or`] rather than polling.
101pub fn wait_timeout(child: &mut Child, timeout: Duration) -> std::io::Result<Option<ExitStatus>> {
102    let deadline = tilo_clock::now().checked_add(timeout);
103    #[cfg(unix)]
104    {
105        Ok(match wait_child_or(child, None, deadline)? {
106            Wakeup::Exited(status) => Some(status),
107            Wakeup::Woken | Wakeup::Deadline => None,
108        })
109    }
110    #[cfg(not(unix))]
111    loop {
112        if let Some(status) = child.try_wait()? {
113            return Ok(Some(status));
114        }
115        if deadline.is_some_and(|deadline| tilo_clock::now() >= deadline) {
116            return Ok(None);
117        }
118        std::thread::sleep(Duration::from_millis(10));
119    }
120}
121
122/// [`wait_timeout`], then kill and reap a child still running at the deadline.
123/// `None` when it had to be killed.
124pub fn wait_or_kill(child: &mut Child, timeout: Duration) -> std::io::Result<Option<ExitStatus>> {
125    let status = wait_timeout(child, timeout)?;
126    if status.is_none() {
127        let _ = child.kill();
128        child.wait()?;
129    }
130    Ok(status)
131}
132
133/// Mark a script or program file executable for everyone and writable only
134/// by its owner (mode `0755` on Unix). A no-op where executability is not a
135/// file permission.
136pub fn make_executable(path: &std::path::Path) -> std::io::Result<()> {
137    #[cfg(unix)]
138    {
139        use std::os::unix::fs::PermissionsExt as _;
140        let mut permissions = std::fs::metadata(path)?.permissions();
141        permissions.set_mode(0o755);
142        std::fs::set_permissions(path, permissions)
143    }
144    #[cfg(not(unix))]
145    {
146        let _ = path;
147        Ok(())
148    }
149}
150
151/// Maximum secret or request body this wrapper accepts.
152pub const MAX_INPUT_BYTES: usize = 64 * 1024;
153
154#[derive(Debug)]
155pub struct Output {
156    pub status: ExitStatus,
157    pub stdout: Vec<u8>,
158    pub stderr: Vec<u8>,
159}
160
161impl Output {
162    /// Standard error as a short diagnostic safe to log or show a person: lossy
163    /// UTF-8 without control characters other than space, newline and tab, at
164    /// most 512 characters, trimmed.
165    #[must_use]
166    pub fn stderr_diagnostic(&self) -> String {
167        String::from_utf8_lossy(&self.stderr)
168            .chars()
169            .filter(|character| !character.is_control() || matches!(character, ' ' | '\n' | '\t'))
170            .take(512)
171            .collect::<String>()
172            .trim()
173            .to_string()
174    }
175}
176
177#[derive(Debug, Error)]
178pub enum Error {
179    #[error("command input exceeds its configured safety limit")]
180    InputTooLarge,
181    #[error("command process failed: {0}")]
182    Process(#[from] std::io::Error),
183    #[error("command {stream} exceeds {limit} bytes")]
184    OutputTooLarge { stream: &'static str, limit: usize },
185    #[error("command timed out after {0} ms")]
186    Timeout(u128),
187    #[error("command output reader failed")]
188    Reader,
189    #[error("command input writer failed")]
190    Writer,
191    #[error("command was cancelled")]
192    Cancelled,
193}
194
195/// An informational copy of bytes the owned stderr capture already read. Capture
196/// stays authoritative; overflow disables only this queue.
197#[derive(Debug)]
198pub enum StderrObservation {
199    /// At most 4096 captured bytes, in stream order.
200    Bytes(Vec<u8>),
201    Overflow,
202}
203
204pub const STDERR_OBSERVATION_CHUNKS: usize = 16;
205
206struct StderrCapture {
207    sender: SyncSender<Vec<u8>>,
208    overflow: Arc<AtomicBool>,
209}
210
211struct StderrObservations {
212    receiver: Receiver<Vec<u8>>,
213    overflow: Arc<AtomicBool>,
214    disabled: bool,
215}
216
217/// A nonblocking bounded command which cancels its process group when dropped.
218pub struct AsyncCommand {
219    cancel: Arc<AtomicBool>,
220    result: Receiver<Result<Output, Error>>,
221    worker: Option<std::thread::JoinHandle<()>>,
222    stderr_observations: Option<StderrObservations>,
223}
224
225impl AsyncCommand {
226    /// Poll the optional stderr queue without blocking. On overflow, pending copies
227    /// are dropped and the queue stays disabled.
228    pub fn try_stderr(&mut self) -> Option<StderrObservation> {
229        let observations = self.stderr_observations.as_mut()?;
230        if observations.disabled {
231            return None;
232        }
233        if observations.overflow.load(Ordering::Acquire) {
234            observations.disabled = true;
235            while observations.receiver.try_recv().is_ok() {}
236            return Some(StderrObservation::Overflow);
237        }
238        observations
239            .receiver
240            .try_recv()
241            .ok()
242            .map(StderrObservation::Bytes)
243    }
244
245    pub fn try_wait(&mut self) -> Option<Result<Output, Error>> {
246        match self.result.try_recv() {
247            Ok(result) => {
248                if let Some(worker) = self.worker.take() {
249                    let _ = worker.join();
250                }
251                Some(result)
252            }
253            Err(TryRecvError::Empty) => None,
254            Err(TryRecvError::Disconnected) => {
255                self.worker.take().map(std::thread::JoinHandle::join);
256                Some(Err(Error::Reader))
257            }
258        }
259    }
260}
261
262impl Drop for AsyncCommand {
263    fn drop(&mut self) {
264        self.cancel.store(true, Ordering::Release);
265        if let Some(worker) = self.worker.take() {
266            let _ = worker.join();
267        }
268    }
269}
270
271/// Spawn a caller-prepared bounded command for nonblocking polling. Dropping the
272/// handle cancels and reaps the process group.
273///
274/// # Errors
275///
276/// [`Error::InputTooLarge`] before spawning a worker.
277pub fn spawn_prepared(
278    command: Command,
279    input: Option<&[u8]>,
280    output_limit: usize,
281    timeout: Duration,
282) -> Result<AsyncCommand, Error> {
283    spawn_prepared_inner(command, input, output_limit, timeout, false)
284}
285
286/// Spawn with a bounded nonblocking copy of the owned stderr capture.
287///
288/// Up to sixteen 4096-byte chunks await observation; a slow observer disables this
289/// informational queue instead of blocking the child or the capture readers. Output
290/// bytes, limits, cancellation and process-tree ownership are unchanged.
291pub fn spawn_prepared_observing_stderr(
292    command: Command,
293    input: Option<&[u8]>,
294    output_limit: usize,
295    timeout: Duration,
296) -> Result<AsyncCommand, Error> {
297    spawn_prepared_inner(command, input, output_limit, timeout, true)
298}
299
300fn spawn_prepared_inner(
301    command: Command,
302    input: Option<&[u8]>,
303    output_limit: usize,
304    timeout: Duration,
305    observe_stderr: bool,
306) -> Result<AsyncCommand, Error> {
307    if input.is_some_and(|bytes| bytes.len() > MAX_INPUT_BYTES) {
308        return Err(Error::InputTooLarge);
309    }
310    let input = input.map(|bytes| Zeroizing::new(bytes.to_vec()));
311    let cancel = Arc::new(AtomicBool::new(false));
312    let worker_cancel = Arc::clone(&cancel);
313    let (sender, result) = std::sync::mpsc::channel();
314    let (capture, stderr_observations) = if observe_stderr {
315        let (sender, receiver) = std::sync::mpsc::sync_channel(STDERR_OBSERVATION_CHUNKS);
316        let overflow = Arc::new(AtomicBool::new(false));
317        (
318            Some(StderrCapture {
319                sender,
320                overflow: Arc::clone(&overflow),
321            }),
322            Some(StderrObservations {
323                receiver,
324                overflow,
325                disabled: false,
326            }),
327        )
328    } else {
329        (None, None)
330    };
331    let worker = std::thread::spawn(move || {
332        let outcome = run_prepared_inner(
333            command,
334            input.map_or(Stdin::Null, Stdin::Bytes),
335            output_limit,
336            output_limit,
337            timeout,
338            Some(&worker_cancel),
339            capture,
340        );
341        let _ = sender.send(outcome);
342    });
343    Ok(AsyncCommand {
344        cancel,
345        result,
346        worker: Some(worker),
347        stderr_observations,
348    })
349}
350
351fn read_bounded(pipe: impl Read, limit: usize) -> Vec<u8> {
352    let read_limit = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1);
353    let mut bytes = Vec::new();
354    let _ = pipe.take(read_limit).read_to_end(&mut bytes);
355    bytes
356}
357
358fn read_bounded_observed(pipe: impl Read, limit: usize, capture: Option<StderrCapture>) -> Vec<u8> {
359    let Some(capture) = capture else {
360        return read_bounded(pipe, limit);
361    };
362    let read_limit = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1);
363    let mut pipe = pipe.take(read_limit);
364    let mut bytes = Vec::new();
365    let mut chunk = [0; 4096];
366    loop {
367        let count = match pipe.read(&mut chunk) {
368            Ok(0) | Err(_) => break,
369            Ok(count) => count,
370        };
371        let Some(captured) = chunk.get(..count) else {
372            break;
373        };
374        bytes.extend_from_slice(captured);
375        if !capture.overflow.load(Ordering::Acquire)
376            && capture.sender.try_send(captured.to_vec()).is_err()
377        {
378            capture.overflow.store(true, Ordering::Release);
379        }
380    }
381    bytes
382}
383
384/// Run one fixed program/argv transaction with bounded input, output, and time.
385///
386/// `stdout` and `stderr` each receive their own `output_limit`. On timeout the
387/// complete child process group is killed, closing pipes inherited by helper
388/// descendants as well.
389pub fn run(
390    program: &str,
391    args: &[&str],
392    input: Option<&[u8]>,
393    output_limit: usize,
394    timeout: Duration,
395) -> Result<Output, Error> {
396    run_os(program, args, input, output_limit, timeout)
397}
398
399pub fn run_os(
400    program: impl AsRef<OsStr>,
401    args: &[impl AsRef<OsStr>],
402    input: Option<&[u8]>,
403    output_limit: usize,
404    timeout: Duration,
405) -> Result<Output, Error> {
406    let mut command = Command::new(program);
407    command.args(args);
408    run_prepared(command, input, output_limit, timeout)
409}
410
411pub fn run_with_env(
412    program: &str,
413    args: &[&str],
414    env: &[(&str, &str)],
415    input: Option<&[u8]>,
416    output_limit: usize,
417    timeout: Duration,
418) -> Result<Output, Error> {
419    let mut command = Command::new(program);
420    command.args(args).envs(env.iter().copied());
421    run_prepared(command, input, output_limit, timeout)
422}
423
424/// Run a caller-prepared command, replacing its standard streams and process-group
425/// configuration with the bounded policy.
426pub fn run_prepared(
427    command: Command,
428    input: Option<&[u8]>,
429    output_limit: usize,
430    timeout: Duration,
431) -> Result<Output, Error> {
432    run_prepared_with_limits(command, input, output_limit, output_limit, timeout)
433}
434
435/// Run a caller-prepared command with independent output-stream ceilings, for
436/// helpers whose primary output is legitimately much larger than their diagnostics,
437/// such as image acquisition tools.
438pub fn run_prepared_with_limits(
439    command: Command,
440    input: Option<&[u8]>,
441    stdout_limit: usize,
442    stderr_limit: usize,
443    timeout: Duration,
444) -> Result<Output, Error> {
445    run_prepared_with_input_limit(
446        command,
447        input,
448        MAX_INPUT_BYTES,
449        stdout_limit,
450        stderr_limit,
451        timeout,
452    )
453}
454
455/// Run a prepared command with caller-selected input and stream ceilings, for
456/// bounded bulk payloads such as print documents. Most callers want
457/// [`run_prepared`].
458pub fn run_prepared_with_input_limit(
459    command: Command,
460    input: Option<&[u8]>,
461    input_limit: usize,
462    stdout_limit: usize,
463    stderr_limit: usize,
464    timeout: Duration,
465) -> Result<Output, Error> {
466    if input.is_some_and(|bytes| bytes.len() > input_limit) {
467        return Err(Error::InputTooLarge);
468    }
469    run_prepared_inner(
470        command,
471        input.map_or(Stdin::Null, |bytes| {
472            Stdin::Bytes(Zeroizing::new(bytes.to_vec()))
473        }),
474        stdout_limit,
475        stderr_limit,
476        timeout,
477        None,
478        None,
479    )
480}
481
482/// Run a prepared command reading `file` as its standard input: a handle the
483/// caller holds (a file the person chose) given to the program as it is,
484/// rather than a path it would open itself.
485pub fn run_prepared_with_stdin(
486    command: Command,
487    file: std::fs::File,
488    output_limit: usize,
489    timeout: Duration,
490) -> Result<Output, Error> {
491    run_prepared_inner(
492        command,
493        Stdin::File(file),
494        output_limit,
495        output_limit,
496        timeout,
497        None,
498        None,
499    )
500}
501
502enum Stdin {
503    Null,
504    Bytes(Zeroizing<Vec<u8>>),
505    File(std::fs::File),
506}
507
508fn run_prepared_inner(
509    mut command: Command,
510    input: Stdin,
511    stdout_limit: usize,
512    stderr_limit: usize,
513    timeout: Duration,
514    cancel: Option<&AtomicBool>,
515    stderr_capture: Option<StderrCapture>,
516) -> Result<Output, Error> {
517    let (stdin, input) = match input {
518        Stdin::Null => (Stdio::null(), None),
519        Stdin::Bytes(bytes) => (Stdio::piped(), Some(bytes)),
520        Stdin::File(file) => (Stdio::from(file), None),
521    };
522    command
523        .stdin(stdin)
524        .stdout(Stdio::piped())
525        .stderr(Stdio::piped());
526    own_process_tree(&mut command);
527    let mut child = command.spawn()?;
528    let input_writer = if let Some(bytes) = input {
529        let mut stdin = child
530            .stdin
531            .take()
532            .ok_or_else(|| Error::Process(std::io::Error::other("command stdin is unavailable")))?;
533        Some(std::thread::spawn(move || stdin.write_all(&bytes)))
534    } else {
535        None
536    };
537
538    let stdout = child
539        .stdout
540        .take()
541        .ok_or_else(|| Error::Process(std::io::Error::other("command stdout is unavailable")))?;
542    let stderr = child
543        .stderr
544        .take()
545        .ok_or_else(|| Error::Process(std::io::Error::other("command stderr is unavailable")))?;
546    let out_reader = std::thread::spawn(move || read_bounded(stdout, stdout_limit));
547    let err_reader =
548        std::thread::spawn(move || read_bounded_observed(stderr, stderr_limit, stderr_capture));
549    // A timeout past what the clock can name (`Duration::MAX`) is no deadline at all.
550    let deadline = tilo_clock::now().checked_add(timeout);
551    let status = loop {
552        if let Some(status) = child.try_wait()? {
553            break Some(status);
554        }
555        let cancelled = cancel.is_some_and(|flag| flag.load(Ordering::Acquire));
556        if cancelled || deadline.is_some_and(|deadline| tilo_clock::now() >= deadline) {
557            kill_tree(&mut child);
558            let _ = child.wait();
559            break None;
560        }
561        std::thread::sleep(Duration::from_millis(5));
562    };
563    let stdout = out_reader.join().map_err(|_| Error::Reader)?;
564    let stderr = err_reader.join().map_err(|_| Error::Reader)?;
565    let input_result = input_writer.map(std::thread::JoinHandle::join);
566    let Some(status) = status else {
567        return Err(if cancel.is_some_and(|flag| flag.load(Ordering::Acquire)) {
568            Error::Cancelled
569        } else {
570            Error::Timeout(timeout.as_millis())
571        });
572    };
573    if let Some(result) = input_result {
574        result.map_err(|_| Error::Writer)?.map_err(Error::Process)?;
575    }
576    if stdout.len() > stdout_limit {
577        return Err(Error::OutputTooLarge {
578            stream: "stdout",
579            limit: stdout_limit,
580        });
581    }
582    if stderr.len() > stderr_limit {
583        return Err(Error::OutputTooLarge {
584            stream: "stderr",
585            limit: stderr_limit,
586        });
587    }
588    Ok(Output {
589        status,
590        stdout,
591        stderr,
592    })
593}
594
595#[cfg(test)]
596#[cfg(unix)]
597mod tests {
598    use super::*;
599    use std::fs;
600    use std::os::unix::fs::PermissionsExt as _;
601    use tilo_test_env::SpawnUnderEnvLock as _;
602
603    /// For tests of anything but the timeout: long enough that a loaded
604    /// machine never turns the expected error into `Error::Timeout`.
605    const UNTESTED_TIMEOUT: Duration = Duration::from_secs(60);
606
607    tilo_test_env::scenario! {
608        /// Running a program within bounds: its input, output, time, stderr and environment.
609        fn a_bounded_command_keeps_its_limits_and_its_child_to_itself;
610
611        phase a_file_given_as_stdin_is_what_the_program_reads;
612        {
613            let directory = tempfile::tempdir().unwrap();
614            let path = directory.path().join("chosen");
615            fs::write(&path, b"chosen bytes").unwrap();
616            let output = run_prepared_with_stdin(
617                Command::new("cat"),
618                fs::File::open(&path).unwrap(),
619                64,
620                UNTESTED_TIMEOUT,
621            )
622            .unwrap();
623            assert!(output.status.success());
624            assert_eq!(output.stdout, b"chosen bytes");
625        }
626
627        phase input_and_output_limits_are_enforced_independently;
628        {
629            {
630                assert!(matches!(
631                    run(
632                        "true",
633                        &[],
634                        Some(&vec![0; MAX_INPUT_BYTES + 1]),
635                        16,
636                        UNTESTED_TIMEOUT
637                    ),
638                    Err(Error::InputTooLarge)
639                ));
640                for (script, stream) in [
641                    ("#!/bin/sh\nhead -c 8192 /dev/zero\n", "stdout"),
642                    ("#!/bin/sh\nhead -c 8192 /dev/zero >&2\n", "stderr"),
643                ] {
644                    let directory = tempfile::tempdir().unwrap();
645                    let helper = directory.path().join("helper");
646                    fs::write(&helper, script).unwrap();
647                    fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
648                    let error =
649                        run(helper.to_str().unwrap(), &[], None, 4096, UNTESTED_TIMEOUT).unwrap_err();
650                    assert!(
651                        matches!(error, Error::OutputTooLarge { stream: got, .. } if got == stream),
652                        "expected {stream} overflow, got {error:?}"
653                    );
654                }
655            }
656            {
657                let mut command = Command::new("sh");
658                command.args(["-c", "head -c 32 /dev/zero; head -c 128 /dev/zero >&2"]);
659                let error =
660                    run_prepared_with_limits(command, None, 64, 32, UNTESTED_TIMEOUT).unwrap_err();
661                assert!(matches!(
662                    error,
663                    Error::OutputTooLarge {
664                        stream: "stderr",
665                        limit: 32
666                    }
667                ));
668            }
669            {
670                let bytes = vec![0x5a; MAX_INPUT_BYTES + 1];
671                let output = run_prepared_with_input_limit(
672                    Command::new("cat"),
673                    Some(&bytes),
674                    bytes.len(),
675                    bytes.len(),
676                    64,
677                    UNTESTED_TIMEOUT,
678                )
679                .unwrap();
680                assert!(output.status.success());
681                assert_eq!(output.stdout, bytes);
682
683                assert!(matches!(
684                    run_prepared_with_input_limit(
685                        Command::new("cat"),
686                        Some(&bytes),
687                        bytes.len() - 1,
688                        bytes.len(),
689                        64,
690                        UNTESTED_TIMEOUT,
691                    ),
692                    Err(Error::InputTooLarge)
693                ));
694            }
695        }
696
697        phase timeouts_and_dropped_handles_terminate_children_promptly;
698        {
699            {
700                // A timeout no deadline can name waits for the child; it never ends it at once.
701                let output = run("sh", &["-c", "sleep 0.05; printf done"], None, 64, Duration::MAX)
702                    .unwrap();
703                assert_eq!(output.stdout, b"done");
704            }
705            {
706                let directory = tempfile::tempdir().unwrap();
707                let helper = directory.path().join("helper");
708                fs::write(&helper, OUTLIVES_THE_TEST).unwrap();
709                fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
710                let error = returns("the timeout to kill the descendant", move || {
711                    run(
712                        helper.to_str().unwrap(),
713                        &[],
714                        None,
715                        4096,
716                        Duration::from_millis(25),
717                    )
718                })
719                .unwrap_err();
720                assert!(matches!(error, Error::Timeout(_)));
721            }
722            {
723                let directory = tempfile::tempdir().unwrap();
724                let helper = directory.path().join("helper");
725                fs::write(&helper, OUTLIVES_THE_TEST).unwrap();
726                fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
727                let error = returns("the timeout to interrupt the child", move || {
728                    run(
729                        helper.to_str().unwrap(),
730                        &[],
731                        Some(&vec![0; MAX_INPUT_BYTES]),
732                        4096,
733                        Duration::from_millis(25),
734                    )
735                })
736                .unwrap_err();
737                assert!(matches!(error, Error::Timeout(_)));
738            }
739            {
740                let mut command = Command::new("sh");
741                command.args(["-c", "printf ready; sleep 3600"]);
742                let mut child = spawn_prepared(command, None, 64, Duration::from_secs(3600)).unwrap();
743                assert!(child.try_wait().is_none());
744                returns("dropping the handle to end the child", move || drop(child));
745            }
746            {
747                let mut command = Command::new("sh");
748                command.args(["-c", "trap '' TERM; sleep 3600"]);
749                let child = own_process_tree(&mut command).spawn_locked().unwrap();
750                let mut child = returns("the escalation to kill the tree", move || {
751                    let mut child = child;
752                    terminate_tree(&mut child, Duration::from_millis(50));
753                    child
754                });
755                assert!(child.try_wait().unwrap().is_some());
756            }
757        }
758
759        phase stderr_observation_is_live_bounded_and_preserves_exact_capture;
760        {
761            let directory = tempfile::tempdir().unwrap();
762            let first_hold = directory.path().join("first-check");
763            let second_hold = directory.path().join("second-check");
764            let mut command = Command::new("sh");
765            command.args([
766                "-c",
767                "printf 'first\\n' >&2; while [ ! -f \"$1\" ]; do sleep 0.01; done; printf 'second\\n' >&2; while [ ! -f \"$2\" ]; do sleep 0.01; done; printf stdout; exit 7",
768                "owned-observer-fixture",
769            ]).arg(&first_hold).arg(&second_hold);
770            let mut child =
771                spawn_prepared_observing_stderr(command, None, 4096, UNTESTED_TIMEOUT).unwrap();
772            let mut observed = Vec::new();
773            for (expected, check) in [
774                (b"first\n".as_slice(), first_hold),
775                (b"first\nsecond\n".as_slice(), second_hold),
776            ] {
777                tilo_test_env::wait_until("the phase's stderr", || {
778                    match child.try_stderr() {
779                        Some(StderrObservation::Bytes(bytes)) => observed.extend(bytes),
780                        Some(StderrObservation::Overflow) => panic!("small guarded output overflowed"),
781                        None => {}
782                    }
783                    observed.len() >= expected.len()
784                });
785                assert_eq!(
786                    observed, expected,
787                    "the phase is observable before its check is released"
788                );
789                assert!(
790                    child.try_wait().is_none(),
791                    "the same owned invocation is still running"
792                );
793                fs::write(check, b"release").unwrap();
794            }
795            let output =
796                tilo_test_env::wait_for("the owned child to complete", || child.try_wait()).unwrap();
797            assert_eq!(output.status.code(), Some(7));
798            assert_eq!(output.stdout, b"stdout");
799            assert_eq!(
800                output.stderr, observed,
801                "observation never removes or rewrites capture bytes"
802            );
803        }
804
805        phase a_slow_stderr_observer_does_not_block_capture_or_change_output_limits;
806        {
807            let mut command = Command::new("sh");
808            command.args(["-c", "head -c 262144 /dev/zero >&2"]);
809            let mut child =
810                spawn_prepared_observing_stderr(command, None, 262_144, UNTESTED_TIMEOUT).unwrap();
811            // A full observation queue that blocked the capture would never
812            // let the child finish.
813            let output = tilo_test_env::wait_for("the capture to finish", || child.try_wait()).unwrap();
814            assert!(output.status.success());
815            assert_eq!(output.stderr, vec![0; 262_144]);
816            assert!(matches!(
817                child.try_stderr(),
818                Some(StderrObservation::Overflow)
819            ));
820            assert!(
821                child.try_stderr().is_none(),
822                "overflow permanently disables only this queue"
823            );
824            let mut overflowing = Command::new("sh");
825            overflowing.args(["-c", "head -c 8192 /dev/zero >&2"]);
826            let mut child =
827                spawn_prepared_observing_stderr(overflowing, None, 1024, UNTESTED_TIMEOUT).unwrap();
828            let error = tilo_test_env::wait_for("the bounded child to complete", || child.try_wait())
829                .unwrap_err();
830            assert!(matches!(
831                error,
832                Error::OutputTooLarge {
833                    stream: "stderr",
834                    limit: 1024
835                }
836            ));
837        }
838
839        phase explicit_environment_overlay_reaches_only_the_child;
840        {
841            let parent_value = std::env::var_os("TILO_BOUNDED_COMMAND_TEST");
842            let output = run_with_env(
843                "sh",
844                &["-c", "printf %s \"$TILO_BOUNDED_COMMAND_TEST\""],
845                &[("TILO_BOUNDED_COMMAND_TEST", "isolated")],
846                None,
847                64,
848                UNTESTED_TIMEOUT,
849            )
850            .unwrap();
851            assert!(output.status.success());
852            assert_eq!(output.stdout, b"isolated");
853            assert_eq!(std::env::var_os("TILO_BOUNDED_COMMAND_TEST"), parent_value);
854        }
855    }
856
857    /// Runs `call` on its own thread and returns what it returned. Each
858    /// child below would outlive the hang bound on its own, so the call
859    /// returning at all shows it ended the child rather than waited for it.
860    fn returns<T: Send + 'static>(what: &str, call: impl FnOnce() -> T + Send + 'static) -> T {
861        let (sender, returned) = std::sync::mpsc::channel();
862        std::thread::spawn(move || {
863            let _ = sender.send(call());
864        });
865        tilo_test_env::recv(what, &returned)
866    }
867
868    /// A child that runs for an hour unless it is ended.
869    const OUTLIVES_THE_TEST: &str = "#!/bin/sh\nsleep 3600\n";
870
871    #[cfg(target_os = "linux")]
872    #[test]
873    fn a_bounded_wait_reaps_an_exited_child_and_kills_only_on_request() {
874        let mut quick = Command::new("true").spawn_locked().unwrap();
875        assert!(
876            wait_or_kill(&mut quick, UNTESTED_TIMEOUT)
877                .unwrap()
878                .is_some_and(|status| status.success())
879        );
880        let mut slow = Command::new("sleep").arg("60").spawn_locked().unwrap();
881        assert_eq!(
882            wait_timeout(&mut slow, Duration::from_millis(50)).unwrap(),
883            None
884        );
885        assert!(
886            slow.try_wait().unwrap().is_none(),
887            "a plain wait leaves it running"
888        );
889        assert_eq!(
890            wait_or_kill(&mut slow, Duration::from_millis(50)).unwrap(),
891            None
892        );
893        assert!(slow.try_wait().unwrap().is_some(), "killed and reaped");
894    }
895}