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