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