use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use sysprims_core::schema::{
ANCESTORS_RESULT_V1, DESCENDANTS_RESULT_SAMPLED_V1, DESCENDANTS_RESULT_V1, FD_SNAPSHOT_V1,
GUARD_EVENT_V1, PORT_BINDINGS_V1, PORT_FILTER_V1, PROCESS_INFO_SAMPLED_V1, PROCESS_INFO_V1,
WAIT_PID_RESULT_V1,
};
use sysprims_core::time::now_rfc3339;
use sysprims_core::{get_platform, guard_signals, time, SysprimsError, SysprimsResult};
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;
pub mod observation;
pub use sysprims_signal::{
open_process_handle, open_process_handle_verified, ProcessHandle, SignalBinding,
};
#[cfg(target_os = "linux")]
use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
#[cfg(windows)]
use windows as platform;
#[derive(Debug, Clone, Serialize)]
pub struct ProcessSnapshot {
pub schema_id: &'static str,
pub timestamp: String,
pub processes: Vec<ProcessInfo>,
}
#[derive(Debug, Clone, Serialize)]
pub struct WaitPidResult {
pub schema_id: &'static str,
pub timestamp: String,
pub platform: &'static str,
pub pid: u32,
pub exited: bool,
pub timed_out: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub exit_code: Option<i32>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PortBindingsSnapshot {
pub schema_id: &'static str,
pub timestamp: String,
pub platform: &'static str,
pub bindings: Vec<PortBinding>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PortBinding {
pub protocol: Protocol,
#[serde(skip_serializing_if = "Option::is_none")]
pub local_addr: Option<IpAddr>,
pub local_port: u16,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pid: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub process: Option<ProcessInfo>,
#[serde(skip)]
pub inode: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Protocol {
Tcp,
Udp,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortFilter {
pub protocol: Option<Protocol>,
pub local_port: Option<u16>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FdKind {
File,
Socket,
Pipe,
Unknown,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FdFilter {
pub kind: Option<FdKind>,
}
impl FdFilter {
pub fn validate(&self) -> SysprimsResult<()> {
Ok(())
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FdInfo {
pub fd: u32,
pub kind: FdKind,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct FdSnapshot {
pub schema_id: &'static str,
pub timestamp: String,
pub platform: &'static str,
pub pid: u32,
pub fds: Vec<FdInfo>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProcessOptions {
pub include_env: bool,
pub include_threads: bool,
}
impl ProcessOptions {
pub fn with_env(mut self) -> Self {
self.include_env = true;
self
}
pub fn with_threads(mut self) -> Self {
self.include_threads = true;
self
}
}
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_ENTRIES: usize = 1024;
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_KEY_BYTES: usize = 1024;
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_VALUE_BYTES: usize = 4096;
#[cfg(all(feature = "proc_ext", unix))]
pub(crate) const MAX_ENV_TOTAL_BYTES: usize = 1_048_576;
#[derive(Debug, Clone, Serialize)]
pub struct ProcessInfo {
pub pid: u32,
pub ppid: u32,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
pub cpu_percent: f64,
pub memory_kb: u64,
pub elapsed_seconds: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_time_unix_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exe_path: Option<String>,
pub state: ProcessState,
pub cmdline: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub env: Option<BTreeMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thread_count: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessState {
Running,
Sleeping,
Stopped,
Zombie,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(windows, allow(dead_code))]
pub(crate) enum Liveness {
Live,
Zombie,
Gone,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessFilter {
pub name_contains: Option<String>,
pub name_equals: Option<String>,
pub user_equals: Option<String>,
pub pid_in: Option<Vec<u32>>,
pub ppid: Option<u32>,
pub state_in: Option<Vec<ProcessState>>,
pub cpu_above: Option<f64>,
pub memory_above_kb: Option<u64>,
pub running_for_at_least_secs: Option<u64>,
}
impl ProcessFilter {
pub fn validate(&self) -> SysprimsResult<()> {
if let Some(cpu) = self.cpu_above {
if !(0.0..=100.0).contains(&cpu) {
return Err(SysprimsError::invalid_argument(
"cpu_above must be between 0 and 100",
));
}
}
Ok(())
}
}
fn validate_process_options(options: &ProcessOptions) -> SysprimsResult<()> {
#[cfg(feature = "proc_ext")]
{
let _ = options;
}
#[cfg(not(feature = "proc_ext"))]
{
if options.include_env || options.include_threads {
return Err(SysprimsError::invalid_argument(
"include_env/include_threads require the proc_ext feature",
));
}
}
Ok(())
}
impl PortFilter {
pub fn validate(&self) -> SysprimsResult<()> {
if let Some(port) = self.local_port {
if port == 0 {
return Err(SysprimsError::invalid_argument(
"local_port must be between 1 and 65535",
));
}
}
Ok(())
}
pub fn schema_id() -> &'static str {
PORT_FILTER_V1
}
}
impl FdInfo {
fn matches(&self, filter: &FdFilter) -> bool {
if let Some(kind) = filter.kind {
if self.kind != kind {
return false;
}
}
true
}
}
impl PortBinding {
fn matches(&self, filter: &PortFilter) -> bool {
if let Some(protocol) = filter.protocol {
if self.protocol != protocol {
return false;
}
}
if let Some(port) = filter.local_port {
if self.local_port != port {
return false;
}
}
true
}
}
impl ProcessFilter {
fn matches(&self, proc: &ProcessInfo) -> bool {
if let Some(ref pattern) = self.name_contains {
if !proc.name.to_lowercase().contains(&pattern.to_lowercase()) {
return false;
}
}
if let Some(ref name) = self.name_equals {
if proc.name != *name {
return false;
}
}
if let Some(ref user) = self.user_equals {
match &proc.user {
Some(proc_user) if proc_user == user => {}
_ => return false,
}
}
if let Some(ref pids) = self.pid_in {
if !pids.contains(&proc.pid) {
return false;
}
}
if let Some(ppid) = self.ppid {
if proc.ppid != ppid {
return false;
}
}
if let Some(ref states) = self.state_in {
if !states.contains(&proc.state) {
return false;
}
}
if let Some(threshold) = self.cpu_above {
if proc.cpu_percent < threshold {
return false;
}
}
if let Some(threshold) = self.memory_above_kb {
if proc.memory_kb < threshold {
return false;
}
}
if let Some(min_secs) = self.running_for_at_least_secs {
if proc.elapsed_seconds < min_secs {
return false;
}
}
true
}
}
pub fn snapshot() -> SysprimsResult<ProcessSnapshot> {
snapshot_with_options(ProcessOptions::default())
}
pub fn snapshot_with_options(options: ProcessOptions) -> SysprimsResult<ProcessSnapshot> {
validate_process_options(&options)?;
platform::snapshot_impl(&options)
}
pub fn cpu_total_time_ns(pid: u32) -> SysprimsResult<u64> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
platform::cpu_total_time_ns_impl(pid)
}
pub fn listening_ports(filter: Option<&PortFilter>) -> SysprimsResult<PortBindingsSnapshot> {
let filter = filter.cloned().unwrap_or_default();
filter.validate()?;
let mut snapshot = platform::listening_ports_impl()?;
if filter.protocol.is_some() || filter.local_port.is_some() {
snapshot.bindings.retain(|binding| binding.matches(&filter));
}
if snapshot.bindings.is_empty() && snapshot.warnings.is_empty() {
let platform = get_platform();
return Err(SysprimsError::not_supported("port bindings", platform));
}
Ok(snapshot)
}
pub fn list_fds(pid: u32, filter: Option<&FdFilter>) -> SysprimsResult<FdSnapshot> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
let filter = filter.cloned().unwrap_or_default();
filter.validate()?;
let (mut fds, mut warnings) = platform::list_fds_impl(pid)?;
if filter.kind.is_some() {
fds.retain(|fd| fd.matches(&filter));
}
if fds.is_empty() {
warnings.push("No file descriptors visible".to_string());
}
Ok(make_fd_snapshot(pid, fds, warnings))
}
pub fn process_by_port(port: u16, protocol: Protocol) -> SysprimsResult<ProcessInfo> {
if port == 0 {
return Err(SysprimsError::invalid_argument(
"port must be between 1 and 65535",
));
}
let filter = PortFilter {
protocol: Some(protocol),
local_port: Some(port),
};
let snapshot = listening_ports(Some(&filter))?;
let binding = snapshot
.bindings
.into_iter()
.find(|binding| binding.pid.is_some())
.ok_or_else(|| SysprimsError::not_found(port as u32))?;
match binding.process {
Some(process) => Ok(process),
None => binding
.pid
.map(get_process)
.unwrap_or_else(|| Err(SysprimsError::not_found(port as u32))),
}
}
#[cfg(unix)]
fn aggregate_permission_warning(skipped: usize, label: &str) -> Option<String> {
if skipped == 0 {
None
} else {
Some(format!(
"Skipped {} {} due to permission errors",
skipped, label
))
}
}
fn aggregate_error_warning(skipped: usize, label: &str) -> Option<String> {
if skipped == 0 {
None
} else {
Some(format!("Skipped {} {} due to read errors", skipped, label))
}
}
pub fn snapshot_filtered(filter: &ProcessFilter) -> SysprimsResult<ProcessSnapshot> {
snapshot_filtered_with_options(filter, ProcessOptions::default())
}
pub fn snapshot_filtered_with_options(
filter: &ProcessFilter,
options: ProcessOptions,
) -> SysprimsResult<ProcessSnapshot> {
filter.validate()?;
validate_process_options(&options)?;
let mut snap = snapshot_with_options(options)?;
snap.processes.retain(|p| filter.matches(p));
Ok(snap)
}
pub fn get_process(pid: u32) -> SysprimsResult<ProcessInfo> {
get_process_with_options(pid, ProcessOptions::default())
}
pub fn get_process_with_options(pid: u32, options: ProcessOptions) -> SysprimsResult<ProcessInfo> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
validate_process_options(&options)?;
platform::get_process_impl(pid, &options)
}
#[derive(Debug, Clone, Serialize)]
pub struct DescendantsLevel {
pub level: u32,
pub processes: Vec<ProcessInfo>,
}
#[derive(Debug, Clone, Serialize)]
pub struct DescendantsResult {
pub schema_id: &'static str,
pub root_pid: u32,
pub max_levels: u32,
pub levels: Vec<DescendantsLevel>,
pub total_found: usize,
pub matched_by_filter: usize,
pub timestamp: String,
pub platform: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum CpuMode {
#[default]
Lifetime,
Monitor,
}
#[derive(Debug, Clone)]
pub struct DescendantsConfig {
pub root_pid: u32,
pub max_levels: Option<u32>,
pub filter: Option<ProcessFilter>,
pub cpu_mode: CpuMode,
pub sample_duration: Option<Duration>,
}
pub fn descendants(
root_pid: u32,
max_levels: u32,
filter: Option<&ProcessFilter>,
) -> SysprimsResult<DescendantsResult> {
descendants_with_options(root_pid, max_levels, filter, ProcessOptions::default())
}
pub fn descendants_with_options(
root_pid: u32,
max_levels: u32,
filter: Option<&ProcessFilter>,
options: ProcessOptions,
) -> SysprimsResult<DescendantsResult> {
descendants_with_config_and_options(
DescendantsConfig {
root_pid,
max_levels: Some(max_levels),
filter: filter.cloned(),
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
},
options,
)
}
pub fn descendants_with_config(config: DescendantsConfig) -> SysprimsResult<DescendantsResult> {
descendants_with_config_and_options(config, ProcessOptions::default())
}
pub fn select_descendant_targets(
result: &DescendantsResult,
filter: Option<&ProcessFilter>,
cascade: bool,
) -> Vec<u32> {
let all_procs: Vec<&ProcessInfo> = result
.levels
.iter()
.flat_map(|l| l.processes.iter())
.collect();
let matched_roots: Vec<u32> = all_procs
.iter()
.filter(|p| filter.map(|f| f.matches(p)).unwrap_or(true))
.map(|p| p.pid)
.collect();
if !cascade {
let mut out = matched_roots;
out.sort_unstable();
out.dedup();
out.retain(|&pid| pid != result.root_pid);
return out;
}
let mut children_map: HashMap<u32, Vec<u32>> = HashMap::new();
for proc in all_procs {
children_map.entry(proc.ppid).or_default().push(proc.pid);
}
let mut expanded: HashSet<u32> = HashSet::new();
for root in matched_roots {
let mut stack = vec![root];
while let Some(pid) = stack.pop() {
if !expanded.insert(pid) {
continue;
}
if let Some(children) = children_map.get(&pid) {
stack.extend(children.iter().copied());
}
}
}
let mut out: Vec<u32> = expanded.into_iter().collect();
out.sort_unstable();
out.retain(|&pid| pid != result.root_pid);
out
}
#[derive(Debug, Clone)]
pub struct GuardRule {
pub root_pid: u32,
pub max_levels: u32,
pub filter: Option<ProcessFilter>,
pub cpu_mode: CpuMode,
pub sample_duration: Option<Duration>,
}
#[derive(Debug, Clone)]
pub enum GuardAction {
KillDescendants {
signal: i32,
cascade: bool,
},
}
#[derive(Debug, Clone)]
pub struct GuardConfig {
pub rule: GuardRule,
pub action: GuardAction,
pub action_enabled: bool,
pub max_targets: u32,
}
#[derive(Debug, Clone, Serialize)]
pub struct GuardEvent {
pub schema_id: &'static str,
pub timestamp: String,
pub platform: &'static str,
pub matched: u32,
pub targeted: u32,
pub killed: u32,
pub failed: u32,
pub skipped_safety: u32,
pub warnings: Vec<String>,
}
pub fn guard_step(config: GuardConfig) -> SysprimsResult<GuardEvent> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if config.rule.root_pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if config.rule.root_pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
config.rule.root_pid, MAX_SAFE_PID
)));
}
if config.max_targets == 0 {
return Err(SysprimsError::invalid_argument("max_targets must be >= 1"));
}
if let Some(f) = config.rule.filter.as_ref() {
f.validate()?;
}
let desc = descendants_with_config_and_options(
DescendantsConfig {
root_pid: config.rule.root_pid,
max_levels: Some(config.rule.max_levels),
filter: None,
cpu_mode: config.rule.cpu_mode,
sample_duration: config.rule.sample_duration,
},
ProcessOptions::default(),
)?;
let matched_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), false);
let matched = matched_pids.len() as u32;
let (signal, cascade) = match config.action {
GuardAction::KillDescendants { signal, cascade } => (signal, cascade),
};
let mut warnings = Vec::new();
if !config.action_enabled {
warnings.push("action disabled; no signals sent".to_string());
return Ok(GuardEvent {
schema_id: GUARD_EVENT_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
matched,
targeted: 0,
killed: 0,
failed: 0,
skipped_safety: 0,
warnings,
});
}
let mut target_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), cascade);
if target_pids.len() > config.max_targets as usize {
target_pids.truncate(config.max_targets as usize);
warnings.push(format!(
"target count capped at max_targets={} for this cycle",
config.max_targets
));
}
let self_pid = std::process::id();
let parent_pid = get_process(self_pid).ok().map(|p| p.ppid);
let before = target_pids.len();
target_pids.retain(|&pid| pid != self_pid && pid != 1 && pid != config.rule.root_pid);
if let Some(ppid) = parent_pid {
target_pids.retain(|&pid| pid != ppid);
}
let skipped_safety = before.saturating_sub(target_pids.len()) as u32;
if skipped_safety > 0 {
warnings.push(format!(
"skipped {} unsafe target(s) (self/PID1/parent/root)",
skipped_safety
));
}
if target_pids.is_empty() {
return Ok(GuardEvent {
schema_id: GUARD_EVENT_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
matched,
targeted: 0,
killed: 0,
failed: 0,
skipped_safety,
warnings,
});
}
let batch = sysprims_signal::kill_many(&target_pids, signal)?;
Ok(GuardEvent {
schema_id: GUARD_EVENT_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
matched,
targeted: target_pids.len() as u32,
killed: batch.succeeded.len() as u32,
failed: batch.failed.len() as u32,
skipped_safety,
warnings,
})
}
#[cfg(any(test, target_os = "linux", target_os = "macos"))]
fn is_sysprims_binary_name(name: &str) -> bool {
name == "sysprims" || name.starts_with("sysprims-")
}
#[cfg(any(test, target_os = "linux", target_os = "macos"))]
fn guard_discovery_name(cmdline: &[String], fallback_name: &str) -> Option<String> {
let binary = cmdline.first()?.rsplit('/').next().unwrap_or(fallback_name);
if !is_sysprims_binary_name(binary) {
return None;
}
let guard_index = cmdline.iter().position(|arg| arg == "guard")?;
let root_pid = cmdline.get(guard_index + 1)?;
if root_pid.parse::<u32>().ok()? == 0 {
return None;
}
Some(format!("sysprims-guard:{root_pid}"))
}
#[cfg(target_os = "linux")]
fn set_guard_process_title(root_pid: u32) {
let title = format!("sysprims-guard:{root_pid}");
let truncated = title.bytes().take(15).collect::<Vec<_>>();
if let Ok(c_title) = std::ffi::CString::new(truncated) {
unsafe {
libc::prctl(
libc::PR_SET_NAME,
c_title.as_ptr() as libc::c_ulong,
0,
0,
0,
);
}
}
}
#[cfg(target_os = "macos")]
fn set_guard_process_title(root_pid: u32) {
unsafe extern "C" {
fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
}
let title = format!("sysprims-guard:{root_pid}");
let thread_title = std::ffi::CString::new(title.bytes().take(63).collect::<Vec<_>>()).ok();
unsafe {
if let Some(name) = thread_title.as_ref() {
let _ = pthread_setname_np(name.as_ptr());
}
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn set_guard_process_title(_root_pid: u32) {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuardPreset {
Interactive,
Background,
Watchdog,
}
impl GuardPreset {
pub fn interval(&self) -> Duration {
match self {
Self::Interactive => Duration::from_secs(3),
Self::Background => Duration::from_secs(180),
Self::Watchdog => Duration::from_secs(300),
}
}
pub fn sample_duration(&self) -> Duration {
match self {
Self::Interactive => Duration::from_secs(2),
Self::Background => Duration::from_secs(3),
Self::Watchdog => Duration::from_secs(5),
}
}
}
#[derive(Debug, Clone)]
pub struct GuardRunnerConfig {
pub guard: GuardConfig,
pub interval: Duration,
pub max_iterations: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct GuardRunnerSummary {
pub ticks: u64,
pub stop_reason: StopReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StopReason {
Signal,
MaxIterations,
Requested,
}
#[derive(Clone)]
pub struct GuardStopHandle {
requested: Arc<std::sync::atomic::AtomicBool>,
signals_flag: guard_signals::StopFlagHandle,
manager: guard_signals::SignalManager,
}
impl GuardStopHandle {
pub fn stop(&self) {
self.requested
.store(true, std::sync::atomic::Ordering::SeqCst);
self.signals_flag.set();
self.manager.stop();
}
}
impl std::fmt::Debug for GuardStopHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GuardStopHandle")
.field(
"requested",
&self.requested.load(std::sync::atomic::Ordering::SeqCst),
)
.finish()
}
}
pub struct GuardRunner {
config: GuardRunnerConfig,
signals: guard_signals::GuardSignals,
tick: time::Tick,
stop_requested: Arc<std::sync::atomic::AtomicBool>,
}
impl GuardRunner {
pub fn new(config: GuardRunnerConfig) -> SysprimsResult<Self> {
let signals = guard_signals::GuardSignals::start()?;
let tick = time::Tick::new(config.interval)?;
Ok(Self {
config,
signals,
tick,
stop_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
})
}
pub fn stop_handle(&self) -> GuardStopHandle {
GuardStopHandle {
requested: Arc::clone(&self.stop_requested),
signals_flag: self.signals.stop_flag_handle(),
manager: self.signals.manager().clone(),
}
}
pub fn run<F, E>(
&mut self,
mut on_event: F,
mut on_error: E,
) -> SysprimsResult<GuardRunnerSummary>
where
F: FnMut(&GuardEvent),
E: FnMut(u64, &SysprimsError),
{
let mut tick_count: u64 = 0;
set_guard_process_title(self.config.guard.rule.root_pid);
while !self.signals.should_stop() {
match guard_step(self.config.guard.clone()) {
Ok(event) => {
tick_count += 1;
on_event(&event);
}
Err(e) => {
tick_count += 1;
on_error(tick_count, &e);
}
}
if let Some(max) = self.config.max_iterations {
if tick_count >= max {
return Ok(GuardRunnerSummary {
ticks: tick_count,
stop_reason: StopReason::MaxIterations,
});
}
}
if self.signals.should_stop() {
break;
}
self.tick.sleep_until_next();
}
let reason = if self
.stop_requested
.load(std::sync::atomic::Ordering::SeqCst)
{
StopReason::Requested
} else {
StopReason::Signal
};
Ok(GuardRunnerSummary {
ticks: tick_count,
stop_reason: reason,
})
}
pub fn signals(&self) -> &guard_signals::GuardSignals {
&self.signals
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AncestorsResult {
pub schema_id: &'static str,
pub timestamp: String,
pub platform: &'static str,
pub pid: u32,
pub chain: Vec<ProcessInfo>,
pub warnings: Vec<String>,
}
pub fn ancestors(
pid: u32,
max_depth: u32,
options: ProcessOptions,
) -> SysprimsResult<AncestorsResult> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
validate_process_options(&options)?;
let mut chain = Vec::new();
let mut warnings = Vec::new();
let mut seen = HashSet::new();
let mut current_pid = pid;
for depth in 0..=max_depth {
if !seen.insert(current_pid) {
warnings.push(format!(
"loop detected: PID {} already visited at depth {}",
current_pid, depth
));
break;
}
match get_process_with_options(current_pid, options) {
Ok(info) => {
let next_pid = info.ppid;
chain.push(info);
if next_pid == 0 || next_pid == 1 || next_pid == current_pid {
if next_pid == 1 && current_pid != 1 {
match get_process_with_options(1, options) {
Ok(init_info) => chain.push(init_info),
Err(_) => {
warnings.push("could not read init/launchd (PID 1)".to_string());
}
}
}
break;
}
current_pid = next_pid;
}
Err(e) => {
if depth == 0 {
return Err(e);
}
warnings.push(format!(
"ancestor walk stopped at PID {}: {}",
current_pid, e
));
break;
}
}
}
Ok(AncestorsResult {
schema_id: ANCESTORS_RESULT_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
pid,
chain,
warnings,
})
}
pub fn descendants_with_config_and_options(
config: DescendantsConfig,
options: ProcessOptions,
) -> SysprimsResult<DescendantsResult> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if config.root_pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if config.root_pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
config.root_pid, MAX_SAFE_PID
)));
}
validate_process_options(&options)?;
if let Some(f) = config.filter.as_ref() {
f.validate()?;
}
let _ = get_process_with_options(config.root_pid, options)?;
let snap = snapshot_for_descendants(options, config.cpu_mode, config.sample_duration)?;
let mut children_map: HashMap<u32, Vec<ProcessInfo>> = HashMap::new();
for proc in snap.processes {
children_map.entry(proc.ppid).or_default().push(proc);
}
let mut levels: Vec<DescendantsLevel> = Vec::new();
let mut current_pids = vec![config.root_pid];
let mut total_found: usize = 0;
let max_levels = config.max_levels.unwrap_or(u32::MAX);
for depth in 1..=max_levels {
let mut level_procs = Vec::new();
let mut next_pids = Vec::new();
for &pid in ¤t_pids {
if let Some(children) = children_map.get(&pid) {
for child in children {
level_procs.push(child.clone());
next_pids.push(child.pid);
}
}
}
if level_procs.is_empty() {
break;
}
total_found += level_procs.len();
levels.push(DescendantsLevel {
level: depth,
processes: level_procs,
});
current_pids = next_pids;
}
let mut matched_by_filter = total_found;
if let Some(f) = config.filter.as_ref() {
for level in &mut levels {
level.processes.retain(|p| f.matches(p));
}
matched_by_filter = levels.iter().map(|l| l.processes.len()).sum();
levels.retain(|l| !l.processes.is_empty());
}
Ok(DescendantsResult {
schema_id: match config.cpu_mode {
CpuMode::Lifetime => DESCENDANTS_RESULT_V1,
CpuMode::Monitor => DESCENDANTS_RESULT_SAMPLED_V1,
},
root_pid: config.root_pid,
max_levels,
levels,
total_found,
matched_by_filter,
timestamp: now_rfc3339(),
platform: get_platform(),
})
}
fn snapshot_for_descendants(
options: ProcessOptions,
cpu_mode: CpuMode,
sample_duration: Option<Duration>,
) -> SysprimsResult<ProcessSnapshot> {
match cpu_mode {
CpuMode::Lifetime => snapshot_with_options(options),
CpuMode::Monitor => {
let sample = sample_duration.unwrap_or_else(|| Duration::from_secs(1));
snapshot_with_sampled_cpu(options, sample)
}
}
}
fn snapshot_with_sampled_cpu(
options: ProcessOptions,
sample_duration: Duration,
) -> SysprimsResult<ProcessSnapshot> {
if sample_duration.is_zero() {
return Err(SysprimsError::invalid_argument(
"sample duration must be > 0",
));
}
let snap0 = snapshot_with_options(options)?;
let mut t0 = HashMap::<u32, (Option<u64>, u64)>::new();
for p in &snap0.processes {
if let Ok(cpu_ns) = cpu_total_time_ns(p.pid) {
t0.insert(p.pid, (p.start_time_unix_ms, cpu_ns));
}
}
std::thread::sleep(sample_duration);
let mut snap1 = snapshot_with_options(options)?;
let dt_ns = sample_duration.as_nanos() as f64;
if dt_ns > 0.0 {
for p in &mut snap1.processes {
if let Some((start0, cpu0)) = t0.get(&p.pid) {
if start0.is_some()
&& p.start_time_unix_ms.is_some()
&& start0 != &p.start_time_unix_ms
{
continue;
}
if let Ok(cpu1) = cpu_total_time_ns(p.pid) {
let delta = cpu1.saturating_sub(*cpu0) as f64;
p.cpu_percent = (delta / dt_ns) * 100.0;
}
}
}
}
snap1.schema_id = PROCESS_INFO_SAMPLED_V1;
Ok(snap1)
}
pub fn wait_pid(pid: u32, timeout: Duration) -> SysprimsResult<WaitPidResult> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
platform::wait_pid_impl(pid, timeout)
}
pub fn is_live(pid: u32) -> SysprimsResult<bool> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
Ok(platform::liveness_impl(pid)? == Liveness::Live)
}
pub fn is_fully_gone(pid: u32) -> SysprimsResult<bool> {
const MAX_SAFE_PID: u32 = i32::MAX as u32;
if pid == 0 {
return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
}
if pid > MAX_SAFE_PID {
return Err(SysprimsError::invalid_argument(format!(
"PID {} exceeds maximum safe value {}",
pid, MAX_SAFE_PID
)));
}
Ok(platform::liveness_impl(pid)? == Liveness::Gone)
}
fn make_port_snapshot(bindings: Vec<PortBinding>, warnings: Vec<String>) -> PortBindingsSnapshot {
let mut warnings = warnings;
if bindings.is_empty() {
warnings.push("No listening ports found".to_string());
}
PortBindingsSnapshot {
schema_id: PORT_BINDINGS_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
bindings,
warnings,
}
}
fn make_fd_snapshot(pid: u32, fds: Vec<FdInfo>, warnings: Vec<String>) -> FdSnapshot {
FdSnapshot {
schema_id: FD_SNAPSHOT_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
pid,
fds,
warnings,
}
}
fn make_snapshot(processes: Vec<ProcessInfo>) -> ProcessSnapshot {
ProcessSnapshot {
schema_id: PROCESS_INFO_V1,
timestamp: now_rfc3339(),
processes,
}
}
fn make_wait_pid_result(
pid: u32,
exited: bool,
timed_out: bool,
exit_code: Option<i32>,
warnings: Vec<String>,
) -> WaitPidResult {
WaitPidResult {
schema_id: WAIT_PID_RESULT_V1,
timestamp: now_rfc3339(),
platform: get_platform(),
pid,
exited,
timed_out,
exit_code,
warnings,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::{Child, Command, Stdio};
use std::thread;
#[test]
fn test_snapshot_not_empty() {
let snap = snapshot().unwrap();
assert!(
!snap.processes.is_empty(),
"Snapshot should contain processes"
);
}
#[test]
fn test_snapshot_has_schema_id() {
let snap = snapshot().unwrap();
assert_eq!(snap.schema_id, PROCESS_INFO_V1);
assert!(snap.schema_id.contains("process-info"));
}
#[test]
fn test_snapshot_has_timestamp() {
let snap = snapshot().unwrap();
assert!(!snap.timestamp.is_empty());
assert!(snap.timestamp.contains('T'));
assert!(snap.timestamp.contains('Z') || snap.timestamp.contains('+'));
}
#[test]
#[cfg(unix)]
fn test_snapshot_has_processes() {
let snap = snapshot().unwrap();
let own_pid = std::process::id();
let has_self = snap.processes.iter().any(|p| p.pid == own_pid);
assert!(has_self, "Snapshot should include our own process");
assert!(
snap.processes.len() >= 3,
"Should have at least a few visible processes, got {}",
snap.processes.len()
);
}
#[test]
fn test_get_self() {
let pid = std::process::id();
let info = get_process(pid).unwrap();
assert_eq!(info.pid, pid);
assert!(!info.name.is_empty(), "Process should have a name");
}
#[test]
#[cfg(target_os = "macos")]
fn test_own_process_has_cmdline() {
let snap = snapshot().unwrap();
let own_pid = std::process::id();
let own_proc = snap
.processes
.iter()
.find(|p| p.pid == own_pid)
.expect("Should find own process in snapshot");
assert!(
!own_proc.cmdline.is_empty(),
"Own process should have cmdline, got empty"
);
}
#[test]
fn test_get_self_has_valid_fields() {
let pid = std::process::id();
let info = get_process(pid).unwrap();
assert!(info.cpu_percent >= 0.0);
assert!(info.cpu_percent <= 100.0);
assert!(info.memory_kb < u64::MAX);
if let Some(ms) = info.start_time_unix_ms {
assert!(ms > 0);
}
if let Some(ref exe) = info.exe_path {
assert!(!exe.is_empty());
}
assert!(
info.state == ProcessState::Running
|| info.state == ProcessState::Sleeping
|| info.state == ProcessState::Unknown,
"Test process should be running, sleeping, or unknown (Windows)"
);
}
#[test]
fn test_wait_pid_self_times_out() {
let pid = std::process::id();
let r = wait_pid(pid, Duration::from_millis(1)).unwrap();
assert_eq!(r.pid, pid);
assert!(r.timed_out);
assert!(!r.exited);
}
#[test]
fn pid_taking_entrypoints_reject_unsafe_pids() {
let over_max = (i32::MAX as u32) + 1;
for &pid in &[0u32, over_max, u32::MAX] {
assert!(
matches!(get_process(pid), Err(SysprimsError::InvalidArgument { .. })),
"get_process must reject unsafe PID {pid}"
);
assert!(
matches!(
wait_pid(pid, Duration::from_millis(1)),
Err(SysprimsError::InvalidArgument { .. })
),
"wait_pid must reject unsafe PID {pid}"
);
assert!(
matches!(
cpu_total_time_ns(pid),
Err(SysprimsError::InvalidArgument { .. })
),
"cpu_total_time_ns must reject unsafe PID {pid}"
);
}
}
#[test]
fn test_filter_by_name_contains() {
let filter = ProcessFilter {
name_contains: Some("sysprims".into()),
..Default::default()
};
let snap = snapshot_filtered(&filter).unwrap();
for proc in &snap.processes {
assert!(
proc.name.to_lowercase().contains("sysprims"),
"Filtered process '{}' should contain 'sysprims'",
proc.name
);
}
}
#[test]
fn test_guard_discovery_name_matches_guard_cmdline() {
let cmdline = vec![
"/usr/local/bin/sysprims".to_string(),
"guard".to_string(),
"27776".to_string(),
"--preset".to_string(),
"watchdog".to_string(),
];
assert_eq!(
guard_discovery_name(&cmdline, "sysprims"),
Some("sysprims-guard:27776".to_string())
);
}
#[test]
fn test_guard_discovery_name_ignores_non_guard_cmdline() {
let cmdline = vec![
"/usr/local/bin/sysprims".to_string(),
"pstat".to_string(),
"--json".to_string(),
];
assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
}
#[test]
fn test_guard_discovery_name_rejects_invalid_root_pid() {
let cmdline = vec![
"/usr/local/bin/sysprims".to_string(),
"guard".to_string(),
"not-a-pid".to_string(),
];
assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
}
#[test]
fn test_filter_by_pid() {
let my_pid = std::process::id();
let filter = ProcessFilter {
pid_in: Some(vec![my_pid]),
..Default::default()
};
let snap = snapshot_filtered(&filter).unwrap();
assert_eq!(snap.processes.len(), 1);
assert_eq!(snap.processes[0].pid, my_pid);
}
#[test]
fn test_filter_validation_cpu_range() {
let filter = ProcessFilter {
cpu_above: Some(150.0),
..Default::default()
};
let result = filter.validate();
assert!(result.is_err());
let filter = ProcessFilter {
cpu_above: Some(-1.0),
..Default::default()
};
let result = filter.validate();
assert!(result.is_err());
let filter = ProcessFilter {
cpu_above: Some(50.0),
..Default::default()
};
let result = filter.validate();
assert!(result.is_ok());
}
#[test]
fn test_nonexistent_pid() {
let result = get_process(99999999);
assert!(
matches!(result, Err(SysprimsError::NotFound { .. })),
"Should return NotFound for nonexistent PID"
);
}
#[test]
fn test_invalid_pid_zero() {
let result = get_process(0);
assert!(
matches!(result, Err(SysprimsError::InvalidArgument { .. })),
"PID 0 should be invalid"
);
}
#[test]
fn test_cpu_normalized() {
let snap = snapshot().unwrap();
for proc in &snap.processes {
assert!(
proc.cpu_percent >= 0.0,
"CPU percent for PID {} should be >= 0",
proc.pid
);
assert!(
proc.cpu_percent <= 100.0,
"CPU percent for PID {} should be <= 100, got {}",
proc.pid,
proc.cpu_percent
);
}
}
#[test]
fn test_process_state_serialization() {
let json = serde_json::to_string(&ProcessState::Running).unwrap();
assert_eq!(json, "\"running\"");
let json = serde_json::to_string(&ProcessState::Sleeping).unwrap();
assert_eq!(json, "\"sleeping\"");
let json = serde_json::to_string(&ProcessState::Zombie).unwrap();
assert_eq!(json, "\"zombie\"");
}
#[test]
fn test_filter_deserialization() {
let json = r#"{"name_contains": "test", "cpu_above": 5.0}"#;
let filter: ProcessFilter = serde_json::from_str(json).unwrap();
assert_eq!(filter.name_contains, Some("test".to_string()));
assert_eq!(filter.cpu_above, Some(5.0));
}
#[test]
fn test_filter_unknown_field_rejected() {
let json = r#"{"unknown_field": "value"}"#;
let result: Result<ProcessFilter, _> = serde_json::from_str(json);
assert!(result.is_err(), "Unknown fields should be rejected");
}
#[test]
fn test_port_filter_unknown_field_rejected() {
let json = r#"{"unknown_field": true}"#;
let result: Result<PortFilter, _> = serde_json::from_str(json);
assert!(result.is_err(), "Unknown fields should be rejected");
}
#[test]
fn test_port_filter_schema_id() {
assert!(PortFilter::schema_id().contains("port-filter"));
}
#[test]
fn test_process_options_builder() {
let opts = ProcessOptions::default();
assert!(!opts.include_env);
assert!(!opts.include_threads);
let opts = ProcessOptions::default().with_env().with_threads();
assert!(opts.include_env);
assert!(opts.include_threads);
}
#[test]
fn test_get_process_with_default_options_has_no_proc_ext_fields() {
let pid = std::process::id();
let info = get_process_with_options(pid, ProcessOptions::default()).unwrap();
assert!(info.env.is_none());
assert!(info.thread_count.is_none());
}
#[test]
#[cfg(feature = "proc_ext")]
fn test_get_process_with_threads_populates_thread_count() {
let pid = std::process::id();
let info = get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
assert!(info.thread_count.is_some());
}
#[test]
#[cfg(all(feature = "proc_ext", unix))]
fn test_get_process_with_env_populates_env_map() {
let pid = std::process::id();
let info = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap();
assert!(info.env.is_some());
}
#[test]
#[cfg(not(feature = "proc_ext"))]
fn test_proc_ext_options_rejected_when_feature_disabled() {
let pid = std::process::id();
let err = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap_err();
assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
}
#[test]
fn test_descendants_with_config_lifetime_self() {
let pid = std::process::id();
let config = DescendantsConfig {
root_pid: pid,
max_levels: Some(1),
filter: None,
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
};
let result = descendants_with_config(config).unwrap();
assert_eq!(result.root_pid, pid);
assert_eq!(result.max_levels, 1);
}
#[test]
fn test_descendants_with_config_monitor_self() {
let pid = std::process::id();
let config = DescendantsConfig {
root_pid: pid,
max_levels: Some(1),
filter: None,
cpu_mode: CpuMode::Monitor,
sample_duration: Some(Duration::from_millis(1)),
};
let result = descendants_with_config(config).unwrap();
assert_eq!(result.schema_id, DESCENDANTS_RESULT_SAMPLED_V1);
assert_eq!(result.root_pid, pid);
assert_eq!(result.max_levels, 1);
}
#[test]
fn test_descendants_with_config_monitor_zero_sample_rejected() {
let config = DescendantsConfig {
root_pid: std::process::id(),
max_levels: Some(1),
filter: None,
cpu_mode: CpuMode::Monitor,
sample_duration: Some(Duration::ZERO),
};
let err = descendants_with_config(config).unwrap_err();
assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
}
#[test]
fn test_descendants_with_config_invalid_pid_zero_rejected_before_sampling() {
let config = DescendantsConfig {
root_pid: 0,
max_levels: Some(1),
filter: None,
cpu_mode: CpuMode::Monitor,
sample_duration: Some(Duration::from_secs(1)),
};
let err = descendants_with_config(config).unwrap_err();
assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
}
#[test]
fn test_snapshot_json_output() {
let snap = snapshot().unwrap();
let json = serde_json::to_string_pretty(&snap).unwrap();
assert!(json.contains("\"schema_id\""));
assert!(json.contains("\"timestamp\""));
assert!(json.contains("\"processes\""));
assert!(json.contains(PROCESS_INFO_V1));
}
fn test_process(pid: u32, ppid: u32, name: &str) -> ProcessInfo {
ProcessInfo {
pid,
ppid,
name: name.to_string(),
user: None,
cpu_percent: 0.0,
memory_kb: 0,
elapsed_seconds: 0,
start_time_unix_ms: None,
exe_path: None,
state: ProcessState::Running,
cmdline: vec![],
env: None,
thread_count: None,
}
}
fn test_descendants_tree() -> DescendantsResult {
DescendantsResult {
schema_id: DESCENDANTS_RESULT_V1,
root_pid: 10,
max_levels: 10,
levels: vec![
DescendantsLevel {
level: 1,
processes: vec![test_process(11, 10, "helper"), test_process(12, 10, "db")],
},
DescendantsLevel {
level: 2,
processes: vec![
test_process(13, 11, "child-a"),
test_process(14, 12, "child-b"),
],
},
],
total_found: 4,
matched_by_filter: 4,
timestamp: "1970-01-01T00:00:00Z".to_string(),
platform: get_platform(),
}
}
fn spawn_sleep_child() -> Child {
#[cfg(unix)]
{
Command::new("sleep")
.arg("30")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn sleep child")
}
#[cfg(windows)]
{
Command::new("cmd")
.args(["/C", "ping -n 60 127.0.0.1 >NUL"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn ping child")
}
}
fn guard_step_retry(config: &GuardConfig, attempts: usize, delay_ms: u64) -> GuardEvent {
let mut last = None;
for attempt in 0..attempts {
let event = guard_step(config.clone()).expect("guard_step should succeed");
let ready = if config.action_enabled {
event.targeted > 0 && (event.killed > 0 || event.failed > 0)
} else {
true
};
if ready {
return event;
}
last = Some(event);
if attempt + 1 < attempts {
thread::sleep(Duration::from_millis(delay_ms));
}
}
last.expect("guard_step retry should record an event")
}
#[test]
fn test_select_descendant_targets_non_cascade() {
let result = test_descendants_tree();
let filter = ProcessFilter {
name_contains: Some("helper".to_string()),
..Default::default()
};
let targets = select_descendant_targets(&result, Some(&filter), false);
assert_eq!(targets, vec![11]);
}
#[test]
fn test_select_descendant_targets_cascade() {
let result = test_descendants_tree();
let filter = ProcessFilter {
name_contains: Some("helper".to_string()),
..Default::default()
};
let targets = select_descendant_targets(&result, Some(&filter), true);
assert_eq!(targets, vec![11, 13]);
}
#[test]
fn test_guard_step_action_disabled_emits_event() {
let cfg = GuardConfig {
rule: GuardRule {
root_pid: std::process::id(),
max_levels: 1,
filter: None,
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
},
action: GuardAction::KillDescendants {
signal: 15,
cascade: false,
},
action_enabled: false,
max_targets: 32,
};
let event = guard_step(cfg).unwrap();
assert_eq!(event.schema_id, GUARD_EVENT_V1);
assert_eq!(event.targeted, 0);
assert_eq!(event.killed, 0);
assert_eq!(event.failed, 0);
assert!(event.warnings.iter().any(|w| w.contains("action disabled")));
}
#[test]
fn test_guard_step_rejects_zero_max_targets() {
let cfg = GuardConfig {
rule: GuardRule {
root_pid: std::process::id(),
max_levels: 1,
filter: None,
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
},
action: GuardAction::KillDescendants {
signal: 15,
cascade: false,
},
action_enabled: false,
max_targets: 0,
};
let err = guard_step(cfg).unwrap_err();
assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
}
#[test]
fn test_guard_step_action_enabled_kills_targeted_child() {
let mut child = spawn_sleep_child();
let child_pid = child.id();
let mut child_visible = false;
for _ in 0..20 {
let desc = descendants_with_config(DescendantsConfig {
root_pid: std::process::id(),
max_levels: Some(1),
filter: Some(ProcessFilter {
pid_in: Some(vec![child_pid]),
..Default::default()
}),
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
})
.unwrap();
if desc.matched_by_filter >= 1 {
child_visible = true;
break;
}
thread::sleep(Duration::from_millis(50));
}
assert!(child_visible, "expected spawned child to be visible");
let cfg = GuardConfig {
rule: GuardRule {
root_pid: std::process::id(),
max_levels: 1,
filter: Some(ProcessFilter {
pid_in: Some(vec![child_pid]),
..Default::default()
}),
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
},
action: GuardAction::KillDescendants {
signal: 15,
cascade: false,
},
action_enabled: true,
max_targets: 8,
};
let event = guard_step_retry(&cfg, 10, 100);
assert_eq!(event.targeted, 1);
assert_eq!(event.killed, 1);
assert_eq!(event.failed, 0);
let mut exited = false;
for _ in 0..20 {
if let Some(_status) = child.try_wait().expect("poll child exit") {
exited = true;
break;
}
thread::sleep(Duration::from_millis(100));
}
if !exited {
let _ = child.kill();
let _ = child.wait();
}
assert!(exited, "guard_step should terminate targeted child");
}
#[test]
fn test_guard_step_action_enabled_applies_max_targets_cap() {
let mut child_a = spawn_sleep_child();
let mut child_b = spawn_sleep_child();
let pids = vec![child_a.id(), child_b.id()];
let mut both_visible = false;
for _ in 0..20 {
let desc = descendants_with_config(DescendantsConfig {
root_pid: std::process::id(),
max_levels: Some(1),
filter: Some(ProcessFilter {
pid_in: Some(pids.clone()),
..Default::default()
}),
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
})
.unwrap();
if desc.matched_by_filter >= 2 {
both_visible = true;
break;
}
thread::sleep(Duration::from_millis(50));
}
assert!(both_visible, "expected both spawned children to be visible");
let cfg = GuardConfig {
rule: GuardRule {
root_pid: std::process::id(),
max_levels: 1,
filter: Some(ProcessFilter {
pid_in: Some(pids.clone()),
..Default::default()
}),
cpu_mode: CpuMode::Lifetime,
sample_duration: None,
},
action: GuardAction::KillDescendants {
signal: 15,
cascade: false,
},
action_enabled: true,
max_targets: 1,
};
let event = guard_step_retry(&cfg, 10, 100);
assert_eq!(event.matched, 2);
assert_eq!(event.targeted, 1);
assert_eq!(event.killed, 1);
assert_eq!(event.failed, 0);
assert!(
event
.warnings
.iter()
.any(|w| w.contains("target count capped at max_targets=1")),
"expected max_targets cap warning, got: {:?}",
event.warnings
);
let mut exited_count = 0;
for _ in 0..20 {
exited_count = 0;
if child_a.try_wait().expect("poll child A").is_some() {
exited_count += 1;
}
if child_b.try_wait().expect("poll child B").is_some() {
exited_count += 1;
}
if exited_count >= 1 {
break;
}
thread::sleep(Duration::from_millis(100));
}
assert!(
exited_count >= 1,
"expected at least one child to exit after capped guard_step kill"
);
for child in [&mut child_a, &mut child_b] {
if child.try_wait().expect("final poll").is_none() {
let _ = child.kill();
let _ = child.wait();
}
}
}
#[test]
fn test_ancestors_self() {
let pid = std::process::id();
let result = ancestors(pid, 64, ProcessOptions::default()).unwrap();
assert_eq!(result.schema_id, ANCESTORS_RESULT_V1);
assert_eq!(result.pid, pid);
assert!(
!result.chain.is_empty(),
"chain should include at least self"
);
assert_eq!(
result.chain[0].pid, pid,
"first element should be starting PID"
);
assert!(
result.chain.len() >= 2,
"chain should include at least self and parent, got {}",
result.chain.len()
);
}
#[test]
fn test_ancestors_rejects_pid_zero() {
let err = ancestors(0, 10, ProcessOptions::default()).unwrap_err();
assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
}
#[test]
fn test_ancestors_nonexistent_pid() {
let err = ancestors(99999999, 10, ProcessOptions::default()).unwrap_err();
assert!(matches!(err, SysprimsError::NotFound { .. }));
}
#[test]
fn test_ancestors_max_depth_zero() {
let pid = std::process::id();
let result = ancestors(pid, 0, ProcessOptions::default()).unwrap();
assert_eq!(result.chain.len(), 1);
assert_eq!(result.chain[0].pid, pid);
}
}