Skip to main content

rsigma_runtime/enrichment/
mod.rs

1//! Post-evaluation enrichment for the rsigma daemon.
2//!
3//! Enrichment runs in the daemon's sink task, after `Engine::evaluate()` has
4//! produced a [`ProcessResult`](rsigma_eval::ProcessResult) (a flat
5//! `Vec<EvaluationResult>`) and before that result is serialized to a sink.
6//! Each enricher inspects an [`EvaluationResult`], optionally fetches
7//! context (HTTP, command, source cache, pure template), and writes the
8//! result into `result.header.enrichments` under a configured
9//! `inject_field`.
10//!
11//! # Architecture
12//!
13//! A single [`Enricher`] trait covers every primitive (`template`, `lookup`,
14//! `http`, `command`) and any bespoke Rust-coded enrichers. Each enricher
15//! declares an [`EnricherKind`] at config time; the [`EnrichmentPipeline`]
16//! filters results by that declared kind against the
17//! [`EvaluationResult::body`] variant before invoking `enrich()`. There are no
18//! parallel `DetectionEnricher` / `CorrelationEnricher` traits and no separate
19//! context types; enrichers consume `&mut EvaluationResult` directly and
20//! match on `result.body` for kind-specific fields.
21//!
22//! # Concurrency
23//!
24//! Results within a single sink batch are enriched concurrently with bounded
25//! concurrency via a single [`tokio::sync::Semaphore`] owned by the pipeline.
26//! Within a single result the enricher chain runs sequentially (so later
27//! enrichers can depend on earlier ones via `${detection.enrichments.*}` in a
28//! follow-up implementation; for this initial cut the chain is linear and
29//! enrichers are independent).
30//!
31//! # Errors
32//!
33//! Failures are scoped per enricher and do not abort the chain by default;
34//! the per-enricher `on_error` policy ([`OnError`]) decides whether to
35//! `skip` the field, inject a JSON `null` for it, or `drop` the entire
36//! result before serialization. Timeouts are enforced via
37//! [`tokio::time::timeout`] using each enricher's [`Enricher::timeout`].
38
39use std::sync::Arc;
40use std::time::Duration;
41
42use async_trait::async_trait;
43use rsigma_eval::{EvaluationResult, ResultBody};
44use tokio::sync::Semaphore;
45
46use crate::metrics::{MetricsHook, NoopMetrics};
47
48mod command;
49pub mod config;
50mod http;
51pub mod http_cache;
52mod lookup;
53mod scope;
54mod template;
55#[cfg(test)]
56mod tests;
57
58pub use command::{CommandEnricher, OutputFormat};
59pub use http::{
60    DEFAULT_ENRICHER_MAX_RESPONSE_BYTES, HttpEnricher, HttpEnricherClient,
61    build_default_http_client,
62};
63pub use http_cache::{CacheKey, CacheOutcome, HttpResponseCache};
64pub use lookup::LookupEnricher;
65pub use scope::Scope;
66pub use template::{TemplateEnricher, TemplateError, validate_template_namespace};
67
68/// The kind of [`EvaluationResult`] an [`Enricher`] applies to.
69///
70/// Fixed at config load. Used for two things:
71/// 1. **Template-namespace validation at config load**: a `Detection` enricher
72///    may only reference `${detection.*}`; a `Correlation` enricher may only
73///    reference `${correlation.*}`. Cross-namespace references fail fast at
74///    startup.
75/// 2. **Runtime gating in [`EnrichmentPipeline::run`]**: enrichers whose
76///    declared kind does not match `result.body`'s variant are skipped before
77///    [`Enricher::enrich`] is invoked.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79pub enum EnricherKind {
80    /// Applies to detection results ([`ResultBody::Detection`]).
81    Detection,
82    /// Applies to correlation results ([`ResultBody::Correlation`]).
83    Correlation,
84}
85
86impl EnricherKind {
87    /// String label used in metrics, logs, and config errors.
88    pub fn as_str(&self) -> &'static str {
89        match self {
90            EnricherKind::Detection => "detection",
91            EnricherKind::Correlation => "correlation",
92        }
93    }
94
95    /// Returns true if this kind matches the given result body variant.
96    pub fn matches(&self, body: &ResultBody) -> bool {
97        matches!(
98            (self, body),
99            (EnricherKind::Detection, ResultBody::Detection(_))
100                | (EnricherKind::Correlation, ResultBody::Correlation(_))
101        )
102    }
103}
104
105/// Behavior when an enricher fails (timeout, fetch error, parse error, …).
106///
107/// Applied per enricher. Defaults to [`OnError::Skip`] so a single failed
108/// enrichment never breaks the result stream.
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
110pub enum OnError {
111    /// Deliver the result unenriched for this field. Default. Logs a warning.
112    #[default]
113    Skip,
114    /// Inject `null` under `inject_field` so downstream consumers see a
115    /// "we tried" marker rather than missing-field ambiguity.
116    Null,
117    /// Suppress the result entirely before serialization. Useful for
118    /// dedup / pre-filter style enrichers that intentionally drop matches
119    /// based on external context.
120    Drop,
121}
122
123/// A typed enrichment failure attributed to a specific enricher.
124#[derive(Debug, Clone)]
125pub struct EnrichError {
126    /// Stable ID of the enricher that produced the error.
127    pub enricher_id: String,
128    /// Categorized failure kind.
129    pub kind: EnrichErrorKind,
130}
131
132impl std::fmt::Display for EnrichError {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(f, "enricher '{}': {}", self.enricher_id, self.kind)
135    }
136}
137
138impl std::error::Error for EnrichError {}
139
140/// Categorized enrichment failure.
141#[derive(Debug, Clone)]
142pub enum EnrichErrorKind {
143    /// The per-enricher timeout elapsed before [`Enricher::enrich`] returned.
144    Timeout,
145    /// External fetch failed (HTTP non-2xx, connection refused, command exit
146    /// status non-zero, etc.).
147    Fetch(String),
148    /// External response could not be parsed (e.g. invalid JSON).
149    Parse(String),
150    /// Extract expression (jq / jsonpath / cel) failed during evaluation.
151    Extract(String),
152    /// Template rendering failed at runtime (missing variable in a strict
153    /// resolver, invalid expansion, …). The config-load-time validator
154    /// catches namespace violations earlier.
155    TemplateRender(String),
156}
157
158impl std::fmt::Display for EnrichErrorKind {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        match self {
161            EnrichErrorKind::Timeout => write!(f, "timeout"),
162            EnrichErrorKind::Fetch(m) => write!(f, "fetch failed: {m}"),
163            EnrichErrorKind::Parse(m) => write!(f, "parse failed: {m}"),
164            EnrichErrorKind::Extract(m) => write!(f, "extract failed: {m}"),
165            EnrichErrorKind::TemplateRender(m) => write!(f, "template render failed: {m}"),
166        }
167    }
168}
169
170/// Trait implemented by every enrichment primitive (`template`, `lookup`,
171/// `http`, `command`) and by any bespoke Rust-coded named enricher
172/// registered via [`register_builtin`].
173///
174/// Implementations read shared rule metadata from [`EvaluationResult::header`]
175/// and dispatch on `result.body` for kind-specific fields. The pipeline
176/// guarantees that `result.body` matches `self.kind()` before calling
177/// `enrich()`, so implementations may rely on the matching variant
178/// (e.g. via [`EvaluationResult::as_detection`] /
179/// [`EvaluationResult::as_correlation`]).
180///
181/// `enrich` is async to accommodate I/O-bound primitives (HTTP, command).
182/// Pure transformations (`template`) still implement `enrich` as `async fn`
183/// even though they perform no I/O.
184#[async_trait]
185pub trait Enricher: Send + Sync {
186    /// The kind of result this enricher applies to. Fixed at config load.
187    fn kind(&self) -> EnricherKind;
188
189    /// Stable identifier for this enricher instance. Used as a metric label
190    /// and in structured log fields. Conventionally something like
191    /// `asset_lookup_det` or `enrich_hash_virustotal`.
192    fn id(&self) -> &str;
193
194    /// Field name under [`RuleHeader::enrichments`](rsigma_eval::RuleHeader::enrichments)
195    /// that this enricher writes to.
196    fn inject_field(&self) -> &str;
197
198    /// Per-enricher timeout. The pipeline wraps each `enrich()` call in
199    /// [`tokio::time::timeout`] using this value. Defaults to 5 seconds.
200    fn timeout(&self) -> Duration {
201        Duration::from_secs(5)
202    }
203
204    /// Optional scope filter. Applied after the kind-vs-body filter and
205    /// before `enrich()` runs. Default is [`Scope::default`] (always fires).
206    fn scope(&self) -> &Scope;
207
208    /// Behavior when this enricher fails (timeout, fetch error, …).
209    /// Defaults to [`OnError::Skip`].
210    fn on_error(&self) -> OnError {
211        OnError::Skip
212    }
213
214    /// Run the enrichment.
215    ///
216    /// Implementations write into [`RuleHeader::enrichments`](rsigma_eval::RuleHeader::enrichments)
217    /// under the configured [`Self::inject_field`]. The pipeline initializes
218    /// the map (`None` → `Some(empty)`) before invoking the first enricher
219    /// for a given result, so implementations can `unwrap` the map safely.
220    async fn enrich(&self, result: &mut EvaluationResult) -> Result<(), EnrichError>;
221}
222
223/// Outcome of running a single enricher against a single result.
224///
225/// Returned internally by [`EnrichmentPipeline::run_one`] so the pipeline
226/// driver can decide whether to drop the entire result, log, or continue.
227enum EnrichOutcome {
228    /// Enricher ran and (possibly) wrote into `enrichments`.
229    Ok,
230    /// Enricher errored or timed out and `on_error: skip` applied.
231    Skip,
232    /// Enricher errored or timed out and `on_error: null` applied; the
233    /// pipeline injected `null` under `inject_field`.
234    Null,
235    /// Enricher errored or timed out and `on_error: drop` applied; the
236    /// pipeline must remove this result from the output vec.
237    Drop,
238    /// Enricher was filtered out (kind or scope mismatch) before running.
239    Filtered,
240}
241
242/// Execution surface for a configured set of enrichers.
243///
244/// One pipeline owns one `Vec<Box<dyn Enricher>>` plus a shared
245/// [`Semaphore`] that bounds the number of in-flight enrichments across
246/// all results in a batch.
247///
248/// The pipeline is constructed by the daemon config layer
249/// (`crates/rsigma-cli/src/daemon/enrichment/config.rs`) and held inside
250/// the daemon's sink task. Each [`ProcessResult`](rsigma_eval::ProcessResult)
251/// (a `Vec<EvaluationResult>`) flows through [`EnrichmentPipeline::run`]
252/// before it is serialized.
253pub struct EnrichmentPipeline {
254    enrichers: Vec<Box<dyn Enricher>>,
255    semaphore: Arc<Semaphore>,
256    metrics: Arc<dyn MetricsHook>,
257}
258
259impl std::fmt::Debug for EnrichmentPipeline {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        f.debug_struct("EnrichmentPipeline")
262            .field("enrichers", &self.enrichers.len())
263            .field("permits", &self.semaphore.available_permits())
264            .finish()
265    }
266}
267
268impl EnrichmentPipeline {
269    /// Build a pipeline from a list of configured enrichers.
270    ///
271    /// `max_concurrent_enrichments` bounds the number of results that can
272    /// be enriched in parallel; defaults to 16 if zero is passed.
273    /// Metrics default to a no-op sink; call [`Self::with_metrics`] to
274    /// route counters and latency histograms into a real
275    /// [`MetricsHook`] implementation.
276    pub fn new(enrichers: Vec<Box<dyn Enricher>>, max_concurrent_enrichments: usize) -> Self {
277        let permits = if max_concurrent_enrichments == 0 {
278            16
279        } else {
280            max_concurrent_enrichments
281        };
282        Self {
283            enrichers,
284            semaphore: Arc::new(Semaphore::new(permits)),
285            metrics: Arc::new(NoopMetrics),
286        }
287    }
288
289    /// Replace the metrics hook this pipeline reports into. The daemon
290    /// passes its Prometheus-backed `Metrics` here; library consumers
291    /// can pass any [`MetricsHook`] implementation.
292    ///
293    /// Pre-registers `(enricher_id, kind)` for every configured
294    /// enricher so `rsigma_enrichment_total{...}` and
295    /// `rsigma_enrichment_duration_seconds{...}` are emitted on
296    /// `/metrics` from the first scrape, even before any enricher has
297    /// fired.
298    pub fn with_metrics(mut self, metrics: Arc<dyn MetricsHook>) -> Self {
299        for enricher in &self.enrichers {
300            metrics.register_enricher(enricher.id(), enricher.kind().as_str());
301        }
302        self.metrics = metrics;
303        self
304    }
305
306    /// Returns true if no enrichers are configured.
307    ///
308    /// The daemon sink task uses this to skip enrichment work entirely
309    /// (no permit acquisition, no per-result loop) when no enrichers are
310    /// configured.
311    pub fn is_empty(&self) -> bool {
312        self.enrichers.is_empty()
313    }
314
315    /// Number of configured enrichers (across both kinds).
316    pub fn len(&self) -> usize {
317        self.enrichers.len()
318    }
319
320    /// Iterate over the configured enrichers (read-only view, used for
321    /// reload-diff logging and tests).
322    pub fn enrichers(&self) -> impl Iterator<Item = &dyn Enricher> {
323        self.enrichers.iter().map(|e| &**e)
324    }
325
326    /// Run every applicable enricher against each result in `results`.
327    ///
328    /// For each result the pipeline:
329    /// 1. Acquires a global semaphore permit (bounded concurrency).
330    /// 2. Iterates the configured enricher list.
331    /// 3. Skips enrichers whose [`EnricherKind`] does not match the
332    ///    result's body variant.
333    /// 4. Skips enrichers whose [`Scope`] excludes this result.
334    /// 5. Wraps each remaining `enrich()` call in
335    ///    [`tokio::time::timeout`] using the enricher's timeout.
336    /// 6. On error, applies the enricher's [`OnError`] policy.
337    /// 7. If any enricher in the chain returns the internal `Drop`
338    ///    outcome (via an enricher whose [`OnError`] policy is set
339    ///    to [`OnError::Drop`]), the result is removed from the
340    ///    output.
341    ///
342    /// The pipeline initializes `result.header.enrichments` to
343    /// `Some(empty)` lazily on first successful injection, so the
344    /// `skip_serializing_if = "Option::is_none"` contract on
345    /// `RuleHeader::enrichments` is preserved when no enricher writes.
346    ///
347    /// Currently sequential per result; concurrent across results would
348    /// require splitting `results` into chunks across futures and is left
349    /// for a follow-up tuning pass once we have realistic throughput
350    /// numbers from the integration tests.
351    pub async fn run(&self, results: &mut Vec<EvaluationResult>) {
352        if self.enrichers.is_empty() || results.is_empty() {
353            return;
354        }
355
356        // Single-pass enrichment with drop bookkeeping.
357        //
358        // We cannot use `Vec::retain_mut` together with `.await` (the
359        // closure must be sync), so we collect drop indices first and
360        // apply them in a single linear pass at the end.
361        let mut drop_indices: Vec<usize> = Vec::new();
362
363        for (idx, result) in results.iter_mut().enumerate() {
364            let permit = self.semaphore.clone().acquire_owned().await.ok();
365            if permit.is_none() {
366                // Semaphore closed (only happens at shutdown). Drain
367                // remaining results unenriched rather than blocking.
368                tracing::debug!("Enrichment semaphore closed, draining remaining results");
369                return;
370            }
371            let _permit = permit.unwrap();
372
373            let mut should_drop = false;
374            for enricher in &self.enrichers {
375                match Self::run_one(enricher.as_ref(), result, self.metrics.as_ref()).await {
376                    EnrichOutcome::Drop => {
377                        should_drop = true;
378                        break;
379                    }
380                    EnrichOutcome::Ok
381                    | EnrichOutcome::Skip
382                    | EnrichOutcome::Null
383                    | EnrichOutcome::Filtered => {}
384                }
385            }
386            if should_drop {
387                drop_indices.push(idx);
388            }
389        }
390
391        if !drop_indices.is_empty() {
392            // Remove from the back so earlier indices stay valid.
393            for idx in drop_indices.into_iter().rev() {
394                results.swap_remove(idx);
395            }
396        }
397    }
398
399    /// Run a single enricher against a single result, applying the
400    /// kind-vs-body filter, scope filter, timeout, and on_error policy.
401    /// Records `rsigma_enrichment_total{enricher_id, kind, status}` and
402    /// `rsigma_enrichment_duration_seconds{enricher_id, kind}` via the
403    /// configured `MetricsHook` for every non-filtered call.
404    async fn run_one(
405        enricher: &dyn Enricher,
406        result: &mut EvaluationResult,
407        metrics: &dyn MetricsHook,
408    ) -> EnrichOutcome {
409        if !enricher.kind().matches(&result.body) {
410            return EnrichOutcome::Filtered;
411        }
412        if !enricher.scope().matches(result) {
413            return EnrichOutcome::Filtered;
414        }
415
416        let inject_field = enricher.inject_field().to_string();
417        let timeout = enricher.timeout();
418        let id = enricher.id().to_string();
419        let kind_label = enricher.kind().as_str();
420        let on_error = enricher.on_error();
421
422        metrics.on_enrichment_queue_depth_change(1);
423        let started = std::time::Instant::now();
424        let outcome = tokio::time::timeout(timeout, enricher.enrich(result)).await;
425        let elapsed = started.elapsed().as_secs_f64();
426        metrics.on_enrichment_queue_depth_change(-1);
427
428        let err = match outcome {
429            Ok(Ok(())) => {
430                metrics.on_enrichment_completed(&id, kind_label, "success", elapsed);
431                return EnrichOutcome::Ok;
432            }
433            Ok(Err(e)) => e,
434            Err(_) => EnrichError {
435                enricher_id: id.clone(),
436                kind: EnrichErrorKind::Timeout,
437            },
438        };
439
440        let is_timeout = matches!(err.kind, EnrichErrorKind::Timeout);
441        match on_error {
442            OnError::Skip => {
443                tracing::warn!(
444                    enricher_id = %id,
445                    kind = %kind_label,
446                    error = %err,
447                    "Enricher failed, skipping"
448                );
449                metrics.on_enrichment_completed(
450                    &id,
451                    kind_label,
452                    if is_timeout { "timeout" } else { "skip" },
453                    elapsed,
454                );
455                EnrichOutcome::Skip
456            }
457            OnError::Null => {
458                tracing::warn!(
459                    enricher_id = %id,
460                    kind = %kind_label,
461                    error = %err,
462                    "Enricher failed, injecting null"
463                );
464                let map = result
465                    .header
466                    .enrichments
467                    .get_or_insert_with(serde_json::Map::new);
468                map.insert(inject_field, serde_json::Value::Null);
469                metrics.on_enrichment_completed(
470                    &id,
471                    kind_label,
472                    if is_timeout { "timeout" } else { "error" },
473                    elapsed,
474                );
475                EnrichOutcome::Null
476            }
477            OnError::Drop => {
478                tracing::warn!(
479                    enricher_id = %id,
480                    kind = %kind_label,
481                    error = %err,
482                    "Enricher failed, dropping result"
483                );
484                metrics.on_enrichment_completed(&id, kind_label, "drop", elapsed);
485                EnrichOutcome::Drop
486            }
487        }
488    }
489}
490
491impl Default for EnrichmentPipeline {
492    fn default() -> Self {
493        Self::new(Vec::new(), 16)
494    }
495}
496
497impl Clone for EnrichmentPipeline {
498    fn clone(&self) -> Self {
499        // Boxes of `dyn Enricher` are not `Clone`, so a true deep clone
500        // is not possible here. The hot-reload path always rebuilds the
501        // pipeline from config rather than cloning, but `Clone` is
502        // useful for tests and for `ArcSwap` adapter code that wants a
503        // throwaway snapshot. Returning an empty pipeline that shares
504        // the metrics hook is the safest behaviour: a misuse degrades
505        // to "no enrichment" rather than panicking or silently
506        // double-counting.
507        Self {
508            enrichers: Vec::new(),
509            semaphore: Arc::clone(&self.semaphore),
510            metrics: Arc::clone(&self.metrics),
511        }
512    }
513}
514
515/// Helper for [`Enricher::enrich`] implementations: write `value` into
516/// `result.header.enrichments` under `inject_field`, allocating the map
517/// if it was previously `None`.
518pub fn inject_enrichment(
519    result: &mut EvaluationResult,
520    inject_field: &str,
521    value: serde_json::Value,
522) {
523    let map = result
524        .header
525        .enrichments
526        .get_or_insert_with(serde_json::Map::new);
527    map.insert(inject_field.to_string(), value);
528}
529
530// ---------------------------------------------------------------------------
531// Bespoke enricher registration
532// ---------------------------------------------------------------------------
533
534/// Factory function signature used by [`register_builtin`].
535///
536/// External crates that ship a bespoke enricher type register a
537/// `Box<dyn Fn(&serde_json::Value) -> Result<Box<dyn Enricher>, String>>`
538/// so the daemon config layer can construct the enricher from its YAML
539/// config block at startup. The `serde_json::Value` argument is the raw
540/// enricher-config block (after `kind` / `id` / `type` fields are
541/// extracted by the loader).
542pub type EnricherFactory =
543    Arc<dyn Fn(&serde_json::Value) -> Result<Box<dyn Enricher>, String> + Send + Sync>;
544
545/// Process-wide registry of bespoke enricher factories keyed by `type`.
546///
547/// External crates call [`register_builtin`] once at startup (typically
548/// in their `lib.rs` via `ctor` or an explicit init function) to wire a
549/// new `type: <name>` value into the daemon's config loader. Generic
550/// primitives (`template`, `lookup`, `http`, `command`) are not in this
551/// registry; they are constructed directly by the loader.
552///
553/// The registry is global and append-only — registering the same name
554/// twice is an error. Concurrent reads are lock-free via [`std::sync::OnceLock`]
555/// at the outer level and a [`std::sync::RwLock`] at the inner level for the
556/// (rare) `register_builtin` writes.
557fn registry() -> &'static std::sync::RwLock<std::collections::HashMap<String, EnricherFactory>> {
558    use std::sync::OnceLock;
559    static REGISTRY: OnceLock<
560        std::sync::RwLock<std::collections::HashMap<String, EnricherFactory>>,
561    > = OnceLock::new();
562    REGISTRY.get_or_init(|| std::sync::RwLock::new(std::collections::HashMap::new()))
563}
564
565/// Register a bespoke enricher factory under `type: <name>`.
566///
567/// Returns an error if `name` is already registered (registration is
568/// process-global and append-only) or if `name` collides with a built-in
569/// primitive type (`template`, `lookup`, `http`, `command`).
570///
571/// External crates call this once at startup before the daemon loads its
572/// config. After config load, the registry is read-only in practice.
573pub fn register_builtin(name: &str, factory: EnricherFactory) -> Result<(), String> {
574    if matches!(name, "template" | "lookup" | "http" | "command") {
575        return Err(format!(
576            "cannot register '{name}': name is reserved for a built-in primitive"
577        ));
578    }
579    let reg = registry();
580    let mut guard = reg
581        .write()
582        .map_err(|_| "enricher registry poisoned".to_string())?;
583    if guard.contains_key(name) {
584        return Err(format!("enricher type '{name}' is already registered"));
585    }
586    guard.insert(name.to_string(), factory);
587    Ok(())
588}
589
590/// Look up a registered bespoke enricher factory by `type` name.
591///
592/// Returns `None` if `name` is not registered. The daemon config loader
593/// uses this to construct bespoke enrichers; missing names are surfaced
594/// to the operator as a clear startup error.
595pub fn lookup_builtin(name: &str) -> Option<EnricherFactory> {
596    let reg = registry();
597    let guard = reg.read().ok()?;
598    guard.get(name).cloned()
599}
600
601/// Clear the bespoke enricher registry. **Test-only**: used by unit tests
602/// that need to register / re-register the same name. Not exposed to
603/// downstream crates.
604#[cfg(test)]
605pub(crate) fn clear_builtin_registry() {
606    if let Ok(mut guard) = registry().write() {
607        guard.clear();
608    }
609}