rsigma_eval/result.rs
1//! Unified result type for rule evaluation and correlation.
2//!
3//! `EvaluationResult` is the single output type produced by both detection
4//! and correlation. Fields shared across kinds (rule metadata, custom
5//! attributes, optional enrichments) live in [`RuleHeader`]; kind-specific
6//! fields live in [`ResultBody`]. Both are merged into one flat top-level
7//! JSON object via `#[serde(flatten)]` on the struct and `#[serde(untagged)]`
8//! on the body enum.
9//!
10//! Downstream JSON consumers distinguish detection from correlation by the
11//! presence of `correlation_type` (correlation-only) and `matched_fields`
12//! (detection-only). The field set, values, and `skip_serializing_if`
13//! behavior match the pre-unification `MatchResult` / `CorrelationResult`
14//! layout; the only visible difference is that a non-empty
15//! `custom_attributes` map is now emitted between header and body fields
16//! rather than at the end of the line, which is invisible to compliant
17//! JSON consumers (objects are unordered per spec). The wire-shape golden
18//! tests under `crates/rsigma-eval/tests/wire_shape_golden.rs` pin the
19//! new ordering for both kinds.
20
21use std::collections::HashMap;
22use std::sync::Arc;
23
24use rsigma_parser::{CorrelationType, Level};
25use serde::Serialize;
26
27use crate::correlation::EventRef;
28
29/// A single evaluation result.
30///
31/// Wraps a detection match ([`ResultBody::Detection`]) or a correlation
32/// firing ([`ResultBody::Correlation`]) behind one shared [`RuleHeader`].
33/// Serialize emits a single flat JSON object combining header and body
34/// fields.
35#[derive(Debug, Clone, Serialize)]
36pub struct EvaluationResult {
37 #[serde(flatten)]
38 pub header: RuleHeader,
39 #[serde(flatten)]
40 pub body: ResultBody,
41}
42
43impl EvaluationResult {
44 /// True when this result was produced by detection rule matching.
45 pub fn is_detection(&self) -> bool {
46 matches!(self.body, ResultBody::Detection(_))
47 }
48
49 /// True when this result was produced by a correlation firing.
50 pub fn is_correlation(&self) -> bool {
51 matches!(self.body, ResultBody::Correlation(_))
52 }
53
54 /// Read the detection-specific body, if this result is a detection.
55 pub fn as_detection(&self) -> Option<&DetectionBody> {
56 match &self.body {
57 ResultBody::Detection(d) => Some(d),
58 ResultBody::Correlation(_) => None,
59 }
60 }
61
62 /// Read the correlation-specific body, if this result is a correlation.
63 pub fn as_correlation(&self) -> Option<&CorrelationBody> {
64 match &self.body {
65 ResultBody::Correlation(c) => Some(c),
66 ResultBody::Detection(_) => None,
67 }
68 }
69
70 /// Mutable accessor for the detection-specific body.
71 pub fn as_detection_mut(&mut self) -> Option<&mut DetectionBody> {
72 match &mut self.body {
73 ResultBody::Detection(d) => Some(d),
74 ResultBody::Correlation(_) => None,
75 }
76 }
77
78 /// Mutable accessor for the correlation-specific body.
79 pub fn as_correlation_mut(&mut self) -> Option<&mut CorrelationBody> {
80 match &mut self.body {
81 ResultBody::Correlation(c) => Some(c),
82 ResultBody::Detection(_) => None,
83 }
84 }
85}
86
87/// Fields shared between detection and correlation results.
88///
89/// The optional `enrichments` map is `None` for results emitted directly
90/// by the engine; downstream middleware can populate it with arbitrary
91/// JSON values to ride along with each result.
92#[derive(Debug, Clone, Serialize)]
93pub struct RuleHeader {
94 /// Title of the matched rule.
95 pub rule_title: String,
96 /// ID of the matched rule (if present).
97 pub rule_id: Option<String>,
98 /// Severity level.
99 pub level: Option<Level>,
100 /// Tags from the matched rule.
101 pub tags: Vec<String>,
102 /// Custom attributes from the rule (merged with pipeline overrides).
103 ///
104 /// Wrapped in `Arc` so per-match cloning is a pointer bump.
105 #[serde(skip_serializing_if = "HashMap::is_empty")]
106 pub custom_attributes: Arc<HashMap<String, serde_json::Value>>,
107 /// Optional map of arbitrary enrichment values, written by downstream
108 /// middleware. `None` for engine-emitted results; skipped on serialize.
109 #[serde(skip_serializing_if = "Option::is_none")]
110 pub enrichments: Option<serde_json::Map<String, serde_json::Value>>,
111}
112
113/// Kind-specific payload of an [`EvaluationResult`].
114///
115/// Serialized as an untagged enum so the variant fields flatten directly
116/// into the parent JSON object. Downstream consumers disambiguate variants
117/// by the kind-unique fields each variant carries (`matched_fields` for
118/// detection, `correlation_type` for correlation).
119///
120/// Invariant: each variant must keep at least one required, kind-unique
121/// field. This is what lets the untagged enum disambiguate on a future
122/// `Deserialize` and keeps the `correlation_type`-presence rule reliable
123/// for existing consumers.
124#[derive(Debug, Clone, Serialize)]
125#[serde(untagged)]
126pub enum ResultBody {
127 /// Detection rule match (stateless, immediate).
128 Detection(DetectionBody),
129 /// Correlation rule firing (stateful, time-windowed).
130 Correlation(CorrelationBody),
131}
132
133/// Detection-specific result fields.
134#[derive(Debug, Clone, Serialize)]
135pub struct DetectionBody {
136 /// The matched detections (selections) that decide the condition, each
137 /// once. A selection that matched but did not make the rule fire, such
138 /// as `a` in `(a and b) or c` firing on `c`, is left out.
139 pub matched_selections: Vec<String>,
140 /// Specific field matches that triggered the detection.
141 pub matched_fields: Vec<FieldMatch>,
142 /// The full event that triggered the match, included when the rule
143 /// sets `rsigma.include_event: "true"`.
144 #[serde(skip_serializing_if = "Option::is_none")]
145 pub event: Option<serde_json::Value>,
146}
147
148/// Correlation-specific result fields.
149#[derive(Debug, Clone, Serialize)]
150pub struct CorrelationBody {
151 /// Type of correlation.
152 pub correlation_type: CorrelationType,
153 /// Group-by field names and their values for this match.
154 pub group_key: Vec<(String, String)>,
155 /// The aggregated value that triggered the condition (count, sum, avg, ...).
156 pub aggregated_value: f64,
157 /// The time window in seconds.
158 pub timespan_secs: u64,
159 /// Full event bodies, included when `correlation_event_mode` is `Full`.
160 #[serde(skip_serializing_if = "Option::is_none")]
161 pub events: Option<Vec<serde_json::Value>>,
162 /// Lightweight event references, included when `correlation_event_mode` is `Refs`.
163 #[serde(skip_serializing_if = "Option::is_none")]
164 pub event_refs: Option<Vec<EventRef>>,
165}
166
167/// Verbosity of the match detail attached to detection results.
168///
169/// Gates how much is recorded in each [`FieldMatch`]. `Off` is the default
170/// and produces the historical `{ field, value }` shape with no extra keys,
171/// so existing wire consumers are unaffected unless they opt in.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
173pub enum MatchDetailLevel {
174 /// Historical behavior: only field-present matches, recorded as
175 /// `{ field, value }`. Keyword and absence matches are not reported.
176 #[default]
177 Off,
178 /// Adds the originating `selection`, the `matcher` kind, and
179 /// `case_sensitive`, and reports previously dropped keyword and
180 /// absence matches.
181 Summary,
182 /// Everything in `Summary` plus the `pattern` that fired.
183 Full,
184}
185
186impl MatchDetailLevel {
187 /// Lowercase wire name (`off` / `summary` / `full`).
188 pub fn as_str(self) -> &'static str {
189 match self {
190 MatchDetailLevel::Off => "off",
191 MatchDetailLevel::Summary => "summary",
192 MatchDetailLevel::Full => "full",
193 }
194 }
195}
196
197impl std::str::FromStr for MatchDetailLevel {
198 type Err = String;
199
200 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
201 match s.trim().to_ascii_lowercase().as_str() {
202 "off" => Ok(MatchDetailLevel::Off),
203 "summary" => Ok(MatchDetailLevel::Summary),
204 "full" => Ok(MatchDetailLevel::Full),
205 other => Err(format!(
206 "invalid match-detail level: {other:?} (expected off, summary, or full)"
207 )),
208 }
209 }
210}
211
212/// The kind of matcher that produced a [`FieldMatch`].
213///
214/// Serialized lowercase. Composite and multi-pattern matchers
215/// (`AnyOf` / `AllOf` / Aho-Corasick / regex sets) collapse to `one_of`.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
217#[serde(rename_all = "lowercase")]
218pub enum MatcherKind {
219 Exact,
220 Contains,
221 StartsWith,
222 EndsWith,
223 Regex,
224 #[serde(rename = "one_of")]
225 OneOf,
226 Cidr,
227 Numeric,
228 Exists,
229 FieldRef,
230 Null,
231 Bool,
232 Expand,
233 Timestamp,
234 Keyword,
235}
236
237/// Serde helper: skip a `bool` field when it is `false`.
238#[inline]
239fn is_false(b: &bool) -> bool {
240 !*b
241}
242
243/// A specific field match within a detection.
244///
245/// The `field` and `value` keys are always present and preserve the
246/// historical wire shape. The remaining keys are populated only when the
247/// engine runs above [`MatchDetailLevel::Off`] and are skipped on
248/// serialization when empty, so the default output is byte-identical to
249/// pre-enrichment releases.
250#[derive(Debug, Clone, Default, Serialize)]
251pub struct FieldMatch {
252 /// The field name that matched (`"keyword"` for keyword matches).
253 pub field: String,
254 /// The event value that triggered the match (`null` for absence matches).
255 pub value: serde_json::Value,
256 /// The selection (named detection) the match came from.
257 #[serde(skip_serializing_if = "Option::is_none")]
258 pub selection: Option<String>,
259 /// The matcher kind that fired.
260 #[serde(skip_serializing_if = "Option::is_none")]
261 pub matcher: Option<MatcherKind>,
262 /// The pattern the matcher tested against (Full level only, truncated).
263 #[serde(skip_serializing_if = "Option::is_none")]
264 pub pattern: Option<String>,
265 /// Whether the match was case-sensitive, when meaningful for the matcher.
266 #[serde(skip_serializing_if = "Option::is_none")]
267 pub case_sensitive: Option<bool>,
268 /// Whether the matcher was negated (`|not` / inverted).
269 #[serde(skip_serializing_if = "is_false", default)]
270 pub negated: bool,
271}
272
273impl FieldMatch {
274 /// Construct a bare match with only `field` and `value` set, matching
275 /// the historical (`MatchDetailLevel::Off`) shape.
276 pub fn new(field: impl Into<String>, value: serde_json::Value) -> Self {
277 FieldMatch {
278 field: field.into(),
279 value,
280 ..Default::default()
281 }
282 }
283}
284
285/// Convenience iterators over a slice of [`EvaluationResult`].
286///
287/// `ProcessResult` is a flat `Vec<EvaluationResult>` (detections then
288/// correlations, in evaluation order); this trait exposes by-kind views
289/// without forcing every caller to write `.iter().filter(|r| r.is_*())`.
290/// Implemented on `[EvaluationResult]` so it works for `Vec`, slices, and
291/// boxed slices alike.
292pub trait ProcessResultExt {
293 /// Iterate over detection results.
294 fn detections(&self) -> impl Iterator<Item = &EvaluationResult>;
295 /// Iterate over correlation results.
296 fn correlations(&self) -> impl Iterator<Item = &EvaluationResult>;
297 /// Number of detection results.
298 fn detection_count(&self) -> usize {
299 self.detections().count()
300 }
301 /// Number of correlation results.
302 fn correlation_count(&self) -> usize {
303 self.correlations().count()
304 }
305}
306
307impl ProcessResultExt for [EvaluationResult] {
308 fn detections(&self) -> impl Iterator<Item = &EvaluationResult> {
309 self.iter().filter(|r| r.is_detection())
310 }
311 fn correlations(&self) -> impl Iterator<Item = &EvaluationResult> {
312 self.iter().filter(|r| r.is_correlation())
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319
320 fn header(title: &str) -> RuleHeader {
321 RuleHeader {
322 rule_title: title.to_string(),
323 rule_id: Some(format!("{title}-id")),
324 level: Some(Level::High),
325 tags: vec!["attack.t1059".to_string()],
326 custom_attributes: Arc::new(HashMap::new()),
327 enrichments: None,
328 }
329 }
330
331 /// Wire-shape snapshot: a detection serializes to a flat JSON object
332 /// with detection-only fields and no `correlation_type` key.
333 #[test]
334 fn detection_wire_shape_is_flat() {
335 let result = EvaluationResult {
336 header: header("Suspicious PowerShell"),
337 body: ResultBody::Detection(DetectionBody {
338 matched_selections: vec!["selection".to_string()],
339 matched_fields: vec![FieldMatch::new(
340 "CommandLine",
341 serde_json::json!("powershell -enc ..."),
342 )],
343 event: None,
344 }),
345 };
346
347 let json = serde_json::to_string(&result).unwrap();
348 assert_eq!(
349 json,
350 r#"{"rule_title":"Suspicious PowerShell","rule_id":"Suspicious PowerShell-id","level":"high","tags":["attack.t1059"],"matched_selections":["selection"],"matched_fields":[{"field":"CommandLine","value":"powershell -enc ..."}]}"#
351 );
352
353 // Downstream-disambiguation contract: detections must not carry
354 // a `correlation_type` key.
355 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
356 assert!(parsed.get("correlation_type").is_none());
357 assert!(parsed.get("matched_fields").is_some());
358 }
359
360 /// Wire-shape snapshot: a correlation serializes to a flat JSON object
361 /// with correlation-only fields and no `matched_fields` key.
362 #[test]
363 fn correlation_wire_shape_is_flat() {
364 let result = EvaluationResult {
365 header: header("SSH brute force"),
366 body: ResultBody::Correlation(CorrelationBody {
367 correlation_type: CorrelationType::EventCount,
368 group_key: vec![("SourceIP".to_string(), "203.0.113.4".to_string())],
369 aggregated_value: 73.0,
370 timespan_secs: 300,
371 events: None,
372 event_refs: None,
373 }),
374 };
375
376 let json = serde_json::to_string(&result).unwrap();
377 assert_eq!(
378 json,
379 r#"{"rule_title":"SSH brute force","rule_id":"SSH brute force-id","level":"high","tags":["attack.t1059"],"correlation_type":"event_count","group_key":[["SourceIP","203.0.113.4"]],"aggregated_value":73.0,"timespan_secs":300}"#
380 );
381
382 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
383 assert!(parsed.get("matched_fields").is_none());
384 assert!(parsed.get("correlation_type").is_some());
385 }
386
387 #[test]
388 fn accessors_dispatch_on_body_variant() {
389 let det = EvaluationResult {
390 header: header("Det"),
391 body: ResultBody::Detection(DetectionBody {
392 matched_selections: vec![],
393 matched_fields: vec![],
394 event: None,
395 }),
396 };
397 assert!(det.is_detection());
398 assert!(!det.is_correlation());
399 assert!(det.as_detection().is_some());
400 assert!(det.as_correlation().is_none());
401
402 let corr = EvaluationResult {
403 header: header("Corr"),
404 body: ResultBody::Correlation(CorrelationBody {
405 correlation_type: CorrelationType::EventCount,
406 group_key: vec![],
407 aggregated_value: 0.0,
408 timespan_secs: 0,
409 events: None,
410 event_refs: None,
411 }),
412 };
413 assert!(corr.is_correlation());
414 assert!(!corr.is_detection());
415 assert!(corr.as_correlation().is_some());
416 assert!(corr.as_detection().is_none());
417 }
418}