1use serde::{Deserialize, Serialize};
45use std::collections::{BTreeMap, HashMap, HashSet};
46use std::net::IpAddr;
47use std::sync::Arc;
48use std::time::Duration;
49use sysprims_core::schema::{
50 ANCESTORS_RESULT_V1, DESCENDANTS_RESULT_SAMPLED_V1, DESCENDANTS_RESULT_V1, FD_SNAPSHOT_V1,
51 GUARD_EVENT_V1, PORT_BINDINGS_V1, PORT_FILTER_V1, PROCESS_INFO_SAMPLED_V1, PROCESS_INFO_V1,
52 WAIT_PID_RESULT_V1,
53};
54use sysprims_core::time::now_rfc3339;
55use sysprims_core::{get_platform, guard_signals, time, SysprimsError, SysprimsResult};
56
57#[cfg(target_os = "linux")]
59mod linux;
60#[cfg(target_os = "macos")]
61mod macos;
62#[cfg(windows)]
63mod windows;
64
65pub mod observation;
67
68pub use sysprims_signal::{
70 open_process_handle, open_process_handle_verified, ProcessHandle, SignalBinding,
71};
72
73#[cfg(target_os = "linux")]
75use linux as platform;
76#[cfg(target_os = "macos")]
77use macos as platform;
78#[cfg(windows)]
79use windows as platform;
80
81#[derive(Debug, Clone, Serialize)]
89pub struct ProcessSnapshot {
90 pub schema_id: &'static str,
92
93 pub timestamp: String,
95
96 pub processes: Vec<ProcessInfo>,
98}
99
100#[derive(Debug, Clone, Serialize)]
106pub struct WaitPidResult {
107 pub schema_id: &'static str,
109
110 pub timestamp: String,
112
113 pub platform: &'static str,
115
116 pub pid: u32,
118
119 pub exited: bool,
121
122 pub timed_out: bool,
124
125 #[serde(skip_serializing_if = "Option::is_none")]
127 pub exit_code: Option<i32>,
128
129 pub warnings: Vec<String>,
131}
132
133#[derive(Debug, Clone, Serialize)]
135pub struct PortBindingsSnapshot {
136 pub schema_id: &'static str,
138
139 pub timestamp: String,
141
142 pub platform: &'static str,
144
145 pub bindings: Vec<PortBinding>,
147
148 pub warnings: Vec<String>,
150}
151
152#[derive(Debug, Clone, Serialize)]
154pub struct PortBinding {
155 pub protocol: Protocol,
157
158 #[serde(skip_serializing_if = "Option::is_none")]
160 pub local_addr: Option<IpAddr>,
161
162 pub local_port: u16,
164
165 #[serde(skip_serializing_if = "Option::is_none")]
167 pub state: Option<String>,
168
169 #[serde(skip_serializing_if = "Option::is_none")]
171 pub pid: Option<u32>,
172
173 #[serde(skip_serializing_if = "Option::is_none")]
175 pub process: Option<ProcessInfo>,
176
177 #[serde(skip)]
179 pub inode: Option<u64>,
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(rename_all = "snake_case")]
185pub enum Protocol {
186 Tcp,
187 Udp,
188}
189
190#[derive(Debug, Clone, Default, Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct PortFilter {
194 pub protocol: Option<Protocol>,
196
197 pub local_port: Option<u16>,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum FdKind {
205 File,
206 Socket,
207 Pipe,
208 Unknown,
209}
210
211#[derive(Debug, Clone, Default, Deserialize)]
213#[serde(deny_unknown_fields)]
214pub struct FdFilter {
215 pub kind: Option<FdKind>,
217}
218
219impl FdFilter {
220 pub fn validate(&self) -> SysprimsResult<()> {
221 Ok(())
223 }
224}
225
226#[derive(Debug, Clone, Serialize)]
228pub struct FdInfo {
229 pub fd: u32,
231
232 pub kind: FdKind,
234
235 #[serde(skip_serializing_if = "Option::is_none")]
237 pub path: Option<String>,
238}
239
240#[derive(Debug, Clone, Serialize)]
242pub struct FdSnapshot {
243 pub schema_id: &'static str,
245
246 pub timestamp: String,
248
249 pub platform: &'static str,
251
252 pub pid: u32,
254
255 pub fds: Vec<FdInfo>,
257
258 pub warnings: Vec<String>,
260}
261
262#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
267#[serde(default, deny_unknown_fields)]
268pub struct ProcessOptions {
269 pub include_env: bool,
275
276 pub include_threads: bool,
278}
279
280impl ProcessOptions {
281 pub fn with_env(mut self) -> Self {
283 self.include_env = true;
284 self
285 }
286
287 pub fn with_threads(mut self) -> Self {
289 self.include_threads = true;
290 self
291 }
292}
293
294#[cfg(all(feature = "proc_ext", unix))]
296pub(crate) const MAX_ENV_ENTRIES: usize = 1024;
297#[cfg(all(feature = "proc_ext", unix))]
298pub(crate) const MAX_ENV_KEY_BYTES: usize = 1024;
299#[cfg(all(feature = "proc_ext", unix))]
300pub(crate) const MAX_ENV_VALUE_BYTES: usize = 4096;
301#[cfg(all(feature = "proc_ext", unix))]
302pub(crate) const MAX_ENV_TOTAL_BYTES: usize = 1_048_576;
303
304#[derive(Debug, Clone, Serialize)]
309pub struct ProcessInfo {
310 pub pid: u32,
312
313 pub ppid: u32,
315
316 pub name: String,
318
319 #[serde(skip_serializing_if = "Option::is_none")]
321 pub user: Option<String>,
322
323 pub cpu_percent: f64,
328
329 pub memory_kb: u64,
331
332 pub elapsed_seconds: u64,
334
335 #[serde(skip_serializing_if = "Option::is_none")]
339 pub start_time_unix_ms: Option<u64>,
340
341 #[serde(skip_serializing_if = "Option::is_none")]
345 pub exe_path: Option<String>,
346
347 pub state: ProcessState,
349
350 pub cmdline: Vec<String>,
354
355 #[serde(skip_serializing_if = "Option::is_none")]
357 pub env: Option<BTreeMap<String, String>>,
358
359 #[serde(skip_serializing_if = "Option::is_none")]
361 pub thread_count: Option<u32>,
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(rename_all = "snake_case")]
369pub enum ProcessState {
370 Running,
372 Sleeping,
374 Stopped,
376 Zombie,
378 Unknown,
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392#[cfg_attr(windows, allow(dead_code))]
393pub(crate) enum Liveness {
394 Live,
396 Zombie,
398 Gone,
400}
401
402#[derive(Debug, Clone, Default, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct ProcessFilter {
409 pub name_contains: Option<String>,
411
412 pub name_equals: Option<String>,
414
415 pub user_equals: Option<String>,
417
418 pub pid_in: Option<Vec<u32>>,
420
421 pub ppid: Option<u32>,
423
424 pub state_in: Option<Vec<ProcessState>>,
426
427 pub cpu_above: Option<f64>,
429
430 pub memory_above_kb: Option<u64>,
432
433 pub running_for_at_least_secs: Option<u64>,
437}
438
439impl ProcessFilter {
440 pub fn validate(&self) -> SysprimsResult<()> {
444 if let Some(cpu) = self.cpu_above {
445 if !(0.0..=100.0).contains(&cpu) {
446 return Err(SysprimsError::invalid_argument(
447 "cpu_above must be between 0 and 100",
448 ));
449 }
450 }
451 Ok(())
452 }
453}
454
455fn validate_process_options(options: &ProcessOptions) -> SysprimsResult<()> {
456 #[cfg(feature = "proc_ext")]
457 {
458 let _ = options;
459 }
460
461 #[cfg(not(feature = "proc_ext"))]
462 {
463 if options.include_env || options.include_threads {
464 return Err(SysprimsError::invalid_argument(
465 "include_env/include_threads require the proc_ext feature",
466 ));
467 }
468 }
469
470 Ok(())
471}
472
473impl PortFilter {
474 pub fn validate(&self) -> SysprimsResult<()> {
476 if let Some(port) = self.local_port {
477 if port == 0 {
478 return Err(SysprimsError::invalid_argument(
479 "local_port must be between 1 and 65535",
480 ));
481 }
482 }
483 Ok(())
484 }
485
486 pub fn schema_id() -> &'static str {
487 PORT_FILTER_V1
488 }
489}
490
491impl FdInfo {
492 fn matches(&self, filter: &FdFilter) -> bool {
493 if let Some(kind) = filter.kind {
494 if self.kind != kind {
495 return false;
496 }
497 }
498
499 true
500 }
501}
502
503impl PortBinding {
504 fn matches(&self, filter: &PortFilter) -> bool {
505 if let Some(protocol) = filter.protocol {
506 if self.protocol != protocol {
507 return false;
508 }
509 }
510
511 if let Some(port) = filter.local_port {
512 if self.local_port != port {
513 return false;
514 }
515 }
516
517 true
518 }
519}
520
521impl ProcessFilter {
522 fn matches(&self, proc: &ProcessInfo) -> bool {
524 if let Some(ref pattern) = self.name_contains {
526 if !proc.name.to_lowercase().contains(&pattern.to_lowercase()) {
527 return false;
528 }
529 }
530
531 if let Some(ref name) = self.name_equals {
533 if proc.name != *name {
534 return false;
535 }
536 }
537
538 if let Some(ref user) = self.user_equals {
540 match &proc.user {
541 Some(proc_user) if proc_user == user => {}
542 _ => return false,
543 }
544 }
545
546 if let Some(ref pids) = self.pid_in {
548 if !pids.contains(&proc.pid) {
549 return false;
550 }
551 }
552
553 if let Some(ppid) = self.ppid {
555 if proc.ppid != ppid {
556 return false;
557 }
558 }
559
560 if let Some(ref states) = self.state_in {
562 if !states.contains(&proc.state) {
563 return false;
564 }
565 }
566
567 if let Some(threshold) = self.cpu_above {
569 if proc.cpu_percent < threshold {
570 return false;
571 }
572 }
573
574 if let Some(threshold) = self.memory_above_kb {
576 if proc.memory_kb < threshold {
577 return false;
578 }
579 }
580
581 if let Some(min_secs) = self.running_for_at_least_secs {
583 if proc.elapsed_seconds < min_secs {
584 return false;
585 }
586 }
587
588 true
589 }
590}
591
592pub fn snapshot() -> SysprimsResult<ProcessSnapshot> {
611 snapshot_with_options(ProcessOptions::default())
612}
613
614pub fn snapshot_with_options(options: ProcessOptions) -> SysprimsResult<ProcessSnapshot> {
626 validate_process_options(&options)?;
627 platform::snapshot_impl(&options)
628}
629
630pub fn cpu_total_time_ns(pid: u32) -> SysprimsResult<u64> {
648 const MAX_SAFE_PID: u32 = i32::MAX as u32;
649
650 if pid == 0 {
651 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
652 }
653 if pid > MAX_SAFE_PID {
654 return Err(SysprimsError::invalid_argument(format!(
655 "PID {} exceeds maximum safe value {}",
656 pid, MAX_SAFE_PID
657 )));
658 }
659 platform::cpu_total_time_ns_impl(pid)
660}
661
662pub fn listening_ports(filter: Option<&PortFilter>) -> SysprimsResult<PortBindingsSnapshot> {
678 let filter = filter.cloned().unwrap_or_default();
679 filter.validate()?;
680
681 let mut snapshot = platform::listening_ports_impl()?;
682 if filter.protocol.is_some() || filter.local_port.is_some() {
683 snapshot.bindings.retain(|binding| binding.matches(&filter));
684 }
685
686 if snapshot.bindings.is_empty() && snapshot.warnings.is_empty() {
687 let platform = get_platform();
688 return Err(SysprimsError::not_supported("port bindings", platform));
689 }
690
691 Ok(snapshot)
692}
693
694pub fn list_fds(pid: u32, filter: Option<&FdFilter>) -> SysprimsResult<FdSnapshot> {
710 const MAX_SAFE_PID: u32 = i32::MAX as u32;
712 if pid == 0 {
713 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
714 }
715 if pid > MAX_SAFE_PID {
716 return Err(SysprimsError::invalid_argument(format!(
717 "PID {} exceeds maximum safe value {}",
718 pid, MAX_SAFE_PID
719 )));
720 }
721
722 let filter = filter.cloned().unwrap_or_default();
723 filter.validate()?;
724
725 let (mut fds, mut warnings) = platform::list_fds_impl(pid)?;
726 if filter.kind.is_some() {
727 fds.retain(|fd| fd.matches(&filter));
728 }
729
730 if fds.is_empty() {
732 warnings.push("No file descriptors visible".to_string());
733 }
734
735 Ok(make_fd_snapshot(pid, fds, warnings))
736}
737
738pub fn process_by_port(port: u16, protocol: Protocol) -> SysprimsResult<ProcessInfo> {
750 if port == 0 {
751 return Err(SysprimsError::invalid_argument(
752 "port must be between 1 and 65535",
753 ));
754 }
755
756 let filter = PortFilter {
757 protocol: Some(protocol),
758 local_port: Some(port),
759 };
760 let snapshot = listening_ports(Some(&filter))?;
761 let binding = snapshot
762 .bindings
763 .into_iter()
764 .find(|binding| binding.pid.is_some())
765 .ok_or_else(|| SysprimsError::not_found(port as u32))?;
766
767 match binding.process {
768 Some(process) => Ok(process),
769 None => binding
770 .pid
771 .map(get_process)
772 .unwrap_or_else(|| Err(SysprimsError::not_found(port as u32))),
773 }
774}
775
776#[cfg(unix)]
777fn aggregate_permission_warning(skipped: usize, label: &str) -> Option<String> {
778 if skipped == 0 {
779 None
780 } else {
781 Some(format!(
782 "Skipped {} {} due to permission errors",
783 skipped, label
784 ))
785 }
786}
787
788fn aggregate_error_warning(skipped: usize, label: &str) -> Option<String> {
789 if skipped == 0 {
790 None
791 } else {
792 Some(format!("Skipped {} {} due to read errors", skipped, label))
793 }
794}
795
796pub fn snapshot_filtered(filter: &ProcessFilter) -> SysprimsResult<ProcessSnapshot> {
814 snapshot_filtered_with_options(filter, ProcessOptions::default())
815}
816
817pub fn snapshot_filtered_with_options(
837 filter: &ProcessFilter,
838 options: ProcessOptions,
839) -> SysprimsResult<ProcessSnapshot> {
840 filter.validate()?;
841 validate_process_options(&options)?;
842
843 let mut snap = snapshot_with_options(options)?;
844 snap.processes.retain(|p| filter.matches(p));
845 Ok(snap)
846}
847
848pub fn get_process(pid: u32) -> SysprimsResult<ProcessInfo> {
878 get_process_with_options(pid, ProcessOptions::default())
879}
880
881pub fn get_process_with_options(pid: u32, options: ProcessOptions) -> SysprimsResult<ProcessInfo> {
894 const MAX_SAFE_PID: u32 = i32::MAX as u32;
895
896 if pid == 0 {
897 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
898 }
899 if pid > MAX_SAFE_PID {
900 return Err(SysprimsError::invalid_argument(format!(
901 "PID {} exceeds maximum safe value {}",
902 pid, MAX_SAFE_PID
903 )));
904 }
905 validate_process_options(&options)?;
906 platform::get_process_impl(pid, &options)
907}
908
909#[derive(Debug, Clone, Serialize)]
915pub struct DescendantsLevel {
916 pub level: u32,
918
919 pub processes: Vec<ProcessInfo>,
921}
922
923#[derive(Debug, Clone, Serialize)]
925pub struct DescendantsResult {
926 pub schema_id: &'static str,
928
929 pub root_pid: u32,
931
932 pub max_levels: u32,
934
935 pub levels: Vec<DescendantsLevel>,
937
938 pub total_found: usize,
940
941 pub matched_by_filter: usize,
943
944 pub timestamp: String,
946
947 pub platform: &'static str,
949}
950
951#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
953#[serde(rename_all = "snake_case")]
954pub enum CpuMode {
955 #[default]
957 Lifetime,
958
959 Monitor,
963}
964
965#[derive(Debug, Clone)]
967pub struct DescendantsConfig {
968 pub root_pid: u32,
970
971 pub max_levels: Option<u32>,
973
974 pub filter: Option<ProcessFilter>,
976
977 pub cpu_mode: CpuMode,
979
980 pub sample_duration: Option<Duration>,
984}
985
986pub fn descendants(
1011 root_pid: u32,
1012 max_levels: u32,
1013 filter: Option<&ProcessFilter>,
1014) -> SysprimsResult<DescendantsResult> {
1015 descendants_with_options(root_pid, max_levels, filter, ProcessOptions::default())
1016}
1017
1018pub fn descendants_with_options(
1041 root_pid: u32,
1042 max_levels: u32,
1043 filter: Option<&ProcessFilter>,
1044 options: ProcessOptions,
1045) -> SysprimsResult<DescendantsResult> {
1046 descendants_with_config_and_options(
1047 DescendantsConfig {
1048 root_pid,
1049 max_levels: Some(max_levels),
1050 filter: filter.cloned(),
1051 cpu_mode: CpuMode::Lifetime,
1052 sample_duration: None,
1053 },
1054 options,
1055 )
1056}
1057
1058pub fn descendants_with_config(config: DescendantsConfig) -> SysprimsResult<DescendantsResult> {
1078 descendants_with_config_and_options(config, ProcessOptions::default())
1079}
1080
1081pub fn select_descendant_targets(
1093 result: &DescendantsResult,
1094 filter: Option<&ProcessFilter>,
1095 cascade: bool,
1096) -> Vec<u32> {
1097 let all_procs: Vec<&ProcessInfo> = result
1098 .levels
1099 .iter()
1100 .flat_map(|l| l.processes.iter())
1101 .collect();
1102
1103 let matched_roots: Vec<u32> = all_procs
1104 .iter()
1105 .filter(|p| filter.map(|f| f.matches(p)).unwrap_or(true))
1106 .map(|p| p.pid)
1107 .collect();
1108
1109 if !cascade {
1110 let mut out = matched_roots;
1111 out.sort_unstable();
1112 out.dedup();
1113 out.retain(|&pid| pid != result.root_pid);
1114 return out;
1115 }
1116
1117 let mut children_map: HashMap<u32, Vec<u32>> = HashMap::new();
1118 for proc in all_procs {
1119 children_map.entry(proc.ppid).or_default().push(proc.pid);
1120 }
1121
1122 let mut expanded: HashSet<u32> = HashSet::new();
1123 for root in matched_roots {
1124 let mut stack = vec![root];
1125 while let Some(pid) = stack.pop() {
1126 if !expanded.insert(pid) {
1127 continue;
1128 }
1129 if let Some(children) = children_map.get(&pid) {
1130 stack.extend(children.iter().copied());
1131 }
1132 }
1133 }
1134
1135 let mut out: Vec<u32> = expanded.into_iter().collect();
1136 out.sort_unstable();
1137 out.retain(|&pid| pid != result.root_pid);
1138 out
1139}
1140
1141#[derive(Debug, Clone)]
1143pub struct GuardRule {
1144 pub root_pid: u32,
1146
1147 pub max_levels: u32,
1149
1150 pub filter: Option<ProcessFilter>,
1152
1153 pub cpu_mode: CpuMode,
1155
1156 pub sample_duration: Option<Duration>,
1158}
1159
1160#[derive(Debug, Clone)]
1162pub enum GuardAction {
1163 KillDescendants {
1165 signal: i32,
1167 cascade: bool,
1169 },
1170}
1171
1172#[derive(Debug, Clone)]
1174pub struct GuardConfig {
1175 pub rule: GuardRule,
1177 pub action: GuardAction,
1179 pub action_enabled: bool,
1181 pub max_targets: u32,
1183}
1184
1185#[derive(Debug, Clone, Serialize)]
1187pub struct GuardEvent {
1188 pub schema_id: &'static str,
1190 pub timestamp: String,
1192 pub platform: &'static str,
1194 pub matched: u32,
1196 pub targeted: u32,
1198 pub killed: u32,
1200 pub failed: u32,
1202 pub skipped_safety: u32,
1204 pub warnings: Vec<String>,
1206}
1207
1208pub fn guard_step(config: GuardConfig) -> SysprimsResult<GuardEvent> {
1213 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1214
1215 if config.rule.root_pid == 0 {
1216 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1217 }
1218 if config.rule.root_pid > MAX_SAFE_PID {
1219 return Err(SysprimsError::invalid_argument(format!(
1220 "PID {} exceeds maximum safe value {}",
1221 config.rule.root_pid, MAX_SAFE_PID
1222 )));
1223 }
1224 if config.max_targets == 0 {
1225 return Err(SysprimsError::invalid_argument("max_targets must be >= 1"));
1226 }
1227 if let Some(f) = config.rule.filter.as_ref() {
1228 f.validate()?;
1229 }
1230
1231 let desc = descendants_with_config_and_options(
1232 DescendantsConfig {
1233 root_pid: config.rule.root_pid,
1234 max_levels: Some(config.rule.max_levels),
1235 filter: None,
1236 cpu_mode: config.rule.cpu_mode,
1237 sample_duration: config.rule.sample_duration,
1238 },
1239 ProcessOptions::default(),
1240 )?;
1241
1242 let matched_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), false);
1243 let matched = matched_pids.len() as u32;
1244
1245 let (signal, cascade) = match config.action {
1246 GuardAction::KillDescendants { signal, cascade } => (signal, cascade),
1247 };
1248
1249 let mut warnings = Vec::new();
1250 if !config.action_enabled {
1251 warnings.push("action disabled; no signals sent".to_string());
1252 return Ok(GuardEvent {
1253 schema_id: GUARD_EVENT_V1,
1254 timestamp: now_rfc3339(),
1255 platform: get_platform(),
1256 matched,
1257 targeted: 0,
1258 killed: 0,
1259 failed: 0,
1260 skipped_safety: 0,
1261 warnings,
1262 });
1263 }
1264
1265 let mut target_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), cascade);
1266
1267 if target_pids.len() > config.max_targets as usize {
1268 target_pids.truncate(config.max_targets as usize);
1269 warnings.push(format!(
1270 "target count capped at max_targets={} for this cycle",
1271 config.max_targets
1272 ));
1273 }
1274
1275 let self_pid = std::process::id();
1276 let parent_pid = get_process(self_pid).ok().map(|p| p.ppid);
1277
1278 let before = target_pids.len();
1279 target_pids.retain(|&pid| pid != self_pid && pid != 1 && pid != config.rule.root_pid);
1280 if let Some(ppid) = parent_pid {
1281 target_pids.retain(|&pid| pid != ppid);
1282 }
1283 let skipped_safety = before.saturating_sub(target_pids.len()) as u32;
1284 if skipped_safety > 0 {
1285 warnings.push(format!(
1286 "skipped {} unsafe target(s) (self/PID1/parent/root)",
1287 skipped_safety
1288 ));
1289 }
1290
1291 if target_pids.is_empty() {
1292 return Ok(GuardEvent {
1293 schema_id: GUARD_EVENT_V1,
1294 timestamp: now_rfc3339(),
1295 platform: get_platform(),
1296 matched,
1297 targeted: 0,
1298 killed: 0,
1299 failed: 0,
1300 skipped_safety,
1301 warnings,
1302 });
1303 }
1304
1305 let batch = sysprims_signal::kill_many(&target_pids, signal)?;
1306
1307 Ok(GuardEvent {
1308 schema_id: GUARD_EVENT_V1,
1309 timestamp: now_rfc3339(),
1310 platform: get_platform(),
1311 matched,
1312 targeted: target_pids.len() as u32,
1313 killed: batch.succeeded.len() as u32,
1314 failed: batch.failed.len() as u32,
1315 skipped_safety,
1316 warnings,
1317 })
1318}
1319
1320#[cfg(any(test, target_os = "linux", target_os = "macos"))]
1321fn is_sysprims_binary_name(name: &str) -> bool {
1322 name == "sysprims" || name.starts_with("sysprims-")
1323}
1324
1325#[cfg(any(test, target_os = "linux", target_os = "macos"))]
1326fn guard_discovery_name(cmdline: &[String], fallback_name: &str) -> Option<String> {
1327 let binary = cmdline.first()?.rsplit('/').next().unwrap_or(fallback_name);
1328 if !is_sysprims_binary_name(binary) {
1329 return None;
1330 }
1331
1332 let guard_index = cmdline.iter().position(|arg| arg == "guard")?;
1333 let root_pid = cmdline.get(guard_index + 1)?;
1334 if root_pid.parse::<u32>().ok()? == 0 {
1335 return None;
1336 }
1337
1338 Some(format!("sysprims-guard:{root_pid}"))
1339}
1340
1341#[cfg(target_os = "linux")]
1342fn set_guard_process_title(root_pid: u32) {
1343 let title = format!("sysprims-guard:{root_pid}");
1344 let truncated = title.bytes().take(15).collect::<Vec<_>>();
1345 if let Ok(c_title) = std::ffi::CString::new(truncated) {
1346 unsafe {
1347 libc::prctl(
1348 libc::PR_SET_NAME,
1349 c_title.as_ptr() as libc::c_ulong,
1350 0,
1351 0,
1352 0,
1353 );
1354 }
1355 }
1356}
1357
1358#[cfg(target_os = "macos")]
1359fn set_guard_process_title(root_pid: u32) {
1360 unsafe extern "C" {
1361 fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
1362 }
1363
1364 let title = format!("sysprims-guard:{root_pid}");
1365 let thread_title = std::ffi::CString::new(title.bytes().take(63).collect::<Vec<_>>()).ok();
1366
1367 unsafe {
1368 if let Some(name) = thread_title.as_ref() {
1369 let _ = pthread_setname_np(name.as_ptr());
1370 }
1371 }
1372}
1373
1374#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1375fn set_guard_process_title(_root_pid: u32) {}
1376
1377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1386pub enum GuardPreset {
1387 Interactive,
1389 Background,
1391 Watchdog,
1393}
1394
1395impl GuardPreset {
1396 pub fn interval(&self) -> Duration {
1398 match self {
1399 Self::Interactive => Duration::from_secs(3),
1400 Self::Background => Duration::from_secs(180),
1401 Self::Watchdog => Duration::from_secs(300),
1402 }
1403 }
1404
1405 pub fn sample_duration(&self) -> Duration {
1407 match self {
1408 Self::Interactive => Duration::from_secs(2),
1409 Self::Background => Duration::from_secs(3),
1410 Self::Watchdog => Duration::from_secs(5),
1411 }
1412 }
1413}
1414
1415#[derive(Debug, Clone)]
1417pub struct GuardRunnerConfig {
1418 pub guard: GuardConfig,
1420 pub interval: Duration,
1422 pub max_iterations: Option<u64>,
1424}
1425
1426#[derive(Debug, Clone)]
1428pub struct GuardRunnerSummary {
1429 pub ticks: u64,
1431 pub stop_reason: StopReason,
1433}
1434
1435#[derive(Debug, Clone, PartialEq, Eq)]
1437pub enum StopReason {
1438 Signal,
1440 MaxIterations,
1442 Requested,
1444}
1445
1446#[derive(Clone)]
1495pub struct GuardStopHandle {
1496 requested: Arc<std::sync::atomic::AtomicBool>,
1498 signals_flag: guard_signals::StopFlagHandle,
1500 manager: guard_signals::SignalManager,
1502}
1503
1504impl GuardStopHandle {
1505 pub fn stop(&self) {
1510 self.requested
1511 .store(true, std::sync::atomic::Ordering::SeqCst);
1512 self.signals_flag.set();
1514 self.manager.stop();
1516 }
1517}
1518
1519impl std::fmt::Debug for GuardStopHandle {
1520 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1521 f.debug_struct("GuardStopHandle")
1522 .field(
1523 "requested",
1524 &self.requested.load(std::sync::atomic::Ordering::SeqCst),
1525 )
1526 .finish()
1527 }
1528}
1529
1530pub struct GuardRunner {
1577 config: GuardRunnerConfig,
1578 signals: guard_signals::GuardSignals,
1579 tick: time::Tick,
1580 stop_requested: Arc<std::sync::atomic::AtomicBool>,
1582}
1583
1584impl GuardRunner {
1585 pub fn new(config: GuardRunnerConfig) -> SysprimsResult<Self> {
1589 let signals = guard_signals::GuardSignals::start()?;
1590 let tick = time::Tick::new(config.interval)?;
1591 Ok(Self {
1592 config,
1593 signals,
1594 tick,
1595 stop_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
1596 })
1597 }
1598
1599 pub fn stop_handle(&self) -> GuardStopHandle {
1604 GuardStopHandle {
1605 requested: Arc::clone(&self.stop_requested),
1606 signals_flag: self.signals.stop_flag_handle(),
1607 manager: self.signals.manager().clone(),
1608 }
1609 }
1610
1611 pub fn run<F, E>(
1619 &mut self,
1620 mut on_event: F,
1621 mut on_error: E,
1622 ) -> SysprimsResult<GuardRunnerSummary>
1623 where
1624 F: FnMut(&GuardEvent),
1625 E: FnMut(u64, &SysprimsError),
1626 {
1627 let mut tick_count: u64 = 0;
1628
1629 set_guard_process_title(self.config.guard.rule.root_pid);
1630
1631 while !self.signals.should_stop() {
1632 match guard_step(self.config.guard.clone()) {
1633 Ok(event) => {
1634 tick_count += 1;
1635 on_event(&event);
1636 }
1637 Err(e) => {
1638 tick_count += 1;
1639 on_error(tick_count, &e);
1640 }
1641 }
1642
1643 if let Some(max) = self.config.max_iterations {
1645 if tick_count >= max {
1646 return Ok(GuardRunnerSummary {
1647 ticks: tick_count,
1648 stop_reason: StopReason::MaxIterations,
1649 });
1650 }
1651 }
1652
1653 if self.signals.should_stop() {
1655 break;
1656 }
1657
1658 self.tick.sleep_until_next();
1659 }
1660
1661 let reason = if self
1662 .stop_requested
1663 .load(std::sync::atomic::Ordering::SeqCst)
1664 {
1665 StopReason::Requested
1666 } else {
1667 StopReason::Signal
1668 };
1669
1670 Ok(GuardRunnerSummary {
1671 ticks: tick_count,
1672 stop_reason: reason,
1673 })
1674 }
1675
1676 pub fn signals(&self) -> &guard_signals::GuardSignals {
1678 &self.signals
1679 }
1680}
1681
1682#[derive(Debug, Clone, Serialize)]
1688pub struct AncestorsResult {
1689 pub schema_id: &'static str,
1691
1692 pub timestamp: String,
1694
1695 pub platform: &'static str,
1697
1698 pub pid: u32,
1700
1701 pub chain: Vec<ProcessInfo>,
1703
1704 pub warnings: Vec<String>,
1706}
1707
1708pub fn ancestors(
1734 pid: u32,
1735 max_depth: u32,
1736 options: ProcessOptions,
1737) -> SysprimsResult<AncestorsResult> {
1738 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1739
1740 if pid == 0 {
1741 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1742 }
1743 if pid > MAX_SAFE_PID {
1744 return Err(SysprimsError::invalid_argument(format!(
1745 "PID {} exceeds maximum safe value {}",
1746 pid, MAX_SAFE_PID
1747 )));
1748 }
1749 validate_process_options(&options)?;
1750
1751 let mut chain = Vec::new();
1752 let mut warnings = Vec::new();
1753 let mut seen = HashSet::new();
1754 let mut current_pid = pid;
1755
1756 for depth in 0..=max_depth {
1757 if !seen.insert(current_pid) {
1758 warnings.push(format!(
1759 "loop detected: PID {} already visited at depth {}",
1760 current_pid, depth
1761 ));
1762 break;
1763 }
1764
1765 match get_process_with_options(current_pid, options) {
1766 Ok(info) => {
1767 let next_pid = info.ppid;
1768 chain.push(info);
1769
1770 if next_pid == 0 || next_pid == 1 || next_pid == current_pid {
1772 if next_pid == 1 && current_pid != 1 {
1774 match get_process_with_options(1, options) {
1775 Ok(init_info) => chain.push(init_info),
1776 Err(_) => {
1777 warnings.push("could not read init/launchd (PID 1)".to_string());
1778 }
1779 }
1780 }
1781 break;
1782 }
1783
1784 current_pid = next_pid;
1785 }
1786 Err(e) => {
1787 if depth == 0 {
1788 return Err(e);
1790 }
1791 warnings.push(format!(
1792 "ancestor walk stopped at PID {}: {}",
1793 current_pid, e
1794 ));
1795 break;
1796 }
1797 }
1798 }
1799
1800 Ok(AncestorsResult {
1801 schema_id: ANCESTORS_RESULT_V1,
1802 timestamp: now_rfc3339(),
1803 platform: get_platform(),
1804 pid,
1805 chain,
1806 warnings,
1807 })
1808}
1809
1810pub fn descendants_with_config_and_options(
1832 config: DescendantsConfig,
1833 options: ProcessOptions,
1834) -> SysprimsResult<DescendantsResult> {
1835 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1836
1837 if config.root_pid == 0 {
1838 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1839 }
1840 if config.root_pid > MAX_SAFE_PID {
1841 return Err(SysprimsError::invalid_argument(format!(
1842 "PID {} exceeds maximum safe value {}",
1843 config.root_pid, MAX_SAFE_PID
1844 )));
1845 }
1846
1847 validate_process_options(&options)?;
1848
1849 if let Some(f) = config.filter.as_ref() {
1850 f.validate()?;
1851 }
1852
1853 let _ = get_process_with_options(config.root_pid, options)?;
1855
1856 let snap = snapshot_for_descendants(options, config.cpu_mode, config.sample_duration)?;
1858
1859 let mut children_map: HashMap<u32, Vec<ProcessInfo>> = HashMap::new();
1861 for proc in snap.processes {
1862 children_map.entry(proc.ppid).or_default().push(proc);
1863 }
1864
1865 let mut levels: Vec<DescendantsLevel> = Vec::new();
1867 let mut current_pids = vec![config.root_pid];
1868 let mut total_found: usize = 0;
1869 let max_levels = config.max_levels.unwrap_or(u32::MAX);
1870
1871 for depth in 1..=max_levels {
1872 let mut level_procs = Vec::new();
1873 let mut next_pids = Vec::new();
1874
1875 for &pid in ¤t_pids {
1876 if let Some(children) = children_map.get(&pid) {
1877 for child in children {
1878 level_procs.push(child.clone());
1879 next_pids.push(child.pid);
1880 }
1881 }
1882 }
1883
1884 if level_procs.is_empty() {
1885 break;
1886 }
1887
1888 total_found += level_procs.len();
1889 levels.push(DescendantsLevel {
1890 level: depth,
1891 processes: level_procs,
1892 });
1893 current_pids = next_pids;
1894 }
1895
1896 let mut matched_by_filter = total_found;
1898 if let Some(f) = config.filter.as_ref() {
1899 for level in &mut levels {
1900 level.processes.retain(|p| f.matches(p));
1901 }
1902 matched_by_filter = levels.iter().map(|l| l.processes.len()).sum();
1903 levels.retain(|l| !l.processes.is_empty());
1905 }
1906
1907 Ok(DescendantsResult {
1908 schema_id: match config.cpu_mode {
1909 CpuMode::Lifetime => DESCENDANTS_RESULT_V1,
1910 CpuMode::Monitor => DESCENDANTS_RESULT_SAMPLED_V1,
1911 },
1912 root_pid: config.root_pid,
1913 max_levels,
1914 levels,
1915 total_found,
1916 matched_by_filter,
1917 timestamp: now_rfc3339(),
1918 platform: get_platform(),
1919 })
1920}
1921
1922fn snapshot_for_descendants(
1923 options: ProcessOptions,
1924 cpu_mode: CpuMode,
1925 sample_duration: Option<Duration>,
1926) -> SysprimsResult<ProcessSnapshot> {
1927 match cpu_mode {
1928 CpuMode::Lifetime => snapshot_with_options(options),
1929 CpuMode::Monitor => {
1930 let sample = sample_duration.unwrap_or_else(|| Duration::from_secs(1));
1931 snapshot_with_sampled_cpu(options, sample)
1932 }
1933 }
1934}
1935
1936fn snapshot_with_sampled_cpu(
1937 options: ProcessOptions,
1938 sample_duration: Duration,
1939) -> SysprimsResult<ProcessSnapshot> {
1940 if sample_duration.is_zero() {
1941 return Err(SysprimsError::invalid_argument(
1942 "sample duration must be > 0",
1943 ));
1944 }
1945
1946 let snap0 = snapshot_with_options(options)?;
1947 let mut t0 = HashMap::<u32, (Option<u64>, u64)>::new();
1948 for p in &snap0.processes {
1949 if let Ok(cpu_ns) = cpu_total_time_ns(p.pid) {
1950 t0.insert(p.pid, (p.start_time_unix_ms, cpu_ns));
1951 }
1952 }
1953
1954 std::thread::sleep(sample_duration);
1955
1956 let mut snap1 = snapshot_with_options(options)?;
1957 let dt_ns = sample_duration.as_nanos() as f64;
1958 if dt_ns > 0.0 {
1959 for p in &mut snap1.processes {
1960 if let Some((start0, cpu0)) = t0.get(&p.pid) {
1961 if start0.is_some()
1963 && p.start_time_unix_ms.is_some()
1964 && start0 != &p.start_time_unix_ms
1965 {
1966 continue;
1967 }
1968
1969 if let Ok(cpu1) = cpu_total_time_ns(p.pid) {
1970 let delta = cpu1.saturating_sub(*cpu0) as f64;
1971 p.cpu_percent = (delta / dt_ns) * 100.0;
1972 }
1973 }
1974 }
1975 }
1976
1977 snap1.schema_id = PROCESS_INFO_SAMPLED_V1;
1979 Ok(snap1)
1980}
1981
1982pub fn wait_pid(pid: u32, timeout: Duration) -> SysprimsResult<WaitPidResult> {
2000 const MAX_SAFE_PID: u32 = i32::MAX as u32;
2001
2002 if pid == 0 {
2003 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2004 }
2005 if pid > MAX_SAFE_PID {
2006 return Err(SysprimsError::invalid_argument(format!(
2007 "PID {} exceeds maximum safe value {}",
2008 pid, MAX_SAFE_PID
2009 )));
2010 }
2011 platform::wait_pid_impl(pid, timeout)
2012}
2013
2014pub fn is_live(pid: u32) -> SysprimsResult<bool> {
2052 const MAX_SAFE_PID: u32 = i32::MAX as u32;
2053
2054 if pid == 0 {
2055 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2056 }
2057 if pid > MAX_SAFE_PID {
2058 return Err(SysprimsError::invalid_argument(format!(
2059 "PID {} exceeds maximum safe value {}",
2060 pid, MAX_SAFE_PID
2061 )));
2062 }
2063 Ok(platform::liveness_impl(pid)? == Liveness::Live)
2064}
2065
2066pub fn is_fully_gone(pid: u32) -> SysprimsResult<bool> {
2089 const MAX_SAFE_PID: u32 = i32::MAX as u32;
2090
2091 if pid == 0 {
2092 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2093 }
2094 if pid > MAX_SAFE_PID {
2095 return Err(SysprimsError::invalid_argument(format!(
2096 "PID {} exceeds maximum safe value {}",
2097 pid, MAX_SAFE_PID
2098 )));
2099 }
2100 Ok(platform::liveness_impl(pid)? == Liveness::Gone)
2101}
2102
2103fn make_port_snapshot(bindings: Vec<PortBinding>, warnings: Vec<String>) -> PortBindingsSnapshot {
2108 let mut warnings = warnings;
2109 if bindings.is_empty() {
2110 warnings.push("No listening ports found".to_string());
2111 }
2112
2113 PortBindingsSnapshot {
2114 schema_id: PORT_BINDINGS_V1,
2115 timestamp: now_rfc3339(),
2116 platform: get_platform(),
2117 bindings,
2118 warnings,
2119 }
2120}
2121
2122fn make_fd_snapshot(pid: u32, fds: Vec<FdInfo>, warnings: Vec<String>) -> FdSnapshot {
2123 FdSnapshot {
2124 schema_id: FD_SNAPSHOT_V1,
2125 timestamp: now_rfc3339(),
2126 platform: get_platform(),
2127 pid,
2128 fds,
2129 warnings,
2130 }
2131}
2132
2133fn make_snapshot(processes: Vec<ProcessInfo>) -> ProcessSnapshot {
2137 ProcessSnapshot {
2138 schema_id: PROCESS_INFO_V1,
2139 timestamp: now_rfc3339(),
2140 processes,
2141 }
2142}
2143
2144fn make_wait_pid_result(
2145 pid: u32,
2146 exited: bool,
2147 timed_out: bool,
2148 exit_code: Option<i32>,
2149 warnings: Vec<String>,
2150) -> WaitPidResult {
2151 WaitPidResult {
2152 schema_id: WAIT_PID_RESULT_V1,
2153 timestamp: now_rfc3339(),
2154 platform: get_platform(),
2155 pid,
2156 exited,
2157 timed_out,
2158 exit_code,
2159 warnings,
2160 }
2161}
2162
2163#[cfg(test)]
2168mod tests {
2169 use super::*;
2170 use std::process::{Child, Command, Stdio};
2171 use std::thread;
2172
2173 #[test]
2174 fn test_snapshot_not_empty() {
2175 let snap = snapshot().unwrap();
2176 assert!(
2177 !snap.processes.is_empty(),
2178 "Snapshot should contain processes"
2179 );
2180 }
2181
2182 #[test]
2183 fn test_snapshot_has_schema_id() {
2184 let snap = snapshot().unwrap();
2185 assert_eq!(snap.schema_id, PROCESS_INFO_V1);
2186 assert!(snap.schema_id.contains("process-info"));
2187 }
2188
2189 #[test]
2190 fn test_snapshot_has_timestamp() {
2191 let snap = snapshot().unwrap();
2192 assert!(!snap.timestamp.is_empty());
2193 assert!(snap.timestamp.contains('T'));
2195 assert!(snap.timestamp.contains('Z') || snap.timestamp.contains('+'));
2196 }
2197
2198 #[test]
2199 #[cfg(unix)]
2200 fn test_snapshot_has_processes() {
2201 let snap = snapshot().unwrap();
2205
2206 let own_pid = std::process::id();
2208 let has_self = snap.processes.iter().any(|p| p.pid == own_pid);
2209 assert!(has_self, "Snapshot should include our own process");
2210
2211 assert!(
2213 snap.processes.len() >= 3,
2214 "Should have at least a few visible processes, got {}",
2215 snap.processes.len()
2216 );
2217 }
2218
2219 #[test]
2220 fn test_get_self() {
2221 let pid = std::process::id();
2222 let info = get_process(pid).unwrap();
2223 assert_eq!(info.pid, pid);
2224 assert!(!info.name.is_empty(), "Process should have a name");
2225 }
2226
2227 #[test]
2228 #[cfg(target_os = "macos")]
2229 fn test_own_process_has_cmdline() {
2230 let snap = snapshot().unwrap();
2231 let own_pid = std::process::id();
2232 let own_proc = snap
2233 .processes
2234 .iter()
2235 .find(|p| p.pid == own_pid)
2236 .expect("Should find own process in snapshot");
2237 assert!(
2238 !own_proc.cmdline.is_empty(),
2239 "Own process should have cmdline, got empty"
2240 );
2241 }
2242
2243 #[test]
2244 fn test_get_self_has_valid_fields() {
2245 let pid = std::process::id();
2246 let info = get_process(pid).unwrap();
2247
2248 assert!(info.cpu_percent >= 0.0);
2250 assert!(info.cpu_percent <= 100.0);
2251
2252 assert!(info.memory_kb < u64::MAX);
2255
2256 if let Some(ms) = info.start_time_unix_ms {
2258 assert!(ms > 0);
2259 }
2260 if let Some(ref exe) = info.exe_path {
2261 assert!(!exe.is_empty());
2262 }
2263
2264 assert!(
2267 info.state == ProcessState::Running
2268 || info.state == ProcessState::Sleeping
2269 || info.state == ProcessState::Unknown,
2270 "Test process should be running, sleeping, or unknown (Windows)"
2271 );
2272 }
2273
2274 #[test]
2275 fn test_wait_pid_self_times_out() {
2276 let pid = std::process::id();
2277 let r = wait_pid(pid, Duration::from_millis(1)).unwrap();
2278 assert_eq!(r.pid, pid);
2279 assert!(r.timed_out);
2280 assert!(!r.exited);
2281 }
2282
2283 #[test]
2287 fn pid_taking_entrypoints_reject_unsafe_pids() {
2288 let over_max = (i32::MAX as u32) + 1;
2289 for &pid in &[0u32, over_max, u32::MAX] {
2290 assert!(
2291 matches!(get_process(pid), Err(SysprimsError::InvalidArgument { .. })),
2292 "get_process must reject unsafe PID {pid}"
2293 );
2294 assert!(
2295 matches!(
2296 wait_pid(pid, Duration::from_millis(1)),
2297 Err(SysprimsError::InvalidArgument { .. })
2298 ),
2299 "wait_pid must reject unsafe PID {pid}"
2300 );
2301 assert!(
2302 matches!(
2303 cpu_total_time_ns(pid),
2304 Err(SysprimsError::InvalidArgument { .. })
2305 ),
2306 "cpu_total_time_ns must reject unsafe PID {pid}"
2307 );
2308 }
2309 }
2310
2311 #[test]
2312 fn test_filter_by_name_contains() {
2313 let filter = ProcessFilter {
2315 name_contains: Some("sysprims".into()),
2316 ..Default::default()
2317 };
2318 let snap = snapshot_filtered(&filter).unwrap();
2319
2320 for proc in &snap.processes {
2321 assert!(
2322 proc.name.to_lowercase().contains("sysprims"),
2323 "Filtered process '{}' should contain 'sysprims'",
2324 proc.name
2325 );
2326 }
2327 }
2328
2329 #[test]
2330 fn test_guard_discovery_name_matches_guard_cmdline() {
2331 let cmdline = vec![
2332 "/usr/local/bin/sysprims".to_string(),
2333 "guard".to_string(),
2334 "27776".to_string(),
2335 "--preset".to_string(),
2336 "watchdog".to_string(),
2337 ];
2338
2339 assert_eq!(
2340 guard_discovery_name(&cmdline, "sysprims"),
2341 Some("sysprims-guard:27776".to_string())
2342 );
2343 }
2344
2345 #[test]
2346 fn test_guard_discovery_name_ignores_non_guard_cmdline() {
2347 let cmdline = vec![
2348 "/usr/local/bin/sysprims".to_string(),
2349 "pstat".to_string(),
2350 "--json".to_string(),
2351 ];
2352
2353 assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
2354 }
2355
2356 #[test]
2357 fn test_guard_discovery_name_rejects_invalid_root_pid() {
2358 let cmdline = vec![
2359 "/usr/local/bin/sysprims".to_string(),
2360 "guard".to_string(),
2361 "not-a-pid".to_string(),
2362 ];
2363
2364 assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
2365 }
2366
2367 #[test]
2368 fn test_filter_by_pid() {
2369 let my_pid = std::process::id();
2370 let filter = ProcessFilter {
2371 pid_in: Some(vec![my_pid]),
2372 ..Default::default()
2373 };
2374 let snap = snapshot_filtered(&filter).unwrap();
2375
2376 assert_eq!(snap.processes.len(), 1);
2377 assert_eq!(snap.processes[0].pid, my_pid);
2378 }
2379
2380 #[test]
2381 fn test_filter_validation_cpu_range() {
2382 let filter = ProcessFilter {
2383 cpu_above: Some(150.0),
2384 ..Default::default()
2385 };
2386 let result = filter.validate();
2387 assert!(result.is_err());
2388
2389 let filter = ProcessFilter {
2390 cpu_above: Some(-1.0),
2391 ..Default::default()
2392 };
2393 let result = filter.validate();
2394 assert!(result.is_err());
2395
2396 let filter = ProcessFilter {
2397 cpu_above: Some(50.0),
2398 ..Default::default()
2399 };
2400 let result = filter.validate();
2401 assert!(result.is_ok());
2402 }
2403
2404 #[test]
2405 fn test_nonexistent_pid() {
2406 let result = get_process(99999999);
2408 assert!(
2409 matches!(result, Err(SysprimsError::NotFound { .. })),
2410 "Should return NotFound for nonexistent PID"
2411 );
2412 }
2413
2414 #[test]
2415 fn test_invalid_pid_zero() {
2416 let result = get_process(0);
2417 assert!(
2418 matches!(result, Err(SysprimsError::InvalidArgument { .. })),
2419 "PID 0 should be invalid"
2420 );
2421 }
2422
2423 #[test]
2424 fn test_cpu_normalized() {
2425 let snap = snapshot().unwrap();
2426 for proc in &snap.processes {
2427 assert!(
2428 proc.cpu_percent >= 0.0,
2429 "CPU percent for PID {} should be >= 0",
2430 proc.pid
2431 );
2432 assert!(
2433 proc.cpu_percent <= 100.0,
2434 "CPU percent for PID {} should be <= 100, got {}",
2435 proc.pid,
2436 proc.cpu_percent
2437 );
2438 }
2439 }
2440
2441 #[test]
2442 fn test_process_state_serialization() {
2443 let json = serde_json::to_string(&ProcessState::Running).unwrap();
2445 assert_eq!(json, "\"running\"");
2446
2447 let json = serde_json::to_string(&ProcessState::Sleeping).unwrap();
2448 assert_eq!(json, "\"sleeping\"");
2449
2450 let json = serde_json::to_string(&ProcessState::Zombie).unwrap();
2451 assert_eq!(json, "\"zombie\"");
2452 }
2453
2454 #[test]
2455 fn test_filter_deserialization() {
2456 let json = r#"{"name_contains": "test", "cpu_above": 5.0}"#;
2457 let filter: ProcessFilter = serde_json::from_str(json).unwrap();
2458 assert_eq!(filter.name_contains, Some("test".to_string()));
2459 assert_eq!(filter.cpu_above, Some(5.0));
2460 }
2461
2462 #[test]
2463 fn test_filter_unknown_field_rejected() {
2464 let json = r#"{"unknown_field": "value"}"#;
2465 let result: Result<ProcessFilter, _> = serde_json::from_str(json);
2466 assert!(result.is_err(), "Unknown fields should be rejected");
2467 }
2468
2469 #[test]
2470 fn test_port_filter_unknown_field_rejected() {
2471 let json = r#"{"unknown_field": true}"#;
2472 let result: Result<PortFilter, _> = serde_json::from_str(json);
2473 assert!(result.is_err(), "Unknown fields should be rejected");
2474 }
2475
2476 #[test]
2477 fn test_port_filter_schema_id() {
2478 assert!(PortFilter::schema_id().contains("port-filter"));
2479 }
2480
2481 #[test]
2482 fn test_process_options_builder() {
2483 let opts = ProcessOptions::default();
2484 assert!(!opts.include_env);
2485 assert!(!opts.include_threads);
2486
2487 let opts = ProcessOptions::default().with_env().with_threads();
2488 assert!(opts.include_env);
2489 assert!(opts.include_threads);
2490 }
2491
2492 #[test]
2493 fn test_get_process_with_default_options_has_no_proc_ext_fields() {
2494 let pid = std::process::id();
2495 let info = get_process_with_options(pid, ProcessOptions::default()).unwrap();
2496 assert!(info.env.is_none());
2497 assert!(info.thread_count.is_none());
2498 }
2499
2500 #[test]
2501 #[cfg(feature = "proc_ext")]
2502 fn test_get_process_with_threads_populates_thread_count() {
2503 let pid = std::process::id();
2504 let info = get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
2505 assert!(info.thread_count.is_some());
2506 }
2507
2508 #[test]
2509 #[cfg(all(feature = "proc_ext", unix))]
2510 fn test_get_process_with_env_populates_env_map() {
2511 let pid = std::process::id();
2512 let info = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap();
2513 assert!(info.env.is_some());
2514 }
2515
2516 #[test]
2517 #[cfg(not(feature = "proc_ext"))]
2518 fn test_proc_ext_options_rejected_when_feature_disabled() {
2519 let pid = std::process::id();
2520 let err = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap_err();
2521 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2522 }
2523
2524 #[test]
2525 fn test_descendants_with_config_lifetime_self() {
2526 let pid = std::process::id();
2527 let config = DescendantsConfig {
2528 root_pid: pid,
2529 max_levels: Some(1),
2530 filter: None,
2531 cpu_mode: CpuMode::Lifetime,
2532 sample_duration: None,
2533 };
2534
2535 let result = descendants_with_config(config).unwrap();
2536 assert_eq!(result.root_pid, pid);
2537 assert_eq!(result.max_levels, 1);
2538 }
2539
2540 #[test]
2541 fn test_descendants_with_config_monitor_self() {
2542 let pid = std::process::id();
2543 let config = DescendantsConfig {
2544 root_pid: pid,
2545 max_levels: Some(1),
2546 filter: None,
2547 cpu_mode: CpuMode::Monitor,
2548 sample_duration: Some(Duration::from_millis(1)),
2549 };
2550
2551 let result = descendants_with_config(config).unwrap();
2552 assert_eq!(result.schema_id, DESCENDANTS_RESULT_SAMPLED_V1);
2553 assert_eq!(result.root_pid, pid);
2554 assert_eq!(result.max_levels, 1);
2555 }
2556
2557 #[test]
2558 fn test_descendants_with_config_monitor_zero_sample_rejected() {
2559 let config = DescendantsConfig {
2560 root_pid: std::process::id(),
2561 max_levels: Some(1),
2562 filter: None,
2563 cpu_mode: CpuMode::Monitor,
2564 sample_duration: Some(Duration::ZERO),
2565 };
2566
2567 let err = descendants_with_config(config).unwrap_err();
2568 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2569 }
2570
2571 #[test]
2572 fn test_descendants_with_config_invalid_pid_zero_rejected_before_sampling() {
2573 let config = DescendantsConfig {
2574 root_pid: 0,
2575 max_levels: Some(1),
2576 filter: None,
2577 cpu_mode: CpuMode::Monitor,
2578 sample_duration: Some(Duration::from_secs(1)),
2579 };
2580
2581 let err = descendants_with_config(config).unwrap_err();
2582 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2583 }
2584
2585 #[test]
2586 fn test_snapshot_json_output() {
2587 let snap = snapshot().unwrap();
2588 let json = serde_json::to_string_pretty(&snap).unwrap();
2589
2590 assert!(json.contains("\"schema_id\""));
2592 assert!(json.contains("\"timestamp\""));
2593 assert!(json.contains("\"processes\""));
2594 assert!(json.contains(PROCESS_INFO_V1));
2595 }
2596
2597 fn test_process(pid: u32, ppid: u32, name: &str) -> ProcessInfo {
2598 ProcessInfo {
2599 pid,
2600 ppid,
2601 name: name.to_string(),
2602 user: None,
2603 cpu_percent: 0.0,
2604 memory_kb: 0,
2605 elapsed_seconds: 0,
2606 start_time_unix_ms: None,
2607 exe_path: None,
2608 state: ProcessState::Running,
2609 cmdline: vec![],
2610 env: None,
2611 thread_count: None,
2612 }
2613 }
2614
2615 fn test_descendants_tree() -> DescendantsResult {
2616 DescendantsResult {
2617 schema_id: DESCENDANTS_RESULT_V1,
2618 root_pid: 10,
2619 max_levels: 10,
2620 levels: vec![
2621 DescendantsLevel {
2622 level: 1,
2623 processes: vec![test_process(11, 10, "helper"), test_process(12, 10, "db")],
2624 },
2625 DescendantsLevel {
2626 level: 2,
2627 processes: vec![
2628 test_process(13, 11, "child-a"),
2629 test_process(14, 12, "child-b"),
2630 ],
2631 },
2632 ],
2633 total_found: 4,
2634 matched_by_filter: 4,
2635 timestamp: "1970-01-01T00:00:00Z".to_string(),
2636 platform: get_platform(),
2637 }
2638 }
2639
2640 fn spawn_sleep_child() -> Child {
2641 #[cfg(unix)]
2642 {
2643 Command::new("sleep")
2644 .arg("30")
2645 .stdin(Stdio::null())
2646 .stdout(Stdio::null())
2647 .stderr(Stdio::null())
2648 .spawn()
2649 .expect("spawn sleep child")
2650 }
2651
2652 #[cfg(windows)]
2653 {
2654 Command::new("cmd")
2655 .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
2656 .stdin(Stdio::null())
2657 .stdout(Stdio::null())
2658 .stderr(Stdio::null())
2659 .spawn()
2660 .expect("spawn ping child")
2661 }
2662 }
2663
2664 fn guard_step_retry(config: &GuardConfig, attempts: usize, delay_ms: u64) -> GuardEvent {
2665 let mut last = None;
2666 for attempt in 0..attempts {
2667 let event = guard_step(config.clone()).expect("guard_step should succeed");
2668 let ready = if config.action_enabled {
2669 event.targeted > 0 && (event.killed > 0 || event.failed > 0)
2670 } else {
2671 true
2672 };
2673 if ready {
2674 return event;
2675 }
2676 last = Some(event);
2677 if attempt + 1 < attempts {
2678 thread::sleep(Duration::from_millis(delay_ms));
2679 }
2680 }
2681 last.expect("guard_step retry should record an event")
2682 }
2683
2684 #[test]
2685 fn test_select_descendant_targets_non_cascade() {
2686 let result = test_descendants_tree();
2687 let filter = ProcessFilter {
2688 name_contains: Some("helper".to_string()),
2689 ..Default::default()
2690 };
2691
2692 let targets = select_descendant_targets(&result, Some(&filter), false);
2693 assert_eq!(targets, vec![11]);
2694 }
2695
2696 #[test]
2697 fn test_select_descendant_targets_cascade() {
2698 let result = test_descendants_tree();
2699 let filter = ProcessFilter {
2700 name_contains: Some("helper".to_string()),
2701 ..Default::default()
2702 };
2703
2704 let targets = select_descendant_targets(&result, Some(&filter), true);
2705 assert_eq!(targets, vec![11, 13]);
2706 }
2707
2708 #[test]
2709 fn test_guard_step_action_disabled_emits_event() {
2710 let cfg = GuardConfig {
2711 rule: GuardRule {
2712 root_pid: std::process::id(),
2713 max_levels: 1,
2714 filter: None,
2715 cpu_mode: CpuMode::Lifetime,
2716 sample_duration: None,
2717 },
2718 action: GuardAction::KillDescendants {
2719 signal: 15,
2720 cascade: false,
2721 },
2722 action_enabled: false,
2723 max_targets: 32,
2724 };
2725
2726 let event = guard_step(cfg).unwrap();
2727 assert_eq!(event.schema_id, GUARD_EVENT_V1);
2728 assert_eq!(event.targeted, 0);
2729 assert_eq!(event.killed, 0);
2730 assert_eq!(event.failed, 0);
2731 assert!(event.warnings.iter().any(|w| w.contains("action disabled")));
2732 }
2733
2734 #[test]
2735 fn test_guard_step_rejects_zero_max_targets() {
2736 let cfg = GuardConfig {
2737 rule: GuardRule {
2738 root_pid: std::process::id(),
2739 max_levels: 1,
2740 filter: None,
2741 cpu_mode: CpuMode::Lifetime,
2742 sample_duration: None,
2743 },
2744 action: GuardAction::KillDescendants {
2745 signal: 15,
2746 cascade: false,
2747 },
2748 action_enabled: false,
2749 max_targets: 0,
2750 };
2751
2752 let err = guard_step(cfg).unwrap_err();
2753 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2754 }
2755
2756 #[test]
2757 fn test_guard_step_action_enabled_kills_targeted_child() {
2758 let mut child = spawn_sleep_child();
2759 let child_pid = child.id();
2760
2761 let mut child_visible = false;
2762 for _ in 0..20 {
2763 let desc = descendants_with_config(DescendantsConfig {
2764 root_pid: std::process::id(),
2765 max_levels: Some(1),
2766 filter: Some(ProcessFilter {
2767 pid_in: Some(vec![child_pid]),
2768 ..Default::default()
2769 }),
2770 cpu_mode: CpuMode::Lifetime,
2771 sample_duration: None,
2772 })
2773 .unwrap();
2774 if desc.matched_by_filter >= 1 {
2775 child_visible = true;
2776 break;
2777 }
2778 thread::sleep(Duration::from_millis(50));
2779 }
2780 assert!(child_visible, "expected spawned child to be visible");
2781
2782 let cfg = GuardConfig {
2783 rule: GuardRule {
2784 root_pid: std::process::id(),
2785 max_levels: 1,
2786 filter: Some(ProcessFilter {
2787 pid_in: Some(vec![child_pid]),
2788 ..Default::default()
2789 }),
2790 cpu_mode: CpuMode::Lifetime,
2791 sample_duration: None,
2792 },
2793 action: GuardAction::KillDescendants {
2794 signal: 15,
2795 cascade: false,
2796 },
2797 action_enabled: true,
2798 max_targets: 8,
2799 };
2800
2801 let event = guard_step_retry(&cfg, 10, 100);
2802 assert_eq!(event.targeted, 1);
2803 assert_eq!(event.killed, 1);
2804 assert_eq!(event.failed, 0);
2805
2806 let mut exited = false;
2807 for _ in 0..20 {
2808 if let Some(_status) = child.try_wait().expect("poll child exit") {
2809 exited = true;
2810 break;
2811 }
2812 thread::sleep(Duration::from_millis(100));
2813 }
2814 if !exited {
2815 let _ = child.kill();
2816 let _ = child.wait();
2817 }
2818 assert!(exited, "guard_step should terminate targeted child");
2819 }
2820
2821 #[test]
2822 fn test_guard_step_action_enabled_applies_max_targets_cap() {
2823 let mut child_a = spawn_sleep_child();
2824 let mut child_b = spawn_sleep_child();
2825 let pids = vec![child_a.id(), child_b.id()];
2826
2827 let mut both_visible = false;
2829 for _ in 0..20 {
2830 let desc = descendants_with_config(DescendantsConfig {
2831 root_pid: std::process::id(),
2832 max_levels: Some(1),
2833 filter: Some(ProcessFilter {
2834 pid_in: Some(pids.clone()),
2835 ..Default::default()
2836 }),
2837 cpu_mode: CpuMode::Lifetime,
2838 sample_duration: None,
2839 })
2840 .unwrap();
2841 if desc.matched_by_filter >= 2 {
2842 both_visible = true;
2843 break;
2844 }
2845 thread::sleep(Duration::from_millis(50));
2846 }
2847 assert!(both_visible, "expected both spawned children to be visible");
2848
2849 let cfg = GuardConfig {
2850 rule: GuardRule {
2851 root_pid: std::process::id(),
2852 max_levels: 1,
2853 filter: Some(ProcessFilter {
2854 pid_in: Some(pids.clone()),
2855 ..Default::default()
2856 }),
2857 cpu_mode: CpuMode::Lifetime,
2858 sample_duration: None,
2859 },
2860 action: GuardAction::KillDescendants {
2861 signal: 15,
2862 cascade: false,
2863 },
2864 action_enabled: true,
2865 max_targets: 1,
2866 };
2867
2868 let event = guard_step_retry(&cfg, 10, 100);
2869
2870 assert_eq!(event.matched, 2);
2871 assert_eq!(event.targeted, 1);
2872 assert_eq!(event.killed, 1);
2873 assert_eq!(event.failed, 0);
2874 assert!(
2875 event
2876 .warnings
2877 .iter()
2878 .any(|w| w.contains("target count capped at max_targets=1")),
2879 "expected max_targets cap warning, got: {:?}",
2880 event.warnings
2881 );
2882
2883 let mut exited_count = 0;
2885 for _ in 0..20 {
2886 exited_count = 0;
2887 if child_a.try_wait().expect("poll child A").is_some() {
2888 exited_count += 1;
2889 }
2890 if child_b.try_wait().expect("poll child B").is_some() {
2891 exited_count += 1;
2892 }
2893 if exited_count >= 1 {
2894 break;
2895 }
2896 thread::sleep(Duration::from_millis(100));
2897 }
2898 assert!(
2899 exited_count >= 1,
2900 "expected at least one child to exit after capped guard_step kill"
2901 );
2902
2903 for child in [&mut child_a, &mut child_b] {
2904 if child.try_wait().expect("final poll").is_none() {
2905 let _ = child.kill();
2906 let _ = child.wait();
2907 }
2908 }
2909 }
2910
2911 #[test]
2912 fn test_ancestors_self() {
2913 let pid = std::process::id();
2914 let result = ancestors(pid, 64, ProcessOptions::default()).unwrap();
2915
2916 assert_eq!(result.schema_id, ANCESTORS_RESULT_V1);
2917 assert_eq!(result.pid, pid);
2918 assert!(
2919 !result.chain.is_empty(),
2920 "chain should include at least self"
2921 );
2922 assert_eq!(
2923 result.chain[0].pid, pid,
2924 "first element should be starting PID"
2925 );
2926
2927 assert!(
2929 result.chain.len() >= 2,
2930 "chain should include at least self and parent, got {}",
2931 result.chain.len()
2932 );
2933 }
2934
2935 #[test]
2936 fn test_ancestors_rejects_pid_zero() {
2937 let err = ancestors(0, 10, ProcessOptions::default()).unwrap_err();
2938 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2939 }
2940
2941 #[test]
2942 fn test_ancestors_nonexistent_pid() {
2943 let err = ancestors(99999999, 10, ProcessOptions::default()).unwrap_err();
2944 assert!(matches!(err, SysprimsError::NotFound { .. }));
2945 }
2946
2947 #[test]
2948 fn test_ancestors_max_depth_zero() {
2949 let pid = std::process::id();
2950 let result = ancestors(pid, 0, ProcessOptions::default()).unwrap();
2951
2952 assert_eq!(result.chain.len(), 1);
2954 assert_eq!(result.chain[0].pid, pid);
2955 }
2956}