Skip to main content

rsigma_eval/pipeline/
sources.rs

1//! Dynamic source declarations and template references for dynamic Sigma pipelines.
2//!
3//! This module defines the types for declaring external data sources in a pipeline
4//! YAML (`sources` section) and for tracking `${source.*}` template references
5//! found throughout the pipeline.
6
7use std::collections::HashMap;
8use std::path::PathBuf;
9use std::sync::LazyLock;
10use std::time::Duration;
11
12use regex::Regex;
13
14// =============================================================================
15// Dynamic source declaration
16// =============================================================================
17
18/// A dynamic source declared in the pipeline's `sources` section.
19///
20/// Each source describes how to fetch external data that can be referenced
21/// by `${source.<id>}` expressions anywhere in the pipeline YAML.
22#[derive(Debug, Clone, PartialEq)]
23pub struct DynamicSource {
24    /// Unique identifier for this source, referenced in `${source.<id>}` expressions.
25    pub id: String,
26    /// The type-specific configuration for fetching data.
27    pub source_type: SourceType,
28    /// How often the source data should be refreshed.
29    pub refresh: RefreshPolicy,
30    /// Maximum time to wait for a fetch to complete.
31    pub timeout: Option<Duration>,
32    /// What to do when a fetch fails.
33    pub on_error: ErrorPolicy,
34    /// Whether the daemon must resolve this source before processing events.
35    pub required: bool,
36    /// Fallback value if the source cannot be resolved.
37    pub default: Option<yaml_serde::Value>,
38}
39
40/// Type-specific configuration for a dynamic source.
41#[derive(Debug, Clone, PartialEq)]
42pub enum SourceType {
43    /// Fetch data from an HTTP endpoint.
44    Http {
45        url: String,
46        method: Option<String>,
47        headers: HashMap<String, String>,
48        /// Optional request body sent verbatim after `${VAR}` expansion. When
49        /// set and `method` is unset, the request defaults to `POST`. Pairs
50        /// with query APIs that require a body (GraphQL, `_search`, TheHive 5's
51        /// `/api/v1/query`).
52        body: Option<String>,
53        format: DataFormat,
54        extract: Option<ExtractExpr>,
55    },
56    /// Run a local command and capture its stdout.
57    Command {
58        command: Vec<String>,
59        format: DataFormat,
60        extract: Option<ExtractExpr>,
61    },
62    /// Read data from a local file.
63    File {
64        path: PathBuf,
65        format: DataFormat,
66        extract: Option<ExtractExpr>,
67    },
68    /// Subscribe to a NATS subject for push-based updates.
69    Nats {
70        url: String,
71        subject: String,
72        format: DataFormat,
73        extract: Option<ExtractExpr>,
74    },
75}
76
77/// An extraction expression applied to source data after parsing.
78///
79/// Supports two syntax forms in YAML:
80/// - Plain string: always jq (the common case): `extract: ".emails[]"`
81/// - Structured object: explicit language: `extract: { expr: "$.emails[*]", type: jsonpath }`
82#[derive(Debug, Clone, PartialEq)]
83pub enum ExtractExpr {
84    /// A jq expression (default). Evaluated via jaq.
85    Jq(String),
86    /// A JSONPath expression. Evaluated via serde_json_path.
87    JsonPath(String),
88    /// A CEL (Common Expression Language) expression. Evaluated via cel-interpreter.
89    Cel(String),
90}
91
92/// How often a source should be refreshed.
93#[derive(Debug, Clone, PartialEq)]
94pub enum RefreshPolicy {
95    /// Fetch at startup only, never refresh.
96    Once,
97    /// Re-fetch on a fixed interval.
98    Interval(Duration),
99    /// Watch the file for changes (file sources only).
100    Watch,
101    /// Value updated on each incoming NATS message (NATS sources only).
102    Push,
103    /// Fetch at startup, then only when explicitly triggered via API/signal.
104    OnDemand,
105}
106
107/// What to do when a source fetch fails.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum ErrorPolicy {
110    /// Use the last successfully fetched value.
111    UseCached,
112    /// Fail the pipeline load (at startup: exit; at runtime: keep previous state).
113    Fail,
114    /// Fall back to the declared `default` value.
115    UseDefault,
116}
117
118/// The format of data returned by a source.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum DataFormat {
121    /// JSON (parsed with serde_json).
122    Json,
123    /// YAML (parsed with yaml_serde).
124    Yaml,
125    /// One value per line.
126    Lines,
127    /// Comma-separated values.
128    Csv,
129}
130
131// =============================================================================
132// Source references (detected during parsing)
133// =============================================================================
134
135/// A `${source.*}` template reference found in the pipeline YAML.
136#[derive(Debug, Clone, PartialEq)]
137pub struct SourceRef {
138    /// The source ID (first path segment after `source.`).
139    pub source_id: String,
140    /// Optional dot-path into the source data (e.g., `field_mapping` in `${source.env_config.field_mapping}`).
141    pub sub_path: Option<String>,
142    /// Where in the pipeline this reference appears.
143    pub location: RefLocation,
144    /// The raw template string as it appeared in the YAML.
145    pub raw_template: String,
146}
147
148/// Whether `id` can be declared as a dynamic source id: one or more ASCII
149/// letters, digits, `_`, or `-`. These are exactly the ids a
150/// `${source.<id>}` template can name.
151pub fn is_valid_source_id(id: &str) -> bool {
152    !id.is_empty()
153        && id
154            .bytes()
155            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
156}
157
158/// One `${source.<id>}` or `${source.<id>.<sub_path>}` template found by
159/// [`scan_source_templates`].
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct SourceTemplate<'a> {
162    /// The whole template, from `${` to `}`.
163    pub raw: &'a str,
164    /// Byte offset of `raw` in the scanned text.
165    pub start: usize,
166    /// The referenced source id.
167    pub source_id: &'a str,
168    /// The dot-path into the source data, if any.
169    pub sub_path: Option<&'a str>,
170}
171
172/// Find every `${source.*}` template in `text`, left to right.
173///
174/// This is the single grammar for source references: pipeline parsing uses it
175/// to record [`SourceRef`]s and the runtime uses it to expand them.
176pub fn scan_source_templates(text: &str) -> impl Iterator<Item = SourceTemplate<'_>> {
177    static RE: LazyLock<Regex> = LazyLock::new(|| {
178        Regex::new(r"\$\{source\.([A-Za-z0-9_-]+)(?:\.([A-Za-z0-9_.]+))?\}")
179            .expect("source template regex is valid")
180    });
181    RE.captures_iter(text).map(|caps| {
182        let whole = caps.get(0).expect("group 0 always participates");
183        SourceTemplate {
184            raw: whole.as_str(),
185            start: whole.start(),
186            source_id: caps.get(1).expect("the id group is required").as_str(),
187            sub_path: caps.get(2).map(|m| m.as_str()),
188        }
189    })
190}
191
192/// Where in the pipeline a source reference appears.
193#[derive(Debug, Clone, PartialEq)]
194pub enum RefLocation {
195    /// In the `vars` section, under the given variable name.
196    Var { var_name: String },
197    /// In a transformation's field value.
198    TransformationField {
199        transform_index: usize,
200        field_name: String,
201    },
202    /// An `include` directive in the transformations list.
203    Include { transform_index: usize },
204}
205
206// =============================================================================
207// Source status (for PipelineState tracking)
208// =============================================================================
209
210/// Resolution status of a dynamic source.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub enum SourceStatus {
213    /// Source has not been resolved yet.
214    Pending,
215    /// Source was successfully resolved.
216    Resolved,
217    /// Source resolution failed.
218    Failed,
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn valid_source_ids() {
227        for id in ["ip_blocklist", "threat-intel", "1st_feed", "A9", "_", "-"] {
228            assert!(is_valid_source_id(id), "{id}");
229        }
230        for id in ["", "bad.id", "has space", "café", "a/b", "${x}"] {
231            assert!(!is_valid_source_id(id), "{id}");
232        }
233    }
234
235    #[test]
236    fn scan_finds_templates_with_offsets() {
237        let text = "a ${source.threat-intel.ips.0} b ${source.1st_feed} ${source.bad id}";
238        let found: Vec<_> = scan_source_templates(text).collect();
239        assert_eq!(
240            found,
241            [
242                SourceTemplate {
243                    raw: "${source.threat-intel.ips.0}",
244                    start: 2,
245                    source_id: "threat-intel",
246                    sub_path: Some("ips.0"),
247                },
248                SourceTemplate {
249                    raw: "${source.1st_feed}",
250                    start: 33,
251                    source_id: "1st_feed",
252                    sub_path: None,
253                },
254            ]
255        );
256        for t in &found {
257            assert_eq!(&text[t.start..t.start + t.raw.len()], t.raw);
258        }
259    }
260}