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
68#[cfg(target_os = "linux")]
70use linux as platform;
71#[cfg(target_os = "macos")]
72use macos as platform;
73#[cfg(windows)]
74use windows as platform;
75
76#[derive(Debug, Clone, Serialize)]
84pub struct ProcessSnapshot {
85 pub schema_id: &'static str,
87
88 pub timestamp: String,
90
91 pub processes: Vec<ProcessInfo>,
93}
94
95#[derive(Debug, Clone, Serialize)]
101pub struct WaitPidResult {
102 pub schema_id: &'static str,
104
105 pub timestamp: String,
107
108 pub platform: &'static str,
110
111 pub pid: u32,
113
114 pub exited: bool,
116
117 pub timed_out: bool,
119
120 #[serde(skip_serializing_if = "Option::is_none")]
122 pub exit_code: Option<i32>,
123
124 pub warnings: Vec<String>,
126}
127
128#[derive(Debug, Clone, Serialize)]
130pub struct PortBindingsSnapshot {
131 pub schema_id: &'static str,
133
134 pub timestamp: String,
136
137 pub platform: &'static str,
139
140 pub bindings: Vec<PortBinding>,
142
143 pub warnings: Vec<String>,
145}
146
147#[derive(Debug, Clone, Serialize)]
149pub struct PortBinding {
150 pub protocol: Protocol,
152
153 #[serde(skip_serializing_if = "Option::is_none")]
155 pub local_addr: Option<IpAddr>,
156
157 pub local_port: u16,
159
160 #[serde(skip_serializing_if = "Option::is_none")]
162 pub state: Option<String>,
163
164 #[serde(skip_serializing_if = "Option::is_none")]
166 pub pid: Option<u32>,
167
168 #[serde(skip_serializing_if = "Option::is_none")]
170 pub process: Option<ProcessInfo>,
171
172 #[serde(skip)]
174 pub inode: Option<u64>,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "snake_case")]
180pub enum Protocol {
181 Tcp,
182 Udp,
183}
184
185#[derive(Debug, Clone, Default, Deserialize)]
187#[serde(deny_unknown_fields)]
188pub struct PortFilter {
189 pub protocol: Option<Protocol>,
191
192 pub local_port: Option<u16>,
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "snake_case")]
199pub enum FdKind {
200 File,
201 Socket,
202 Pipe,
203 Unknown,
204}
205
206#[derive(Debug, Clone, Default, Deserialize)]
208#[serde(deny_unknown_fields)]
209pub struct FdFilter {
210 pub kind: Option<FdKind>,
212}
213
214impl FdFilter {
215 pub fn validate(&self) -> SysprimsResult<()> {
216 Ok(())
218 }
219}
220
221#[derive(Debug, Clone, Serialize)]
223pub struct FdInfo {
224 pub fd: u32,
226
227 pub kind: FdKind,
229
230 #[serde(skip_serializing_if = "Option::is_none")]
232 pub path: Option<String>,
233}
234
235#[derive(Debug, Clone, Serialize)]
237pub struct FdSnapshot {
238 pub schema_id: &'static str,
240
241 pub timestamp: String,
243
244 pub platform: &'static str,
246
247 pub pid: u32,
249
250 pub fds: Vec<FdInfo>,
252
253 pub warnings: Vec<String>,
255}
256
257#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
262#[serde(default, deny_unknown_fields)]
263pub struct ProcessOptions {
264 pub include_env: bool,
270
271 pub include_threads: bool,
273}
274
275impl ProcessOptions {
276 pub fn with_env(mut self) -> Self {
278 self.include_env = true;
279 self
280 }
281
282 pub fn with_threads(mut self) -> Self {
284 self.include_threads = true;
285 self
286 }
287}
288
289#[cfg(all(feature = "proc_ext", unix))]
291pub(crate) const MAX_ENV_ENTRIES: usize = 1024;
292#[cfg(all(feature = "proc_ext", unix))]
293pub(crate) const MAX_ENV_KEY_BYTES: usize = 1024;
294#[cfg(all(feature = "proc_ext", unix))]
295pub(crate) const MAX_ENV_VALUE_BYTES: usize = 4096;
296#[cfg(all(feature = "proc_ext", unix))]
297pub(crate) const MAX_ENV_TOTAL_BYTES: usize = 1_048_576;
298
299#[derive(Debug, Clone, Serialize)]
304pub struct ProcessInfo {
305 pub pid: u32,
307
308 pub ppid: u32,
310
311 pub name: String,
313
314 #[serde(skip_serializing_if = "Option::is_none")]
316 pub user: Option<String>,
317
318 pub cpu_percent: f64,
323
324 pub memory_kb: u64,
326
327 pub elapsed_seconds: u64,
329
330 #[serde(skip_serializing_if = "Option::is_none")]
334 pub start_time_unix_ms: Option<u64>,
335
336 #[serde(skip_serializing_if = "Option::is_none")]
340 pub exe_path: Option<String>,
341
342 pub state: ProcessState,
344
345 pub cmdline: Vec<String>,
349
350 #[serde(skip_serializing_if = "Option::is_none")]
352 pub env: Option<BTreeMap<String, String>>,
353
354 #[serde(skip_serializing_if = "Option::is_none")]
356 pub thread_count: Option<u32>,
357}
358
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
363#[serde(rename_all = "snake_case")]
364pub enum ProcessState {
365 Running,
367 Sleeping,
369 Stopped,
371 Zombie,
373 Unknown,
375}
376
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387#[cfg_attr(windows, allow(dead_code))]
388pub(crate) enum Liveness {
389 Live,
391 Zombie,
393 Gone,
395}
396
397#[derive(Debug, Clone, Default, Deserialize)]
402#[serde(deny_unknown_fields)]
403pub struct ProcessFilter {
404 pub name_contains: Option<String>,
406
407 pub name_equals: Option<String>,
409
410 pub user_equals: Option<String>,
412
413 pub pid_in: Option<Vec<u32>>,
415
416 pub ppid: Option<u32>,
418
419 pub state_in: Option<Vec<ProcessState>>,
421
422 pub cpu_above: Option<f64>,
424
425 pub memory_above_kb: Option<u64>,
427
428 pub running_for_at_least_secs: Option<u64>,
432}
433
434impl ProcessFilter {
435 pub fn validate(&self) -> SysprimsResult<()> {
439 if let Some(cpu) = self.cpu_above {
440 if !(0.0..=100.0).contains(&cpu) {
441 return Err(SysprimsError::invalid_argument(
442 "cpu_above must be between 0 and 100",
443 ));
444 }
445 }
446 Ok(())
447 }
448}
449
450fn validate_process_options(options: &ProcessOptions) -> SysprimsResult<()> {
451 #[cfg(feature = "proc_ext")]
452 {
453 let _ = options;
454 }
455
456 #[cfg(not(feature = "proc_ext"))]
457 {
458 if options.include_env || options.include_threads {
459 return Err(SysprimsError::invalid_argument(
460 "include_env/include_threads require the proc_ext feature",
461 ));
462 }
463 }
464
465 Ok(())
466}
467
468impl PortFilter {
469 pub fn validate(&self) -> SysprimsResult<()> {
471 if let Some(port) = self.local_port {
472 if port == 0 {
473 return Err(SysprimsError::invalid_argument(
474 "local_port must be between 1 and 65535",
475 ));
476 }
477 }
478 Ok(())
479 }
480
481 pub fn schema_id() -> &'static str {
482 PORT_FILTER_V1
483 }
484}
485
486impl FdInfo {
487 fn matches(&self, filter: &FdFilter) -> bool {
488 if let Some(kind) = filter.kind {
489 if self.kind != kind {
490 return false;
491 }
492 }
493
494 true
495 }
496}
497
498impl PortBinding {
499 fn matches(&self, filter: &PortFilter) -> bool {
500 if let Some(protocol) = filter.protocol {
501 if self.protocol != protocol {
502 return false;
503 }
504 }
505
506 if let Some(port) = filter.local_port {
507 if self.local_port != port {
508 return false;
509 }
510 }
511
512 true
513 }
514}
515
516impl ProcessFilter {
517 fn matches(&self, proc: &ProcessInfo) -> bool {
519 if let Some(ref pattern) = self.name_contains {
521 if !proc.name.to_lowercase().contains(&pattern.to_lowercase()) {
522 return false;
523 }
524 }
525
526 if let Some(ref name) = self.name_equals {
528 if proc.name != *name {
529 return false;
530 }
531 }
532
533 if let Some(ref user) = self.user_equals {
535 match &proc.user {
536 Some(proc_user) if proc_user == user => {}
537 _ => return false,
538 }
539 }
540
541 if let Some(ref pids) = self.pid_in {
543 if !pids.contains(&proc.pid) {
544 return false;
545 }
546 }
547
548 if let Some(ppid) = self.ppid {
550 if proc.ppid != ppid {
551 return false;
552 }
553 }
554
555 if let Some(ref states) = self.state_in {
557 if !states.contains(&proc.state) {
558 return false;
559 }
560 }
561
562 if let Some(threshold) = self.cpu_above {
564 if proc.cpu_percent < threshold {
565 return false;
566 }
567 }
568
569 if let Some(threshold) = self.memory_above_kb {
571 if proc.memory_kb < threshold {
572 return false;
573 }
574 }
575
576 if let Some(min_secs) = self.running_for_at_least_secs {
578 if proc.elapsed_seconds < min_secs {
579 return false;
580 }
581 }
582
583 true
584 }
585}
586
587pub fn snapshot() -> SysprimsResult<ProcessSnapshot> {
606 snapshot_with_options(ProcessOptions::default())
607}
608
609pub fn snapshot_with_options(options: ProcessOptions) -> SysprimsResult<ProcessSnapshot> {
621 validate_process_options(&options)?;
622 platform::snapshot_impl(&options)
623}
624
625pub fn cpu_total_time_ns(pid: u32) -> SysprimsResult<u64> {
643 const MAX_SAFE_PID: u32 = i32::MAX as u32;
644
645 if pid == 0 {
646 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
647 }
648 if pid > MAX_SAFE_PID {
649 return Err(SysprimsError::invalid_argument(format!(
650 "PID {} exceeds maximum safe value {}",
651 pid, MAX_SAFE_PID
652 )));
653 }
654 platform::cpu_total_time_ns_impl(pid)
655}
656
657pub fn listening_ports(filter: Option<&PortFilter>) -> SysprimsResult<PortBindingsSnapshot> {
673 let filter = filter.cloned().unwrap_or_default();
674 filter.validate()?;
675
676 let mut snapshot = platform::listening_ports_impl()?;
677 if filter.protocol.is_some() || filter.local_port.is_some() {
678 snapshot.bindings.retain(|binding| binding.matches(&filter));
679 }
680
681 if snapshot.bindings.is_empty() && snapshot.warnings.is_empty() {
682 let platform = get_platform();
683 return Err(SysprimsError::not_supported("port bindings", platform));
684 }
685
686 Ok(snapshot)
687}
688
689pub fn list_fds(pid: u32, filter: Option<&FdFilter>) -> SysprimsResult<FdSnapshot> {
705 const MAX_SAFE_PID: u32 = i32::MAX as u32;
707 if pid == 0 {
708 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
709 }
710 if pid > MAX_SAFE_PID {
711 return Err(SysprimsError::invalid_argument(format!(
712 "PID {} exceeds maximum safe value {}",
713 pid, MAX_SAFE_PID
714 )));
715 }
716
717 let filter = filter.cloned().unwrap_or_default();
718 filter.validate()?;
719
720 let (mut fds, mut warnings) = platform::list_fds_impl(pid)?;
721 if filter.kind.is_some() {
722 fds.retain(|fd| fd.matches(&filter));
723 }
724
725 if fds.is_empty() {
727 warnings.push("No file descriptors visible".to_string());
728 }
729
730 Ok(make_fd_snapshot(pid, fds, warnings))
731}
732
733pub fn process_by_port(port: u16, protocol: Protocol) -> SysprimsResult<ProcessInfo> {
745 if port == 0 {
746 return Err(SysprimsError::invalid_argument(
747 "port must be between 1 and 65535",
748 ));
749 }
750
751 let filter = PortFilter {
752 protocol: Some(protocol),
753 local_port: Some(port),
754 };
755 let snapshot = listening_ports(Some(&filter))?;
756 let binding = snapshot
757 .bindings
758 .into_iter()
759 .find(|binding| binding.pid.is_some())
760 .ok_or_else(|| SysprimsError::not_found(port as u32))?;
761
762 match binding.process {
763 Some(process) => Ok(process),
764 None => binding
765 .pid
766 .map(get_process)
767 .unwrap_or_else(|| Err(SysprimsError::not_found(port as u32))),
768 }
769}
770
771#[cfg(unix)]
772fn aggregate_permission_warning(skipped: usize, label: &str) -> Option<String> {
773 if skipped == 0 {
774 None
775 } else {
776 Some(format!(
777 "Skipped {} {} due to permission errors",
778 skipped, label
779 ))
780 }
781}
782
783fn aggregate_error_warning(skipped: usize, label: &str) -> Option<String> {
784 if skipped == 0 {
785 None
786 } else {
787 Some(format!("Skipped {} {} due to read errors", skipped, label))
788 }
789}
790
791pub fn snapshot_filtered(filter: &ProcessFilter) -> SysprimsResult<ProcessSnapshot> {
809 snapshot_filtered_with_options(filter, ProcessOptions::default())
810}
811
812pub fn snapshot_filtered_with_options(
832 filter: &ProcessFilter,
833 options: ProcessOptions,
834) -> SysprimsResult<ProcessSnapshot> {
835 filter.validate()?;
836 validate_process_options(&options)?;
837
838 let mut snap = snapshot_with_options(options)?;
839 snap.processes.retain(|p| filter.matches(p));
840 Ok(snap)
841}
842
843pub fn get_process(pid: u32) -> SysprimsResult<ProcessInfo> {
873 get_process_with_options(pid, ProcessOptions::default())
874}
875
876pub fn get_process_with_options(pid: u32, options: ProcessOptions) -> SysprimsResult<ProcessInfo> {
889 const MAX_SAFE_PID: u32 = i32::MAX as u32;
890
891 if pid == 0 {
892 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
893 }
894 if pid > MAX_SAFE_PID {
895 return Err(SysprimsError::invalid_argument(format!(
896 "PID {} exceeds maximum safe value {}",
897 pid, MAX_SAFE_PID
898 )));
899 }
900 validate_process_options(&options)?;
901 platform::get_process_impl(pid, &options)
902}
903
904#[derive(Debug, Clone, Serialize)]
910pub struct DescendantsLevel {
911 pub level: u32,
913
914 pub processes: Vec<ProcessInfo>,
916}
917
918#[derive(Debug, Clone, Serialize)]
920pub struct DescendantsResult {
921 pub schema_id: &'static str,
923
924 pub root_pid: u32,
926
927 pub max_levels: u32,
929
930 pub levels: Vec<DescendantsLevel>,
932
933 pub total_found: usize,
935
936 pub matched_by_filter: usize,
938
939 pub timestamp: String,
941
942 pub platform: &'static str,
944}
945
946#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
948#[serde(rename_all = "snake_case")]
949pub enum CpuMode {
950 #[default]
952 Lifetime,
953
954 Monitor,
958}
959
960#[derive(Debug, Clone)]
962pub struct DescendantsConfig {
963 pub root_pid: u32,
965
966 pub max_levels: Option<u32>,
968
969 pub filter: Option<ProcessFilter>,
971
972 pub cpu_mode: CpuMode,
974
975 pub sample_duration: Option<Duration>,
979}
980
981pub fn descendants(
1006 root_pid: u32,
1007 max_levels: u32,
1008 filter: Option<&ProcessFilter>,
1009) -> SysprimsResult<DescendantsResult> {
1010 descendants_with_options(root_pid, max_levels, filter, ProcessOptions::default())
1011}
1012
1013pub fn descendants_with_options(
1036 root_pid: u32,
1037 max_levels: u32,
1038 filter: Option<&ProcessFilter>,
1039 options: ProcessOptions,
1040) -> SysprimsResult<DescendantsResult> {
1041 descendants_with_config_and_options(
1042 DescendantsConfig {
1043 root_pid,
1044 max_levels: Some(max_levels),
1045 filter: filter.cloned(),
1046 cpu_mode: CpuMode::Lifetime,
1047 sample_duration: None,
1048 },
1049 options,
1050 )
1051}
1052
1053pub fn descendants_with_config(config: DescendantsConfig) -> SysprimsResult<DescendantsResult> {
1073 descendants_with_config_and_options(config, ProcessOptions::default())
1074}
1075
1076pub fn select_descendant_targets(
1088 result: &DescendantsResult,
1089 filter: Option<&ProcessFilter>,
1090 cascade: bool,
1091) -> Vec<u32> {
1092 let all_procs: Vec<&ProcessInfo> = result
1093 .levels
1094 .iter()
1095 .flat_map(|l| l.processes.iter())
1096 .collect();
1097
1098 let matched_roots: Vec<u32> = all_procs
1099 .iter()
1100 .filter(|p| filter.map(|f| f.matches(p)).unwrap_or(true))
1101 .map(|p| p.pid)
1102 .collect();
1103
1104 if !cascade {
1105 let mut out = matched_roots;
1106 out.sort_unstable();
1107 out.dedup();
1108 out.retain(|&pid| pid != result.root_pid);
1109 return out;
1110 }
1111
1112 let mut children_map: HashMap<u32, Vec<u32>> = HashMap::new();
1113 for proc in all_procs {
1114 children_map.entry(proc.ppid).or_default().push(proc.pid);
1115 }
1116
1117 let mut expanded: HashSet<u32> = HashSet::new();
1118 for root in matched_roots {
1119 let mut stack = vec![root];
1120 while let Some(pid) = stack.pop() {
1121 if !expanded.insert(pid) {
1122 continue;
1123 }
1124 if let Some(children) = children_map.get(&pid) {
1125 stack.extend(children.iter().copied());
1126 }
1127 }
1128 }
1129
1130 let mut out: Vec<u32> = expanded.into_iter().collect();
1131 out.sort_unstable();
1132 out.retain(|&pid| pid != result.root_pid);
1133 out
1134}
1135
1136#[derive(Debug, Clone)]
1138pub struct GuardRule {
1139 pub root_pid: u32,
1141
1142 pub max_levels: u32,
1144
1145 pub filter: Option<ProcessFilter>,
1147
1148 pub cpu_mode: CpuMode,
1150
1151 pub sample_duration: Option<Duration>,
1153}
1154
1155#[derive(Debug, Clone)]
1157pub enum GuardAction {
1158 KillDescendants {
1160 signal: i32,
1162 cascade: bool,
1164 },
1165}
1166
1167#[derive(Debug, Clone)]
1169pub struct GuardConfig {
1170 pub rule: GuardRule,
1172 pub action: GuardAction,
1174 pub action_enabled: bool,
1176 pub max_targets: u32,
1178}
1179
1180#[derive(Debug, Clone, Serialize)]
1182pub struct GuardEvent {
1183 pub schema_id: &'static str,
1185 pub timestamp: String,
1187 pub platform: &'static str,
1189 pub matched: u32,
1191 pub targeted: u32,
1193 pub killed: u32,
1195 pub failed: u32,
1197 pub skipped_safety: u32,
1199 pub warnings: Vec<String>,
1201}
1202
1203pub fn guard_step(config: GuardConfig) -> SysprimsResult<GuardEvent> {
1208 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1209
1210 if config.rule.root_pid == 0 {
1211 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1212 }
1213 if config.rule.root_pid > MAX_SAFE_PID {
1214 return Err(SysprimsError::invalid_argument(format!(
1215 "PID {} exceeds maximum safe value {}",
1216 config.rule.root_pid, MAX_SAFE_PID
1217 )));
1218 }
1219 if config.max_targets == 0 {
1220 return Err(SysprimsError::invalid_argument("max_targets must be >= 1"));
1221 }
1222 if let Some(f) = config.rule.filter.as_ref() {
1223 f.validate()?;
1224 }
1225
1226 let desc = descendants_with_config_and_options(
1227 DescendantsConfig {
1228 root_pid: config.rule.root_pid,
1229 max_levels: Some(config.rule.max_levels),
1230 filter: None,
1231 cpu_mode: config.rule.cpu_mode,
1232 sample_duration: config.rule.sample_duration,
1233 },
1234 ProcessOptions::default(),
1235 )?;
1236
1237 let matched_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), false);
1238 let matched = matched_pids.len() as u32;
1239
1240 let (signal, cascade) = match config.action {
1241 GuardAction::KillDescendants { signal, cascade } => (signal, cascade),
1242 };
1243
1244 let mut warnings = Vec::new();
1245 if !config.action_enabled {
1246 warnings.push("action disabled; no signals sent".to_string());
1247 return Ok(GuardEvent {
1248 schema_id: GUARD_EVENT_V1,
1249 timestamp: now_rfc3339(),
1250 platform: get_platform(),
1251 matched,
1252 targeted: 0,
1253 killed: 0,
1254 failed: 0,
1255 skipped_safety: 0,
1256 warnings,
1257 });
1258 }
1259
1260 let mut target_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), cascade);
1261
1262 if target_pids.len() > config.max_targets as usize {
1263 target_pids.truncate(config.max_targets as usize);
1264 warnings.push(format!(
1265 "target count capped at max_targets={} for this cycle",
1266 config.max_targets
1267 ));
1268 }
1269
1270 let self_pid = std::process::id();
1271 let parent_pid = get_process(self_pid).ok().map(|p| p.ppid);
1272
1273 let before = target_pids.len();
1274 target_pids.retain(|&pid| pid != self_pid && pid != 1 && pid != config.rule.root_pid);
1275 if let Some(ppid) = parent_pid {
1276 target_pids.retain(|&pid| pid != ppid);
1277 }
1278 let skipped_safety = before.saturating_sub(target_pids.len()) as u32;
1279 if skipped_safety > 0 {
1280 warnings.push(format!(
1281 "skipped {} unsafe target(s) (self/PID1/parent/root)",
1282 skipped_safety
1283 ));
1284 }
1285
1286 if target_pids.is_empty() {
1287 return Ok(GuardEvent {
1288 schema_id: GUARD_EVENT_V1,
1289 timestamp: now_rfc3339(),
1290 platform: get_platform(),
1291 matched,
1292 targeted: 0,
1293 killed: 0,
1294 failed: 0,
1295 skipped_safety,
1296 warnings,
1297 });
1298 }
1299
1300 let batch = sysprims_signal::kill_many(&target_pids, signal)?;
1301
1302 Ok(GuardEvent {
1303 schema_id: GUARD_EVENT_V1,
1304 timestamp: now_rfc3339(),
1305 platform: get_platform(),
1306 matched,
1307 targeted: target_pids.len() as u32,
1308 killed: batch.succeeded.len() as u32,
1309 failed: batch.failed.len() as u32,
1310 skipped_safety,
1311 warnings,
1312 })
1313}
1314
1315#[cfg(any(test, target_os = "linux", target_os = "macos"))]
1316fn is_sysprims_binary_name(name: &str) -> bool {
1317 name == "sysprims" || name.starts_with("sysprims-")
1318}
1319
1320#[cfg(any(test, target_os = "linux", target_os = "macos"))]
1321fn guard_discovery_name(cmdline: &[String], fallback_name: &str) -> Option<String> {
1322 let binary = cmdline.first()?.rsplit('/').next().unwrap_or(fallback_name);
1323 if !is_sysprims_binary_name(binary) {
1324 return None;
1325 }
1326
1327 let guard_index = cmdline.iter().position(|arg| arg == "guard")?;
1328 let root_pid = cmdline.get(guard_index + 1)?;
1329 if root_pid.parse::<u32>().ok()? == 0 {
1330 return None;
1331 }
1332
1333 Some(format!("sysprims-guard:{root_pid}"))
1334}
1335
1336#[cfg(target_os = "linux")]
1337fn set_guard_process_title(root_pid: u32) {
1338 let title = format!("sysprims-guard:{root_pid}");
1339 let truncated = title.bytes().take(15).collect::<Vec<_>>();
1340 if let Ok(c_title) = std::ffi::CString::new(truncated) {
1341 unsafe {
1342 libc::prctl(
1343 libc::PR_SET_NAME,
1344 c_title.as_ptr() as libc::c_ulong,
1345 0,
1346 0,
1347 0,
1348 );
1349 }
1350 }
1351}
1352
1353#[cfg(target_os = "macos")]
1354fn set_guard_process_title(root_pid: u32) {
1355 unsafe extern "C" {
1356 fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
1357 }
1358
1359 let title = format!("sysprims-guard:{root_pid}");
1360 let thread_title = std::ffi::CString::new(title.bytes().take(63).collect::<Vec<_>>()).ok();
1361
1362 unsafe {
1363 if let Some(name) = thread_title.as_ref() {
1364 let _ = pthread_setname_np(name.as_ptr());
1365 }
1366 }
1367}
1368
1369#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1370fn set_guard_process_title(_root_pid: u32) {}
1371
1372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1381pub enum GuardPreset {
1382 Interactive,
1384 Background,
1386 Watchdog,
1388}
1389
1390impl GuardPreset {
1391 pub fn interval(&self) -> Duration {
1393 match self {
1394 Self::Interactive => Duration::from_secs(3),
1395 Self::Background => Duration::from_secs(180),
1396 Self::Watchdog => Duration::from_secs(300),
1397 }
1398 }
1399
1400 pub fn sample_duration(&self) -> Duration {
1402 match self {
1403 Self::Interactive => Duration::from_secs(2),
1404 Self::Background => Duration::from_secs(3),
1405 Self::Watchdog => Duration::from_secs(5),
1406 }
1407 }
1408}
1409
1410#[derive(Debug, Clone)]
1412pub struct GuardRunnerConfig {
1413 pub guard: GuardConfig,
1415 pub interval: Duration,
1417 pub max_iterations: Option<u64>,
1419}
1420
1421#[derive(Debug, Clone)]
1423pub struct GuardRunnerSummary {
1424 pub ticks: u64,
1426 pub stop_reason: StopReason,
1428}
1429
1430#[derive(Debug, Clone, PartialEq, Eq)]
1432pub enum StopReason {
1433 Signal,
1435 MaxIterations,
1437 Requested,
1439}
1440
1441#[derive(Clone)]
1490pub struct GuardStopHandle {
1491 requested: Arc<std::sync::atomic::AtomicBool>,
1493 signals_flag: guard_signals::StopFlagHandle,
1495 manager: guard_signals::SignalManager,
1497}
1498
1499impl GuardStopHandle {
1500 pub fn stop(&self) {
1505 self.requested
1506 .store(true, std::sync::atomic::Ordering::SeqCst);
1507 self.signals_flag.set();
1509 self.manager.stop();
1511 }
1512}
1513
1514impl std::fmt::Debug for GuardStopHandle {
1515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1516 f.debug_struct("GuardStopHandle")
1517 .field(
1518 "requested",
1519 &self.requested.load(std::sync::atomic::Ordering::SeqCst),
1520 )
1521 .finish()
1522 }
1523}
1524
1525pub struct GuardRunner {
1572 config: GuardRunnerConfig,
1573 signals: guard_signals::GuardSignals,
1574 tick: time::Tick,
1575 stop_requested: Arc<std::sync::atomic::AtomicBool>,
1577}
1578
1579impl GuardRunner {
1580 pub fn new(config: GuardRunnerConfig) -> SysprimsResult<Self> {
1584 let signals = guard_signals::GuardSignals::start()?;
1585 let tick = time::Tick::new(config.interval)?;
1586 Ok(Self {
1587 config,
1588 signals,
1589 tick,
1590 stop_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
1591 })
1592 }
1593
1594 pub fn stop_handle(&self) -> GuardStopHandle {
1599 GuardStopHandle {
1600 requested: Arc::clone(&self.stop_requested),
1601 signals_flag: self.signals.stop_flag_handle(),
1602 manager: self.signals.manager().clone(),
1603 }
1604 }
1605
1606 pub fn run<F, E>(
1614 &mut self,
1615 mut on_event: F,
1616 mut on_error: E,
1617 ) -> SysprimsResult<GuardRunnerSummary>
1618 where
1619 F: FnMut(&GuardEvent),
1620 E: FnMut(u64, &SysprimsError),
1621 {
1622 let mut tick_count: u64 = 0;
1623
1624 set_guard_process_title(self.config.guard.rule.root_pid);
1625
1626 while !self.signals.should_stop() {
1627 match guard_step(self.config.guard.clone()) {
1628 Ok(event) => {
1629 tick_count += 1;
1630 on_event(&event);
1631 }
1632 Err(e) => {
1633 tick_count += 1;
1634 on_error(tick_count, &e);
1635 }
1636 }
1637
1638 if let Some(max) = self.config.max_iterations {
1640 if tick_count >= max {
1641 return Ok(GuardRunnerSummary {
1642 ticks: tick_count,
1643 stop_reason: StopReason::MaxIterations,
1644 });
1645 }
1646 }
1647
1648 if self.signals.should_stop() {
1650 break;
1651 }
1652
1653 self.tick.sleep_until_next();
1654 }
1655
1656 let reason = if self
1657 .stop_requested
1658 .load(std::sync::atomic::Ordering::SeqCst)
1659 {
1660 StopReason::Requested
1661 } else {
1662 StopReason::Signal
1663 };
1664
1665 Ok(GuardRunnerSummary {
1666 ticks: tick_count,
1667 stop_reason: reason,
1668 })
1669 }
1670
1671 pub fn signals(&self) -> &guard_signals::GuardSignals {
1673 &self.signals
1674 }
1675}
1676
1677#[derive(Debug, Clone, Serialize)]
1683pub struct AncestorsResult {
1684 pub schema_id: &'static str,
1686
1687 pub timestamp: String,
1689
1690 pub platform: &'static str,
1692
1693 pub pid: u32,
1695
1696 pub chain: Vec<ProcessInfo>,
1698
1699 pub warnings: Vec<String>,
1701}
1702
1703pub fn ancestors(
1729 pid: u32,
1730 max_depth: u32,
1731 options: ProcessOptions,
1732) -> SysprimsResult<AncestorsResult> {
1733 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1734
1735 if pid == 0 {
1736 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1737 }
1738 if pid > MAX_SAFE_PID {
1739 return Err(SysprimsError::invalid_argument(format!(
1740 "PID {} exceeds maximum safe value {}",
1741 pid, MAX_SAFE_PID
1742 )));
1743 }
1744 validate_process_options(&options)?;
1745
1746 let mut chain = Vec::new();
1747 let mut warnings = Vec::new();
1748 let mut seen = HashSet::new();
1749 let mut current_pid = pid;
1750
1751 for depth in 0..=max_depth {
1752 if !seen.insert(current_pid) {
1753 warnings.push(format!(
1754 "loop detected: PID {} already visited at depth {}",
1755 current_pid, depth
1756 ));
1757 break;
1758 }
1759
1760 match get_process_with_options(current_pid, options) {
1761 Ok(info) => {
1762 let next_pid = info.ppid;
1763 chain.push(info);
1764
1765 if next_pid == 0 || next_pid == 1 || next_pid == current_pid {
1767 if next_pid == 1 && current_pid != 1 {
1769 match get_process_with_options(1, options) {
1770 Ok(init_info) => chain.push(init_info),
1771 Err(_) => {
1772 warnings.push("could not read init/launchd (PID 1)".to_string());
1773 }
1774 }
1775 }
1776 break;
1777 }
1778
1779 current_pid = next_pid;
1780 }
1781 Err(e) => {
1782 if depth == 0 {
1783 return Err(e);
1785 }
1786 warnings.push(format!(
1787 "ancestor walk stopped at PID {}: {}",
1788 current_pid, e
1789 ));
1790 break;
1791 }
1792 }
1793 }
1794
1795 Ok(AncestorsResult {
1796 schema_id: ANCESTORS_RESULT_V1,
1797 timestamp: now_rfc3339(),
1798 platform: get_platform(),
1799 pid,
1800 chain,
1801 warnings,
1802 })
1803}
1804
1805pub fn descendants_with_config_and_options(
1827 config: DescendantsConfig,
1828 options: ProcessOptions,
1829) -> SysprimsResult<DescendantsResult> {
1830 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1831
1832 if config.root_pid == 0 {
1833 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1834 }
1835 if config.root_pid > MAX_SAFE_PID {
1836 return Err(SysprimsError::invalid_argument(format!(
1837 "PID {} exceeds maximum safe value {}",
1838 config.root_pid, MAX_SAFE_PID
1839 )));
1840 }
1841
1842 validate_process_options(&options)?;
1843
1844 if let Some(f) = config.filter.as_ref() {
1845 f.validate()?;
1846 }
1847
1848 let _ = get_process_with_options(config.root_pid, options)?;
1850
1851 let snap = snapshot_for_descendants(options, config.cpu_mode, config.sample_duration)?;
1853
1854 let mut children_map: HashMap<u32, Vec<ProcessInfo>> = HashMap::new();
1856 for proc in snap.processes {
1857 children_map.entry(proc.ppid).or_default().push(proc);
1858 }
1859
1860 let mut levels: Vec<DescendantsLevel> = Vec::new();
1862 let mut current_pids = vec![config.root_pid];
1863 let mut total_found: usize = 0;
1864 let max_levels = config.max_levels.unwrap_or(u32::MAX);
1865
1866 for depth in 1..=max_levels {
1867 let mut level_procs = Vec::new();
1868 let mut next_pids = Vec::new();
1869
1870 for &pid in ¤t_pids {
1871 if let Some(children) = children_map.get(&pid) {
1872 for child in children {
1873 level_procs.push(child.clone());
1874 next_pids.push(child.pid);
1875 }
1876 }
1877 }
1878
1879 if level_procs.is_empty() {
1880 break;
1881 }
1882
1883 total_found += level_procs.len();
1884 levels.push(DescendantsLevel {
1885 level: depth,
1886 processes: level_procs,
1887 });
1888 current_pids = next_pids;
1889 }
1890
1891 let mut matched_by_filter = total_found;
1893 if let Some(f) = config.filter.as_ref() {
1894 for level in &mut levels {
1895 level.processes.retain(|p| f.matches(p));
1896 }
1897 matched_by_filter = levels.iter().map(|l| l.processes.len()).sum();
1898 levels.retain(|l| !l.processes.is_empty());
1900 }
1901
1902 Ok(DescendantsResult {
1903 schema_id: match config.cpu_mode {
1904 CpuMode::Lifetime => DESCENDANTS_RESULT_V1,
1905 CpuMode::Monitor => DESCENDANTS_RESULT_SAMPLED_V1,
1906 },
1907 root_pid: config.root_pid,
1908 max_levels,
1909 levels,
1910 total_found,
1911 matched_by_filter,
1912 timestamp: now_rfc3339(),
1913 platform: get_platform(),
1914 })
1915}
1916
1917fn snapshot_for_descendants(
1918 options: ProcessOptions,
1919 cpu_mode: CpuMode,
1920 sample_duration: Option<Duration>,
1921) -> SysprimsResult<ProcessSnapshot> {
1922 match cpu_mode {
1923 CpuMode::Lifetime => snapshot_with_options(options),
1924 CpuMode::Monitor => {
1925 let sample = sample_duration.unwrap_or_else(|| Duration::from_secs(1));
1926 snapshot_with_sampled_cpu(options, sample)
1927 }
1928 }
1929}
1930
1931fn snapshot_with_sampled_cpu(
1932 options: ProcessOptions,
1933 sample_duration: Duration,
1934) -> SysprimsResult<ProcessSnapshot> {
1935 if sample_duration.is_zero() {
1936 return Err(SysprimsError::invalid_argument(
1937 "sample duration must be > 0",
1938 ));
1939 }
1940
1941 let snap0 = snapshot_with_options(options)?;
1942 let mut t0 = HashMap::<u32, (Option<u64>, u64)>::new();
1943 for p in &snap0.processes {
1944 if let Ok(cpu_ns) = cpu_total_time_ns(p.pid) {
1945 t0.insert(p.pid, (p.start_time_unix_ms, cpu_ns));
1946 }
1947 }
1948
1949 std::thread::sleep(sample_duration);
1950
1951 let mut snap1 = snapshot_with_options(options)?;
1952 let dt_ns = sample_duration.as_nanos() as f64;
1953 if dt_ns > 0.0 {
1954 for p in &mut snap1.processes {
1955 if let Some((start0, cpu0)) = t0.get(&p.pid) {
1956 if start0.is_some()
1958 && p.start_time_unix_ms.is_some()
1959 && start0 != &p.start_time_unix_ms
1960 {
1961 continue;
1962 }
1963
1964 if let Ok(cpu1) = cpu_total_time_ns(p.pid) {
1965 let delta = cpu1.saturating_sub(*cpu0) as f64;
1966 p.cpu_percent = (delta / dt_ns) * 100.0;
1967 }
1968 }
1969 }
1970 }
1971
1972 snap1.schema_id = PROCESS_INFO_SAMPLED_V1;
1974 Ok(snap1)
1975}
1976
1977pub fn wait_pid(pid: u32, timeout: Duration) -> SysprimsResult<WaitPidResult> {
1995 const MAX_SAFE_PID: u32 = i32::MAX as u32;
1996
1997 if pid == 0 {
1998 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1999 }
2000 if pid > MAX_SAFE_PID {
2001 return Err(SysprimsError::invalid_argument(format!(
2002 "PID {} exceeds maximum safe value {}",
2003 pid, MAX_SAFE_PID
2004 )));
2005 }
2006 platform::wait_pid_impl(pid, timeout)
2007}
2008
2009pub fn is_live(pid: u32) -> SysprimsResult<bool> {
2047 const MAX_SAFE_PID: u32 = i32::MAX as u32;
2048
2049 if pid == 0 {
2050 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2051 }
2052 if pid > MAX_SAFE_PID {
2053 return Err(SysprimsError::invalid_argument(format!(
2054 "PID {} exceeds maximum safe value {}",
2055 pid, MAX_SAFE_PID
2056 )));
2057 }
2058 Ok(platform::liveness_impl(pid)? == Liveness::Live)
2059}
2060
2061pub fn is_fully_gone(pid: u32) -> SysprimsResult<bool> {
2084 const MAX_SAFE_PID: u32 = i32::MAX as u32;
2085
2086 if pid == 0 {
2087 return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2088 }
2089 if pid > MAX_SAFE_PID {
2090 return Err(SysprimsError::invalid_argument(format!(
2091 "PID {} exceeds maximum safe value {}",
2092 pid, MAX_SAFE_PID
2093 )));
2094 }
2095 Ok(platform::liveness_impl(pid)? == Liveness::Gone)
2096}
2097
2098fn make_port_snapshot(bindings: Vec<PortBinding>, warnings: Vec<String>) -> PortBindingsSnapshot {
2103 let mut warnings = warnings;
2104 if bindings.is_empty() {
2105 warnings.push("No listening ports found".to_string());
2106 }
2107
2108 PortBindingsSnapshot {
2109 schema_id: PORT_BINDINGS_V1,
2110 timestamp: now_rfc3339(),
2111 platform: get_platform(),
2112 bindings,
2113 warnings,
2114 }
2115}
2116
2117fn make_fd_snapshot(pid: u32, fds: Vec<FdInfo>, warnings: Vec<String>) -> FdSnapshot {
2118 FdSnapshot {
2119 schema_id: FD_SNAPSHOT_V1,
2120 timestamp: now_rfc3339(),
2121 platform: get_platform(),
2122 pid,
2123 fds,
2124 warnings,
2125 }
2126}
2127
2128fn make_snapshot(processes: Vec<ProcessInfo>) -> ProcessSnapshot {
2132 ProcessSnapshot {
2133 schema_id: PROCESS_INFO_V1,
2134 timestamp: now_rfc3339(),
2135 processes,
2136 }
2137}
2138
2139fn make_wait_pid_result(
2140 pid: u32,
2141 exited: bool,
2142 timed_out: bool,
2143 exit_code: Option<i32>,
2144 warnings: Vec<String>,
2145) -> WaitPidResult {
2146 WaitPidResult {
2147 schema_id: WAIT_PID_RESULT_V1,
2148 timestamp: now_rfc3339(),
2149 platform: get_platform(),
2150 pid,
2151 exited,
2152 timed_out,
2153 exit_code,
2154 warnings,
2155 }
2156}
2157
2158#[cfg(test)]
2163mod tests {
2164 use super::*;
2165 use std::process::{Child, Command, Stdio};
2166 use std::thread;
2167
2168 #[test]
2169 fn test_snapshot_not_empty() {
2170 let snap = snapshot().unwrap();
2171 assert!(
2172 !snap.processes.is_empty(),
2173 "Snapshot should contain processes"
2174 );
2175 }
2176
2177 #[test]
2178 fn test_snapshot_has_schema_id() {
2179 let snap = snapshot().unwrap();
2180 assert_eq!(snap.schema_id, PROCESS_INFO_V1);
2181 assert!(snap.schema_id.contains("process-info"));
2182 }
2183
2184 #[test]
2185 fn test_snapshot_has_timestamp() {
2186 let snap = snapshot().unwrap();
2187 assert!(!snap.timestamp.is_empty());
2188 assert!(snap.timestamp.contains('T'));
2190 assert!(snap.timestamp.contains('Z') || snap.timestamp.contains('+'));
2191 }
2192
2193 #[test]
2194 #[cfg(unix)]
2195 fn test_snapshot_has_processes() {
2196 let snap = snapshot().unwrap();
2200
2201 let own_pid = std::process::id();
2203 let has_self = snap.processes.iter().any(|p| p.pid == own_pid);
2204 assert!(has_self, "Snapshot should include our own process");
2205
2206 assert!(
2208 snap.processes.len() >= 3,
2209 "Should have at least a few visible processes, got {}",
2210 snap.processes.len()
2211 );
2212 }
2213
2214 #[test]
2215 fn test_get_self() {
2216 let pid = std::process::id();
2217 let info = get_process(pid).unwrap();
2218 assert_eq!(info.pid, pid);
2219 assert!(!info.name.is_empty(), "Process should have a name");
2220 }
2221
2222 #[test]
2223 #[cfg(target_os = "macos")]
2224 fn test_own_process_has_cmdline() {
2225 let snap = snapshot().unwrap();
2226 let own_pid = std::process::id();
2227 let own_proc = snap
2228 .processes
2229 .iter()
2230 .find(|p| p.pid == own_pid)
2231 .expect("Should find own process in snapshot");
2232 assert!(
2233 !own_proc.cmdline.is_empty(),
2234 "Own process should have cmdline, got empty"
2235 );
2236 }
2237
2238 #[test]
2239 fn test_get_self_has_valid_fields() {
2240 let pid = std::process::id();
2241 let info = get_process(pid).unwrap();
2242
2243 assert!(info.cpu_percent >= 0.0);
2245 assert!(info.cpu_percent <= 100.0);
2246
2247 assert!(info.memory_kb < u64::MAX);
2250
2251 if let Some(ms) = info.start_time_unix_ms {
2253 assert!(ms > 0);
2254 }
2255 if let Some(ref exe) = info.exe_path {
2256 assert!(!exe.is_empty());
2257 }
2258
2259 assert!(
2262 info.state == ProcessState::Running
2263 || info.state == ProcessState::Sleeping
2264 || info.state == ProcessState::Unknown,
2265 "Test process should be running, sleeping, or unknown (Windows)"
2266 );
2267 }
2268
2269 #[test]
2270 fn test_wait_pid_self_times_out() {
2271 let pid = std::process::id();
2272 let r = wait_pid(pid, Duration::from_millis(1)).unwrap();
2273 assert_eq!(r.pid, pid);
2274 assert!(r.timed_out);
2275 assert!(!r.exited);
2276 }
2277
2278 #[test]
2282 fn pid_taking_entrypoints_reject_unsafe_pids() {
2283 let over_max = (i32::MAX as u32) + 1;
2284 for &pid in &[0u32, over_max, u32::MAX] {
2285 assert!(
2286 matches!(get_process(pid), Err(SysprimsError::InvalidArgument { .. })),
2287 "get_process must reject unsafe PID {pid}"
2288 );
2289 assert!(
2290 matches!(
2291 wait_pid(pid, Duration::from_millis(1)),
2292 Err(SysprimsError::InvalidArgument { .. })
2293 ),
2294 "wait_pid must reject unsafe PID {pid}"
2295 );
2296 assert!(
2297 matches!(
2298 cpu_total_time_ns(pid),
2299 Err(SysprimsError::InvalidArgument { .. })
2300 ),
2301 "cpu_total_time_ns must reject unsafe PID {pid}"
2302 );
2303 }
2304 }
2305
2306 #[test]
2307 fn test_filter_by_name_contains() {
2308 let filter = ProcessFilter {
2310 name_contains: Some("sysprims".into()),
2311 ..Default::default()
2312 };
2313 let snap = snapshot_filtered(&filter).unwrap();
2314
2315 for proc in &snap.processes {
2316 assert!(
2317 proc.name.to_lowercase().contains("sysprims"),
2318 "Filtered process '{}' should contain 'sysprims'",
2319 proc.name
2320 );
2321 }
2322 }
2323
2324 #[test]
2325 fn test_guard_discovery_name_matches_guard_cmdline() {
2326 let cmdline = vec![
2327 "/usr/local/bin/sysprims".to_string(),
2328 "guard".to_string(),
2329 "27776".to_string(),
2330 "--preset".to_string(),
2331 "watchdog".to_string(),
2332 ];
2333
2334 assert_eq!(
2335 guard_discovery_name(&cmdline, "sysprims"),
2336 Some("sysprims-guard:27776".to_string())
2337 );
2338 }
2339
2340 #[test]
2341 fn test_guard_discovery_name_ignores_non_guard_cmdline() {
2342 let cmdline = vec![
2343 "/usr/local/bin/sysprims".to_string(),
2344 "pstat".to_string(),
2345 "--json".to_string(),
2346 ];
2347
2348 assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
2349 }
2350
2351 #[test]
2352 fn test_guard_discovery_name_rejects_invalid_root_pid() {
2353 let cmdline = vec![
2354 "/usr/local/bin/sysprims".to_string(),
2355 "guard".to_string(),
2356 "not-a-pid".to_string(),
2357 ];
2358
2359 assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
2360 }
2361
2362 #[test]
2363 fn test_filter_by_pid() {
2364 let my_pid = std::process::id();
2365 let filter = ProcessFilter {
2366 pid_in: Some(vec![my_pid]),
2367 ..Default::default()
2368 };
2369 let snap = snapshot_filtered(&filter).unwrap();
2370
2371 assert_eq!(snap.processes.len(), 1);
2372 assert_eq!(snap.processes[0].pid, my_pid);
2373 }
2374
2375 #[test]
2376 fn test_filter_validation_cpu_range() {
2377 let filter = ProcessFilter {
2378 cpu_above: Some(150.0),
2379 ..Default::default()
2380 };
2381 let result = filter.validate();
2382 assert!(result.is_err());
2383
2384 let filter = ProcessFilter {
2385 cpu_above: Some(-1.0),
2386 ..Default::default()
2387 };
2388 let result = filter.validate();
2389 assert!(result.is_err());
2390
2391 let filter = ProcessFilter {
2392 cpu_above: Some(50.0),
2393 ..Default::default()
2394 };
2395 let result = filter.validate();
2396 assert!(result.is_ok());
2397 }
2398
2399 #[test]
2400 fn test_nonexistent_pid() {
2401 let result = get_process(99999999);
2403 assert!(
2404 matches!(result, Err(SysprimsError::NotFound { .. })),
2405 "Should return NotFound for nonexistent PID"
2406 );
2407 }
2408
2409 #[test]
2410 fn test_invalid_pid_zero() {
2411 let result = get_process(0);
2412 assert!(
2413 matches!(result, Err(SysprimsError::InvalidArgument { .. })),
2414 "PID 0 should be invalid"
2415 );
2416 }
2417
2418 #[test]
2419 fn test_cpu_normalized() {
2420 let snap = snapshot().unwrap();
2421 for proc in &snap.processes {
2422 assert!(
2423 proc.cpu_percent >= 0.0,
2424 "CPU percent for PID {} should be >= 0",
2425 proc.pid
2426 );
2427 assert!(
2428 proc.cpu_percent <= 100.0,
2429 "CPU percent for PID {} should be <= 100, got {}",
2430 proc.pid,
2431 proc.cpu_percent
2432 );
2433 }
2434 }
2435
2436 #[test]
2437 fn test_process_state_serialization() {
2438 let json = serde_json::to_string(&ProcessState::Running).unwrap();
2440 assert_eq!(json, "\"running\"");
2441
2442 let json = serde_json::to_string(&ProcessState::Sleeping).unwrap();
2443 assert_eq!(json, "\"sleeping\"");
2444
2445 let json = serde_json::to_string(&ProcessState::Zombie).unwrap();
2446 assert_eq!(json, "\"zombie\"");
2447 }
2448
2449 #[test]
2450 fn test_filter_deserialization() {
2451 let json = r#"{"name_contains": "test", "cpu_above": 5.0}"#;
2452 let filter: ProcessFilter = serde_json::from_str(json).unwrap();
2453 assert_eq!(filter.name_contains, Some("test".to_string()));
2454 assert_eq!(filter.cpu_above, Some(5.0));
2455 }
2456
2457 #[test]
2458 fn test_filter_unknown_field_rejected() {
2459 let json = r#"{"unknown_field": "value"}"#;
2460 let result: Result<ProcessFilter, _> = serde_json::from_str(json);
2461 assert!(result.is_err(), "Unknown fields should be rejected");
2462 }
2463
2464 #[test]
2465 fn test_port_filter_unknown_field_rejected() {
2466 let json = r#"{"unknown_field": true}"#;
2467 let result: Result<PortFilter, _> = serde_json::from_str(json);
2468 assert!(result.is_err(), "Unknown fields should be rejected");
2469 }
2470
2471 #[test]
2472 fn test_port_filter_schema_id() {
2473 assert!(PortFilter::schema_id().contains("port-filter"));
2474 }
2475
2476 #[test]
2477 fn test_process_options_builder() {
2478 let opts = ProcessOptions::default();
2479 assert!(!opts.include_env);
2480 assert!(!opts.include_threads);
2481
2482 let opts = ProcessOptions::default().with_env().with_threads();
2483 assert!(opts.include_env);
2484 assert!(opts.include_threads);
2485 }
2486
2487 #[test]
2488 fn test_get_process_with_default_options_has_no_proc_ext_fields() {
2489 let pid = std::process::id();
2490 let info = get_process_with_options(pid, ProcessOptions::default()).unwrap();
2491 assert!(info.env.is_none());
2492 assert!(info.thread_count.is_none());
2493 }
2494
2495 #[test]
2496 #[cfg(feature = "proc_ext")]
2497 fn test_get_process_with_threads_populates_thread_count() {
2498 let pid = std::process::id();
2499 let info = get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
2500 assert!(info.thread_count.is_some());
2501 }
2502
2503 #[test]
2504 #[cfg(all(feature = "proc_ext", unix))]
2505 fn test_get_process_with_env_populates_env_map() {
2506 let pid = std::process::id();
2507 let info = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap();
2508 assert!(info.env.is_some());
2509 }
2510
2511 #[test]
2512 #[cfg(not(feature = "proc_ext"))]
2513 fn test_proc_ext_options_rejected_when_feature_disabled() {
2514 let pid = std::process::id();
2515 let err = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap_err();
2516 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2517 }
2518
2519 #[test]
2520 fn test_descendants_with_config_lifetime_self() {
2521 let pid = std::process::id();
2522 let config = DescendantsConfig {
2523 root_pid: pid,
2524 max_levels: Some(1),
2525 filter: None,
2526 cpu_mode: CpuMode::Lifetime,
2527 sample_duration: None,
2528 };
2529
2530 let result = descendants_with_config(config).unwrap();
2531 assert_eq!(result.root_pid, pid);
2532 assert_eq!(result.max_levels, 1);
2533 }
2534
2535 #[test]
2536 fn test_descendants_with_config_monitor_self() {
2537 let pid = std::process::id();
2538 let config = DescendantsConfig {
2539 root_pid: pid,
2540 max_levels: Some(1),
2541 filter: None,
2542 cpu_mode: CpuMode::Monitor,
2543 sample_duration: Some(Duration::from_millis(1)),
2544 };
2545
2546 let result = descendants_with_config(config).unwrap();
2547 assert_eq!(result.schema_id, DESCENDANTS_RESULT_SAMPLED_V1);
2548 assert_eq!(result.root_pid, pid);
2549 assert_eq!(result.max_levels, 1);
2550 }
2551
2552 #[test]
2553 fn test_descendants_with_config_monitor_zero_sample_rejected() {
2554 let config = DescendantsConfig {
2555 root_pid: std::process::id(),
2556 max_levels: Some(1),
2557 filter: None,
2558 cpu_mode: CpuMode::Monitor,
2559 sample_duration: Some(Duration::ZERO),
2560 };
2561
2562 let err = descendants_with_config(config).unwrap_err();
2563 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2564 }
2565
2566 #[test]
2567 fn test_descendants_with_config_invalid_pid_zero_rejected_before_sampling() {
2568 let config = DescendantsConfig {
2569 root_pid: 0,
2570 max_levels: Some(1),
2571 filter: None,
2572 cpu_mode: CpuMode::Monitor,
2573 sample_duration: Some(Duration::from_secs(1)),
2574 };
2575
2576 let err = descendants_with_config(config).unwrap_err();
2577 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2578 }
2579
2580 #[test]
2581 fn test_snapshot_json_output() {
2582 let snap = snapshot().unwrap();
2583 let json = serde_json::to_string_pretty(&snap).unwrap();
2584
2585 assert!(json.contains("\"schema_id\""));
2587 assert!(json.contains("\"timestamp\""));
2588 assert!(json.contains("\"processes\""));
2589 assert!(json.contains(PROCESS_INFO_V1));
2590 }
2591
2592 fn test_process(pid: u32, ppid: u32, name: &str) -> ProcessInfo {
2593 ProcessInfo {
2594 pid,
2595 ppid,
2596 name: name.to_string(),
2597 user: None,
2598 cpu_percent: 0.0,
2599 memory_kb: 0,
2600 elapsed_seconds: 0,
2601 start_time_unix_ms: None,
2602 exe_path: None,
2603 state: ProcessState::Running,
2604 cmdline: vec![],
2605 env: None,
2606 thread_count: None,
2607 }
2608 }
2609
2610 fn test_descendants_tree() -> DescendantsResult {
2611 DescendantsResult {
2612 schema_id: DESCENDANTS_RESULT_V1,
2613 root_pid: 10,
2614 max_levels: 10,
2615 levels: vec![
2616 DescendantsLevel {
2617 level: 1,
2618 processes: vec![test_process(11, 10, "helper"), test_process(12, 10, "db")],
2619 },
2620 DescendantsLevel {
2621 level: 2,
2622 processes: vec![
2623 test_process(13, 11, "child-a"),
2624 test_process(14, 12, "child-b"),
2625 ],
2626 },
2627 ],
2628 total_found: 4,
2629 matched_by_filter: 4,
2630 timestamp: "1970-01-01T00:00:00Z".to_string(),
2631 platform: get_platform(),
2632 }
2633 }
2634
2635 fn spawn_sleep_child() -> Child {
2636 #[cfg(unix)]
2637 {
2638 Command::new("sleep")
2639 .arg("30")
2640 .stdin(Stdio::null())
2641 .stdout(Stdio::null())
2642 .stderr(Stdio::null())
2643 .spawn()
2644 .expect("spawn sleep child")
2645 }
2646
2647 #[cfg(windows)]
2648 {
2649 Command::new("cmd")
2650 .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
2651 .stdin(Stdio::null())
2652 .stdout(Stdio::null())
2653 .stderr(Stdio::null())
2654 .spawn()
2655 .expect("spawn ping child")
2656 }
2657 }
2658
2659 fn guard_step_retry(config: &GuardConfig, attempts: usize, delay_ms: u64) -> GuardEvent {
2660 let mut last = None;
2661 for attempt in 0..attempts {
2662 let event = guard_step(config.clone()).expect("guard_step should succeed");
2663 let ready = if config.action_enabled {
2664 event.targeted > 0 && (event.killed > 0 || event.failed > 0)
2665 } else {
2666 true
2667 };
2668 if ready {
2669 return event;
2670 }
2671 last = Some(event);
2672 if attempt + 1 < attempts {
2673 thread::sleep(Duration::from_millis(delay_ms));
2674 }
2675 }
2676 last.expect("guard_step retry should record an event")
2677 }
2678
2679 #[test]
2680 fn test_select_descendant_targets_non_cascade() {
2681 let result = test_descendants_tree();
2682 let filter = ProcessFilter {
2683 name_contains: Some("helper".to_string()),
2684 ..Default::default()
2685 };
2686
2687 let targets = select_descendant_targets(&result, Some(&filter), false);
2688 assert_eq!(targets, vec![11]);
2689 }
2690
2691 #[test]
2692 fn test_select_descendant_targets_cascade() {
2693 let result = test_descendants_tree();
2694 let filter = ProcessFilter {
2695 name_contains: Some("helper".to_string()),
2696 ..Default::default()
2697 };
2698
2699 let targets = select_descendant_targets(&result, Some(&filter), true);
2700 assert_eq!(targets, vec![11, 13]);
2701 }
2702
2703 #[test]
2704 fn test_guard_step_action_disabled_emits_event() {
2705 let cfg = GuardConfig {
2706 rule: GuardRule {
2707 root_pid: std::process::id(),
2708 max_levels: 1,
2709 filter: None,
2710 cpu_mode: CpuMode::Lifetime,
2711 sample_duration: None,
2712 },
2713 action: GuardAction::KillDescendants {
2714 signal: 15,
2715 cascade: false,
2716 },
2717 action_enabled: false,
2718 max_targets: 32,
2719 };
2720
2721 let event = guard_step(cfg).unwrap();
2722 assert_eq!(event.schema_id, GUARD_EVENT_V1);
2723 assert_eq!(event.targeted, 0);
2724 assert_eq!(event.killed, 0);
2725 assert_eq!(event.failed, 0);
2726 assert!(event.warnings.iter().any(|w| w.contains("action disabled")));
2727 }
2728
2729 #[test]
2730 fn test_guard_step_rejects_zero_max_targets() {
2731 let cfg = GuardConfig {
2732 rule: GuardRule {
2733 root_pid: std::process::id(),
2734 max_levels: 1,
2735 filter: None,
2736 cpu_mode: CpuMode::Lifetime,
2737 sample_duration: None,
2738 },
2739 action: GuardAction::KillDescendants {
2740 signal: 15,
2741 cascade: false,
2742 },
2743 action_enabled: false,
2744 max_targets: 0,
2745 };
2746
2747 let err = guard_step(cfg).unwrap_err();
2748 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2749 }
2750
2751 #[test]
2752 fn test_guard_step_action_enabled_kills_targeted_child() {
2753 let mut child = spawn_sleep_child();
2754 let child_pid = child.id();
2755
2756 let mut child_visible = false;
2757 for _ in 0..20 {
2758 let desc = descendants_with_config(DescendantsConfig {
2759 root_pid: std::process::id(),
2760 max_levels: Some(1),
2761 filter: Some(ProcessFilter {
2762 pid_in: Some(vec![child_pid]),
2763 ..Default::default()
2764 }),
2765 cpu_mode: CpuMode::Lifetime,
2766 sample_duration: None,
2767 })
2768 .unwrap();
2769 if desc.matched_by_filter >= 1 {
2770 child_visible = true;
2771 break;
2772 }
2773 thread::sleep(Duration::from_millis(50));
2774 }
2775 assert!(child_visible, "expected spawned child to be visible");
2776
2777 let cfg = GuardConfig {
2778 rule: GuardRule {
2779 root_pid: std::process::id(),
2780 max_levels: 1,
2781 filter: Some(ProcessFilter {
2782 pid_in: Some(vec![child_pid]),
2783 ..Default::default()
2784 }),
2785 cpu_mode: CpuMode::Lifetime,
2786 sample_duration: None,
2787 },
2788 action: GuardAction::KillDescendants {
2789 signal: 15,
2790 cascade: false,
2791 },
2792 action_enabled: true,
2793 max_targets: 8,
2794 };
2795
2796 let event = guard_step_retry(&cfg, 10, 100);
2797 assert_eq!(event.targeted, 1);
2798 assert_eq!(event.killed, 1);
2799 assert_eq!(event.failed, 0);
2800
2801 let mut exited = false;
2802 for _ in 0..20 {
2803 if let Some(_status) = child.try_wait().expect("poll child exit") {
2804 exited = true;
2805 break;
2806 }
2807 thread::sleep(Duration::from_millis(100));
2808 }
2809 if !exited {
2810 let _ = child.kill();
2811 let _ = child.wait();
2812 }
2813 assert!(exited, "guard_step should terminate targeted child");
2814 }
2815
2816 #[test]
2817 fn test_guard_step_action_enabled_applies_max_targets_cap() {
2818 let mut child_a = spawn_sleep_child();
2819 let mut child_b = spawn_sleep_child();
2820 let pids = vec![child_a.id(), child_b.id()];
2821
2822 let mut both_visible = false;
2824 for _ in 0..20 {
2825 let desc = descendants_with_config(DescendantsConfig {
2826 root_pid: std::process::id(),
2827 max_levels: Some(1),
2828 filter: Some(ProcessFilter {
2829 pid_in: Some(pids.clone()),
2830 ..Default::default()
2831 }),
2832 cpu_mode: CpuMode::Lifetime,
2833 sample_duration: None,
2834 })
2835 .unwrap();
2836 if desc.matched_by_filter >= 2 {
2837 both_visible = true;
2838 break;
2839 }
2840 thread::sleep(Duration::from_millis(50));
2841 }
2842 assert!(both_visible, "expected both spawned children to be visible");
2843
2844 let cfg = GuardConfig {
2845 rule: GuardRule {
2846 root_pid: std::process::id(),
2847 max_levels: 1,
2848 filter: Some(ProcessFilter {
2849 pid_in: Some(pids.clone()),
2850 ..Default::default()
2851 }),
2852 cpu_mode: CpuMode::Lifetime,
2853 sample_duration: None,
2854 },
2855 action: GuardAction::KillDescendants {
2856 signal: 15,
2857 cascade: false,
2858 },
2859 action_enabled: true,
2860 max_targets: 1,
2861 };
2862
2863 let event = guard_step_retry(&cfg, 10, 100);
2864
2865 assert_eq!(event.matched, 2);
2866 assert_eq!(event.targeted, 1);
2867 assert_eq!(event.killed, 1);
2868 assert_eq!(event.failed, 0);
2869 assert!(
2870 event
2871 .warnings
2872 .iter()
2873 .any(|w| w.contains("target count capped at max_targets=1")),
2874 "expected max_targets cap warning, got: {:?}",
2875 event.warnings
2876 );
2877
2878 let mut exited_count = 0;
2880 for _ in 0..20 {
2881 exited_count = 0;
2882 if child_a.try_wait().expect("poll child A").is_some() {
2883 exited_count += 1;
2884 }
2885 if child_b.try_wait().expect("poll child B").is_some() {
2886 exited_count += 1;
2887 }
2888 if exited_count >= 1 {
2889 break;
2890 }
2891 thread::sleep(Duration::from_millis(100));
2892 }
2893 assert!(
2894 exited_count >= 1,
2895 "expected at least one child to exit after capped guard_step kill"
2896 );
2897
2898 for child in [&mut child_a, &mut child_b] {
2899 if child.try_wait().expect("final poll").is_none() {
2900 let _ = child.kill();
2901 let _ = child.wait();
2902 }
2903 }
2904 }
2905
2906 #[test]
2907 fn test_ancestors_self() {
2908 let pid = std::process::id();
2909 let result = ancestors(pid, 64, ProcessOptions::default()).unwrap();
2910
2911 assert_eq!(result.schema_id, ANCESTORS_RESULT_V1);
2912 assert_eq!(result.pid, pid);
2913 assert!(
2914 !result.chain.is_empty(),
2915 "chain should include at least self"
2916 );
2917 assert_eq!(
2918 result.chain[0].pid, pid,
2919 "first element should be starting PID"
2920 );
2921
2922 assert!(
2924 result.chain.len() >= 2,
2925 "chain should include at least self and parent, got {}",
2926 result.chain.len()
2927 );
2928 }
2929
2930 #[test]
2931 fn test_ancestors_rejects_pid_zero() {
2932 let err = ancestors(0, 10, ProcessOptions::default()).unwrap_err();
2933 assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2934 }
2935
2936 #[test]
2937 fn test_ancestors_nonexistent_pid() {
2938 let err = ancestors(99999999, 10, ProcessOptions::default()).unwrap_err();
2939 assert!(matches!(err, SysprimsError::NotFound { .. }));
2940 }
2941
2942 #[test]
2943 fn test_ancestors_max_depth_zero() {
2944 let pid = std::process::id();
2945 let result = ancestors(pid, 0, ProcessOptions::default()).unwrap();
2946
2947 assert_eq!(result.chain.len(), 1);
2949 assert_eq!(result.chain[0].pid, pid);
2950 }
2951}