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
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
796pub 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 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 sysprims_signal::kill(pid, config.signal)?;
848
849 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 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 timed_out {
880 match sysprims_proc::get_process(pid) {
881 Ok(_) => {
882 }
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#[derive(Debug)]
916pub enum TimeoutOutcome {
917 Completed {
919 exit_status: ExitStatus,
921 },
922
923 TimedOut {
925 signal_sent: i32,
927
928 escalated: bool,
933
934 tree_kill_reliability: TreeKillReliability,
940 },
941}
942
943pub 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
990pub 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 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 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}