rsigma_eval/correlation/keys.rs
1use std::borrow::Cow;
2
3use serde::Serialize;
4
5use crate::event::Event;
6
7use super::types::GroupByField;
8
9// =============================================================================
10// Group Key
11// =============================================================================
12
13/// Composite key for group-by partitioning.
14///
15/// Each element corresponds to a `GroupByField` value extracted from an event.
16#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, serde::Deserialize)]
17pub struct GroupKey(pub Vec<Option<String>>);
18
19impl GroupKey {
20 /// Extract a group key from an event given the group-by fields and the
21 /// rule reference identifiers (ID, name, etc.) that produced the detection match.
22 ///
23 /// Returns `None` when any group-by field is absent, null, or cannot be
24 /// represented as a scalar string.
25 pub fn extract(
26 event: &impl Event,
27 group_by: &[GroupByField],
28 rule_refs: &[&str],
29 ) -> Option<Self> {
30 let values: Option<Vec<_>> = group_by
31 .iter()
32 .map(|field| {
33 let field_name = field.resolve(rule_refs);
34 event
35 .get_field(field_name)
36 .and_then(|v| v.as_str().map(Cow::into_owned))
37 .map(Some)
38 })
39 .collect();
40 values.map(GroupKey)
41 }
42
43 /// Build a group key from explicit field-value pairs (for chaining).
44 ///
45 /// Returns `None` when the child correlation did not provide every field
46 /// required by the parent.
47 pub fn from_pairs(pairs: &[(String, String)], group_by: &[GroupByField]) -> Option<Self> {
48 let values: Option<Vec<_>> = group_by
49 .iter()
50 .map(|field| {
51 let name = field.name();
52 pairs
53 .iter()
54 .find(|(k, _)| k == name)
55 .map(|(_, v)| v.clone())
56 .map(Some)
57 })
58 .collect();
59 values.map(GroupKey)
60 }
61
62 /// Convert to field-name/value pairs for output.
63 pub fn to_pairs(&self, group_by: &[GroupByField]) -> Vec<(String, String)> {
64 group_by
65 .iter()
66 .zip(self.0.iter())
67 .filter_map(|(field, value)| {
68 value
69 .as_ref()
70 .map(|v| (field.name().to_string(), v.clone()))
71 })
72 .collect()
73 }
74}