rsigma_eval/logsource.rs
1//! Event logsource extraction for opt-in, conflict-based logsource pruning.
2//!
3//! A [`LogSourceExtractor`] derives a [`LogSource`] from an event by reading
4//! configurable field names (defaulting to the literals `product`, `service`,
5//! and `category`), falling back to optional static defaults. The result feeds
6//! the engine's conflict-based pruning: an event tagged `product: windows`
7//! skips `product: linux` rules without dropping Windows-category or
8//! logsource-less rules.
9//!
10//! Extraction is fail-open per dimension: a field that is absent, null, or
11//! blank leaves that dimension unset (after the static default is consulted),
12//! so a missing tag never prunes anything.
13//!
14//! Embedders whose events carry their logsource somewhere other than a
15//! matchable field (out-of-band metadata, a transport envelope) implement
16//! [`ExtractLogSource`] for their event type instead, and build the engine
17//! around it with [`Engine::with_logsource_extractor`].
18//!
19//! [`Engine::with_logsource_extractor`]: crate::Engine::with_logsource_extractor
20
21use rsigma_parser::LogSource;
22
23use crate::event::Event;
24
25/// Derives an event's [`LogSource`] for conflict-based logsource pruning.
26///
27/// [`Engine`](crate::Engine), [`CorrelationEngine`](crate::CorrelationEngine),
28/// and [`SchemaRouter`](crate::SchemaRouter) are generic over their extractor
29/// type, defaulting to the field-reading [`LogSourceExtractor`], and call it
30/// once per event with static dispatch. The trait is generic over the event
31/// type, so an extractor can read state that only a concrete event type
32/// carries.
33///
34/// A dimension left unset is a wildcard for pruning. An extractor that cannot
35/// determine a dimension must leave it `None` rather than guess, so a missing
36/// value never prunes a rule.
37///
38/// # Example
39///
40/// An event type that carries its logsource as metadata beside the payload:
41///
42/// ```rust
43/// use std::borrow::Cow;
44///
45/// use rsigma_eval::event::{Event, EventValue, JsonEvent};
46/// use rsigma_eval::{Engine, ExtractLogSource};
47/// use rsigma_parser::{LogSource, parse_sigma_yaml};
48/// use serde_json::{Value, json};
49///
50/// struct TaggedEvent {
51/// product: &'static str,
52/// payload: JsonEvent<'static>,
53/// }
54///
55/// impl Event for TaggedEvent {
56/// fn get_field(&self, path: &str) -> Option<EventValue<'_>> {
57/// self.payload.get_field(path)
58/// }
59/// fn any_string_value(&self, pred: &dyn Fn(&str) -> bool) -> bool {
60/// self.payload.any_string_value(pred)
61/// }
62/// fn all_string_values(&self) -> Vec<Cow<'_, str>> {
63/// self.payload.all_string_values()
64/// }
65/// fn to_json(&self) -> Value {
66/// self.payload.to_json()
67/// }
68/// }
69///
70/// struct MetadataExtractor;
71///
72/// impl ExtractLogSource<TaggedEvent> for MetadataExtractor {
73/// fn extract(&self, event: &TaggedEvent) -> LogSource {
74/// LogSource {
75/// product: Some(event.product.to_string()),
76/// ..LogSource::default()
77/// }
78/// }
79/// }
80///
81/// let rules = parse_sigma_yaml(r#"
82/// title: Linux whoami
83/// logsource:
84/// product: linux
85/// detection:
86/// selection:
87/// CommandLine|contains: whoami
88/// condition: selection
89/// "#).unwrap();
90///
91/// let mut engine = Engine::with_logsource_extractor(MetadataExtractor);
92/// engine.add_collection(&rules).unwrap();
93///
94/// let payload = || JsonEvent::owned(json!({"CommandLine": "whoami"}));
95/// let linux = TaggedEvent { product: "linux", payload: payload() };
96/// let windows = TaggedEvent { product: "windows", payload: payload() };
97///
98/// assert_eq!(engine.evaluate(&linux).len(), 1);
99/// assert!(engine.evaluate(&windows).is_empty()); // pruned by metadata
100/// ```
101pub trait ExtractLogSource<E: Event> {
102 /// Extract the event's logsource.
103 fn extract(&self, event: &E) -> LogSource;
104}
105
106/// Derives an event [`LogSource`] from configurable fields plus static
107/// defaults, for conflict-based logsource pruning on the evaluation hot path.
108///
109/// Each dimension is resolved independently in precedence order: the value of
110/// the configured event field, then the static default, then unset (`None`).
111/// A present-but-blank field value is treated as unset.
112///
113/// # Example
114///
115/// ```rust
116/// use rsigma_eval::LogSourceExtractor;
117/// use rsigma_eval::event::JsonEvent;
118/// use serde_json::json;
119///
120/// let extractor = LogSourceExtractor::new();
121/// let ev = json!({"product": "windows"});
122/// let event = JsonEvent::borrow(&ev);
123///
124/// let ls = extractor.extract(&event);
125/// assert_eq!(ls.product.as_deref(), Some("windows"));
126/// assert_eq!(ls.category, None); // absent fields stay unset (fail-open)
127/// ```
128#[derive(Debug, Clone)]
129pub struct LogSourceExtractor {
130 product_field: String,
131 service_field: String,
132 category_field: String,
133 /// Extra dimensions: `(logsource custom key, event field name)`. Each
134 /// resolves into [`LogSource::custom`] for conflict-based pruning beyond
135 /// the standard three dimensions.
136 custom_fields: Vec<(String, String)>,
137 defaults: LogSource,
138}
139
140impl LogSourceExtractor {
141 /// Create an extractor that reads the literal `product`, `service`, and
142 /// `category` fields with no static defaults.
143 pub fn new() -> Self {
144 LogSourceExtractor {
145 product_field: "product".to_string(),
146 service_field: "service".to_string(),
147 category_field: "category".to_string(),
148 custom_fields: Vec::new(),
149 defaults: LogSource::default(),
150 }
151 }
152
153 /// Override the event field names read for each dimension.
154 #[must_use]
155 pub fn with_field_names(
156 mut self,
157 product_field: impl Into<String>,
158 service_field: impl Into<String>,
159 category_field: impl Into<String>,
160 ) -> Self {
161 self.product_field = product_field.into();
162 self.service_field = service_field.into();
163 self.category_field = category_field.into();
164 self
165 }
166
167 /// Set the extra `(custom dimension, event field)` mappings read into
168 /// [`LogSource::custom`]. Each pair reads the event field and stores it
169 /// under the custom dimension key; absent fields fall back to the static
170 /// custom default (if any) and are otherwise omitted (fail-open).
171 #[must_use]
172 pub fn with_custom_fields(mut self, custom_fields: Vec<(String, String)>) -> Self {
173 self.custom_fields = custom_fields;
174 self
175 }
176
177 /// Set the static per-dimension defaults applied when a field is absent.
178 /// `product`, `service`, `category`, and the `custom` map are consulted.
179 #[must_use]
180 pub fn with_defaults(mut self, defaults: LogSource) -> Self {
181 self.defaults = defaults;
182 self
183 }
184
185 /// Extract the event's logsource. Each dimension resolves to the configured
186 /// field value, then the static default, then `None`/absent (fail-open).
187 pub fn extract<E: Event>(&self, event: &E) -> LogSource {
188 // Start from the static custom defaults, then let event-field values
189 // win per key.
190 let mut custom = self.defaults.custom.clone();
191 for (dimension, field) in &self.custom_fields {
192 if let Some(value) = event.get_field(field)
193 && let Some(s) = value.as_str()
194 {
195 let trimmed = s.trim();
196 if !trimmed.is_empty() {
197 custom.insert(dimension.clone(), trimmed.to_string());
198 }
199 }
200 }
201 LogSource {
202 product: self.resolve(event, &self.product_field, &self.defaults.product),
203 service: self.resolve(event, &self.service_field, &self.defaults.service),
204 category: self.resolve(event, &self.category_field, &self.defaults.category),
205 custom,
206 ..LogSource::default()
207 }
208 }
209
210 fn resolve<E: Event>(
211 &self,
212 event: &E,
213 field: &str,
214 default: &Option<String>,
215 ) -> Option<String> {
216 if let Some(value) = event.get_field(field)
217 && let Some(s) = value.as_str()
218 {
219 let trimmed = s.trim();
220 if !trimmed.is_empty() {
221 return Some(trimmed.to_string());
222 }
223 }
224 default.clone()
225 }
226}
227
228impl<E: Event> ExtractLogSource<E> for LogSourceExtractor {
229 fn extract(&self, event: &E) -> LogSource {
230 LogSourceExtractor::extract(self, event)
231 }
232}
233
234impl Default for LogSourceExtractor {
235 fn default() -> Self {
236 Self::new()
237 }
238}