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
52#[cfg(unix)]
53mod unix;
54#[cfg(windows)]
55mod windows;
56
57pub use sysprims_signal::{SIGKILL, SIGTERM};
59#[cfg(windows)]
60pub use windows::{PreparedWindowsJob, WindowsJobReceipt};
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
67#[serde(rename_all = "snake_case")]
68pub enum GroupingMode {
69 #[default]
72 GroupByDefault,
73
74 Foreground,
77}
78
79#[derive(Debug, Clone)]
81pub struct TimeoutConfig {
82 pub signal: i32,
86
87 pub kill_after: Duration,
91
92 pub grouping: GroupingMode,
96
97 pub preserve_status: bool,
104}
105
106impl Default for TimeoutConfig {
107 fn default() -> Self {
108 Self {
109 signal: SIGTERM,
110 kill_after: Duration::from_secs(10),
111 grouping: GroupingMode::GroupByDefault,
112 preserve_status: false,
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
122#[serde(rename_all = "snake_case")]
123pub enum TreeKillReliability {
124 Guaranteed,
128
129 Unproven,
132
133 BestEffort,
136}
137
138#[non_exhaustive]
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
146#[serde(rename_all = "snake_case")]
147pub enum ContainmentBoundaryStrength {
148 KernelEnforcedJob,
151 CooperativeGroup,
153 Unknown,
155}
156
157pub(crate) const MAX_COMPLETION_OBSERVED_PIDS: usize = 4096;
158pub(crate) const MAX_COMPLETION_OBSERVATION_RETRIES: usize = 3;
159
160#[non_exhaustive]
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
163#[serde(rename_all = "snake_case")]
164pub enum ContainmentObservation {
165 LinuxProcfsProcessGroup,
167 MacosLibprocProcessGroup,
169 WindowsJobProcessIdList,
171 UnsupportedPlatform,
173}
174
175#[non_exhaustive]
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
182#[serde(tag = "status", rename_all = "snake_case")]
183pub enum ContainmentCompletionEvidence {
184 Empty { observation: ContainmentObservation },
186 Survivors {
188 observation: ContainmentObservation,
189 observed_count: u32,
190 survivor_pids: Vec<u32>,
191 },
192 Unknown { observation: ContainmentObservation },
194}
195
196pub(crate) fn unknown_completion(
197 observation: ContainmentObservation,
198) -> ContainmentCompletionEvidence {
199 ContainmentCompletionEvidence::Unknown { observation }
200}
201
202pub(crate) fn completion_from_pids(
203 observation: ContainmentObservation,
204 mut pids: Vec<u32>,
205) -> ContainmentCompletionEvidence {
206 if pids.len() >= MAX_COMPLETION_OBSERVED_PIDS
207 || pids
208 .iter()
209 .any(|pid| *pid == 0 || *pid > sysprims_signal::MAX_SAFE_PID)
210 {
211 return unknown_completion(observation);
212 }
213
214 let observed_count = pids.len();
215 pids.sort_unstable();
216 pids.dedup();
217 if pids.len() != observed_count {
218 return unknown_completion(observation);
219 }
220 if pids.is_empty() {
221 ContainmentCompletionEvidence::Empty { observation }
222 } else {
223 ContainmentCompletionEvidence::Survivors {
224 observation,
225 observed_count: pids.len() as u32,
226 survivor_pids: pids,
227 }
228 }
229}
230
231impl TreeKillReliability {
232 pub fn as_str(self) -> &'static str {
233 match self {
234 Self::Guaranteed => "guaranteed",
235 Self::Unproven => "unproven",
236 Self::BestEffort => "best_effort",
237 }
238 }
239}
240
241impl ContainmentBoundaryStrength {
242 pub fn as_str(self) -> &'static str {
243 match self {
244 Self::KernelEnforcedJob => "kernel_enforced_job",
245 Self::CooperativeGroup => "cooperative_group",
246 Self::Unknown => "unknown",
247 }
248 }
249}
250
251#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
253pub struct ContainmentIdentity {
254 pub pid: u32,
255 pub start_time_unix_ms: u64,
258 pub exe_path: String,
265}
266
267pub trait ContainmentChild {
274 fn process_id(&self) -> Option<u32>;
275 fn try_wait(&mut self) -> std::io::Result<bool>;
277
278 #[cfg(windows)]
279 fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle>;
280}
281
282impl ContainmentChild for Child {
283 fn process_id(&self) -> Option<u32> {
284 Some(self.id())
285 }
286
287 fn try_wait(&mut self) -> std::io::Result<bool> {
288 Child::try_wait(self).map(|status| status.is_some())
289 }
290
291 #[cfg(windows)]
292 fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
293 use std::os::windows::io::AsRawHandle;
294 Some(self.as_raw_handle())
295 }
296}
297
298pub struct ContainmentAdoptionError<C> {
303 pub error: SysprimsError,
304 pub child: C,
305}
306
307impl<C> std::fmt::Debug for ContainmentAdoptionError<C> {
308 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309 formatter
310 .debug_struct("ContainmentAdoptionError")
311 .field("error", &self.error)
312 .finish_non_exhaustive()
313 }
314}
315
316impl<C> std::fmt::Display for ContainmentAdoptionError<C> {
317 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318 self.error.fmt(formatter)
319 }
320}
321
322impl<C> std::error::Error for ContainmentAdoptionError<C> {}
323
324#[derive(Debug)]
326pub enum ContainmentSpawnError {
327 Spawn(SysprimsError),
328 Adoption(SysprimsError),
329}
330
331impl std::fmt::Display for ContainmentSpawnError {
332 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
333 match self {
334 Self::Spawn(error) => error.fmt(formatter),
335 Self::Adoption(error) => error.fmt(formatter),
336 }
337 }
338}
339
340impl std::error::Error for ContainmentSpawnError {}
341
342pub struct ContainmentGuard<C: ContainmentChild> {
349 child: Option<C>,
350 identity: ContainmentIdentity,
351 reliability: TreeKillReliability,
352 boundary_strength: ContainmentBoundaryStrength,
353 finalized: bool,
354 #[cfg(unix)]
355 pgid: u32,
356 #[cfg(unix)]
357 session_id: u32,
358 #[cfg(unix)]
359 session_receipt: Option<sysprims_session::UnixSessionReceipt>,
360 #[cfg(windows)]
361 job: std::os::windows::io::OwnedHandle,
362}
363
364impl<C: ContainmentChild> ContainmentGuard<C> {
365 pub fn identity(&self) -> &ContainmentIdentity {
366 &self.identity
367 }
368
369 pub fn tree_kill_reliability(&self) -> TreeKillReliability {
370 self.reliability
371 }
372
373 pub fn boundary_strength(&self) -> ContainmentBoundaryStrength {
374 self.boundary_strength
375 }
376
377 pub fn into_child(mut self) -> Result<C, Self> {
379 if self.finalized {
380 Ok(self
381 .child
382 .take()
383 .expect("finalized guard retains its child"))
384 } else {
385 Err(self)
386 }
387 }
388
389 pub fn try_complete(
395 &mut self,
396 config: TerminateTreeConfig,
397 ) -> SysprimsResult<Option<ContainmentOutcome>> {
398 if self.finalized {
399 return Err(SysprimsError::invalid_argument(
400 "containment guard has already been finalized",
401 ));
402 }
403
404 #[cfg(unix)]
405 if !unix::contained_child_has_exited(self)? {
406 return Ok(None);
407 }
408
409 #[cfg(windows)]
410 if !windows::contained_child_has_exited(self)? {
411 return Ok(None);
412 }
413
414 self.terminate(config).map(Some)
415 }
416
417 pub fn terminate(&mut self, config: TerminateTreeConfig) -> SysprimsResult<ContainmentOutcome> {
419 if self.finalized {
420 return Err(SysprimsError::invalid_argument(
421 "containment guard has already been finalized",
422 ));
423 }
424
425 #[cfg(unix)]
426 return unix::terminate_contained_impl(self, config);
427
428 #[cfg(windows)]
429 return windows::terminate_contained_impl(self, config);
430 }
431}
432
433impl<C: ContainmentChild> Drop for ContainmentGuard<C> {
434 fn drop(&mut self) {
435 if self.finalized || self.child.is_none() {
436 return;
437 }
438
439 #[cfg(unix)]
440 unix::drop_contained_impl(self);
441
442 #[cfg(windows)]
443 windows::drop_contained_impl(self);
444 }
445}
446
447#[derive(Debug, Clone, Serialize)]
449pub struct ContainmentOutcome {
450 pub identity: ContainmentIdentity,
451 #[serde(skip_serializing_if = "Option::is_none")]
452 pub pgid: Option<u32>,
453 #[serde(skip_serializing_if = "Option::is_none")]
454 pub signal_sent: Option<i32>,
455 #[serde(skip_serializing_if = "Option::is_none")]
456 pub kill_signal: Option<i32>,
457 pub escalated: bool,
458 pub exited: bool,
459 pub timed_out: bool,
460 pub tree_kill_reliability: TreeKillReliability,
461 pub boundary_strength: ContainmentBoundaryStrength,
462 pub completion: ContainmentCompletionEvidence,
464 pub warnings: Vec<String>,
465}
466
467pub fn adopt_contained<C: ContainmentChild>(
472 child: C,
473) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
474 #[cfg(unix)]
475 return unix::adopt_contained_impl(child);
476
477 #[cfg(windows)]
478 return windows::adopt_contained_impl(child);
479}
480
481#[cfg(unix)]
496pub unsafe fn contain_acquired_session<C: ContainmentChild>(
497 child: C,
498 receipt: sysprims_session::UnixSessionReceipt,
499) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
500 unix::contain_acquired_session_impl(child, receipt)
501}
502
503#[cfg(windows)]
517pub unsafe fn contain_acquired_windows_job<C: ContainmentChild>(
518 child: C,
519 receipt: WindowsJobReceipt,
520) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
521 windows::contain_acquired_windows_job_impl(child, receipt)
522}
523
524pub fn spawn_contained(command: Command) -> Result<ContainmentGuard<Child>, ContainmentSpawnError> {
532 #[cfg(unix)]
533 return unix::spawn_contained_impl(command);
534
535 #[cfg(windows)]
536 return windows::spawn_contained_impl(command);
537}
538
539fn capture_containment_identity(pid: u32) -> SysprimsResult<ContainmentIdentity> {
540 capture_containment_identity_with_mode(pid, ContainmentIdentityValidation::Strict)
541}
542
543#[cfg(unix)]
544fn capture_receipt_bound_containment_identity(pid: u32) -> SysprimsResult<ContainmentIdentity> {
545 capture_containment_identity_with_mode(
546 pid,
547 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
548 )
549}
550
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552enum ContainmentIdentityValidation {
553 Strict,
554 #[cfg(unix)]
555 ReceiptBoundExecVolatile,
556}
557
558fn capture_containment_identity_with_mode(
559 pid: u32,
560 mode: ContainmentIdentityValidation,
561) -> SysprimsResult<ContainmentIdentity> {
562 if pid == 0 || pid > sysprims_signal::MAX_SAFE_PID {
563 return Err(SysprimsError::invalid_argument(format!(
564 "pid {pid} is outside the safe process identity range"
565 )));
566 }
567
568 let process = sysprims_proc::get_process(pid)?;
569 let start_time_unix_ms = process.start_time_unix_ms.ok_or_else(|| {
570 SysprimsError::system(
571 "process start time unavailable during containment acquisition",
572 0,
573 )
574 })?;
575 let exe_path = match (mode, process.exe_path.filter(|path| !path.is_empty())) {
576 (_, Some(path)) => path,
577 (ContainmentIdentityValidation::Strict, None) => {
578 return Err(SysprimsError::system(
579 "process executable unavailable during containment acquisition",
580 0,
581 ));
582 }
583 #[cfg(unix)]
584 (ContainmentIdentityValidation::ReceiptBoundExecVolatile, None) => String::new(),
585 };
586
587 Ok(ContainmentIdentity {
588 pid,
589 start_time_unix_ms,
590 exe_path,
591 })
592}
593
594#[cfg(unix)]
595fn verify_containment_identity(
596 expected: &ContainmentIdentity,
597 mode: ContainmentIdentityValidation,
598) -> SysprimsResult<bool> {
599 let process = match sysprims_proc::get_process(expected.pid) {
600 Ok(process) => process,
601 Err(SysprimsError::NotFound { .. } | SysprimsError::PermissionDenied { .. }) => {
602 return Ok(false);
603 }
604 Err(error) => return Err(error),
605 };
606
607 verify_containment_identity_observation(
608 expected,
609 process.start_time_unix_ms,
610 process.exe_path.as_deref(),
611 mode,
612 )
613}
614
615#[cfg(unix)]
616fn verify_containment_identity_observation(
617 expected: &ContainmentIdentity,
618 actual_start_time_unix_ms: Option<u64>,
619 actual_exe_path: Option<&str>,
620 mode: ContainmentIdentityValidation,
621) -> SysprimsResult<bool> {
622 if actual_start_time_unix_ms.is_some_and(|actual| actual != expected.start_time_unix_ms) {
623 return Err(SysprimsError::invalid_argument(
624 "process identity changed; refusing containment operation",
625 ));
626 }
627
628 match mode {
629 ContainmentIdentityValidation::Strict => {
630 if actual_exe_path.is_some_and(|actual| actual != expected.exe_path) {
631 return Err(SysprimsError::invalid_argument(
632 "process identity changed; refusing containment operation",
633 ));
634 }
635 Ok(actual_start_time_unix_ms.is_some() && actual_exe_path.is_some())
636 }
637 ContainmentIdentityValidation::ReceiptBoundExecVolatile => {
638 Ok(actual_start_time_unix_ms.is_some())
639 }
640 }
641}
642
643#[derive(Debug, Clone, Deserialize)]
652#[serde(deny_unknown_fields)]
653pub struct TerminateTreeConfig {
654 #[serde(default = "default_grace_timeout_ms")]
656 pub grace_timeout_ms: u64,
657
658 #[serde(default = "default_kill_timeout_ms")]
660 pub kill_timeout_ms: u64,
661
662 #[serde(default = "default_grace_signal")]
664 pub signal: i32,
665
666 #[serde(default = "default_kill_signal")]
668 pub kill_signal: i32,
669}
670
671fn default_grace_timeout_ms() -> u64 {
672 10_000
673}
674
675fn default_kill_timeout_ms() -> u64 {
676 2_000
677}
678
679fn default_grace_signal() -> i32 {
680 SIGTERM
681}
682
683fn default_kill_signal() -> i32 {
684 SIGKILL
685}
686
687impl Default for TerminateTreeConfig {
688 fn default() -> Self {
689 Self {
690 grace_timeout_ms: default_grace_timeout_ms(),
691 kill_timeout_ms: default_kill_timeout_ms(),
692 signal: default_grace_signal(),
693 kill_signal: default_kill_signal(),
694 }
695 }
696}
697
698#[derive(Debug, Clone, Serialize)]
699pub struct TerminateTreeResult {
700 pub schema_id: &'static str,
701 pub timestamp: String,
702 pub platform: &'static str,
703 pub pid: u32,
704
705 #[serde(skip_serializing_if = "Option::is_none")]
706 pub pgid: Option<u32>,
707
708 pub signal_sent: i32,
709 #[serde(skip_serializing_if = "Option::is_none")]
710 pub kill_signal: Option<i32>,
711 pub escalated: bool,
712 pub exited: bool,
713 pub timed_out: bool,
714 pub tree_kill_reliability: String,
715 pub warnings: Vec<String>,
716}
717
718#[derive(Debug, Clone, Deserialize)]
724#[serde(deny_unknown_fields)]
725pub struct SpawnInGroupConfig {
726 pub argv: Vec<String>,
728
729 #[serde(default)]
731 pub cwd: Option<String>,
732
733 #[serde(default)]
737 pub env: Option<std::collections::BTreeMap<String, String>>,
738}
739
740#[derive(Debug, Clone, Serialize)]
741pub struct SpawnInGroupResult {
742 pub schema_id: &'static str,
743 pub timestamp: String,
744 pub platform: &'static str,
745 pub pid: u32,
746
747 #[serde(skip_serializing_if = "Option::is_none")]
748 pub pgid: Option<u32>,
749
750 pub tree_kill_reliability: String,
751 pub warnings: Vec<String>,
752}
753
754pub fn spawn_in_group(config: SpawnInGroupConfig) -> SysprimsResult<SpawnInGroupResult> {
779 if config.argv.is_empty() {
780 return Err(SysprimsError::invalid_argument("argv must not be empty"));
781 }
782
783 #[cfg(unix)]
784 return unix::spawn_in_group_impl(config);
785
786 #[cfg(windows)]
787 return windows::spawn_in_group_impl(config);
788}
789
790pub fn terminate_tree(
808 pid: u32,
809 config: TerminateTreeConfig,
810) -> SysprimsResult<TerminateTreeResult> {
811 if pid == 0 {
812 return Err(SysprimsError::invalid_argument("pid must be > 0"));
813 }
814
815 if pid > sysprims_signal::MAX_SAFE_PID {
818 return Err(SysprimsError::invalid_argument(format!(
819 "pid {} exceeds maximum safe value {}",
820 pid,
821 sysprims_signal::MAX_SAFE_PID
822 )));
823 }
824
825 let mut warnings: Vec<String> = Vec::new();
826 let pgid: Option<u32> = None;
827 let reliability = TreeKillReliability::BestEffort;
828
829 #[cfg(windows)]
830 warnings.push(
831 "Windows PID termination is best-effort; use an owned containment guard for Job Objects"
832 .to_string(),
833 );
834 #[cfg(unix)]
835 warnings.push(
836 "PID-only termination has no sealed group capability; signaling the target PID only"
837 .to_string(),
838 );
839
840 sysprims_signal::kill(pid, config.signal)?;
842
843 let grace = Duration::from_millis(config.grace_timeout_ms);
845 let grace_wait = wait_pid(pid, grace)?;
846 if grace_wait.exited {
847 return Ok(TerminateTreeResult {
848 schema_id: TERMINATE_TREE_RESULT_V1,
849 timestamp: now_rfc3339(),
850 platform: get_platform(),
851 pid,
852 pgid,
853 signal_sent: config.signal,
854 kill_signal: None,
855 escalated: false,
856 exited: true,
857 timed_out: false,
858 tree_kill_reliability: reliability.as_str().to_string(),
859 warnings,
860 });
861 }
862
863 sysprims_signal::kill(pid, config.kill_signal)?;
865
866 let kill_wait = wait_pid(pid, Duration::from_millis(config.kill_timeout_ms))?;
867 let mut exited = kill_wait.exited;
868 let mut timed_out = kill_wait.timed_out;
869
870 if timed_out {
874 match sysprims_proc::get_process(pid) {
875 Ok(_) => {
876 }
878 Err(SysprimsError::NotFound { .. }) => {
879 exited = true;
880 timed_out = false;
881 warnings.push("PID no longer found after timeout; treating as exited".to_string());
882 }
883 Err(SysprimsError::PermissionDenied { .. }) => {
884 warnings.push("Permission denied while confirming exit after timeout".to_string());
885 }
886 Err(e) => {
887 warnings.push(format!("Failed to confirm exit after timeout: {}", e));
888 }
889 }
890 }
891
892 Ok(TerminateTreeResult {
893 schema_id: TERMINATE_TREE_RESULT_V1,
894 timestamp: now_rfc3339(),
895 platform: get_platform(),
896 pid,
897 pgid,
898 signal_sent: config.signal,
899 kill_signal: Some(config.kill_signal),
900 escalated: true,
901 exited,
902 timed_out,
903 tree_kill_reliability: reliability.as_str().to_string(),
904 warnings,
905 })
906}
907
908#[derive(Debug)]
910pub enum TimeoutOutcome {
911 Completed {
913 exit_status: ExitStatus,
915 },
916
917 TimedOut {
919 signal_sent: i32,
921
922 escalated: bool,
927
928 tree_kill_reliability: TreeKillReliability,
934 },
935}
936
937pub fn run_with_timeout(
972 command: &str,
973 args: &[&str],
974 timeout: Duration,
975 config: TimeoutConfig,
976) -> SysprimsResult<TimeoutOutcome> {
977 #[cfg(unix)]
978 return unix::run_with_timeout_impl(command, args, timeout, &config);
979
980 #[cfg(windows)]
981 return windows::run_with_timeout_impl(command, args, timeout, &config);
982}
983
984pub fn run_with_timeout_default(
1004 command: &str,
1005 args: &[&str],
1006 timeout: Duration,
1007) -> SysprimsResult<TimeoutOutcome> {
1008 run_with_timeout(command, args, timeout, TimeoutConfig::default())
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013 use super::*;
1014 use std::process::{Command, Stdio};
1015
1016 struct ChildWithoutPid;
1017
1018 impl ContainmentChild for ChildWithoutPid {
1019 fn process_id(&self) -> Option<u32> {
1020 None
1021 }
1022
1023 fn try_wait(&mut self) -> std::io::Result<bool> {
1024 Ok(false)
1025 }
1026
1027 #[cfg(windows)]
1028 fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
1029 None
1030 }
1031 }
1032
1033 #[test]
1034 fn default_config_uses_sigterm() {
1035 let config = TimeoutConfig::default();
1036 assert_eq!(config.signal, SIGTERM);
1037 }
1038
1039 #[test]
1040 fn default_config_uses_group_by_default() {
1041 let config = TimeoutConfig::default();
1042 assert_eq!(config.grouping, GroupingMode::GroupByDefault);
1043 }
1044
1045 #[test]
1046 fn default_config_kill_after_is_10_seconds() {
1047 let config = TimeoutConfig::default();
1048 assert_eq!(config.kill_after, Duration::from_secs(10));
1049 }
1050
1051 #[test]
1052 fn default_config_does_not_preserve_status() {
1053 let config = TimeoutConfig::default();
1054 assert!(!config.preserve_status);
1055 }
1056
1057 #[test]
1058 fn reliability_strings_include_unproven() {
1059 assert_eq!(TreeKillReliability::Guaranteed.as_str(), "guaranteed");
1060 assert_eq!(TreeKillReliability::Unproven.as_str(), "unproven");
1061 assert_eq!(TreeKillReliability::BestEffort.as_str(), "best_effort");
1062 }
1063
1064 #[test]
1065 fn boundary_strength_strings_are_independent() {
1066 assert_eq!(
1067 ContainmentBoundaryStrength::KernelEnforcedJob.as_str(),
1068 "kernel_enforced_job"
1069 );
1070 assert_eq!(
1071 ContainmentBoundaryStrength::CooperativeGroup.as_str(),
1072 "cooperative_group"
1073 );
1074 assert_eq!(ContainmentBoundaryStrength::Unknown.as_str(), "unknown");
1075 }
1076
1077 #[test]
1078 #[cfg(unix)]
1079 fn receipt_bound_identity_treats_executable_as_observational() {
1080 let expected = ContainmentIdentity {
1081 pid: 42,
1082 start_time_unix_ms: 1_000,
1083 exe_path: "/before-exec".to_string(),
1084 };
1085
1086 assert!(verify_containment_identity_observation(
1087 &expected,
1088 Some(1_000),
1089 Some("/after-two-execs"),
1090 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1091 )
1092 .unwrap());
1093 assert!(verify_containment_identity_observation(
1094 &expected,
1095 Some(1_000),
1096 None,
1097 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1098 )
1099 .unwrap());
1100 }
1101
1102 #[test]
1103 #[cfg(unix)]
1104 fn receipt_bound_identity_requires_matching_observable_start_time() {
1105 let expected = ContainmentIdentity {
1106 pid: 42,
1107 start_time_unix_ms: 1_000,
1108 exe_path: "/before-exec".to_string(),
1109 };
1110
1111 assert!(!verify_containment_identity_observation(
1112 &expected,
1113 None,
1114 Some("/after-exec"),
1115 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1116 )
1117 .unwrap());
1118 assert!(matches!(
1119 verify_containment_identity_observation(
1120 &expected,
1121 Some(2_000),
1122 Some("/after-exec"),
1123 ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1124 ),
1125 Err(SysprimsError::InvalidArgument { .. })
1126 ));
1127 }
1128
1129 #[test]
1130 #[cfg(unix)]
1131 fn adopted_identity_keeps_strict_executable_validation() {
1132 let expected = ContainmentIdentity {
1133 pid: 42,
1134 start_time_unix_ms: 1_000,
1135 exe_path: "/before-exec".to_string(),
1136 };
1137
1138 assert!(matches!(
1139 verify_containment_identity_observation(
1140 &expected,
1141 Some(1_000),
1142 Some("/after-exec"),
1143 ContainmentIdentityValidation::Strict,
1144 ),
1145 Err(SysprimsError::InvalidArgument { .. })
1146 ));
1147 assert!(!verify_containment_identity_observation(
1148 &expected,
1149 Some(1_000),
1150 None,
1151 ContainmentIdentityValidation::Strict,
1152 )
1153 .unwrap());
1154 }
1155
1156 #[test]
1157 fn completion_evidence_sorts_unique_safe_pids() {
1158 assert_eq!(
1159 completion_from_pids(
1160 ContainmentObservation::LinuxProcfsProcessGroup,
1161 vec![42, 7, 19],
1162 ),
1163 ContainmentCompletionEvidence::Survivors {
1164 observation: ContainmentObservation::LinuxProcfsProcessGroup,
1165 observed_count: 3,
1166 survivor_pids: vec![7, 19, 42],
1167 }
1168 );
1169 }
1170
1171 #[test]
1172 fn duplicate_completion_evidence_is_unknown() {
1173 assert_eq!(
1174 completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, vec![7, 7],),
1175 ContainmentCompletionEvidence::Unknown {
1176 observation: ContainmentObservation::LinuxProcfsProcessGroup,
1177 }
1178 );
1179 }
1180
1181 #[test]
1182 fn completion_evidence_at_pid_limit_is_unknown() {
1183 let pids = (2..2 + MAX_COMPLETION_OBSERVED_PIDS as u32).collect();
1184 assert_eq!(
1185 completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, pids),
1186 ContainmentCompletionEvidence::Unknown {
1187 observation: ContainmentObservation::LinuxProcfsProcessGroup,
1188 }
1189 );
1190 }
1191
1192 #[test]
1193 fn completion_evidence_serializes_as_a_tagged_receipt() {
1194 let value = serde_json::to_value(ContainmentCompletionEvidence::Survivors {
1195 observation: ContainmentObservation::MacosLibprocProcessGroup,
1196 observed_count: 2,
1197 survivor_pids: vec![17, 23],
1198 })
1199 .expect("completion evidence should serialize");
1200 assert_eq!(
1201 value,
1202 serde_json::json!({
1203 "status": "survivors",
1204 "observation": "macos_libproc_process_group",
1205 "observed_count": 2,
1206 "survivor_pids": [17, 23],
1207 })
1208 );
1209 }
1210
1211 #[test]
1212 fn failed_adoption_returns_child_ownership() {
1213 let error = match adopt_contained(ChildWithoutPid) {
1214 Ok(_) => panic!("adoption without a pid must fail"),
1215 Err(error) => error,
1216 };
1217 assert!(matches!(error.error, SysprimsError::InvalidArgument { .. }));
1218 assert!(error.child.process_id().is_none());
1219 }
1220
1221 #[test]
1222 fn terminate_tree_rejects_pid_zero() {
1223 let err = terminate_tree(0, TerminateTreeConfig::default()).unwrap_err();
1224 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
1225 }
1226
1227 #[test]
1228 #[cfg(unix)]
1229 fn terminate_tree_kills_spawned_child() {
1230 let mut child = Command::new("sleep")
1232 .arg("60")
1233 .stdin(Stdio::null())
1234 .stdout(Stdio::null())
1235 .stderr(Stdio::null())
1236 .spawn()
1237 .expect("Failed to spawn sleep process");
1238
1239 let pid = child.id();
1240 let result = terminate_tree(
1241 pid,
1242 TerminateTreeConfig {
1243 grace_timeout_ms: 100,
1244 kill_timeout_ms: 5000,
1245 ..TerminateTreeConfig::default()
1246 },
1247 )
1248 .expect("terminate_tree should succeed");
1249
1250 assert_eq!(result.pid, pid);
1251 assert!(
1252 result.exited,
1253 "expected child to be exited, got: {result:?}"
1254 );
1255 assert!(!result.timed_out, "unexpected timeout: {result:?}");
1256 assert_eq!(result.tree_kill_reliability, "best_effort");
1257 assert_eq!(result.pgid, None);
1258
1259 let _ = child.wait();
1260 }
1261
1262 #[test]
1263 #[cfg(windows)]
1264 fn terminate_tree_kills_spawned_child() {
1265 let mut child = Command::new("cmd")
1267 .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
1268 .stdin(Stdio::null())
1269 .stdout(Stdio::null())
1270 .stderr(Stdio::null())
1271 .spawn()
1272 .expect("Failed to spawn ping sleep process");
1273
1274 let pid = child.id();
1275 let result = terminate_tree(
1276 pid,
1277 TerminateTreeConfig {
1278 grace_timeout_ms: 100,
1279 kill_timeout_ms: 5000,
1280 ..TerminateTreeConfig::default()
1281 },
1282 )
1283 .expect("terminate_tree should succeed");
1284
1285 assert_eq!(result.pid, pid);
1286 let _ = child.wait();
1287 }
1288}