1use 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
63pub use sysprims_signal::{SIGKILL, SIGTERM};
65#[cfg(windows)]
66pub use windows::{PreparedWindowsJob, WindowsJobReceipt};
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
73#[serde(rename_all = "snake_case")]
74pub enum GroupingMode {
75 #[default]
78 GroupByDefault,
79
80 Foreground,
83}
84
85#[derive(Debug, Clone)]
87pub struct TimeoutConfig {
88 pub signal: i32,
92
93 pub kill_after: Duration,
97
98 pub grouping: GroupingMode,
102
103 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
128#[serde(rename_all = "snake_case")]
129pub enum TreeKillReliability {
130 Guaranteed,
134
135 Unproven,
138
139 BestEffort,
142}
143
144#[non_exhaustive]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
152#[serde(rename_all = "snake_case")]
153pub enum ContainmentBoundaryStrength {
154 KernelEnforcedJob,
157 CooperativeGroup,
159 Unknown,
161}
162
163pub(crate) const MAX_COMPLETION_OBSERVED_PIDS: usize = 4096;
164pub(crate) const MAX_COMPLETION_OBSERVATION_RETRIES: usize = 3;
165
166#[non_exhaustive]
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
169#[serde(rename_all = "snake_case")]
170pub enum ContainmentObservation {
171 LinuxProcfsProcessGroup,
173 MacosLibprocProcessGroup,
175 WindowsJobProcessIdList,
177 UnsupportedPlatform,
179}
180
181#[non_exhaustive]
187#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
188#[serde(tag = "status", rename_all = "snake_case")]
189pub enum ContainmentCompletionEvidence {
190 Empty { observation: ContainmentObservation },
192 Survivors {
194 observation: ContainmentObservation,
195 observed_count: u32,
196 survivor_pids: Vec<u32>,
197 },
198 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
259pub struct ContainmentIdentity {
260 pub pid: u32,
261 pub start_time_unix_ms: u64,
264 pub exe_path: String,
271}
272
273pub trait ContainmentChild {
280 fn process_id(&self) -> Option<u32>;
281 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
304pub 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#[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
348pub 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 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 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 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#[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 pub completion: ContainmentCompletionEvidence,
470 pub warnings: Vec<String>,
471}
472
473pub 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#[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#[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
530pub 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#[derive(Debug, Clone, Deserialize)]
658#[serde(deny_unknown_fields)]
659pub struct TerminateTreeConfig {
660 #[serde(default = "default_grace_timeout_ms")]
662 pub grace_timeout_ms: u64,
663
664 #[serde(default = "default_kill_timeout_ms")]
666 pub kill_timeout_ms: u64,
667
668 #[serde(default = "default_grace_signal")]
670 pub signal: i32,
671
672 #[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#[derive(Debug, Clone, Deserialize)]
730#[serde(deny_unknown_fields)]
731pub struct SpawnInGroupConfig {
732 pub argv: Vec<String>,
734
735 #[serde(default)]
737 pub cwd: Option<String>,
738
739 #[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
760pub 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 if config.argv[0].is_empty() {
789 return Err(SysprimsError::invalid_argument(
790 "argv[0] (command) must not be empty",
791 ));
792 }
793
794 #[cfg(unix)]
795 return unix::spawn_in_group_impl(config);
796
797 #[cfg(windows)]
798 return windows::spawn_in_group_impl(config);
799}
800
801pub fn terminate_tree(
819 pid: u32,
820 config: TerminateTreeConfig,
821) -> SysprimsResult<TerminateTreeResult> {
822 if pid == 0 {
823 return Err(SysprimsError::invalid_argument("pid must be > 0"));
824 }
825
826 if pid > sysprims_signal::MAX_SAFE_PID {
829 return Err(SysprimsError::invalid_argument(format!(
830 "pid {} exceeds maximum safe value {}",
831 pid,
832 sysprims_signal::MAX_SAFE_PID
833 )));
834 }
835
836 managed::validate_terminate_tree_config(&config)?;
837
838 let mut warnings: Vec<String> = Vec::new();
839 let pgid: Option<u32> = None;
840 let reliability = TreeKillReliability::BestEffort;
841
842 #[cfg(windows)]
843 warnings.push(
844 "Windows PID termination is best-effort; use an owned containment guard for Job Objects"
845 .to_string(),
846 );
847 #[cfg(unix)]
848 warnings.push(
849 "PID-only termination has no sealed group capability; signaling the target PID only"
850 .to_string(),
851 );
852
853 sysprims_signal::kill(pid, config.signal)?;
855
856 let grace = Duration::from_millis(config.grace_timeout_ms);
858 let grace_wait = wait_pid(pid, grace)?;
859 if grace_wait.exited {
860 return Ok(TerminateTreeResult {
861 schema_id: TERMINATE_TREE_RESULT_V1,
862 timestamp: now_rfc3339(),
863 platform: get_platform(),
864 pid,
865 pgid,
866 signal_sent: config.signal,
867 kill_signal: None,
868 escalated: false,
869 exited: true,
870 timed_out: false,
871 tree_kill_reliability: reliability.as_str().to_string(),
872 warnings,
873 });
874 }
875
876 sysprims_signal::kill(pid, config.kill_signal)?;
878
879 let kill_wait = wait_pid(pid, Duration::from_millis(config.kill_timeout_ms))?;
880 let mut exited = kill_wait.exited;
881 let mut timed_out = kill_wait.timed_out;
882
883 if timed_out {
887 match sysprims_proc::get_process(pid) {
888 Ok(_) => {
889 }
891 Err(SysprimsError::NotFound { .. }) => {
892 exited = true;
893 timed_out = false;
894 warnings.push("PID no longer found after timeout; treating as exited".to_string());
895 }
896 Err(SysprimsError::PermissionDenied { .. }) => {
897 warnings.push("Permission denied while confirming exit after timeout".to_string());
898 }
899 Err(e) => {
900 warnings.push(format!("Failed to confirm exit after timeout: {}", e));
901 }
902 }
903 }
904
905 Ok(TerminateTreeResult {
906 schema_id: TERMINATE_TREE_RESULT_V1,
907 timestamp: now_rfc3339(),
908 platform: get_platform(),
909 pid,
910 pgid,
911 signal_sent: config.signal,
912 kill_signal: Some(config.kill_signal),
913 escalated: true,
914 exited,
915 timed_out,
916 tree_kill_reliability: reliability.as_str().to_string(),
917 warnings,
918 })
919}
920
921#[derive(Debug)]
923pub enum TimeoutOutcome {
924 Completed {
926 exit_status: ExitStatus,
928 },
929
930 TimedOut {
932 signal_sent: i32,
934
935 escalated: bool,
940
941 tree_kill_reliability: TreeKillReliability,
947 },
948}
949
950pub fn run_with_timeout(
985 command: &str,
986 args: &[&str],
987 timeout: Duration,
988 config: TimeoutConfig,
989) -> SysprimsResult<TimeoutOutcome> {
990 #[cfg(unix)]
991 return unix::run_with_timeout_impl(command, args, timeout, &config);
992
993 #[cfg(windows)]
994 return windows::run_with_timeout_impl(command, args, timeout, &config);
995}
996
997pub fn run_with_timeout_default(
1017 command: &str,
1018 args: &[&str],
1019 timeout: Duration,
1020) -> SysprimsResult<TimeoutOutcome> {
1021 run_with_timeout(command, args, timeout, TimeoutConfig::default())
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026 use super::*;
1027 use std::process::{Command, Stdio};
1028
1029 struct ChildWithoutPid;
1030
1031 impl ContainmentChild for ChildWithoutPid {
1032 fn process_id(&self) -> Option<u32> {
1033 None
1034 }
1035
1036 fn try_wait(&mut self) -> std::io::Result<bool> {
1037 Ok(false)
1038 }
1039
1040 #[cfg(windows)]
1041 fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
1042 None
1043 }
1044 }
1045
1046 #[test]
1047 fn default_config_uses_sigterm() {
1048 let config = TimeoutConfig::default();
1049 assert_eq!(config.signal, SIGTERM);
1050 }
1051
1052 #[test]
1053 fn default_config_uses_group_by_default() {
1054 let config = TimeoutConfig::default();
1055 assert_eq!(config.grouping, GroupingMode::GroupByDefault);
1056 }
1057
1058 #[test]
1059 fn default_config_kill_after_is_10_seconds() {
1060 let config = TimeoutConfig::default();
1061 assert_eq!(config.kill_after, Duration::from_secs(10));
1062 }
1063
1064 #[test]
1065 fn default_config_does_not_preserve_status() {
1066 let config = TimeoutConfig::default();
1067 assert!(!config.preserve_status);
1068 }
1069
1070 #[test]
1071 fn reliability_strings_include_unproven() {
1072 assert_eq!(TreeKillReliability::Guaranteed.as_str(), "guaranteed");
1073 assert_eq!(TreeKillReliability::Unproven.as_str(), "unproven");
1074 assert_eq!(TreeKillReliability::BestEffort.as_str(), "best_effort");
1075 }
1076
1077 #[test]
1078 fn boundary_strength_strings_are_independent() {
1079 assert_eq!(
1080 ContainmentBoundaryStrength::KernelEnforcedJob.as_str(),
1081 "kernel_enforced_job"
1082 );
1083 assert_eq!(
1084 ContainmentBoundaryStrength::CooperativeGroup.as_str(),
1085 "cooperative_group"
1086 );
1087 assert_eq!(ContainmentBoundaryStrength::Unknown.as_str(), "unknown");
1088 }
1089
1090 #[test]
1091 #[cfg(unix)]
1092 fn receipt_bound_identity_treats_executable_as_observational() {
1093 let expected = ContainmentIdentity {
1094 pid: 42,
1095 start_time_unix_ms: 1_000,
1096 exe_path: "/before-exec".to_string(),
1097 };
1098
1099 assert!(verify_containment_identity_observation(
1100 &expected,
1101 Some(1_000),
1102 Some("/after-two-execs"),
1103 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1104 )
1105 .unwrap());
1106 assert!(verify_containment_identity_observation(
1107 &expected,
1108 Some(1_000),
1109 None,
1110 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1111 )
1112 .unwrap());
1113 }
1114
1115 #[test]
1116 #[cfg(unix)]
1117 fn receipt_bound_identity_requires_matching_observable_start_time() {
1118 let expected = ContainmentIdentity {
1119 pid: 42,
1120 start_time_unix_ms: 1_000,
1121 exe_path: "/before-exec".to_string(),
1122 };
1123
1124 assert!(!verify_containment_identity_observation(
1125 &expected,
1126 None,
1127 Some("/after-exec"),
1128 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1129 )
1130 .unwrap());
1131 assert!(matches!(
1132 verify_containment_identity_observation(
1133 &expected,
1134 Some(2_000),
1135 Some("/after-exec"),
1136 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1137 ),
1138 Err(SysprimsError::InvalidArgument { .. })
1139 ));
1140 }
1141
1142 #[test]
1143 #[cfg(unix)]
1144 fn adopted_identity_keeps_strict_executable_validation() {
1145 let expected = ContainmentIdentity {
1146 pid: 42,
1147 start_time_unix_ms: 1_000,
1148 exe_path: "/before-exec".to_string(),
1149 };
1150
1151 assert!(matches!(
1152 verify_containment_identity_observation(
1153 &expected,
1154 Some(1_000),
1155 Some("/after-exec"),
1156 ContainmentIdentityValidation::Strict,
1157 ),
1158 Err(SysprimsError::InvalidArgument { .. })
1159 ));
1160 assert!(!verify_containment_identity_observation(
1161 &expected,
1162 Some(1_000),
1163 None,
1164 ContainmentIdentityValidation::Strict,
1165 )
1166 .unwrap());
1167 }
1168
1169 #[test]
1170 fn completion_evidence_sorts_unique_safe_pids() {
1171 assert_eq!(
1172 completion_from_pids(
1173 ContainmentObservation::LinuxProcfsProcessGroup,
1174 vec![42, 7, 19],
1175 ),
1176 ContainmentCompletionEvidence::Survivors {
1177 observation: ContainmentObservation::LinuxProcfsProcessGroup,
1178 observed_count: 3,
1179 survivor_pids: vec![7, 19, 42],
1180 }
1181 );
1182 }
1183
1184 #[test]
1185 fn duplicate_completion_evidence_is_unknown() {
1186 assert_eq!(
1187 completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, vec![7, 7],),
1188 ContainmentCompletionEvidence::Unknown {
1189 observation: ContainmentObservation::LinuxProcfsProcessGroup,
1190 }
1191 );
1192 }
1193
1194 #[test]
1195 fn completion_evidence_at_pid_limit_is_unknown() {
1196 let pids = (2..2 + MAX_COMPLETION_OBSERVED_PIDS as u32).collect();
1197 assert_eq!(
1198 completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, pids),
1199 ContainmentCompletionEvidence::Unknown {
1200 observation: ContainmentObservation::LinuxProcfsProcessGroup,
1201 }
1202 );
1203 }
1204
1205 #[test]
1206 fn completion_evidence_serializes_as_a_tagged_receipt() {
1207 let value = serde_json::to_value(ContainmentCompletionEvidence::Survivors {
1208 observation: ContainmentObservation::MacosLibprocProcessGroup,
1209 observed_count: 2,
1210 survivor_pids: vec![17, 23],
1211 })
1212 .expect("completion evidence should serialize");
1213 assert_eq!(
1214 value,
1215 serde_json::json!({
1216 "status": "survivors",
1217 "observation": "macos_libproc_process_group",
1218 "observed_count": 2,
1219 "survivor_pids": [17, 23],
1220 })
1221 );
1222 }
1223
1224 #[test]
1225 fn failed_adoption_returns_child_ownership() {
1226 let error = match adopt_contained(ChildWithoutPid) {
1227 Ok(_) => panic!("adoption without a pid must fail"),
1228 Err(error) => error,
1229 };
1230 assert!(matches!(error.error, SysprimsError::InvalidArgument { .. }));
1231 assert!(error.child.process_id().is_none());
1232 }
1233
1234 #[test]
1235 fn terminate_tree_rejects_pid_zero() {
1236 let err = terminate_tree(0, TerminateTreeConfig::default()).unwrap_err();
1237 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
1238 }
1239
1240 #[test]
1241 #[cfg(unix)]
1242 fn terminate_tree_kills_spawned_child() {
1243 let mut child = Command::new("sleep")
1245 .arg("60")
1246 .stdin(Stdio::null())
1247 .stdout(Stdio::null())
1248 .stderr(Stdio::null())
1249 .spawn()
1250 .expect("Failed to spawn sleep process");
1251
1252 let pid = child.id();
1253 let result = terminate_tree(
1254 pid,
1255 TerminateTreeConfig {
1256 grace_timeout_ms: 100,
1257 kill_timeout_ms: 5000,
1258 ..TerminateTreeConfig::default()
1259 },
1260 )
1261 .expect("terminate_tree should succeed");
1262
1263 assert_eq!(result.pid, pid);
1264 assert!(
1265 result.exited,
1266 "expected child to be exited, got: {result:?}"
1267 );
1268 assert!(!result.timed_out, "unexpected timeout: {result:?}");
1269 assert_eq!(result.tree_kill_reliability, "best_effort");
1270 assert_eq!(result.pgid, None);
1271
1272 let _ = child.wait();
1273 }
1274
1275 #[test]
1276 #[cfg(windows)]
1277 fn terminate_tree_kills_spawned_child() {
1278 let mut child = Command::new("cmd")
1280 .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
1281 .stdin(Stdio::null())
1282 .stdout(Stdio::null())
1283 .stderr(Stdio::null())
1284 .spawn()
1285 .expect("Failed to spawn ping sleep process");
1286
1287 let pid = child.id();
1288 let result = terminate_tree(
1289 pid,
1290 TerminateTreeConfig {
1291 grace_timeout_ms: 100,
1292 kill_timeout_ms: 5000,
1293 ..TerminateTreeConfig::default()
1294 },
1295 )
1296 .expect("terminate_tree should succeed");
1297
1298 assert_eq!(result.pid, pid);
1299 let _ = child.wait();
1300 }
1301}