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,
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(command, limits, process::CleanupScope::DirectChild)
455        .map_err(|source| ToolError::Execution(Box::new(source)))
456}
457
458/// Capture one caller-configured command in a newly owned process group.
459///
460/// Uses the same bounded, fair stdout/stderr capture and deadline as
461/// [`capture_command`], with null stdin and no executable admission or retries.
462/// Preserves caller command settings except IO and process-group selection;
463/// the latter is replaced with a new owned group. On natural leader exit,
464/// timeout, overflow or IO failure, remaining group members are signalled before
465/// reaping the leader. Original failures and group/direct-child cleanup errors
466/// remain separate in [`ExecutionError`]. There is no implicit background handoff.
467///
468/// Callers must not reap the leader independently or change its group. Escaped
469/// descendants are not contained, and signalling is not proof of descendant exit
470/// or completed external effects. Synchronous spawning/setup/cleanup can exceed
471/// the deadline. Admission, budgets, inherited descriptors and recovery remain
472/// caller-owned. Use [`capture_command`] for the existing direct-child contract.
473/// # Errors
474/// Rejects invalid deadlines before modifying/spawning the command. Execution
475/// failures retain bounded output, observed status and separate cleanup errors.
476pub fn capture_group_command(
477    command: &mut Command,
478    limits: OutputLimits,
479) -> Result<CompletedExecution, ToolError> {
480    validate_limits(limits)?;
481    process::capture_command(command, limits, process::CleanupScope::ProcessGroup)
482        .map_err(|source| ToolError::Execution(Box::new(source)))
483}
484
485/// Successful leader disposition during [`communicate_child`].
486#[derive(Clone, Copy, Debug, Eq, PartialEq)]
487pub enum SuccessfulExit {
488    /// Clean according to child ownership before reaping, then drain captured pipes.
489    /// Direct-child ownership never signals descendants or other group members.
490    Cleanup,
491    /// Reserve the successful leader through IO completion and caller admission.
492    /// The caller must then explicitly wait, terminate or hand off the owner.
493    Retain,
494}
495
496/// Communicate once with a caller-spawned child using its configured IO.
497///
498/// Uses the capture engine to fairly drain available stdout/stderr pipes and
499/// write borrowed input without blocking reader/writer threads. The caller
500/// configures IO before [`crate::child::OwnedChild::spawn`]: absent output pipes
501/// are left alone (for example inherited progress output or files). Limits only
502/// apply to captured pipes. Do not take the child's pipes before this call.
503/// `Some(input)`, including empty input, requires piped stdin. `None` closes any
504/// available stdin pipe immediately; inherited stdin remains caller-selected.
505/// [`crate::child::OwnedChild::spawn_direct`] preserves process-group selection
506/// and limits cleanup to the direct child. Descendant-held pipes can still delay
507/// EOF; this function does not acquire descendant or terminal ownership.
508/// Stdin closes after input is written. An early broken pipe is accepted, like
509/// standard communicate semantics; command status and diagnostics remain primary.
510/// This does not guarantee the command consumed all input or applied its effects.
511///
512/// A selected deadline starts on entry, excluding earlier spawn time;
513/// `timeout: None` imposes no elapsed-time deadline. Output retention and
514/// cleanup remain active in either case. `cancelled` is
515/// polled between bounded IO steps and before returning success; it must return
516/// promptly. No signal handler, cancellation thread, retry or output decoding
517/// is installed. IO failure, cancellation, timeout and overflow
518/// close pipes and terminate/reap through the child's existing owner,
519/// retaining original failure and separate cleanup errors.
520///
521/// Completed zero/nonzero/signalled exits return a required status with all
522/// owned pipes closed. Nonzero/signalled leaders always undergo ordinary cleanup
523/// and reaping, including with [`SuccessfulExit::Retain`]; they cannot be handed off.
524/// With [`SuccessfulExit::Cleanup`],
525/// cleanup for the selected ownership scope and reaping occur as soon as child
526/// exit is observed. With [`SuccessfulExit::Retain`], the successful child remains
527/// reserved and its selected cleanup remains armed. After admitting output and checking
528/// application cancellation/deadlines, the caller must choose ordinary
529/// [`crate::child::OwnedChild::wait`] cleanup or explicit
530/// [`crate::child::OwnedChild::handoff`]. Rejected output can use `terminate`
531/// to retain cleanup evidence. Dropping the owner provides best-effort cleanup.
532/// This is not process-tree confinement or a descendant-exit barrier.
533///
534/// # Errors
535/// Invalid deadlines leave the already spawned child and its pipes untouched;
536/// the caller retains cleanup responsibility. An already terminating/reaped/transferred
537/// owner is rejected instead of reporting reserved success. Other failures return execution
538/// evidence after cleanup. Cleanup uses the policy chosen at child spawn and
539/// can exceed the communication deadline by its separate grace/reap allowance.
540pub fn communicate_child(
541    child: &mut crate::child::OwnedChild,
542    input: Option<&[u8]>,
543    limits: OutputLimits,
544    successful_exit: SuccessfulExit,
545    cancelled: impl FnMut() -> bool,
546) -> Result<CompletedExecution, ToolError> {
547    communicate_child_with_observer(child, input, limits, successful_exit, cancelled, |_, _| {
548        Ok(())
549    })
550}
551
552/// Communicate with an owned child while observing output bytes live.
553///
554/// Uses the same bounds, pipe handling and cleanup as [`communicate_child`].
555/// `output` receives nonempty borrowed chunks after retention, in order within
556/// each stream; chunk boundaries and ordering between streams are unspecified.
557/// With [`OutputLimit::Terminate`], only the retained prefix is reported before
558/// overflow fails. With [`OutputLimit::Truncate`], every drained byte is reported,
559/// while evidence retains only the selected prefix. A zero retained-byte budget
560/// can therefore forward output without storing it.
561/// Output is raw bytes, not necessarily complete lines or UTF-8.
562/// The observer returns `io::Result<()>`. Its first error stops observation,
563/// closes pipes and attempts cleanup, preserving the original sink error as
564/// [`ExecutionFailure::Observer`] alongside retained bytes and cleanup failures.
565/// A chunk is retained and any truncation recorded before observation; rejection
566/// takes precedence over a hard overflow detected in that same chunk.
567///
568/// Both callbacks run synchronously and must return promptly. `cancelled` also
569/// runs while the child is silent and may project caller-owned heartbeat events;
570/// no exact callback cadence is guaranteed. Callback time counts toward any
571/// selected communication deadline. A callback panic closes the pipes, attempts cleanup
572/// using the child's policy and resumes the original unwind, even if the caller
573/// catches it while retaining the child. Cleanup errors cannot be returned during
574/// unwind; any unreaped child remains owned for caller recovery.
575///
576/// Callers own event schemas, scheduling, output budgets and diagnostic rendering.
577/// Each stream explicitly selects hard overflow or truncation-and-continue.
578///
579/// # Panics
580/// Resumes callback panics after attempting cleanup with the selected policy.
581///
582/// # Errors
583/// Returns the same validation and execution errors as [`communicate_child`].
584pub fn communicate_child_with_observer(
585    child: &mut crate::child::OwnedChild,
586    input: Option<&[u8]>,
587    limits: OutputLimits,
588    successful_exit: SuccessfulExit,
589    cancelled: impl FnMut() -> bool,
590    output: impl FnMut(OutputStream, &[u8]) -> io::Result<()>,
591) -> Result<CompletedExecution, ToolError> {
592    validate_limits(limits)?;
593    process::communicate(child, input, limits, successful_exit, cancelled, output)
594        .map_err(|source| ToolError::Execution(Box::new(source)))
595}
596
597/// Complete a child after a caller has read control frames from its stdout.
598///
599/// Hand off the original buffered pipe without converting it to its raw inner
600/// pipe: unread prefetched bytes count against the same output budget as later
601/// bytes. `None` uses any stdout still held by the child, or captures no stdout
602/// if the caller consumed it completely. Stdin is closed; stderr is taken from
603/// the child and both streams use the existing nonblocking capture engine.
604/// No child is respawned and no retry occurs.
605///
606/// Unlike [`communicate_child`], a previously reaped/terminated child may be
607/// drained using its cached status; it is never signalled again. Transferred
608/// ownership refuses. Successful children use ordinary cleanup and cannot be
609/// handed off. Callers retain pipe provenance, protocol decoding, limits and
610/// cancellation. A selected timeout starts on entry; no default deadline is added.
611///
612/// # Errors
613/// Returns validation, capture and cleanup evidence as [`communicate_child`].
614/// Invalid limits do not touch the child; the passed reader is consumed/dropped.
615pub fn drain_child_output(
616    child: &mut crate::child::OwnedChild,
617    stdout: Option<std::io::BufReader<std::process::ChildStdout>>,
618    limits: OutputLimits,
619    cancelled: impl FnMut() -> bool,
620) -> Result<CompletedExecution, ToolError> {
621    validate_limits(limits)?;
622    process::drain_output(child, stdout, limits, cancelled)
623        .map_err(|source| ToolError::Execution(Box::new(source)))
624}
625
626impl fmt::Display for ToolError {
627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628        match self {
629            Self::InvalidInvocation(input) => write!(f, "invalid tool invocation: {input:?}"),
630            Self::Io(_) => f.write_str("tool filesystem inspection failed"),
631            Self::NotExecutable => f.write_str("tool file is not executable"),
632            Self::Artifact(source) => write!(f, "tool identity verification failed: {source}"),
633            Self::Execution(source) => source.fmt(f),
634            Self::VersionUtf8 { .. } => f.write_str("tool version output is not UTF-8"),
635            Self::VersionMismatch { .. } => f.write_str("tool version does not match authority"),
636        }
637    }
638}
639impl std::error::Error for ToolError {
640    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
641        match self {
642            Self::Io(source) => Some(source),
643            Self::Artifact(source) => Some(source),
644            Self::Execution(source) => Some(source.as_ref()),
645            Self::VersionUtf8 { source, .. } => Some(source),
646            _ => None,
647        }
648    }
649}
650
651/// An executable with retained byte and version identities.
652///
653/// [`Self::admit`] requires a consumer-supplied digest. [`Self::admit_version`]
654/// records the installed identity without authenticating it against a pin.
655/// [`Self::observe_version`] records both identities without an expected version.
656/// Every execution rechecks digest/permission before spawning. Consumers must
657/// exclude concurrent writers to the executable and its parent directories:
658/// filesystem checks and `exec` are separate operations. This is not a file
659/// capability or verification of dynamic libraries, interpreters, or descendants.
660pub struct AdmittedTool {
661    path: PathBuf,
662    identity: ArtifactIdentity,
663    executable_bytes: u64,
664    version_identity: String,
665    no_follow: bool,
666}
667
668impl AdmittedTool {
669    /// Admit exact executable bytes and require the selected version identity.
670    ///
671    /// `expected_version` is exact UTF-8 stdout after Unicode whitespace trimming.
672    ///
673    /// # Errors
674    /// Rejects invalid inputs, non-executable files, digest/size mismatch, process
675    /// failures, non-UTF-8 stdout, and a different successful version identity.
676    pub fn admit(
677        spec: &VersionSpec<'_>,
678        expected: Sha256Digest,
679        expected_version: &str,
680        context: &ExecutionContext<'_>,
681        limits: OutputLimits,
682    ) -> Result<Self, ToolError> {
683        Self::admit_observation(
684            spec,
685            Some(expected),
686            Some(expected_version),
687            context,
688            limits,
689            false,
690        )
691    }
692
693    /// Admit exact bytes without following the executable's final-component symlink.
694    ///
695    /// Performs one bounded no-follow hash before the version command. Parents
696    /// and concurrent writers remain caller-owned. The retained canonical path
697    /// also rejects final-component links during subsequent [`Self::run`] calls.
698    ///
699    /// # Errors
700    /// Returns the same admission failures as [`Self::admit`], additionally
701    /// refusing final-component symbolic links and special files before execution.
702    pub fn admit_no_follow(
703        spec: &VersionSpec<'_>,
704        expected: Sha256Digest,
705        expected_version: &str,
706        context: &ExecutionContext<'_>,
707        limits: OutputLimits,
708    ) -> Result<Self, ToolError> {
709        Self::admit_observation(
710            spec,
711            Some(expected),
712            Some(expected_version),
713            context,
714            limits,
715            true,
716        )
717    }
718
719    /// Admit an exact version and record the caller-trusted installed bytes.
720    ///
721    /// `expected_version` is exact UTF-8 stdout after Unicode whitespace trimming.
722    ///
723    /// For tools built locally, no portable published digest may exist. This
724    /// entry hashes the executable within the supplied budget before running
725    /// the version command. The resulting [`Self::identity`] is an observation,
726    /// not a trusted published pin. All later runs reject changed bytes using
727    /// the same verification and capture engine as [`Self::admit`].
728    ///
729    /// The caller must trust the installation before admission: the version
730    /// command executes those bytes. Exact version output does not establish
731    /// authenticity. No version ranges, tool installation or PATH search occur.
732    /// The caller must exclude concurrent executable/directory writers.
733    ///
734    /// # Errors
735    /// Rejects invalid inputs, non-executable or oversized files, process
736    /// failures, non-UTF-8 stdout and a different successful version identity.
737    pub fn admit_version(
738        spec: &VersionSpec<'_>,
739        expected_version: &str,
740        context: &ExecutionContext<'_>,
741        limits: OutputLimits,
742    ) -> Result<Self, ToolError> {
743        Self::admit_observation(spec, None, Some(expected_version), context, limits, false)
744    }
745
746    /// Record installed bytes and their version with one version invocation.
747    ///
748    /// This is suitable for provenance of a caller-trusted installation when no
749    /// expected version is selected. Hashing precedes version dispatch; later
750    /// runs recheck that byte identity. The complete UTF-8 version stdout must
751    /// be nonempty after trimming. It does not authenticate the installation.
752    /// Consumers must exclude concurrent executable/directory writers and own
753    /// trust, output budgets, deadlines and environment, as for [`Self::admit_version`].
754    ///
755    /// # Errors
756    /// Rejects invalid inputs, non-executable or oversized files, process
757    /// failures, truncated output, non-UTF-8 stdout and an empty version.
758    /// An empty observation returns [`ToolError::VersionMismatch`] with the
759    /// original capture, just as an unmatched expected version does.
760    pub fn observe_version(
761        spec: &VersionSpec<'_>,
762        context: &ExecutionContext<'_>,
763        limits: OutputLimits,
764    ) -> Result<Self, ToolError> {
765        Self::admit_observation(spec, None, None, context, limits, false)
766    }
767
768    fn admit_observation(
769        spec: &VersionSpec<'_>,
770        expected: Option<Sha256Digest>,
771        expected_version: Option<&str>,
772        context: &ExecutionContext<'_>,
773        limits: OutputLimits,
774        no_follow: bool,
775    ) -> Result<Self, ToolError> {
776        if !spec.executable.is_absolute() {
777            return Err(ToolError::InvalidInvocation(
778                InvalidInvocation::ExecutablePath,
779            ));
780        }
781        if expected_version.is_some_and(|version| version.is_empty() || version.trim() != version) {
782            return Err(ToolError::InvalidInvocation(
783                InvalidInvocation::VersionIdentity,
784            ));
785        }
786        validate_invocation(spec.version_arguments, context, limits)?;
787        let path = fs::canonicalize(spec.executable).map_err(ToolError::Io)?;
788        let identity = verify_executable(
789            if no_follow { spec.executable } else { &path },
790            spec.executable_bytes,
791            expected,
792            no_follow,
793        )?;
794        let evidence = process::capture(&path, spec.version_arguments, context, limits)
795            .map_err(|source| ToolError::Execution(Box::new(source)))?
796            .require_success()?
797            .require_complete()?;
798        let version = match std::str::from_utf8(&evidence.stdout) {
799            Ok(version) => version.trim(),
800            Err(source) => {
801                return Err(ToolError::VersionUtf8 {
802                    source,
803                    evidence: Box::new(evidence.into()),
804                });
805            }
806        };
807        if version.is_empty() || expected_version.is_some_and(|expected| version != expected) {
808            return Err(ToolError::VersionMismatch {
809                evidence: Box::new(evidence.into()),
810            });
811        }
812        Ok(Self {
813            path,
814            identity,
815            executable_bytes: spec.executable_bytes,
816            version_identity: version.to_owned(),
817            no_follow,
818        })
819    }
820
821    /// Canonical absolute path selected during admission.
822    #[must_use]
823    pub fn path(&self) -> &Path {
824        &self.path
825    }
826
827    /// Retained raw executable identity.
828    ///
829    /// With [`Self::admit_version`] or [`Self::observe_version`], this is an observed identity, not proof of
830    /// a published binary pin or trusted installation provenance.
831    #[must_use]
832    pub const fn identity(&self) -> ArtifactIdentity {
833        self.identity
834    }
835
836    /// Successfully observed, trimmed version identity.
837    #[must_use]
838    pub fn version_identity(&self) -> &str {
839        &self.version_identity
840    }
841
842    /// Run once with a cleared, explicitly supplied environment and null stdin.
843    ///
844    /// Stdout/stderr are drained fairly through nonblocking pipes without reader
845    /// threads. On overflow/deadline the direct child is killed and reaped; pipe
846    /// handles are closed without waiting for descendants to close their copies.
847    /// Descendant processes remain caller-owned. This must not be interpreted
848    /// as a rollback or safe automatic retry of a command with external effects.
849    /// Nonzero/signalled exits are completed results. Call
850    /// [`CompletedExecution::require_success`] before success-only interpretation.
851    ///
852    /// # Errors
853    /// Returns invalid-input or identity failures before execution, or an
854    /// execution failure retaining bounded prefixes and cleanup outcomes.
855    pub fn run(
856        &self,
857        arguments: &[OsString],
858        context: &ExecutionContext<'_>,
859        limits: OutputLimits,
860    ) -> Result<CompletedExecution, ToolError> {
861        validate_invocation(arguments, context, limits)?;
862        verify_executable(
863            &self.path,
864            self.executable_bytes,
865            Some(self.identity.sha256),
866            self.no_follow,
867        )?;
868        process::capture(&self.path, arguments, context, limits)
869            .map_err(|source| ToolError::Execution(Box::new(source)))
870    }
871}
872
873fn verify_executable(
874    path: &Path,
875    limit: u64,
876    expected: Option<Sha256Digest>,
877    no_follow: bool,
878) -> Result<ArtifactIdentity, ToolError> {
879    let (actual, metadata) = if no_follow {
880        hash_file_no_follow_with_metadata(path, limit)
881    } else {
882        hash_file_with_metadata(path, limit)
883    }
884    .map_err(ToolError::Artifact)?;
885    if let Some(expected) = expected {
886        actual.verify(expected).map_err(ToolError::Artifact)?;
887    }
888    if metadata.permissions().mode() & 0o111 == 0 {
889        return Err(ToolError::NotExecutable);
890    }
891    Ok(actual)
892}
893
894fn validate_invocation(
895    arguments: &[OsString],
896    context: &ExecutionContext<'_>,
897    limits: OutputLimits,
898) -> Result<(), ToolError> {
899    let reject = |input| ToolError::InvalidInvocation(input);
900    if !context.current_dir.is_absolute() {
901        return Err(reject(InvalidInvocation::WorkingDirectory));
902    }
903    validate_limits(limits)?;
904    for (index, argument) in arguments.iter().enumerate() {
905        if argument.as_bytes().contains(&0) {
906            return Err(reject(InvalidInvocation::Argument { index }));
907        }
908    }
909    for (index, (key, value)) in context.environment.iter().enumerate() {
910        if key.is_empty()
911            || key.as_bytes().iter().any(|byte| matches!(byte, b'=' | 0))
912            || context.environment[..index]
913                .iter()
914                .any(|(earlier, _)| earlier == key)
915        {
916            return Err(reject(InvalidInvocation::EnvironmentName { index }));
917        }
918        if value.as_bytes().contains(&0) {
919            return Err(reject(InvalidInvocation::EnvironmentValue { index }));
920        }
921    }
922    Ok(())
923}
924
925fn validate_limits(limits: OutputLimits) -> Result<(), ToolError> {
926    if limits.timeout.is_some_and(|timeout| {
927        timeout.is_zero() || std::time::Instant::now().checked_add(timeout).is_none()
928    }) {
929        return Err(ToolError::InvalidInvocation(InvalidInvocation::Deadline));
930    }
931    Ok(())
932}