Skip to main content

ic_host_process/tool/
mod.rs

1//! Executable admission and bounded execution of caller-selected Unix commands.
2//!
3//! Consumers own pins, arguments, credentials, environment and trusted executable
4//! directories. Execution is not a sandbox or process-tree supervisor. Calls
5//! execute once, including on timeout or ambiguous completion; no retry occurs.
6
7mod diagnostics;
8mod process;
9mod resolution;
10#[cfg(test)]
11mod tests;
12
13pub use diagnostics::format_failure_evidence;
14pub use resolution::{ResolutionError, resolve_executable};
15
16use ic_host_artifacts::artifact::{ArtifactError, ArtifactIdentity, Sha256Digest};
17use ic_host_fs::read::{hash_file_no_follow_with_metadata, hash_file_with_metadata};
18use std::{
19    ffi::OsString,
20    fmt, fs, io,
21    os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _},
22    path::{Path, PathBuf},
23    process::{Command, ExitStatus},
24    time::{Duration, Instant},
25};
26
27/// Retention and overflow behavior for one output stream.
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum OutputLimit {
30    /// Retain at most this many bytes; excess output fails and cleans up the child.
31    Terminate(usize),
32    /// Retain this prefix, drain the rest, and report every byte to an observer.
33    /// Truncation is recorded in evidence, without failing the command.
34    Truncate(usize),
35}
36
37impl OutputLimit {
38    /// Maximum retained bytes, independently of overflow behavior.
39    #[must_use]
40    pub const fn retained_bytes(self) -> usize {
41        match self {
42            Self::Terminate(bytes) | Self::Truncate(bytes) => bytes,
43        }
44    }
45}
46
47/// Caller-selected output retention and optional elapsed-time deadline.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub struct OutputLimits {
50    /// Standard output retention and overflow behavior.
51    pub stdout: OutputLimit,
52    /// Standard error retention and overflow behavior.
53    pub stderr: OutputLimit,
54    /// Positive deadline from immediately before spawning through output EOF,
55    /// or from entry to [`communicate_child`] for an already spawned child.
56    /// Verification reads, spawning syscalls and kill/reap may take longer.
57    ///
58    /// `None` still enforces output bounds, polls cancellation and cleans up on
59    /// failure. It can wait indefinitely for child exit or pipe EOF, including
60    /// descendant-held pipes with [`SuccessfulExit::Retain`]. Choose cancellation
61    /// and successful-exit policy deliberately. Cleanup timing remains governed
62    /// by the child's [`crate::child::CleanupPolicy`].
63    pub timeout: Option<Duration>,
64}
65
66/// Explicit process context. The child's inherited environment is cleared.
67///
68/// No ambient PATH, HOME or credentials are added. Consumers must include any
69/// environment needed by their tool. This type intentionally has no `Debug`
70/// implementation because its values may contain credentials.
71pub struct ExecutionContext<'a> {
72    /// Absolute current directory for the child.
73    pub current_dir: &'a Path,
74    /// Complete environment; names must be nonempty, unique, and contain no
75    /// `=` or NUL bytes. Values must contain no NUL bytes.
76    pub environment: &'a [(OsString, OsString)],
77}
78
79/// Executable and version-probe configuration selected by a consumer.
80///
81/// Verifying operations require a separate exact version authority. Pinned
82/// admission additionally requires a trusted digest. Observation executes a
83/// caller-trusted installation without an independently selected version.
84/// Consumers own installation provenance; a version does not authenticate bytes.
85pub struct VersionSpec<'a> {
86    /// Absolute path in a caller-controlled filesystem; no PATH search occurs.
87    pub executable: &'a Path,
88    /// Maximum executable bytes read during admission and every later run.
89    pub executable_bytes: u64,
90    /// Exact argument vector used once to observe version identity.
91    pub version_arguments: &'a [OsString],
92}
93
94/// Invocation parameters rejected before dispatch or communication.
95/// An already spawned child remains owned and untouched by this validation.
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
97pub enum InvalidInvocation {
98    /// Tool paths must be absolute.
99    ExecutablePath,
100    /// Working directories must be absolute.
101    WorkingDirectory,
102    /// Deadlines must be positive and representable by the host clock.
103    Deadline,
104    /// Version identity must be nonempty and already trimmed.
105    VersionIdentity,
106    /// An argument contains a NUL byte.
107    Argument {
108        /// Argument position.
109        index: usize,
110    },
111    /// An environment name is empty, contains `=`/NUL, or duplicates an earlier name.
112    EnvironmentName {
113        /// Environment entry position.
114        index: usize,
115    },
116    /// An environment value contains a NUL byte.
117    EnvironmentValue {
118        /// Environment entry position.
119        index: usize,
120    },
121}
122
123/// A captured output stream.
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum OutputStream {
126    /// Standard output.
127    Stdout,
128    /// Standard error.
129    Stderr,
130}
131
132/// Bounded evidence retained after an invocation or admission failure.
133///
134/// Bytes are available explicitly to the caller; formatting prints only lengths
135/// and status. Error messages never include command arguments or environment.
136#[derive(Default)]
137pub struct ExecutionEvidence {
138    /// Observed direct-child status. Communication can reserve a successful
139    /// leader without reaping it. Status does not prove external effects absent.
140    pub status: Option<ExitStatus>,
141    /// Retained stdout prefix, bounded by the selected limit.
142    pub stdout: Vec<u8>,
143    /// Retained stderr prefix, bounded by the selected limit.
144    pub stderr: Vec<u8>,
145    /// More stdout bytes were observed than could be retained.
146    pub stdout_truncated: bool,
147    /// More stderr bytes were observed than could be retained.
148    pub stderr_truncated: bool,
149}
150
151/// One completed invocation, with a required exit status and bounded output.
152///
153/// Completion includes nonzero exits and signals. It does not imply successful
154/// application effects. Use [`Self::require_success`] before success-only parsing.
155/// A retained successful child still requires caller-owned disposition.
156pub struct CompletedExecution {
157    /// Direct-child exit status, including nonzero exits and signals.
158    pub status: ExitStatus,
159    /// Retained stdout prefix.
160    pub stdout: Vec<u8>,
161    /// Retained stderr prefix.
162    pub stderr: Vec<u8>,
163    /// More stdout bytes were observed than retained.
164    pub stdout_truncated: bool,
165    /// More stderr bytes were observed than retained.
166    pub stderr_truncated: bool,
167}
168
169impl CompletedExecution {
170    /// Require a successful exit while preserving output on rejection.
171    ///
172    /// # Errors
173    /// Returns [`ExecutionFailure::ExitStatus`] for a nonzero or signalled exit.
174    /// This does not perform child cleanup or transfer retained ownership.
175    pub fn require_success(self) -> Result<Self, ToolError> {
176        if self.status.success() {
177            Ok(self)
178        } else {
179            Err(self.failure(ExecutionFailure::ExitStatus))
180        }
181    }
182
183    /// Require complete output before parsing or treating it as an identity.
184    ///
185    /// # Errors
186    /// Returns an output-limit failure with the original evidence if either
187    /// stream was truncated. This does not perform child cleanup; callers using
188    /// retained ownership still own the child's disposition.
189    pub fn require_complete(self) -> Result<Self, ToolError> {
190        let stream = if self.stdout_truncated {
191            OutputStream::Stdout
192        } else if self.stderr_truncated {
193            OutputStream::Stderr
194        } else {
195            return Ok(self);
196        };
197        Err(self.failure(ExecutionFailure::OutputLimit { stream }))
198    }
199
200    fn failure(self, failure: ExecutionFailure) -> ToolError {
201        ToolError::Execution(Box::new(ExecutionError {
202            failure,
203            evidence: self.into(),
204            cleanup: None,
205        }))
206    }
207}
208
209impl From<CompletedExecution> for ExecutionEvidence {
210    fn from(completed: CompletedExecution) -> Self {
211        Self {
212            status: Some(completed.status),
213            stdout: completed.stdout,
214            stderr: completed.stderr,
215            stdout_truncated: completed.stdout_truncated,
216            stderr_truncated: completed.stderr_truncated,
217        }
218    }
219}
220
221impl fmt::Debug for CompletedExecution {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        f.debug_struct("CompletedExecution")
224            .field("status", &self.status)
225            .field("stdout_bytes", &self.stdout.len())
226            .field("stderr_bytes", &self.stderr.len())
227            .field("stdout_truncated", &self.stdout_truncated)
228            .field("stderr_truncated", &self.stderr_truncated)
229            .finish()
230    }
231}
232
233impl fmt::Debug for ExecutionEvidence {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.debug_struct("ExecutionEvidence")
236            .field("status", &self.status)
237            .field("stdout_bytes", &self.stdout.len())
238            .field("stderr_bytes", &self.stderr.len())
239            .field("stdout_truncated", &self.stdout_truncated)
240            .field("stderr_truncated", &self.stderr_truncated)
241            .finish()
242    }
243}
244
245/// Process or pipe operation that produced an IO failure.
246///
247/// These categories contain no arguments, environment or captured output.
248#[derive(Clone, Copy, Debug, Eq, PartialEq)]
249pub enum ExecutionOperation {
250    /// Create the child process in its selected working directory.
251    Spawn,
252    /// Obtain the child's pipe for explicitly supplied input.
253    StdinPipe,
254    /// Read an IO pipe's current descriptor flags.
255    ReadPipeFlags,
256    /// Enable nonblocking IO on a pipe.
257    SetPipeFlags,
258    /// Read bytes from a capture pipe.
259    ReadOutput,
260    /// Write bytes to the child's stdin pipe.
261    WriteInput,
262    /// Observe child exit, including selected group cleanup before reaping.
263    Wait,
264}
265
266impl fmt::Display for ExecutionOperation {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        f.write_str(match self {
269            Self::Spawn => "spawn",
270            Self::StdinPipe => "stdin pipe",
271            Self::ReadPipeFlags => "read pipe flags",
272            Self::SetPipeFlags => "set pipe flags",
273            Self::ReadOutput => "read output",
274            Self::WriteInput => "write input",
275            Self::Wait => "wait",
276        })
277    }
278}
279
280/// Why an invocation failed, independently of its retained output.
281#[derive(Debug)]
282pub enum ExecutionFailure {
283    /// An explicit success check rejected the completed status in evidence.
284    ExitStatus,
285    /// Child exit or pipe EOF was not observed before the caller's deadline.
286    TimedOut,
287    /// The caller's cancellation predicate requested cleanup.
288    Cancelled,
289    /// The output observer rejected a chunk; its original sink error is retained.
290    Observer {
291        /// Stream being observed.
292        stream: OutputStream,
293        /// Caller-provided output-sink failure.
294        source: io::Error,
295    },
296    /// A stream emitted more bytes than allowed.
297    OutputLimit {
298        /// Stream whose bound was exceeded.
299        stream: OutputStream,
300    },
301    /// A process or pipe operation failed.
302    Io {
303        /// Operation category; contains no command or credential values.
304        operation: ExecutionOperation,
305        /// Underlying typed failure.
306        source: io::Error,
307    },
308    /// Retained output storage could not be allocated.
309    Allocation {
310        /// Stream being captured.
311        stream: OutputStream,
312        /// Underlying allocation failure.
313        source: std::collections::TryReserveError,
314    },
315}
316
317/// A failed invocation with bounded output and separately retained cleanup errors.
318#[derive(Debug)]
319pub struct ExecutionError {
320    /// Original failure; never replaced by a cleanup failure.
321    pub failure: ExecutionFailure,
322    /// Observed status and bounded stdout/stderr prefixes.
323    pub evidence: ExecutionEvidence,
324    /// Cleanup failures retained by the child owner, if cleanup failed.
325    pub cleanup: Option<Box<crate::child::CleanupError>>,
326}
327
328impl fmt::Display for ExecutionError {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        match &self.failure {
331            ExecutionFailure::ExitStatus => {
332                write!(f, "tool exited unsuccessfully: {:?}", self.evidence.status)
333            }
334            ExecutionFailure::TimedOut => f.write_str("tool capture exceeded its deadline"),
335            ExecutionFailure::Cancelled => f.write_str("tool communication cancelled"),
336            ExecutionFailure::Observer { stream, .. } => {
337                write!(f, "tool {stream:?} observer failed")
338            }
339            ExecutionFailure::OutputLimit { stream } => {
340                write!(f, "tool {stream:?} exceeded its byte limit")
341            }
342            ExecutionFailure::Io { operation, .. } => write!(f, "tool {operation} failed"),
343            ExecutionFailure::Allocation { stream, .. } => {
344                write!(f, "tool {stream:?} allocation failed")
345            }
346        }?;
347        if let Some(cleanup) = &self.cleanup {
348            write!(f, "; cleanup failed: {cleanup}")?;
349        }
350        Ok(())
351    }
352}
353impl std::error::Error for ExecutionError {
354    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
355        match &self.failure {
356            ExecutionFailure::Io { source, .. } | ExecutionFailure::Observer { source, .. } => {
357                Some(source)
358            }
359            ExecutionFailure::Allocation { source, .. } => Some(source),
360            _ => None,
361        }
362    }
363}
364
365/// Executable admission or execution failed.
366#[derive(Debug)]
367pub enum ToolError {
368    /// Invalid context, authority or arguments; no new child was spawned.
369    /// Communication validation leaves an existing child and its pipes untouched.
370    InvalidInvocation(InvalidInvocation),
371    /// Filesystem path resolution or metadata failed before execution.
372    Io(io::Error),
373    /// The selected file has no Unix executable permission bits.
374    NotExecutable,
375    /// Executable identity could not be read or did not match authority.
376    Artifact(ArtifactError),
377    /// One invocation failed; includes bounded evidence.
378    Execution(Box<ExecutionError>),
379    /// Successful version stdout was not valid UTF-8.
380    VersionUtf8 {
381        /// UTF-8 validation failure.
382        source: std::str::Utf8Error,
383        /// Raw bounded version output.
384        evidence: Box<ExecutionEvidence>,
385    },
386    /// Successful trimmed version stdout did not match the selected identity,
387    /// or observation produced an empty identity.
388    VersionMismatch {
389        /// Raw bounded version output; never formatted into the error.
390        evidence: Box<ExecutionEvidence>,
391    },
392}
393
394impl ToolError {
395    /// Borrow the original bounded capture, including successful version output.
396    ///
397    /// Validation and filesystem/admission failures have no capture and return
398    /// `None`. A failed spawn retains its existing empty execution evidence.
399    /// No output is copied, decoded, logged or formatted by this accessor.
400    #[must_use]
401    pub fn evidence(&self) -> Option<&ExecutionEvidence> {
402        match self {
403            Self::Execution(error) => Some(&error.evidence),
404            Self::VersionUtf8 { evidence, .. } | Self::VersionMismatch { evidence } => {
405                Some(evidence)
406            }
407            Self::InvalidInvocation(_) | Self::Io(_) | Self::NotExecutable | Self::Artifact(_) => {
408                None
409            }
410        }
411    }
412
413    /// Borrow the original execution failure and its kill/reap outcomes, if any.
414    ///
415    /// A successful version capture rejected by admission has evidence but no
416    /// execution failure. Formatting, redaction and recovery remain caller-owned.
417    #[must_use]
418    pub fn execution_error(&self) -> Option<&ExecutionError> {
419        match self {
420            Self::Execution(error) => Some(error),
421            _ => None,
422        }
423    }
424}
425
426/// Capture one caller-configured command without performing executable admission.
427///
428/// The caller owns the program, arguments, working directory, environment and
429/// platform setup. Their [`Command`] settings are used unchanged except that
430/// stdin is set to null and stdout/stderr to pipes. Ambient environment or PATH
431/// search remains enabled if the caller's command enables it. No digest/version
432/// check, credential selection, command reconstruction or retry is performed.
433/// Use [`AdmittedTool`] when exact executable-byte/version admission is required.
434///
435/// Shares the admitted-tool execution engine: stdout/stderr are drained fairly
436/// with bounded storage, and the deadline starts immediately before spawning
437/// and extends through pipe EOF. On failure, pipes are closed and the direct
438/// child is terminated/reaped, retaining the original failure and cleanup
439/// evidence. Descendants, platform setup hooks and inherited descriptor lifetimes
440/// remain caller-owned. Spawning, setup hooks and kill/reap are synchronous and
441/// may exceed the deadline. This does not supervise a process group, roll back
442/// an external effect or make an uncertain command safe to repeat.
443///
444/// # Errors
445/// Rejects an invalid deadline before touching or spawning the command. Spawn,
446/// capture, overflow and deadline failures retain bounded evidence. Ordinary
447/// nonzero/signalled exits return [`CompletedExecution`]; select
448/// [`CompletedExecution::require_success`] when the caller requires zero exit.
449pub fn capture_command(
450    command: &mut Command,
451    limits: OutputLimits,
452) -> Result<CompletedExecution, ToolError> {
453    validate_limits(limits)?;
454    process::capture_command(
455        command,
456        limits,
457        process::CleanupScope::DirectChild,
458        true,
459        || false,
460    )
461    .map_err(|source| ToolError::Execution(Box::new(source)))
462}
463
464/// Capture one caller-configured command in a newly owned process group.
465///
466/// Uses the same bounded, fair stdout/stderr capture and deadline as
467/// [`capture_command`], with null stdin and no executable admission or retries.
468/// Preserves caller command settings except IO and process-group selection;
469/// the latter is replaced with a new owned group. On natural leader exit,
470/// timeout, overflow or IO failure, remaining group members are signalled before
471/// reaping the leader. Original failures and group/direct-child cleanup errors
472/// remain separate in [`ExecutionError`]. There is no implicit background handoff.
473///
474/// Callers must not reap the leader independently or change its group. Escaped
475/// descendants are not contained, and signalling is not proof of descendant exit
476/// or completed external effects. Synchronous spawning/setup/cleanup can exceed
477/// the deadline. Admission, budgets, inherited descriptors and recovery remain
478/// caller-owned. Use [`capture_command`] for the existing direct-child contract.
479/// # Errors
480/// Rejects invalid deadlines before modifying/spawning the command. Execution
481/// failures retain bounded output, observed status and separate cleanup errors.
482pub fn capture_group_command(
483    command: &mut Command,
484    limits: OutputLimits,
485) -> Result<CompletedExecution, ToolError> {
486    validate_limits(limits)?;
487    process::capture_command(
488        command,
489        limits,
490        process::CleanupScope::ProcessGroup {
491            cleanup: crate::child::CleanupPolicy::KillAndWait,
492            deadline: None,
493        },
494        true,
495        || false,
496    )
497    .map_err(|source| ToolError::Execution(Box::new(source)))
498}
499
500/// Capture a command with caller-selected group cleanup, deadline and cancellation.
501///
502/// Shares [`capture_group_command`]'s IO, bounds, exit and cleanup contract.
503/// The callback runs before command modification/spawn and during communication;
504/// it must return promptly. A true value refuses startup or cleans up the owned
505/// group, retaining output and cleanup evidence. An expired absolute deadline
506/// refuses before command effects; a live deadline is shared across calls without
507/// restarting its allowance. If `limits.timeout` is also set, the earlier bound
508/// applies. Both bounds include callback/spawn time, but synchronous spawning and
509/// cleanup may exceed them. `None` adds no deadline. No signal handler, retry or
510/// admission policy is installed. Cleanup and limits remain caller-selected.
511///
512/// # Errors
513/// Invalid limits refuse before the callback or command effects. Cancellation,
514/// spawn and communication failures retain the existing typed execution evidence.
515pub fn capture_group_command_with_cancellation(
516    command: &mut Command,
517    limits: OutputLimits,
518    cleanup: crate::child::CleanupPolicy,
519    deadline: Option<Instant>,
520    cancelled: impl FnMut() -> bool,
521) -> Result<CompletedExecution, ToolError> {
522    validate_limits(limits)?;
523    process::capture_command(
524        command,
525        limits,
526        process::CleanupScope::ProcessGroup { cleanup, deadline },
527        true,
528        cancelled,
529    )
530    .map_err(|source| ToolError::Execution(Box::new(source)))
531}
532
533/// Run one caller-configured command in an owned process group.
534///
535/// Preserves the caller's stdin/stdout/stderr selection, including inherited
536/// progress output and file-backed streams. Only piped output is captured and
537/// bounded. Any piped stdin is closed; this entry point sends no input bytes.
538/// Group selection is replaced with a new owned group. This shares
539/// [`capture_group_command_with_cancellation`]'s pre-spawn validation,
540/// cancellation, absolute/relative deadlines and typed cleanup evidence.
541/// The caller selects budgets, cleanup and cancellation; `None` adds no deadline.
542/// Ordinary nonzero/signalled exits return [`CompletedExecution`]; callers
543/// choose [`CompletedExecution::require_success`]. There is no admission or retry.
544///
545/// # Errors
546/// Invalid limits, initial cancellation and expired deadlines refuse before
547/// modifying/spawning the command. Later failures clean up the owned group.
548pub fn run_group_command(
549    command: &mut Command,
550    limits: OutputLimits,
551    cleanup: crate::child::CleanupPolicy,
552    deadline: Option<Instant>,
553    cancelled: impl FnMut() -> bool,
554) -> Result<CompletedExecution, ToolError> {
555    validate_limits(limits)?;
556    process::capture_command(
557        command,
558        limits,
559        process::CleanupScope::ProcessGroup { cleanup, deadline },
560        false,
561        cancelled,
562    )
563    .map_err(|source| ToolError::Execution(Box::new(source)))
564}
565
566/// Successful leader disposition during [`communicate_child`].
567#[derive(Clone, Copy, Debug, Eq, PartialEq)]
568pub enum SuccessfulExit {
569    /// Clean according to child ownership before reaping, then drain captured pipes.
570    /// Direct-child ownership never signals descendants or other group members.
571    Cleanup,
572    /// Reserve the successful leader through IO completion and caller admission.
573    /// The caller must then explicitly wait, terminate or hand off the owner.
574    Retain,
575}
576
577/// Communicate once with a caller-spawned child using its configured IO.
578///
579/// Uses the capture engine to fairly drain available stdout/stderr pipes and
580/// write borrowed input without blocking reader/writer threads. The caller
581/// configures IO before [`crate::child::OwnedChild::spawn`]: absent output pipes
582/// are left alone (for example inherited progress output or files). Limits only
583/// apply to captured pipes. Do not take the child's pipes before this call.
584/// `Some(input)`, including empty input, requires piped stdin. `None` closes any
585/// available stdin pipe immediately; inherited stdin remains caller-selected.
586/// [`crate::child::OwnedChild::spawn_direct`] preserves process-group selection
587/// and limits cleanup to the direct child. Descendant-held pipes can still delay
588/// EOF; this function does not acquire descendant or terminal ownership.
589/// Stdin closes after input is written. An early broken pipe is accepted, like
590/// standard communicate semantics; command status and diagnostics remain primary.
591/// This does not guarantee the command consumed all input or applied its effects.
592///
593/// A selected deadline starts on entry, excluding earlier spawn time;
594/// `timeout: None` imposes no elapsed-time deadline. Output retention and
595/// cleanup remain active in either case. `cancelled` is
596/// polled between bounded IO steps and before returning success; it must return
597/// promptly. No signal handler, cancellation thread, retry or output decoding
598/// is installed. IO failure, cancellation, timeout and overflow
599/// close pipes and terminate/reap through the child's existing owner,
600/// retaining original failure and separate cleanup errors.
601///
602/// Completed zero/nonzero/signalled exits return a required status with all
603/// owned pipes closed. Nonzero/signalled leaders always undergo ordinary cleanup
604/// and reaping, including with [`SuccessfulExit::Retain`]; they cannot be handed off.
605/// With [`SuccessfulExit::Cleanup`],
606/// cleanup for the selected ownership scope and reaping occur as soon as child
607/// exit is observed. With [`SuccessfulExit::Retain`], the successful child remains
608/// reserved and its selected cleanup remains armed. After admitting output and checking
609/// application cancellation/deadlines, the caller must choose ordinary
610/// [`crate::child::OwnedChild::wait`] cleanup or explicit
611/// [`crate::child::OwnedChild::handoff`]. Rejected output can use `terminate`
612/// to retain cleanup evidence. Dropping the owner provides best-effort cleanup.
613/// This is not process-tree confinement or a descendant-exit barrier.
614///
615/// # Errors
616/// Invalid deadlines leave the already spawned child and its pipes untouched;
617/// the caller retains cleanup responsibility. An already terminating/reaped/transferred
618/// owner is rejected instead of reporting reserved success. Other failures return execution
619/// evidence after cleanup. Cleanup uses the policy chosen at child spawn and
620/// can exceed the communication deadline by its separate grace/reap allowance.
621pub fn communicate_child(
622    child: &mut crate::child::OwnedChild,
623    input: Option<&[u8]>,
624    limits: OutputLimits,
625    successful_exit: SuccessfulExit,
626    cancelled: impl FnMut() -> bool,
627) -> Result<CompletedExecution, ToolError> {
628    communicate_child_with_observer(child, input, limits, successful_exit, cancelled, |_, _| {
629        Ok(())
630    })
631}
632
633/// Communicate with an owned child while observing output bytes live.
634///
635/// Uses the same bounds, pipe handling and cleanup as [`communicate_child`].
636/// `output` receives nonempty borrowed chunks after retention, in order within
637/// each stream; chunk boundaries and ordering between streams are unspecified.
638/// With [`OutputLimit::Terminate`], only the retained prefix is reported before
639/// overflow fails. With [`OutputLimit::Truncate`], every drained byte is reported,
640/// while evidence retains only the selected prefix. A zero retained-byte budget
641/// can therefore forward output without storing it.
642/// Output is raw bytes, not necessarily complete lines or UTF-8.
643/// The observer returns `io::Result<()>`. Its first error stops observation,
644/// closes pipes and attempts cleanup, preserving the original sink error as
645/// [`ExecutionFailure::Observer`] alongside retained bytes and cleanup failures.
646/// A chunk is retained and any truncation recorded before observation; rejection
647/// takes precedence over a hard overflow detected in that same chunk.
648///
649/// Both callbacks run synchronously and must return promptly. `cancelled` also
650/// runs while the child is silent and may project caller-owned heartbeat events;
651/// no exact callback cadence is guaranteed. Callback time counts toward any
652/// selected communication deadline. A callback panic closes the pipes, attempts cleanup
653/// using the child's policy and resumes the original unwind, even if the caller
654/// catches it while retaining the child. Cleanup errors cannot be returned during
655/// unwind; any unreaped child remains owned for caller recovery.
656///
657/// Callers own event schemas, scheduling, output budgets and diagnostic rendering.
658/// Each stream explicitly selects hard overflow or truncation-and-continue.
659///
660/// # Panics
661/// Resumes callback panics after attempting cleanup with the selected policy.
662///
663/// # Errors
664/// Returns the same validation and execution errors as [`communicate_child`].
665pub fn communicate_child_with_observer(
666    child: &mut crate::child::OwnedChild,
667    input: Option<&[u8]>,
668    limits: OutputLimits,
669    successful_exit: SuccessfulExit,
670    cancelled: impl FnMut() -> bool,
671    output: impl FnMut(OutputStream, &[u8]) -> io::Result<()>,
672) -> Result<CompletedExecution, ToolError> {
673    validate_limits(limits)?;
674    process::communicate(child, input, limits, successful_exit, cancelled, output)
675        .map_err(|source| ToolError::Execution(Box::new(source)))
676}
677
678/// Complete a child after a caller has read control frames from its stdout.
679///
680/// Hand off the original buffered pipe without converting it to its raw inner
681/// pipe: unread prefetched bytes count against the same output budget as later
682/// bytes. `None` uses any stdout still held by the child, or captures no stdout
683/// if the caller consumed it completely. Stdin is closed; stderr is taken from
684/// the child and both streams use the existing nonblocking capture engine.
685/// No child is respawned and no retry occurs.
686///
687/// Unlike [`communicate_child`], a previously reaped/terminated child may be
688/// drained using its cached status; it is never signalled again. Transferred
689/// ownership refuses. Successful children use ordinary cleanup and cannot be
690/// handed off. Callers retain pipe provenance, protocol decoding, limits and
691/// cancellation. A selected timeout starts on entry; no default deadline is added.
692///
693/// # Errors
694/// Returns validation, capture and cleanup evidence as [`communicate_child`].
695/// Invalid limits do not touch the child; the passed reader is consumed/dropped.
696pub fn drain_child_output(
697    child: &mut crate::child::OwnedChild,
698    stdout: Option<std::io::BufReader<std::process::ChildStdout>>,
699    limits: OutputLimits,
700    cancelled: impl FnMut() -> bool,
701) -> Result<CompletedExecution, ToolError> {
702    validate_limits(limits)?;
703    process::drain_output(child, stdout, limits, cancelled)
704        .map_err(|source| ToolError::Execution(Box::new(source)))
705}
706
707impl fmt::Display for ToolError {
708    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709        match self {
710            Self::InvalidInvocation(input) => write!(f, "invalid tool invocation: {input:?}"),
711            Self::Io(_) => f.write_str("tool filesystem inspection failed"),
712            Self::NotExecutable => f.write_str("tool file is not executable"),
713            Self::Artifact(source) => write!(f, "tool identity verification failed: {source}"),
714            Self::Execution(source) => source.fmt(f),
715            Self::VersionUtf8 { .. } => f.write_str("tool version output is not UTF-8"),
716            Self::VersionMismatch { .. } => f.write_str("tool version does not match authority"),
717        }
718    }
719}
720impl std::error::Error for ToolError {
721    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
722        match self {
723            Self::Io(source) => Some(source),
724            Self::Artifact(source) => Some(source),
725            Self::Execution(source) => Some(source.as_ref()),
726            Self::VersionUtf8 { source, .. } => Some(source),
727            _ => None,
728        }
729    }
730}
731
732/// An executable with retained byte and version identities.
733///
734/// [`Self::admit`] requires a consumer-supplied digest. [`Self::admit_version`]
735/// records the installed identity without authenticating it against a pin.
736/// [`Self::observe_version`] records both identities without an expected version.
737/// Every execution rechecks digest/permission before spawning. Consumers must
738/// exclude concurrent writers to the executable and its parent directories:
739/// filesystem checks and `exec` are separate operations. This is not a file
740/// capability or verification of dynamic libraries, interpreters, or descendants.
741pub struct AdmittedTool {
742    path: PathBuf,
743    identity: ArtifactIdentity,
744    executable_bytes: u64,
745    version_identity: String,
746    no_follow: bool,
747}
748
749impl AdmittedTool {
750    /// Admit exact executable bytes and require the selected version identity.
751    ///
752    /// `expected_version` is exact UTF-8 stdout after Unicode whitespace trimming.
753    ///
754    /// # Errors
755    /// Rejects invalid inputs, non-executable files, digest/size mismatch, process
756    /// failures, non-UTF-8 stdout, and a different successful version identity.
757    pub fn admit(
758        spec: &VersionSpec<'_>,
759        expected: Sha256Digest,
760        expected_version: &str,
761        context: &ExecutionContext<'_>,
762        limits: OutputLimits,
763    ) -> Result<Self, ToolError> {
764        Self::admit_observation(
765            spec,
766            Some(expected),
767            Some(expected_version),
768            context,
769            limits,
770            false,
771        )
772    }
773
774    /// Admit exact bytes without following the executable's final-component symlink.
775    ///
776    /// Performs one bounded no-follow hash before the version command. Parents
777    /// and concurrent writers remain caller-owned. The retained canonical path
778    /// also rejects final-component links during subsequent [`Self::run`] calls.
779    ///
780    /// # Errors
781    /// Returns the same admission failures as [`Self::admit`], additionally
782    /// refusing final-component symbolic links and special files before execution.
783    pub fn admit_no_follow(
784        spec: &VersionSpec<'_>,
785        expected: Sha256Digest,
786        expected_version: &str,
787        context: &ExecutionContext<'_>,
788        limits: OutputLimits,
789    ) -> Result<Self, ToolError> {
790        Self::admit_observation(
791            spec,
792            Some(expected),
793            Some(expected_version),
794            context,
795            limits,
796            true,
797        )
798    }
799
800    /// Admit an exact version and record the caller-trusted installed bytes.
801    ///
802    /// `expected_version` is exact UTF-8 stdout after Unicode whitespace trimming.
803    ///
804    /// For tools built locally, no portable published digest may exist. This
805    /// entry hashes the executable within the supplied budget before running
806    /// the version command. The resulting [`Self::identity`] is an observation,
807    /// not a trusted published pin. All later runs reject changed bytes using
808    /// the same verification and capture engine as [`Self::admit`].
809    ///
810    /// The caller must trust the installation before admission: the version
811    /// command executes those bytes. Exact version output does not establish
812    /// authenticity. No version ranges, tool installation or PATH search occur.
813    /// The caller must exclude concurrent executable/directory writers.
814    ///
815    /// # Errors
816    /// Rejects invalid inputs, non-executable or oversized files, process
817    /// failures, non-UTF-8 stdout and a different successful version identity.
818    pub fn admit_version(
819        spec: &VersionSpec<'_>,
820        expected_version: &str,
821        context: &ExecutionContext<'_>,
822        limits: OutputLimits,
823    ) -> Result<Self, ToolError> {
824        Self::admit_observation(spec, None, Some(expected_version), context, limits, false)
825    }
826
827    /// Record installed bytes and their version with one version invocation.
828    ///
829    /// This is suitable for provenance of a caller-trusted installation when no
830    /// expected version is selected. Hashing precedes version dispatch; later
831    /// runs recheck that byte identity. The complete UTF-8 version stdout must
832    /// be nonempty after trimming. It does not authenticate the installation.
833    /// Consumers must exclude concurrent executable/directory writers and own
834    /// trust, output budgets, deadlines and environment, as for [`Self::admit_version`].
835    ///
836    /// # Errors
837    /// Rejects invalid inputs, non-executable or oversized files, process
838    /// failures, truncated output, non-UTF-8 stdout and an empty version.
839    /// An empty observation returns [`ToolError::VersionMismatch`] with the
840    /// original capture, just as an unmatched expected version does.
841    pub fn observe_version(
842        spec: &VersionSpec<'_>,
843        context: &ExecutionContext<'_>,
844        limits: OutputLimits,
845    ) -> Result<Self, ToolError> {
846        Self::admit_observation(spec, None, None, context, limits, false)
847    }
848
849    fn admit_observation(
850        spec: &VersionSpec<'_>,
851        expected: Option<Sha256Digest>,
852        expected_version: Option<&str>,
853        context: &ExecutionContext<'_>,
854        limits: OutputLimits,
855        no_follow: bool,
856    ) -> Result<Self, ToolError> {
857        if !spec.executable.is_absolute() {
858            return Err(ToolError::InvalidInvocation(
859                InvalidInvocation::ExecutablePath,
860            ));
861        }
862        if expected_version.is_some_and(|version| version.is_empty() || version.trim() != version) {
863            return Err(ToolError::InvalidInvocation(
864                InvalidInvocation::VersionIdentity,
865            ));
866        }
867        validate_invocation(spec.version_arguments, context, limits)?;
868        let path = fs::canonicalize(spec.executable).map_err(ToolError::Io)?;
869        let identity = verify_executable(
870            if no_follow { spec.executable } else { &path },
871            spec.executable_bytes,
872            expected,
873            no_follow,
874        )?;
875        let evidence = process::capture(&path, spec.version_arguments, context, limits)
876            .map_err(|source| ToolError::Execution(Box::new(source)))?
877            .require_success()?
878            .require_complete()?;
879        let version = match std::str::from_utf8(&evidence.stdout) {
880            Ok(version) => version.trim(),
881            Err(source) => {
882                return Err(ToolError::VersionUtf8 {
883                    source,
884                    evidence: Box::new(evidence.into()),
885                });
886            }
887        };
888        if version.is_empty() || expected_version.is_some_and(|expected| version != expected) {
889            return Err(ToolError::VersionMismatch {
890                evidence: Box::new(evidence.into()),
891            });
892        }
893        Ok(Self {
894            path,
895            identity,
896            executable_bytes: spec.executable_bytes,
897            version_identity: version.to_owned(),
898            no_follow,
899        })
900    }
901
902    /// Canonical absolute path selected during admission.
903    #[must_use]
904    pub fn path(&self) -> &Path {
905        &self.path
906    }
907
908    /// Retained raw executable identity.
909    ///
910    /// With [`Self::admit_version`] or [`Self::observe_version`], this is an observed identity, not proof of
911    /// a published binary pin or trusted installation provenance.
912    #[must_use]
913    pub const fn identity(&self) -> ArtifactIdentity {
914        self.identity
915    }
916
917    /// Successfully observed, trimmed version identity.
918    #[must_use]
919    pub fn version_identity(&self) -> &str {
920        &self.version_identity
921    }
922
923    /// Run once with a cleared, explicitly supplied environment and null stdin.
924    ///
925    /// Stdout/stderr are drained fairly through nonblocking pipes without reader
926    /// threads. On overflow/deadline the direct child is killed and reaped; pipe
927    /// handles are closed without waiting for descendants to close their copies.
928    /// Descendant processes remain caller-owned. This must not be interpreted
929    /// as a rollback or safe automatic retry of a command with external effects.
930    /// Nonzero/signalled exits are completed results. Call
931    /// [`CompletedExecution::require_success`] before success-only interpretation.
932    ///
933    /// # Errors
934    /// Returns invalid-input or identity failures before execution, or an
935    /// execution failure retaining bounded prefixes and cleanup outcomes.
936    pub fn run(
937        &self,
938        arguments: &[OsString],
939        context: &ExecutionContext<'_>,
940        limits: OutputLimits,
941    ) -> Result<CompletedExecution, ToolError> {
942        validate_invocation(arguments, context, limits)?;
943        verify_executable(
944            &self.path,
945            self.executable_bytes,
946            Some(self.identity.sha256),
947            self.no_follow,
948        )?;
949        process::capture(&self.path, arguments, context, limits)
950            .map_err(|source| ToolError::Execution(Box::new(source)))
951    }
952}
953
954fn verify_executable(
955    path: &Path,
956    limit: u64,
957    expected: Option<Sha256Digest>,
958    no_follow: bool,
959) -> Result<ArtifactIdentity, ToolError> {
960    let (actual, metadata) = if no_follow {
961        hash_file_no_follow_with_metadata(path, limit)
962    } else {
963        hash_file_with_metadata(path, limit)
964    }
965    .map_err(ToolError::Artifact)?;
966    if let Some(expected) = expected {
967        actual.verify(expected).map_err(ToolError::Artifact)?;
968    }
969    if metadata.permissions().mode() & 0o111 == 0 {
970        return Err(ToolError::NotExecutable);
971    }
972    Ok(actual)
973}
974
975fn validate_invocation(
976    arguments: &[OsString],
977    context: &ExecutionContext<'_>,
978    limits: OutputLimits,
979) -> Result<(), ToolError> {
980    let reject = |input| ToolError::InvalidInvocation(input);
981    if !context.current_dir.is_absolute() {
982        return Err(reject(InvalidInvocation::WorkingDirectory));
983    }
984    validate_limits(limits)?;
985    for (index, argument) in arguments.iter().enumerate() {
986        if argument.as_bytes().contains(&0) {
987            return Err(reject(InvalidInvocation::Argument { index }));
988        }
989    }
990    for (index, (key, value)) in context.environment.iter().enumerate() {
991        if key.is_empty()
992            || key.as_bytes().iter().any(|byte| matches!(byte, b'=' | 0))
993            || context.environment[..index]
994                .iter()
995                .any(|(earlier, _)| earlier == key)
996        {
997            return Err(reject(InvalidInvocation::EnvironmentName { index }));
998        }
999        if value.as_bytes().contains(&0) {
1000            return Err(reject(InvalidInvocation::EnvironmentValue { index }));
1001        }
1002    }
1003    Ok(())
1004}
1005
1006fn validate_limits(limits: OutputLimits) -> Result<(), ToolError> {
1007    if limits.timeout.is_some_and(|timeout| {
1008        timeout.is_zero() || std::time::Instant::now().checked_add(timeout).is_none()
1009    }) {
1010        return Err(ToolError::InvalidInvocation(InvalidInvocation::Deadline));
1011    }
1012    Ok(())
1013}