Skip to main content

sysprims_timeout/
lib.rs

1//! sysprims-timeout: Process timeout with group-by-default tree management.
2//!
3//! This crate provides:
4//! - Process execution with timeout ([`run_with_timeout`])
5//! - Group-by-default semantics (cooperative process groups signaled on timeout)
6//! - Signal escalation (SIGTERM → SIGKILL after configurable delay)
7//! - Observable fallback status for tree-kill reliability
8//!
9//! # Group-by-Default
10//!
11//! When a command times out, the acquired process group or Windows Job Object
12//! is signaled, not just the direct child:
13//!
14//! - **Unix**: Creates a new process group; child is group leader
15//! - **Windows**: Creates a Job Object with `KILL_ON_JOB_CLOSE`
16//!
17//! This gives race-free group acquisition and signaling eligibility. It is not
18//! an OS-enforced promise that descendants cannot later leave the group.
19//!
20//! # Examples
21//!
22//! ```no_run
23//! use std::time::Duration;
24//! use sysprims_timeout::{run_with_timeout, TimeoutConfig, TimeoutOutcome};
25//!
26//! let result = run_with_timeout(
27//!     "sleep",
28//!     &["60"],
29//!     Duration::from_secs(5),
30//!     TimeoutConfig::default(),
31//! ).unwrap();
32//!
33//! match result {
34//!     TimeoutOutcome::Completed { exit_status } => {
35//!         println!("Command completed: {:?}", exit_status);
36//!     }
37//!     TimeoutOutcome::TimedOut { signal_sent, escalated, .. } => {
38//!         println!("Timed out, sent signal {}, escalated: {}", signal_sent, escalated);
39//!     }
40//! }
41//! ```
42
43use std::process::{Child, Command, ExitStatus};
44use std::time::Duration;
45
46use serde::{Deserialize, Serialize};
47use sysprims_core::schema::TERMINATE_TREE_RESULT_V1;
48use sysprims_core::time::now_rfc3339;
49use sysprims_core::{get_platform, SysprimsError, SysprimsResult};
50use sysprims_proc::wait_pid;
51
52pub mod managed;
53#[cfg(unix)]
54mod unix;
55#[cfg(windows)]
56mod windows;
57pub use managed::{
58    close as containment_close, identity as containment_identity, poll as containment_poll,
59    spawn as containment_spawn, terminate as containment_terminate, wait as containment_wait,
60    ManagedSnapshot, ManagedSpawnRequest,
61};
62
63// Re-export signal constants for convenience
64pub use sysprims_signal::{SIGKILL, SIGTERM};
65#[cfg(windows)]
66pub use windows::{PreparedWindowsJob, WindowsJobReceipt};
67
68/// Process grouping strategy.
69///
70/// Controls whether timeout creates a process group (Unix) or Job Object
71/// (Windows) to enable tree-kill on timeout.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
73#[serde(rename_all = "snake_case")]
74pub enum GroupingMode {
75    /// Create new process group (Unix) or Job Object (Windows).
76    /// Signal the acquired group/job on timeout. **This is the default.**
77    #[default]
78    GroupByDefault,
79
80    /// Run in foreground. Only kills direct child on timeout.
81    /// Use when the child must inherit the parent's process group.
82    Foreground,
83}
84
85/// Configuration for timeout execution.
86#[derive(Debug, Clone)]
87pub struct TimeoutConfig {
88    /// Initial signal to send on timeout.
89    ///
90    /// Default: `SIGTERM` (15)
91    pub signal: i32,
92
93    /// Delay before escalating to SIGKILL if process doesn't exit.
94    ///
95    /// Default: 10 seconds
96    pub kill_after: Duration,
97
98    /// Process grouping strategy.
99    ///
100    /// Default: `GroupByDefault`
101    pub grouping: GroupingMode,
102
103    /// Propagate child exit code when command completes normally.
104    ///
105    /// When `true`, the timeout exit code matches the child's exit code.
106    /// When `false`, successful completion returns exit code 0.
107    ///
108    /// Default: `false`
109    pub preserve_status: bool,
110}
111
112impl Default for TimeoutConfig {
113    fn default() -> Self {
114        Self {
115            signal: SIGTERM,
116            kill_after: Duration::from_secs(10),
117            grouping: GroupingMode::GroupByDefault,
118            preserve_status: false,
119        }
120    }
121}
122
123/// Reliability of tree-kill operation.
124///
125/// Distinguishes proven spawn-time acquisition, post-spawn containment with an
126/// escape window, and direct-child best effort.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
128#[serde(rename_all = "snake_case")]
129pub enum TreeKillReliability {
130    /// Spawn-time containment acquisition and group-signaling eligibility were
131    /// proven. On Unix, descendants can still leave a cooperative process
132    /// group later; this is not a non-escape guarantee.
133    Guaranteed,
134
135    /// A containment capability is owned, but it was attached after the child
136    /// started and descendants may have escaped before attachment completed.
137    Unproven,
138
139    /// Best-effort only. No owned, proven containment capability is retained;
140    /// coverage may be limited to the direct child.
141    BestEffort,
142}
143
144/// Strength of the acquired containment boundary.
145///
146/// This is independent of [`TreeKillReliability`]. Reliability describes when
147/// termination authority was acquired; boundary strength describes whether
148/// descendants are constrained by a cooperative group or a kernel-enforced
149/// non-breakaway Job.
150#[non_exhaustive]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
152#[serde(rename_all = "snake_case")]
153pub enum ContainmentBoundaryStrength {
154    /// The exact Windows child was assigned before first execution to an owned
155    /// Job configured without either breakaway mode.
156    KernelEnforcedJob,
157    /// A Unix session/process-group boundary. Descendants may later leave.
158    CooperativeGroup,
159    /// The stronger boundary property was not proven.
160    Unknown,
161}
162
163pub(crate) const MAX_COMPLETION_OBSERVED_PIDS: usize = 4096;
164pub(crate) const MAX_COMPLETION_OBSERVATION_RETRIES: usize = 3;
165
166/// Read-only mechanism used to observe containment membership.
167#[non_exhaustive]
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
169#[serde(rename_all = "snake_case")]
170pub enum ContainmentObservation {
171    /// Linux `/proc` process-group and session scan.
172    LinuxProcfsProcessGroup,
173    /// macOS libproc process-group scan.
174    MacosLibprocProcessGroup,
175    /// Windows Job process-ID-list query.
176    WindowsJobProcessIdList,
177    /// No trustworthy platform observation mechanism was available.
178    UnsupportedPlatform,
179}
180
181/// Point-in-time evidence observed after the final containment cleanup action.
182///
183/// This evidence is independent of leader reap and containment acquisition
184/// reliability. Survivor PIDs are evidence only: PID reuse makes them unsafe to
185/// pass to process-signaling APIs or treat as suggested cleanup targets.
186#[non_exhaustive]
187#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
188#[serde(tag = "status", rename_all = "snake_case")]
189pub enum ContainmentCompletionEvidence {
190    /// A complete supported observation found no live containment members.
191    Empty { observation: ContainmentObservation },
192    /// A complete supported observation found live containment members.
193    Survivors {
194        observation: ContainmentObservation,
195        observed_count: u32,
196        survivor_pids: Vec<u32>,
197    },
198    /// A complete, trustworthy observation was unavailable.
199    Unknown { observation: ContainmentObservation },
200}
201
202pub(crate) fn unknown_completion(
203    observation: ContainmentObservation,
204) -> ContainmentCompletionEvidence {
205    ContainmentCompletionEvidence::Unknown { observation }
206}
207
208pub(crate) fn completion_from_pids(
209    observation: ContainmentObservation,
210    mut pids: Vec<u32>,
211) -> ContainmentCompletionEvidence {
212    if pids.len() >= MAX_COMPLETION_OBSERVED_PIDS
213        || pids
214            .iter()
215            .any(|pid| *pid == 0 || *pid > sysprims_signal::MAX_SAFE_PID)
216    {
217        return unknown_completion(observation);
218    }
219
220    let observed_count = pids.len();
221    pids.sort_unstable();
222    pids.dedup();
223    if pids.len() != observed_count {
224        return unknown_completion(observation);
225    }
226    if pids.is_empty() {
227        ContainmentCompletionEvidence::Empty { observation }
228    } else {
229        ContainmentCompletionEvidence::Survivors {
230            observation,
231            observed_count: pids.len() as u32,
232            survivor_pids: pids,
233        }
234    }
235}
236
237impl TreeKillReliability {
238    pub fn as_str(self) -> &'static str {
239        match self {
240            Self::Guaranteed => "guaranteed",
241            Self::Unproven => "unproven",
242            Self::BestEffort => "best_effort",
243        }
244    }
245}
246
247impl ContainmentBoundaryStrength {
248    pub fn as_str(self) -> &'static str {
249        match self {
250            Self::KernelEnforcedJob => "kernel_enforced_job",
251            Self::CooperativeGroup => "cooperative_group",
252            Self::Unknown => "unknown",
253        }
254    }
255}
256
257/// Stable process evidence captured when containment is acquired.
258#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
259pub struct ContainmentIdentity {
260    pub pid: u32,
261    /// Zero only when a sealed same-spawn receipt is paired with an already
262    /// exited, unreaped child before live metadata can be captured.
263    pub start_time_unix_ms: u64,
264    /// Observational executable metadata captured when containment is acquired.
265    ///
266    /// Unix guards backed by a sealed same-spawn receipt allow this value to
267    /// change across `exec` and may leave it empty when it is unavailable.
268    /// Adopted guards require it to remain available and unchanged. It is also
269    /// empty for the receipt-bound fast-exit state described above.
270    pub exe_path: String,
271}
272
273/// Minimal owned-child contract used by [`ContainmentGuard`].
274///
275/// Consumers can wrap an external child type without exposing PTY handles or
276/// terminal data to sysprims. The adapter must retain exclusive reap ownership
277/// from receipt consumption through guard finalization; `process_id` must name
278/// that unreaped child for the adapter's lifetime.
279pub trait ContainmentChild {
280    fn process_id(&self) -> Option<u32>;
281    /// Poll and reap the child when it has exited.
282    fn try_wait(&mut self) -> std::io::Result<bool>;
283
284    #[cfg(windows)]
285    fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle>;
286}
287
288impl ContainmentChild for Child {
289    fn process_id(&self) -> Option<u32> {
290        Some(self.id())
291    }
292
293    fn try_wait(&mut self) -> std::io::Result<bool> {
294        Child::try_wait(self).map(|status| status.is_some())
295    }
296
297    #[cfg(windows)]
298    fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
299        use std::os::windows::io::AsRawHandle;
300        Some(self.as_raw_handle())
301    }
302}
303
304/// Error returned when containment cannot be acquired.
305///
306/// The child is returned so acquisition failure never silently loses the
307/// caller's only reap handle.
308pub struct ContainmentAdoptionError<C> {
309    pub error: SysprimsError,
310    pub child: C,
311}
312
313impl<C> std::fmt::Debug for ContainmentAdoptionError<C> {
314    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
315        formatter
316            .debug_struct("ContainmentAdoptionError")
317            .field("error", &self.error)
318            .finish_non_exhaustive()
319    }
320}
321
322impl<C> std::fmt::Display for ContainmentAdoptionError<C> {
323    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        self.error.fmt(formatter)
325    }
326}
327
328impl<C> std::error::Error for ContainmentAdoptionError<C> {}
329
330/// Error returned when an owned contained spawn cannot complete.
331#[derive(Debug)]
332pub enum ContainmentSpawnError {
333    Spawn(SysprimsError),
334    Adoption(SysprimsError),
335}
336
337impl std::fmt::Display for ContainmentSpawnError {
338    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339        match self {
340            Self::Spawn(error) => error.fmt(formatter),
341            Self::Adoption(error) => error.fmt(formatter),
342        }
343    }
344}
345
346impl std::error::Error for ContainmentSpawnError {}
347
348/// An owned, stateful containment capability and child lifecycle.
349///
350/// Termination and normal completion mutably borrow the guard and are one-shot.
351/// Dropping an active guard kills the contained tree and makes a bounded attempt
352/// to reap the child. The guard never reconstructs containment from a
353/// caller-supplied PID.
354pub struct ContainmentGuard<C: ContainmentChild> {
355    child: Option<C>,
356    identity: ContainmentIdentity,
357    reliability: TreeKillReliability,
358    boundary_strength: ContainmentBoundaryStrength,
359    finalized: bool,
360    #[cfg(unix)]
361    pgid: u32,
362    #[cfg(unix)]
363    session_id: u32,
364    #[cfg(unix)]
365    session_receipt: Option<sysprims_session::UnixSessionReceipt>,
366    #[cfg(windows)]
367    job: std::os::windows::io::OwnedHandle,
368}
369
370impl<C: ContainmentChild> ContainmentGuard<C> {
371    pub fn identity(&self) -> &ContainmentIdentity {
372        &self.identity
373    }
374
375    pub fn tree_kill_reliability(&self) -> TreeKillReliability {
376        self.reliability
377    }
378
379    pub fn boundary_strength(&self) -> ContainmentBoundaryStrength {
380        self.boundary_strength
381    }
382
383    /// Recover the child adapter after successful termination or completion.
384    pub fn into_child(mut self) -> Result<C, Self> {
385        if self.finalized {
386            Ok(self
387                .child
388                .take()
389                .expect("finalized guard retains its child"))
390        } else {
391            Err(self)
392        }
393    }
394
395    /// Finalize a normally exited child without surrendering containment early.
396    ///
397    /// This observes leader exit without reaping. When the leader has exited,
398    /// the method cleans any remaining descendants before reaping and returns
399    /// the resulting outcome. It returns `Ok(None)` while the leader is running.
400    pub fn try_complete(
401        &mut self,
402        config: TerminateTreeConfig,
403    ) -> SysprimsResult<Option<ContainmentOutcome>> {
404        if self.finalized {
405            return Err(SysprimsError::invalid_argument(
406                "containment guard has already been finalized",
407            ));
408        }
409
410        #[cfg(unix)]
411        if !unix::contained_child_has_exited(self)? {
412            return Ok(None);
413        }
414
415        #[cfg(windows)]
416        if !windows::contained_child_has_exited(self)? {
417            return Ok(None);
418        }
419
420        self.terminate(config).map(Some)
421    }
422
423    /// Terminate the owned containment once, preserving the child until reap.
424    pub fn terminate(&mut self, config: TerminateTreeConfig) -> SysprimsResult<ContainmentOutcome> {
425        if self.finalized {
426            return Err(SysprimsError::invalid_argument(
427                "containment guard has already been finalized",
428            ));
429        }
430
431        #[cfg(unix)]
432        return unix::terminate_contained_impl(self, config);
433
434        #[cfg(windows)]
435        return windows::terminate_contained_impl(self, config);
436    }
437}
438
439impl<C: ContainmentChild> Drop for ContainmentGuard<C> {
440    fn drop(&mut self) {
441        if self.finalized || self.child.is_none() {
442            return;
443        }
444
445        #[cfg(unix)]
446        unix::drop_contained_impl(self);
447
448        #[cfg(windows)]
449        windows::drop_contained_impl(self);
450    }
451}
452
453/// Result from terminating an owned containment guard.
454#[derive(Debug, Clone, Serialize)]
455pub struct ContainmentOutcome {
456    pub identity: ContainmentIdentity,
457    #[serde(skip_serializing_if = "Option::is_none")]
458    pub pgid: Option<u32>,
459    #[serde(skip_serializing_if = "Option::is_none")]
460    pub signal_sent: Option<i32>,
461    #[serde(skip_serializing_if = "Option::is_none")]
462    pub kill_signal: Option<i32>,
463    pub escalated: bool,
464    pub exited: bool,
465    pub timed_out: bool,
466    pub tree_kill_reliability: TreeKillReliability,
467    pub boundary_strength: ContainmentBoundaryStrength,
468    /// Point-in-time membership evidence collected before leader reap or Job release.
469    pub completion: ContainmentCompletionEvidence,
470    pub warnings: Vec<String>,
471}
472
473/// Adopt an already-running child into an owned containment guard.
474///
475/// Post-spawn adoption is reported as [`TreeKillReliability::Unproven`]
476/// because descendants may escape before acquisition completes.
477pub fn adopt_contained<C: ContainmentChild>(
478    child: C,
479) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
480    #[cfg(unix)]
481    return unix::adopt_contained_impl(child);
482
483    #[cfg(windows)]
484    return windows::adopt_contained_impl(child);
485}
486
487/// Consume a sealed same-spawn session receipt with its owned child.
488///
489/// This is the Unix entry point for an external spawner that installed
490/// [`sysprims_session::UnixSessionAcquisitionHook`] in place of its own
491/// `setsid`/`setpgid` acquisition. The receipt is destroyed on every failure,
492/// and the child is returned through [`ContainmentAdoptionError`].
493///
494/// # Safety
495///
496/// `child` must be the same spawned child that emitted `receipt`. The adapter
497/// must hold exclusive, unreaped ownership, keep `process_id()` stable, and
498/// perform no external wait or reap until the guard finalizes. Violating these
499/// requirements can let PID reuse redirect a group signal to an unrelated
500/// process. Runtime ownership and identity checks remain defense-in-depth.
501#[cfg(unix)]
502pub unsafe fn contain_acquired_session<C: ContainmentChild>(
503    child: C,
504    receipt: sysprims_session::UnixSessionReceipt,
505) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
506    unix::contain_acquired_session_impl(child, receipt)
507}
508
509/// Consume a sealed pre-execution Windows Job receipt with its owned child.
510///
511/// The receipt can only be produced by [`PreparedWindowsJob::assign_process`],
512/// which assigns and verifies the exact process in a non-breakaway Job before
513/// this transition. The child remains suspended until the adapter has received
514/// the guard and explicitly resumes its separately owned primary thread.
515///
516/// # Safety
517///
518/// `child` must own the exact process handle passed to
519/// [`PreparedWindowsJob::assign_process`]. The adapter must still own the
520/// corresponding suspended primary thread, must not have resumed it, and must
521/// transfer exclusive wait/reap authority to the returned guard.
522#[cfg(windows)]
523pub unsafe fn contain_acquired_windows_job<C: ContainmentChild>(
524    child: C,
525    receipt: WindowsJobReceipt,
526) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
527    windows::contain_acquired_windows_job_impl(child, receipt)
528}
529
530/// Spawn a standard-library child and return its owned containment guard.
531///
532/// Unix uses the same sealed spawn-time session receipt as
533/// [`contain_acquired_session`] and reports guaranteed acquisition/group
534/// signaling eligibility. Windows fails closed until a create-suspended Job
535/// assignment path is available; use [`adopt_contained`] for explicitly
536/// unproven adoption.
537pub fn spawn_contained(command: Command) -> Result<ContainmentGuard<Child>, ContainmentSpawnError> {
538    #[cfg(unix)]
539    return unix::spawn_contained_impl(command);
540
541    #[cfg(windows)]
542    return windows::spawn_contained_impl(command);
543}
544
545fn capture_containment_identity(pid: u32) -> SysprimsResult<ContainmentIdentity> {
546    capture_containment_identity_with_mode(pid, ContainmentIdentityValidation::Strict)
547}
548
549#[cfg(unix)]
550fn capture_receipt_bound_containment_identity(pid: u32) -> SysprimsResult<ContainmentIdentity> {
551    capture_containment_identity_with_mode(
552        pid,
553        ContainmentIdentityValidation::ReceiptBoundExecVolatile,
554    )
555}
556
557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558enum ContainmentIdentityValidation {
559    Strict,
560    #[cfg(unix)]
561    ReceiptBoundExecVolatile,
562}
563
564fn capture_containment_identity_with_mode(
565    pid: u32,
566    mode: ContainmentIdentityValidation,
567) -> SysprimsResult<ContainmentIdentity> {
568    if pid == 0 || pid > sysprims_signal::MAX_SAFE_PID {
569        return Err(SysprimsError::invalid_argument(format!(
570            "pid {pid} is outside the safe process identity range"
571        )));
572    }
573
574    let process = sysprims_proc::get_process(pid)?;
575    let start_time_unix_ms = process.start_time_unix_ms.ok_or_else(|| {
576        SysprimsError::system(
577            "process start time unavailable during containment acquisition",
578            0,
579        )
580    })?;
581    let exe_path = match (mode, process.exe_path.filter(|path| !path.is_empty())) {
582        (_, Some(path)) => path,
583        (ContainmentIdentityValidation::Strict, None) => {
584            return Err(SysprimsError::system(
585                "process executable unavailable during containment acquisition",
586                0,
587            ));
588        }
589        #[cfg(unix)]
590        (ContainmentIdentityValidation::ReceiptBoundExecVolatile, None) => String::new(),
591    };
592
593    Ok(ContainmentIdentity {
594        pid,
595        start_time_unix_ms,
596        exe_path,
597    })
598}
599
600#[cfg(unix)]
601fn verify_containment_identity(
602    expected: &ContainmentIdentity,
603    mode: ContainmentIdentityValidation,
604) -> SysprimsResult<bool> {
605    let process = match sysprims_proc::get_process(expected.pid) {
606        Ok(process) => process,
607        Err(SysprimsError::NotFound { .. } | SysprimsError::PermissionDenied { .. }) => {
608            return Ok(false);
609        }
610        Err(error) => return Err(error),
611    };
612
613    verify_containment_identity_observation(
614        expected,
615        process.start_time_unix_ms,
616        process.exe_path.as_deref(),
617        mode,
618    )
619}
620
621#[cfg(unix)]
622fn verify_containment_identity_observation(
623    expected: &ContainmentIdentity,
624    actual_start_time_unix_ms: Option<u64>,
625    actual_exe_path: Option<&str>,
626    mode: ContainmentIdentityValidation,
627) -> SysprimsResult<bool> {
628    if actual_start_time_unix_ms.is_some_and(|actual| actual != expected.start_time_unix_ms) {
629        return Err(SysprimsError::invalid_argument(
630            "process identity changed; refusing containment operation",
631        ));
632    }
633
634    match mode {
635        ContainmentIdentityValidation::Strict => {
636            if actual_exe_path.is_some_and(|actual| actual != expected.exe_path) {
637                return Err(SysprimsError::invalid_argument(
638                    "process identity changed; refusing containment operation",
639                ));
640            }
641            Ok(actual_start_time_unix_ms.is_some() && actual_exe_path.is_some())
642        }
643        ContainmentIdentityValidation::ReceiptBoundExecVolatile => {
644            Ok(actual_start_time_unix_ms.is_some())
645        }
646    }
647}
648
649// =============================================================================
650// Terminate Tree (PID-based)
651// =============================================================================
652
653/// Configuration for PID-based terminate-tree.
654///
655/// This is intentionally small and conservative; higher-level spawn-in-group
656/// APIs can provide stronger guarantees.
657#[derive(Debug, Clone, Deserialize)]
658#[serde(deny_unknown_fields)]
659pub struct TerminateTreeConfig {
660    /// Timeout before escalation.
661    #[serde(default = "default_grace_timeout_ms")]
662    pub grace_timeout_ms: u64,
663
664    /// Timeout to wait after escalation signal.
665    #[serde(default = "default_kill_timeout_ms")]
666    pub kill_timeout_ms: u64,
667
668    /// Signal to send first (default SIGTERM).
669    #[serde(default = "default_grace_signal")]
670    pub signal: i32,
671
672    /// Signal to send on escalation (default SIGKILL).
673    #[serde(default = "default_kill_signal")]
674    pub kill_signal: i32,
675}
676
677fn default_grace_timeout_ms() -> u64 {
678    10_000
679}
680
681fn default_kill_timeout_ms() -> u64 {
682    2_000
683}
684
685fn default_grace_signal() -> i32 {
686    SIGTERM
687}
688
689fn default_kill_signal() -> i32 {
690    SIGKILL
691}
692
693impl Default for TerminateTreeConfig {
694    fn default() -> Self {
695        Self {
696            grace_timeout_ms: default_grace_timeout_ms(),
697            kill_timeout_ms: default_kill_timeout_ms(),
698            signal: default_grace_signal(),
699            kill_signal: default_kill_signal(),
700        }
701    }
702}
703
704#[derive(Debug, Clone, Serialize)]
705pub struct TerminateTreeResult {
706    pub schema_id: &'static str,
707    pub timestamp: String,
708    pub platform: &'static str,
709    pub pid: u32,
710
711    #[serde(skip_serializing_if = "Option::is_none")]
712    pub pgid: Option<u32>,
713
714    pub signal_sent: i32,
715    #[serde(skip_serializing_if = "Option::is_none")]
716    pub kill_signal: Option<i32>,
717    pub escalated: bool,
718    pub exited: bool,
719    pub timed_out: bool,
720    pub tree_kill_reliability: String,
721    pub warnings: Vec<String>,
722}
723
724// =============================================================================
725// Spawn In Group / Job
726// =============================================================================
727
728/// Configuration for [`spawn_in_group`].
729#[derive(Debug, Clone, Deserialize)]
730#[serde(deny_unknown_fields)]
731pub struct SpawnInGroupConfig {
732    /// argv[0] is the command, argv[1..] are args.
733    pub argv: Vec<String>,
734
735    /// Optional working directory.
736    #[serde(default)]
737    pub cwd: Option<String>,
738
739    /// Environment variable overrides/additions.
740    ///
741    /// By default the child inherits the parent's environment.
742    #[serde(default)]
743    pub env: Option<std::collections::BTreeMap<String, String>>,
744}
745
746#[derive(Debug, Clone, Serialize)]
747pub struct SpawnInGroupResult {
748    pub schema_id: &'static str,
749    pub timestamp: String,
750    pub platform: &'static str,
751    pub pid: u32,
752
753    #[serde(skip_serializing_if = "Option::is_none")]
754    pub pgid: Option<u32>,
755
756    pub tree_kill_reliability: String,
757    pub warnings: Vec<String>,
758}
759
760/// Spawn a process in a new process group on Unix.
761///
762/// Use this when you would otherwise shell out to `setsid`/wrapper scripts to
763/// make jobs kill-tree safe.
764///
765/// This PID-returning compatibility API cannot retain the owned child and
766/// sealed receipt required for [`TreeKillReliability::Guaranteed`]. Unix
767/// therefore reports `best_effort`; Windows fails closed because it cannot
768/// retain an owned Job handle. Use [`spawn_contained`] instead.
769///
770/// # Examples
771///
772/// ```rust,no_run
773/// use sysprims_timeout::{spawn_in_group, SpawnInGroupConfig};
774///
775/// // Replaces: setsid sleep 5
776/// let result = spawn_in_group(SpawnInGroupConfig {
777///     argv: vec!["sleep".into(), "5".into()],
778///     cwd: None,
779///     env: None,
780/// })
781/// .unwrap();
782/// println!("spawned pid: {}", result.pid);
783/// ```
784pub fn spawn_in_group(config: SpawnInGroupConfig) -> SysprimsResult<SpawnInGroupResult> {
785    if config.argv.is_empty() {
786        return Err(SysprimsError::invalid_argument("argv must not be empty"));
787    }
788
789    #[cfg(unix)]
790    return unix::spawn_in_group_impl(config);
791
792    #[cfg(windows)]
793    return windows::spawn_in_group_impl(config);
794}
795
796// Timestamp generation consolidated in sysprims_core::time::now_rfc3339()
797
798/// Terminate a process by PID with escalation.
799///
800/// This compatibility API has no owned child or sealed containment receipt, so
801/// it signals only the supplied PID and always reports `best_effort`. Use an
802/// owned [`ContainmentGuard`] for process-group or Job Object termination.
803///
804/// # Examples
805///
806/// ```rust,no_run
807/// use sysprims_timeout::{terminate_tree, TerminateTreeConfig};
808///
809/// // Replaces: kill -TERM 1234; sleep 2; kill -KILL 1234
810/// let result = terminate_tree(1234, TerminateTreeConfig::default()).unwrap();
811/// println!("exited={} timed_out={}", result.exited, result.timed_out);
812/// ```
813pub fn terminate_tree(
814    pid: u32,
815    config: TerminateTreeConfig,
816) -> SysprimsResult<TerminateTreeResult> {
817    if pid == 0 {
818        return Err(SysprimsError::invalid_argument("pid must be > 0"));
819    }
820
821    // Defense in depth: avoid unsafe casts on Unix.
822    // See ADR-0011 (PID Validation Safety).
823    if pid > sysprims_signal::MAX_SAFE_PID {
824        return Err(SysprimsError::invalid_argument(format!(
825            "pid {} exceeds maximum safe value {}",
826            pid,
827            sysprims_signal::MAX_SAFE_PID
828        )));
829    }
830
831    let mut warnings: Vec<String> = Vec::new();
832    let pgid: Option<u32> = None;
833    let reliability = TreeKillReliability::BestEffort;
834
835    #[cfg(windows)]
836    warnings.push(
837        "Windows PID termination is best-effort; use an owned containment guard for Job Objects"
838            .to_string(),
839    );
840    #[cfg(unix)]
841    warnings.push(
842        "PID-only termination has no sealed group capability; signaling the target PID only"
843            .to_string(),
844    );
845
846    // Step 1: send graceful signal
847    sysprims_signal::kill(pid, config.signal)?;
848
849    // Step 2: wait for exit
850    let grace = Duration::from_millis(config.grace_timeout_ms);
851    let grace_wait = wait_pid(pid, grace)?;
852    if grace_wait.exited {
853        return Ok(TerminateTreeResult {
854            schema_id: TERMINATE_TREE_RESULT_V1,
855            timestamp: now_rfc3339(),
856            platform: get_platform(),
857            pid,
858            pgid,
859            signal_sent: config.signal,
860            kill_signal: None,
861            escalated: false,
862            exited: true,
863            timed_out: false,
864            tree_kill_reliability: reliability.as_str().to_string(),
865            warnings,
866        });
867    }
868
869    // Step 3: escalate
870    sysprims_signal::kill(pid, config.kill_signal)?;
871
872    let kill_wait = wait_pid(pid, Duration::from_millis(config.kill_timeout_ms))?;
873    let mut exited = kill_wait.exited;
874    let mut timed_out = kill_wait.timed_out;
875
876    // If we timed out, attempt one final best-effort confirmation.
877    // On some platforms/permission contexts, a process may become unobservable
878    // (or a zombie) even after it has exited.
879    if timed_out {
880        match sysprims_proc::get_process(pid) {
881            Ok(_) => {
882                // Still observable -> treat as still running.
883            }
884            Err(SysprimsError::NotFound { .. }) => {
885                exited = true;
886                timed_out = false;
887                warnings.push("PID no longer found after timeout; treating as exited".to_string());
888            }
889            Err(SysprimsError::PermissionDenied { .. }) => {
890                warnings.push("Permission denied while confirming exit after timeout".to_string());
891            }
892            Err(e) => {
893                warnings.push(format!("Failed to confirm exit after timeout: {}", e));
894            }
895        }
896    }
897
898    Ok(TerminateTreeResult {
899        schema_id: TERMINATE_TREE_RESULT_V1,
900        timestamp: now_rfc3339(),
901        platform: get_platform(),
902        pid,
903        pgid,
904        signal_sent: config.signal,
905        kill_signal: Some(config.kill_signal),
906        escalated: true,
907        exited,
908        timed_out,
909        tree_kill_reliability: reliability.as_str().to_string(),
910        warnings,
911    })
912}
913
914/// Outcome of timeout execution.
915#[derive(Debug)]
916pub enum TimeoutOutcome {
917    /// Command completed within timeout.
918    Completed {
919        /// Exit status of the child process.
920        exit_status: ExitStatus,
921    },
922
923    /// Command timed out and was killed.
924    TimedOut {
925        /// Signal that was sent to terminate the process.
926        signal_sent: i32,
927
928        /// Whether escalation to SIGKILL occurred.
929        ///
930        /// `true` if the process didn't exit after receiving `signal_sent`
931        /// and had to be forcefully killed with SIGKILL.
932        escalated: bool,
933
934        /// Whether tree-kill was reliable.
935        ///
936        /// `Guaranteed` when spawn-time acquisition and group/job signaling
937        /// eligibility were proven.
938        /// `BestEffort` if only the direct child was killed.
939        tree_kill_reliability: TreeKillReliability,
940    },
941}
942
943/// Run a command with timeout.
944///
945/// Spawns the command and waits for it to complete or timeout. If the command
946/// times out, the acquired process group or Job is signaled (when using
947/// `GroupByDefault`). Cooperative descendants in that containment are targeted;
948/// Unix descendants can still leave a process group later.
949///
950/// # Arguments
951///
952/// * `command` - Command to execute (path or name in PATH)
953/// * `args` - Command arguments
954/// * `timeout` - Maximum duration to wait for command completion
955/// * `config` - Timeout configuration (signal, escalation, grouping)
956///
957/// # Returns
958///
959/// * `Ok(TimeoutOutcome::Completed { .. })` - Command finished within timeout
960/// * `Ok(TimeoutOutcome::TimedOut { .. })` - Command was killed due to timeout
961/// * `Err(SysprimsError)` - Failed to spawn or fatal error
962///
963/// # Examples
964///
965/// ```no_run
966/// use std::time::Duration;
967/// use sysprims_timeout::{run_with_timeout, TimeoutConfig};
968///
969/// // Replaces: timeout 300s make build
970/// let result = run_with_timeout(
971///     "make",
972///     &["build"],
973///     Duration::from_secs(300),
974///     TimeoutConfig::default(),
975/// );
976/// ```
977pub fn run_with_timeout(
978    command: &str,
979    args: &[&str],
980    timeout: Duration,
981    config: TimeoutConfig,
982) -> SysprimsResult<TimeoutOutcome> {
983    #[cfg(unix)]
984    return unix::run_with_timeout_impl(command, args, timeout, &config);
985
986    #[cfg(windows)]
987    return windows::run_with_timeout_impl(command, args, timeout, &config);
988}
989
990/// Run a command with timeout using default configuration.
991///
992/// Equivalent to `run_with_timeout(command, args, timeout, TimeoutConfig::default())`.
993///
994/// Default configuration:
995/// - Signal: SIGTERM
996/// - Kill after: 10 seconds
997/// - Grouping: GroupByDefault
998/// - Preserve status: false
999///
1000/// # Examples
1001///
1002/// ```rust,no_run
1003/// use std::time::Duration;
1004/// use sysprims_timeout::run_with_timeout_default;
1005///
1006/// // Replaces: timeout 2s sleep 1
1007/// let _ = run_with_timeout_default("sleep", &["1"], Duration::from_secs(2));
1008/// ```
1009pub fn run_with_timeout_default(
1010    command: &str,
1011    args: &[&str],
1012    timeout: Duration,
1013) -> SysprimsResult<TimeoutOutcome> {
1014    run_with_timeout(command, args, timeout, TimeoutConfig::default())
1015}
1016
1017#[cfg(test)]
1018mod tests {
1019    use super::*;
1020    use std::process::{Command, Stdio};
1021
1022    struct ChildWithoutPid;
1023
1024    impl ContainmentChild for ChildWithoutPid {
1025        fn process_id(&self) -> Option<u32> {
1026            None
1027        }
1028
1029        fn try_wait(&mut self) -> std::io::Result<bool> {
1030            Ok(false)
1031        }
1032
1033        #[cfg(windows)]
1034        fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
1035            None
1036        }
1037    }
1038
1039    #[test]
1040    fn default_config_uses_sigterm() {
1041        let config = TimeoutConfig::default();
1042        assert_eq!(config.signal, SIGTERM);
1043    }
1044
1045    #[test]
1046    fn default_config_uses_group_by_default() {
1047        let config = TimeoutConfig::default();
1048        assert_eq!(config.grouping, GroupingMode::GroupByDefault);
1049    }
1050
1051    #[test]
1052    fn default_config_kill_after_is_10_seconds() {
1053        let config = TimeoutConfig::default();
1054        assert_eq!(config.kill_after, Duration::from_secs(10));
1055    }
1056
1057    #[test]
1058    fn default_config_does_not_preserve_status() {
1059        let config = TimeoutConfig::default();
1060        assert!(!config.preserve_status);
1061    }
1062
1063    #[test]
1064    fn reliability_strings_include_unproven() {
1065        assert_eq!(TreeKillReliability::Guaranteed.as_str(), "guaranteed");
1066        assert_eq!(TreeKillReliability::Unproven.as_str(), "unproven");
1067        assert_eq!(TreeKillReliability::BestEffort.as_str(), "best_effort");
1068    }
1069
1070    #[test]
1071    fn boundary_strength_strings_are_independent() {
1072        assert_eq!(
1073            ContainmentBoundaryStrength::KernelEnforcedJob.as_str(),
1074            "kernel_enforced_job"
1075        );
1076        assert_eq!(
1077            ContainmentBoundaryStrength::CooperativeGroup.as_str(),
1078            "cooperative_group"
1079        );
1080        assert_eq!(ContainmentBoundaryStrength::Unknown.as_str(), "unknown");
1081    }
1082
1083    #[test]
1084    #[cfg(unix)]
1085    fn receipt_bound_identity_treats_executable_as_observational() {
1086        let expected = ContainmentIdentity {
1087            pid: 42,
1088            start_time_unix_ms: 1_000,
1089            exe_path: "/before-exec".to_string(),
1090        };
1091
1092        assert!(verify_containment_identity_observation(
1093            &expected,
1094            Some(1_000),
1095            Some("/after-two-execs"),
1096            ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1097        )
1098        .unwrap());
1099        assert!(verify_containment_identity_observation(
1100            &expected,
1101            Some(1_000),
1102            None,
1103            ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1104        )
1105        .unwrap());
1106    }
1107
1108    #[test]
1109    #[cfg(unix)]
1110    fn receipt_bound_identity_requires_matching_observable_start_time() {
1111        let expected = ContainmentIdentity {
1112            pid: 42,
1113            start_time_unix_ms: 1_000,
1114            exe_path: "/before-exec".to_string(),
1115        };
1116
1117        assert!(!verify_containment_identity_observation(
1118            &expected,
1119            None,
1120            Some("/after-exec"),
1121            ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1122        )
1123        .unwrap());
1124        assert!(matches!(
1125            verify_containment_identity_observation(
1126                &expected,
1127                Some(2_000),
1128                Some("/after-exec"),
1129                ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1130            ),
1131            Err(SysprimsError::InvalidArgument { .. })
1132        ));
1133    }
1134
1135    #[test]
1136    #[cfg(unix)]
1137    fn adopted_identity_keeps_strict_executable_validation() {
1138        let expected = ContainmentIdentity {
1139            pid: 42,
1140            start_time_unix_ms: 1_000,
1141            exe_path: "/before-exec".to_string(),
1142        };
1143
1144        assert!(matches!(
1145            verify_containment_identity_observation(
1146                &expected,
1147                Some(1_000),
1148                Some("/after-exec"),
1149                ContainmentIdentityValidation::Strict,
1150            ),
1151            Err(SysprimsError::InvalidArgument { .. })
1152        ));
1153        assert!(!verify_containment_identity_observation(
1154            &expected,
1155            Some(1_000),
1156            None,
1157            ContainmentIdentityValidation::Strict,
1158        )
1159        .unwrap());
1160    }
1161
1162    #[test]
1163    fn completion_evidence_sorts_unique_safe_pids() {
1164        assert_eq!(
1165            completion_from_pids(
1166                ContainmentObservation::LinuxProcfsProcessGroup,
1167                vec![42, 7, 19],
1168            ),
1169            ContainmentCompletionEvidence::Survivors {
1170                observation: ContainmentObservation::LinuxProcfsProcessGroup,
1171                observed_count: 3,
1172                survivor_pids: vec![7, 19, 42],
1173            }
1174        );
1175    }
1176
1177    #[test]
1178    fn duplicate_completion_evidence_is_unknown() {
1179        assert_eq!(
1180            completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, vec![7, 7],),
1181            ContainmentCompletionEvidence::Unknown {
1182                observation: ContainmentObservation::LinuxProcfsProcessGroup,
1183            }
1184        );
1185    }
1186
1187    #[test]
1188    fn completion_evidence_at_pid_limit_is_unknown() {
1189        let pids = (2..2 + MAX_COMPLETION_OBSERVED_PIDS as u32).collect();
1190        assert_eq!(
1191            completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, pids),
1192            ContainmentCompletionEvidence::Unknown {
1193                observation: ContainmentObservation::LinuxProcfsProcessGroup,
1194            }
1195        );
1196    }
1197
1198    #[test]
1199    fn completion_evidence_serializes_as_a_tagged_receipt() {
1200        let value = serde_json::to_value(ContainmentCompletionEvidence::Survivors {
1201            observation: ContainmentObservation::MacosLibprocProcessGroup,
1202            observed_count: 2,
1203            survivor_pids: vec![17, 23],
1204        })
1205        .expect("completion evidence should serialize");
1206        assert_eq!(
1207            value,
1208            serde_json::json!({
1209                "status": "survivors",
1210                "observation": "macos_libproc_process_group",
1211                "observed_count": 2,
1212                "survivor_pids": [17, 23],
1213            })
1214        );
1215    }
1216
1217    #[test]
1218    fn failed_adoption_returns_child_ownership() {
1219        let error = match adopt_contained(ChildWithoutPid) {
1220            Ok(_) => panic!("adoption without a pid must fail"),
1221            Err(error) => error,
1222        };
1223        assert!(matches!(error.error, SysprimsError::InvalidArgument { .. }));
1224        assert!(error.child.process_id().is_none());
1225    }
1226
1227    #[test]
1228    fn terminate_tree_rejects_pid_zero() {
1229        let err = terminate_tree(0, TerminateTreeConfig::default()).unwrap_err();
1230        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
1231    }
1232
1233    #[test]
1234    #[cfg(unix)]
1235    fn terminate_tree_kills_spawned_child() {
1236        // SAFETY: We spawn this process ourselves and control its PID.
1237        let mut child = Command::new("sleep")
1238            .arg("60")
1239            .stdin(Stdio::null())
1240            .stdout(Stdio::null())
1241            .stderr(Stdio::null())
1242            .spawn()
1243            .expect("Failed to spawn sleep process");
1244
1245        let pid = child.id();
1246        let result = terminate_tree(
1247            pid,
1248            TerminateTreeConfig {
1249                grace_timeout_ms: 100,
1250                kill_timeout_ms: 5000,
1251                ..TerminateTreeConfig::default()
1252            },
1253        )
1254        .expect("terminate_tree should succeed");
1255
1256        assert_eq!(result.pid, pid);
1257        assert!(
1258            result.exited,
1259            "expected child to be exited, got: {result:?}"
1260        );
1261        assert!(!result.timed_out, "unexpected timeout: {result:?}");
1262        assert_eq!(result.tree_kill_reliability, "best_effort");
1263        assert_eq!(result.pgid, None);
1264
1265        let _ = child.wait();
1266    }
1267
1268    #[test]
1269    #[cfg(windows)]
1270    fn terminate_tree_kills_spawned_child() {
1271        // SAFETY: We spawn this process ourselves and control its PID.
1272        let mut child = Command::new("cmd")
1273            .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
1274            .stdin(Stdio::null())
1275            .stdout(Stdio::null())
1276            .stderr(Stdio::null())
1277            .spawn()
1278            .expect("Failed to spawn ping sleep process");
1279
1280        let pid = child.id();
1281        let result = terminate_tree(
1282            pid,
1283            TerminateTreeConfig {
1284                grace_timeout_ms: 100,
1285                kill_timeout_ms: 5000,
1286                ..TerminateTreeConfig::default()
1287            },
1288        )
1289        .expect("terminate_tree should succeed");
1290
1291        assert_eq!(result.pid, pid);
1292        let _ = child.wait();
1293    }
1294}