Skip to main content

rsigma_eval/correlation_engine/
introspect.rs

1//! Read-only introspection of correlation window state.
2//!
3//! The only built-in visibility into correlation state is the aggregate
4//! `correlation_state_entries` count. That answers "is there state?" but not
5//! the operator's real question: "why did this correlation not fire?"
6//! [`CorrelationEngine::introspect`] projects, per correlation and per group,
7//! the current aggregate versus the threshold (the gap made explicit), the
8//! window contents, the last alert and remaining suppression, and the seconds
9//! until the next eviction. It is a read-only projection over the existing
10//! state with no hot-path cost.
11
12use serde::Serialize;
13
14use rsigma_parser::{ConditionOperator, CorrelationType};
15
16use super::CorrelationEngine;
17use crate::correlation::{CompiledCorrelation, GroupKey, WindowState};
18use crate::tenant::TenantId;
19
20/// A snapshot of every compiled correlation and its live per-group window
21/// state at the moment [`CorrelationEngine::introspect`] was called.
22#[derive(Debug, Clone, Serialize)]
23pub struct CorrelationStateSnapshot {
24    /// One entry per compiled correlation (independent of whether it has
25    /// active state).
26    pub correlations: Vec<CorrelationInfo>,
27    /// One entry per live `(correlation, group_key)` window.
28    pub groups: Vec<GroupStateInfo>,
29}
30
31/// Static description of one compiled correlation.
32#[derive(Debug, Clone, Serialize)]
33pub struct CorrelationInfo {
34    pub index: usize,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub id: Option<String>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub name: Option<String>,
39    pub title: String,
40    #[serde(rename = "type")]
41    pub correlation_type: CorrelationType,
42    pub timespan_secs: u64,
43    pub group_by: Vec<String>,
44    pub rule_refs: Vec<String>,
45    /// The threshold predicates rendered for display, e.g. `>= 5`.
46    pub threshold: String,
47    /// Number of live group windows for this correlation.
48    pub active_groups: usize,
49    /// Ruleset that owns this correlation, set when rows from several rulesets
50    /// share one list. `RulesetEngines::introspect` keys its map by ruleset
51    /// and leaves this `None`.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub ruleset: Option<String>,
54}
55
56/// One field of a resolved group key.
57#[derive(Debug, Clone, Serialize)]
58pub struct GroupKeyPart {
59    pub field: String,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub value: Option<String>,
62}
63
64/// Live state of one `(correlation, group_key)` window.
65#[derive(Debug, Clone, Serialize)]
66pub struct GroupStateInfo {
67    pub correlation_index: usize,
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub correlation_id: Option<String>,
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub correlation_name: Option<String>,
72    pub correlation_title: String,
73    #[serde(rename = "type")]
74    pub correlation_type: CorrelationType,
75    /// The resolved group key, field by field.
76    pub group_key: Vec<GroupKeyPart>,
77    /// A flat `field=value` rendering of the group key for display and
78    /// substring filtering.
79    pub group_key_display: String,
80    /// The current aggregate (count / sum / avg / distinct / fired-rule count).
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub got: Option<f64>,
83    /// The threshold predicates rendered for display.
84    pub threshold: String,
85    /// Whether the threshold condition is currently satisfied.
86    pub met: bool,
87    /// Number of retained entries in the window.
88    pub entries: usize,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub earliest: Option<i64>,
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub latest: Option<i64>,
93    pub timespan_secs: u64,
94    /// Seconds until the oldest entry leaves the window, relative to the
95    /// latest observed event time (`earliest + timespan - latest`, clamped at
96    /// zero).
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub seconds_to_eviction: Option<i64>,
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub last_alert: Option<i64>,
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub suppress_secs: Option<u64>,
103    /// Seconds remaining in the suppression window after the last alert,
104    /// relative to the latest observed event time.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub suppression_remaining: Option<i64>,
107    /// The raw window state (timestamps / values), serialized as-is.
108    pub window: WindowState,
109    /// Ruleset that owns this window, set when rows from several rulesets
110    /// share one list. `RulesetEngines::introspect` keys its map by ruleset
111    /// and leaves this `None`.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub ruleset: Option<String>,
114    /// Tenant that owns this window, when tenancy is enabled.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub tenant: Option<TenantId>,
117}
118
119impl<L> CorrelationEngine<L> {
120    /// Snapshot every compiled correlation and its live per-group window state.
121    pub fn introspect(&self) -> CorrelationStateSnapshot {
122        self.introspect_for_tenant(None, None, None)
123    }
124
125    /// Like [`introspect`](CorrelationEngine::introspect) but keeps only the
126    /// correlations whose id, name, or title equals `id_filter` and the groups
127    /// whose rendered key contains `group_filter`.
128    pub fn introspect_filtered(
129        &self,
130        id_filter: Option<&str>,
131        group_filter: Option<&str>,
132    ) -> CorrelationStateSnapshot {
133        self.introspect_for_tenant(id_filter, group_filter, None)
134    }
135
136    /// Like [`introspect_filtered`](CorrelationEngine::introspect_filtered)
137    /// but, when `tenant_filter` is set, keeps only groups owned by that
138    /// tenant and counts only its groups as active.
139    pub fn introspect_for_tenant(
140        &self,
141        id_filter: Option<&str>,
142        group_filter: Option<&str>,
143        tenant_filter: Option<&TenantId>,
144    ) -> CorrelationStateSnapshot {
145        let mut active_per_corr = vec![0usize; self.correlations.len()];
146        for key in self.state.keys() {
147            if tenant_filter.is_none_or(|tenant| key.tenant.as_ref() == Some(tenant)) {
148                active_per_corr[key.corr_idx] += 1;
149            }
150        }
151
152        let correlations = self
153            .correlations
154            .iter()
155            .enumerate()
156            .filter(|(_, c)| matches_id(c, id_filter))
157            .map(|(i, c)| CorrelationInfo {
158                index: i,
159                id: c.id.clone(),
160                name: c.name.clone(),
161                title: c.title.clone(),
162                correlation_type: c.correlation_type,
163                timespan_secs: c.timespan_secs,
164                group_by: c.group_by.iter().map(|g| g.name().to_string()).collect(),
165                rule_refs: c.rule_refs.clone(),
166                threshold: render_threshold(c),
167                active_groups: active_per_corr[i],
168                ruleset: None,
169            })
170            .collect();
171
172        let mut groups = Vec::new();
173        for (key, ws) in &self.state {
174            let corr = &self.correlations[key.corr_idx];
175            if !matches_id(corr, id_filter) {
176                continue;
177            }
178            if !tenant_filter.is_none_or(|tenant| key.tenant.as_ref() == Some(tenant)) {
179                continue;
180            }
181            let parts = group_key_parts(corr, &key.group_key);
182            let display = render_group_key(&parts);
183            if let Some(filter) = group_filter
184                && !display.contains(filter)
185            {
186                continue;
187            }
188
189            let got = ws.current_value(
190                corr.correlation_type,
191                &corr.rule_refs,
192                corr.condition.percentile,
193            );
194            let met = ws
195                .check_condition(
196                    &corr.condition,
197                    corr.correlation_type,
198                    &corr.rule_refs,
199                    corr.extended_expr.as_ref(),
200                )
201                .is_some();
202            let earliest = ws.earliest_timestamp();
203            let latest = ws.latest_timestamp();
204            let seconds_to_eviction = match (earliest, latest) {
205                (Some(e), Some(l)) => Some((e + corr.timespan_secs as i64 - l).max(0)),
206                _ => None,
207            };
208            let last_alert = self.last_alert.get(key).copied();
209            let suppress_secs = corr.suppress_secs.or(self.config.suppress);
210            let suppression_remaining = match (last_alert, suppress_secs, latest) {
211                (Some(la), Some(s), Some(l)) => Some((la + s as i64 - l).max(0)),
212                _ => None,
213            };
214
215            groups.push(GroupStateInfo {
216                correlation_index: key.corr_idx,
217                correlation_id: corr.id.clone(),
218                correlation_name: corr.name.clone(),
219                correlation_title: corr.title.clone(),
220                correlation_type: corr.correlation_type,
221                group_key: parts,
222                group_key_display: display,
223                got,
224                threshold: render_threshold(corr),
225                met,
226                entries: ws.entry_count(),
227                earliest,
228                latest,
229                timespan_secs: corr.timespan_secs,
230                seconds_to_eviction,
231                last_alert,
232                suppress_secs,
233                suppression_remaining,
234                window: ws.clone(),
235                ruleset: None,
236                tenant: key.tenant.clone(),
237            });
238        }
239
240        // Deterministic order for stable output and golden tests.
241        groups.sort_by(|a, b| {
242            a.correlation_index
243                .cmp(&b.correlation_index)
244                .then_with(|| a.group_key_display.cmp(&b.group_key_display))
245                .then_with(|| a.tenant.cmp(&b.tenant))
246        });
247
248        CorrelationStateSnapshot {
249            correlations,
250            groups,
251        }
252    }
253}
254
255fn matches_id(corr: &CompiledCorrelation, id_filter: Option<&str>) -> bool {
256    match id_filter {
257        None => true,
258        Some(f) => {
259            corr.id.as_deref() == Some(f) || corr.name.as_deref() == Some(f) || corr.title == f
260        }
261    }
262}
263
264fn group_key_parts(corr: &CompiledCorrelation, key: &GroupKey) -> Vec<GroupKeyPart> {
265    corr.group_by
266        .iter()
267        .enumerate()
268        .map(|(i, field)| GroupKeyPart {
269            field: field.name().to_string(),
270            value: key.0.get(i).and_then(|v| v.clone()),
271        })
272        .collect()
273}
274
275fn render_group_key(parts: &[GroupKeyPart]) -> String {
276    if parts.is_empty() {
277        return "(no group-by)".to_string();
278    }
279    parts
280        .iter()
281        .map(|p| format!("{}={}", p.field, p.value.as_deref().unwrap_or("<none>")))
282        .collect::<Vec<_>>()
283        .join(", ")
284}
285
286fn render_threshold(corr: &CompiledCorrelation) -> String {
287    let preds: Vec<String> = corr
288        .condition
289        .predicates
290        .iter()
291        .map(|(op, v)| format!("{} {}", op_symbol(*op), v))
292        .collect();
293    if preds.is_empty() {
294        "(none)".to_string()
295    } else {
296        preds.join(", ")
297    }
298}
299
300fn op_symbol(op: ConditionOperator) -> &'static str {
301    match op {
302        ConditionOperator::Lt => "<",
303        ConditionOperator::Lte => "<=",
304        ConditionOperator::Gt => ">",
305        ConditionOperator::Gte => ">=",
306        ConditionOperator::Eq => "==",
307        ConditionOperator::Neq => "!=",
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use crate::event::JsonEvent;
314    use crate::{CorrelationConfig, CorrelationEngine};
315    use rsigma_parser::parse_sigma_yaml;
316    use serde_json::json;
317
318    const RULES: &str = r#"
319title: Login
320id: login-rule
321logsource:
322    category: auth
323detection:
324    selection:
325        EventType: login
326    condition: selection
327---
328title: Many Logins
329correlation:
330    type: event_count
331    rules:
332        - login-rule
333    group-by:
334        - User
335    timespan: 60s
336    condition:
337        gte: 3
338level: high
339"#;
340
341    fn engine() -> CorrelationEngine {
342        let coll = parse_sigma_yaml(RULES).unwrap();
343        let mut e = CorrelationEngine::new(CorrelationConfig::default());
344        e.add_collection(&coll).unwrap();
345        e
346    }
347
348    #[test]
349    fn introspect_reports_gap_below_threshold() {
350        let mut e = engine();
351        // Two logins for admin: below the gte:3 threshold.
352        for i in 0..2 {
353            let v = json!({"EventType": "login", "User": "admin"});
354            e.process_event_at(&JsonEvent::borrow(&v), 1000 + i);
355        }
356        let snap = e.introspect();
357        assert_eq!(snap.correlations.len(), 1);
358        assert_eq!(snap.correlations[0].threshold, ">= 3");
359        assert_eq!(snap.correlations[0].active_groups, 1);
360
361        let g = snap
362            .groups
363            .iter()
364            .find(|g| g.group_key_display.contains("admin"))
365            .expect("admin group present");
366        assert_eq!(g.got, Some(2.0));
367        assert!(!g.met);
368        assert_eq!(g.entries, 2);
369        assert_eq!(g.threshold, ">= 3");
370        assert_eq!(g.group_key_display, "User=admin");
371    }
372
373    #[test]
374    fn introspect_marks_met_when_threshold_reached() {
375        let mut e = engine();
376        for i in 0..3 {
377            let v = json!({"EventType": "login", "User": "admin"});
378            e.process_event_at(&JsonEvent::borrow(&v), 1000 + i);
379        }
380        let snap = e.introspect();
381        let g = &snap.groups[0];
382        assert_eq!(g.got, Some(3.0));
383        assert!(g.met);
384        // The window spans ts 1000..=1002 with a 60s timespan, so the oldest
385        // entry (1000) is evicted 60s after it arrived, relative to the latest.
386        assert_eq!(g.seconds_to_eviction, Some(1000 + 60 - 1002));
387    }
388
389    #[test]
390    fn introspect_filter_by_group_substring() {
391        let mut e = engine();
392        for u in ["admin", "alice"] {
393            let v = json!({"EventType": "login", "User": u});
394            e.process_event_at(&JsonEvent::borrow(&v), 1000);
395        }
396        let snap = e.introspect_filtered(None, Some("alice"));
397        assert_eq!(snap.groups.len(), 1);
398        assert!(snap.groups[0].group_key_display.contains("alice"));
399    }
400
401    #[test]
402    fn introspect_filter_by_unknown_id_is_empty() {
403        let mut e = engine();
404        let v = json!({"EventType": "login", "User": "admin"});
405        e.process_event_at(&JsonEvent::borrow(&v), 1000);
406        let snap = e.introspect_filtered(Some("nope"), None);
407        assert!(snap.correlations.is_empty());
408        assert!(snap.groups.is_empty());
409    }
410}