Skip to main content

rsigma_parser/ruleset/
overlay.rs

1//! Metadata overlays: loading, application, and validation.
2//!
3//! Overlays change metadata on already-selected rules without editing the
4//! source files. They target a kept detection rule or correlation by id and
5//! apply after dependency closure, before any pipeline.
6
7use std::collections::{HashMap, HashSet};
8use std::fmt;
9use std::path::{Path, PathBuf};
10use std::sync::Mutex;
11
12use yaml_serde::Value;
13
14use crate::ads::{ADS_PREFIX, AdsContent, EXEMPT_KEY};
15use crate::ast::{Level, Status};
16use crate::exemplar::{EXEMPLARS_KEY, ExemplarRuleKind, exemplars_from_attrs};
17
18use super::closure;
19use super::error::RulesetError;
20use super::select::Decision;
21use super::source::{
22    Candidate, CandidateDoc, DocumentKind, ResolveOptions, SourceFile, confine, relative_to,
23};
24use super::spec::{
25    APPEND_KEYS, OverlayEntry, OverlayPatch, RulesetSpec, SET_KEYS, StaleOverlayPolicy, suggestion,
26    validate_patch,
27};
28
29/// Where an applied overlay came from.
30#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
31pub enum OverlayOrigin {
32    /// An inline entry at this index in the spec.
33    Inline {
34        /// Index into the spec's `overlays`.
35        index: usize,
36    },
37    /// An entry at this index in an overlay file.
38    File {
39        /// The overlay file.
40        path: PathBuf,
41        /// Index of the entry in that file.
42        index: usize,
43    },
44}
45
46impl fmt::Display for OverlayOrigin {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Self::Inline { index } => write!(f, "inline:{index}"),
50            Self::File { path, index } => write!(f, "{}:{index}", path.display()),
51        }
52    }
53}
54
55/// An overlay that was applied to a kept document.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct AppliedOverlay {
58    /// Where the overlay entry was declared.
59    pub origin: OverlayOrigin,
60    /// Key paths that were set, such as `level` or
61    /// `custom_attributes.rsigma.exemplars`.
62    pub set: Vec<String>,
63    /// Key paths that were appended.
64    pub appended: Vec<String>,
65}
66
67/// Expands `file` and `dir` overlay entries. Inline entries are handled by the
68/// resolver and are never passed to a loader.
69pub trait OverlayLoader {
70    /// Expand one `file` or `dir` entry into its inline entries, in order.
71    fn load(
72        &self,
73        entry: &OverlayEntry,
74    ) -> Result<Vec<(OverlayOrigin, OverlayEntry)>, RulesetError>;
75
76    /// Overlay files read by this loader, for the lockfile.
77    fn files(&self) -> Vec<SourceFile> {
78        Vec::new()
79    }
80}
81
82/// Reads overlay files and directories from disk, recording what it read.
83pub struct FsOverlayLoader {
84    /// Reject overlay paths outside this root.
85    pub confine_to: Option<PathBuf>,
86    files: Mutex<Vec<SourceFile>>,
87}
88
89impl FsOverlayLoader {
90    /// A loader confined to `confine_to`, when set.
91    pub fn new(confine_to: Option<PathBuf>) -> Self {
92        Self {
93            confine_to,
94            files: Mutex::new(Vec::new()),
95        }
96    }
97
98    fn load_file(
99        &self,
100        path: &Path,
101        opts: &ResolveOptions,
102        out: &mut Vec<(OverlayOrigin, OverlayEntry)>,
103    ) -> Result<(), RulesetError> {
104        let canonical = path.canonicalize().map_err(|e| RulesetError::Io {
105            ruleset: None,
106            path: path.to_path_buf(),
107            source: e,
108        })?;
109        confine(&canonical, opts)?;
110        let bytes = std::fs::read(path).map_err(|e| RulesetError::Io {
111            ruleset: None,
112            path: path.to_path_buf(),
113            source: e,
114        })?;
115        let text = String::from_utf8_lossy(&bytes);
116        let entries = parse_overlay_file(&text, path)?;
117        self.files
118            .lock()
119            .expect("overlay file list lock")
120            .push(SourceFile {
121                source: 0,
122                path: path.to_path_buf(),
123                relative: relative_to(path, Path::new(".")),
124                sha256_input: bytes,
125            });
126        for (index, entry) in entries.into_iter().enumerate() {
127            out.push((
128                OverlayOrigin::File {
129                    path: path.to_path_buf(),
130                    index,
131                },
132                entry,
133            ));
134        }
135        Ok(())
136    }
137
138    fn load_dir(
139        &self,
140        dir: &Path,
141        opts: &ResolveOptions,
142        out: &mut Vec<(OverlayOrigin, OverlayEntry)>,
143    ) -> Result<(), RulesetError> {
144        if !dir.exists() {
145            return Err(RulesetError::Io {
146                ruleset: None,
147                path: dir.to_path_buf(),
148                source: std::io::Error::new(
149                    std::io::ErrorKind::NotFound,
150                    "overlay directory does not exist",
151                ),
152            });
153        }
154        let canonical = dir.canonicalize().map_err(|e| RulesetError::Io {
155            ruleset: None,
156            path: dir.to_path_buf(),
157            source: e,
158        })?;
159        confine(&canonical, opts)?;
160        let mut paths = Vec::new();
161        let mut visited = HashSet::new();
162        crate::walk::collect_yaml_files(dir, dir, None, &mut paths, &mut visited).map_err(|e| {
163            RulesetError::Io {
164                ruleset: None,
165                path: dir.to_path_buf(),
166                source: std::io::Error::other(e.to_string()),
167            }
168        })?;
169        for path in paths {
170            self.load_file(&path, opts, out)?;
171        }
172        Ok(())
173    }
174}
175
176impl OverlayLoader for FsOverlayLoader {
177    fn load(
178        &self,
179        entry: &OverlayEntry,
180    ) -> Result<Vec<(OverlayOrigin, OverlayEntry)>, RulesetError> {
181        if entry.id.is_some() {
182            return Err(RulesetError::Overlay(
183                "inline overlay entry passed to a filesystem loader".into(),
184            ));
185        }
186        let opts = ResolveOptions {
187            confine_to: self.confine_to.clone(),
188        };
189        let mut out = Vec::new();
190        if let Some(file) = &entry.file {
191            self.load_file(file, &opts, &mut out)?;
192        } else if let Some(dir) = &entry.dir {
193            self.load_dir(dir, &opts, &mut out)?;
194        } else {
195            return Err(RulesetError::Overlay(
196                "overlay entry must set one of id, file, or dir".into(),
197            ));
198        }
199        Ok(out)
200    }
201
202    fn files(&self) -> Vec<SourceFile> {
203        self.files.lock().expect("overlay file list lock").clone()
204    }
205}
206
207/// A loader that accepts only inline overlays, for fuzzing and benchmarks.
208pub struct InlineOnlyOverlayLoader;
209
210impl OverlayLoader for InlineOnlyOverlayLoader {
211    fn load(
212        &self,
213        _entry: &OverlayEntry,
214    ) -> Result<Vec<(OverlayOrigin, OverlayEntry)>, RulesetError> {
215        Err(RulesetError::Overlay(
216            "file and dir overlays need a filesystem loader".into(),
217        ))
218    }
219}
220
221fn parse_overlay_file(text: &str, path: &Path) -> Result<Vec<OverlayEntry>, RulesetError> {
222    let entries: Option<Vec<OverlayEntry>> = yaml_serde::from_str(text).map_err(|e| {
223        RulesetError::Overlay(format!("cannot parse overlay file {}: {e}", path.display()))
224    })?;
225    Ok(entries.unwrap_or_default())
226}
227
228/// Expand every overlay entry in declaration order, replacing file and dir
229/// entries with their contents at that position.
230pub(crate) fn expand_overlays(
231    name: &str,
232    spec: &RulesetSpec,
233    loader: &dyn OverlayLoader,
234) -> Result<Vec<(OverlayOrigin, OverlayEntry)>, RulesetError> {
235    let mut expanded = Vec::new();
236    for (index, entry) in spec.overlays.iter().enumerate() {
237        if entry.id.is_some() {
238            expanded.push((OverlayOrigin::Inline { index }, entry.clone()));
239        } else {
240            expanded.extend(loader.load(entry).map_err(|e| e.named(name))?);
241        }
242    }
243    for (origin, entry) in &expanded {
244        validate_expanded(name, origin, entry)?;
245    }
246    Ok(expanded)
247}
248
249/// Apply overlays to kept candidates and return per-candidate provenance.
250pub(crate) fn apply_overlays(
251    name: &str,
252    spec: &RulesetSpec,
253    candidates: &mut [Candidate],
254    decisions: &[Decision],
255    expanded: Vec<(OverlayOrigin, OverlayEntry)>,
256) -> Result<(Vec<Vec<AppliedOverlay>>, Vec<String>), RulesetError> {
257    let policy = match &spec.stale_overlays {
258        Some(value) => StaleOverlayPolicy::parse(value)
259            .map_err(|e| RulesetError::InvalidSpec(vec![format!("ruleset '{name}': {e}")]))?,
260        None => StaleOverlayPolicy::Error,
261    };
262
263    let mut kept_by_id: HashMap<String, usize> = HashMap::new();
264    let mut filter_ids: HashSet<String> = HashSet::new();
265    let mut any_by_id: HashMap<String, usize> = HashMap::new();
266    for (index, candidate) in candidates.iter().enumerate() {
267        let Some(id) = candidate.id() else {
268            continue;
269        };
270        let key = id.to_ascii_lowercase();
271        any_by_id.entry(key.clone()).or_insert(index);
272        if candidate.kind() == DocumentKind::Filter {
273            filter_ids.insert(key);
274        } else if closure::is_kept(&decisions[index]) {
275            kept_by_id.insert(key, index);
276        }
277    }
278
279    let mut applied: Vec<Vec<AppliedOverlay>> = vec![Vec::new(); candidates.len()];
280    let mut warnings = Vec::new();
281    let mut stale = Vec::new();
282
283    for (origin, entry) in expanded {
284        let Some(id) = entry.id.as_deref() else {
285            // `validate_expanded` guarantees an id.
286            continue;
287        };
288        let key = id.to_ascii_lowercase();
289        if let Some(index) = kept_by_id.get(&key).copied() {
290            let (set, appended) =
291                apply_to_candidate(name, &origin, &mut candidates[index], &entry)?;
292            applied[index].push(AppliedOverlay {
293                origin,
294                set,
295                appended,
296            });
297        } else if filter_ids.contains(&key) {
298            return Err(RulesetError::Overlay(format!(
299                "ruleset '{name}': overlay {origin} targets id '{id}', which is a filter; filters cannot be overlaid"
300            )));
301        } else {
302            let reason = stale_reason(name, &origin, id, any_by_id.get(&key).copied(), decisions);
303            match policy {
304                StaleOverlayPolicy::Error => stale.push(reason),
305                StaleOverlayPolicy::Warn => warnings.push(reason),
306            }
307        }
308    }
309
310    if !stale.is_empty() {
311        return Err(RulesetError::StaleOverlay(stale));
312    }
313    Ok((applied, warnings))
314}
315
316fn stale_reason(
317    name: &str,
318    origin: &OverlayOrigin,
319    id: &str,
320    candidate_index: Option<usize>,
321    decisions: &[Decision],
322) -> String {
323    let because = match candidate_index {
324        None => "exists in no source".to_string(),
325        Some(index) => match &decisions[index] {
326            Decision::Excluded { selector } => {
327                format!("is excluded by exclude selector {selector}")
328            }
329            Decision::NotSelected => "is not matched by include".to_string(),
330            Decision::Dropped { reason } => format!("was dropped: {reason}"),
331            other => format!("is {}", other.as_str()),
332        },
333    };
334    format!("ruleset '{name}': overlay {origin} targets id '{id}', which {because}")
335}
336
337struct Metadata<'a> {
338    level: &'a mut Option<Level>,
339    status: &'a mut Option<Status>,
340    description: &'a mut Option<String>,
341    author: &'a mut Option<String>,
342    tags: &'a mut Vec<String>,
343    references: &'a mut Vec<String>,
344    falsepositives: &'a mut Vec<String>,
345    fields: &'a mut Vec<String>,
346    custom_attributes: &'a mut HashMap<String, Value>,
347}
348
349fn metadata_mut(doc: &mut CandidateDoc) -> Metadata<'_> {
350    match doc {
351        CandidateDoc::Detection(rule) => Metadata {
352            level: &mut rule.level,
353            status: &mut rule.status,
354            description: &mut rule.description,
355            author: &mut rule.author,
356            tags: &mut rule.tags,
357            references: &mut rule.references,
358            falsepositives: &mut rule.falsepositives,
359            fields: &mut rule.fields,
360            custom_attributes: &mut rule.custom_attributes,
361        },
362        CandidateDoc::Correlation(rule) => Metadata {
363            level: &mut rule.level,
364            status: &mut rule.status,
365            description: &mut rule.description,
366            author: &mut rule.author,
367            tags: &mut rule.tags,
368            references: &mut rule.references,
369            falsepositives: &mut rule.falsepositives,
370            fields: &mut rule.fields,
371            custom_attributes: &mut rule.custom_attributes,
372        },
373        CandidateDoc::Filter(rule) => Metadata {
374            level: &mut rule.level,
375            status: &mut rule.status,
376            description: &mut rule.description,
377            author: &mut rule.author,
378            tags: &mut rule.tags,
379            references: &mut rule.references,
380            falsepositives: &mut rule.falsepositives,
381            fields: &mut rule.fields,
382            custom_attributes: &mut rule.custom_attributes,
383        },
384    }
385}
386
387fn apply_to_candidate(
388    name: &str,
389    origin: &OverlayOrigin,
390    candidate: &mut Candidate,
391    entry: &OverlayEntry,
392) -> Result<(Vec<String>, Vec<String>), RulesetError> {
393    let mut set_keys = Vec::new();
394    let mut appended_keys = Vec::new();
395    {
396        let mut meta = metadata_mut(&mut candidate.doc);
397        if let Some(patch) = &entry.set {
398            apply_set(name, origin, &mut meta, patch, &mut set_keys)?;
399        }
400        if let Some(patch) = &entry.append {
401            apply_append(name, origin, &mut meta, patch, &mut appended_keys)?;
402        }
403    }
404    validate_touched(name, origin, &candidate.doc, &set_keys, &appended_keys)?;
405    Ok((set_keys, appended_keys))
406}
407
408fn apply_set(
409    name: &str,
410    origin: &OverlayOrigin,
411    meta: &mut Metadata<'_>,
412    patch: &OverlayPatch,
413    keys: &mut Vec<String>,
414) -> Result<(), RulesetError> {
415    if let Some(value) = &patch.level {
416        let level = value.parse::<Level>().map_err(|_| {
417            overlay_error(
418                name,
419                origin,
420                format!("set level '{value}' is not a valid level"),
421            )
422        })?;
423        *meta.level = Some(level);
424        keys.push("level".into());
425    }
426    if let Some(value) = &patch.status {
427        let status = value.parse::<Status>().map_err(|_| {
428            overlay_error(
429                name,
430                origin,
431                format!("set status '{value}' is not a valid status"),
432            )
433        })?;
434        *meta.status = Some(status);
435        keys.push("status".into());
436    }
437    if let Some(value) = &patch.description {
438        *meta.description = Some(value.clone());
439        keys.push("description".into());
440    }
441    if let Some(value) = &patch.author {
442        *meta.author = Some(value.clone());
443        keys.push("author".into());
444    }
445    if let Some(value) = &patch.tags {
446        *meta.tags = value.clone();
447        keys.push("tags".into());
448    }
449    if let Some(value) = &patch.references {
450        *meta.references = value.clone();
451        keys.push("references".into());
452    }
453    if let Some(value) = &patch.falsepositives {
454        *meta.falsepositives = value.clone();
455        keys.push("falsepositives".into());
456    }
457    if let Some(value) = &patch.fields {
458        *meta.fields = value.clone();
459        keys.push("fields".into());
460    }
461    if let Some(attributes) = &patch.custom_attributes {
462        for (key, value) in attributes {
463            if value.is_null() {
464                meta.custom_attributes.remove(key);
465            } else {
466                let converted = canonical_yaml_value(yaml_serde::to_value(value).map_err(|e| {
467                    overlay_error(
468                        name,
469                        origin,
470                        format!("cannot convert custom attribute '{key}': {e}"),
471                    )
472                })?);
473                meta.custom_attributes.insert(key.clone(), converted);
474            }
475            keys.push(format!("custom_attributes.{key}"));
476        }
477    }
478    Ok(())
479}
480
481fn apply_append(
482    name: &str,
483    origin: &OverlayOrigin,
484    meta: &mut Metadata<'_>,
485    patch: &OverlayPatch,
486    keys: &mut Vec<String>,
487) -> Result<(), RulesetError> {
488    if let Some(values) = &patch.tags {
489        for value in values {
490            if !meta.tags.contains(value) {
491                meta.tags.push(value.clone());
492            }
493        }
494        keys.push("tags".into());
495    }
496    if let Some(values) = &patch.references {
497        meta.references.extend(values.iter().cloned());
498        keys.push("references".into());
499    }
500    if let Some(values) = &patch.falsepositives {
501        meta.falsepositives.extend(values.iter().cloned());
502        keys.push("falsepositives".into());
503    }
504    if let Some(values) = &patch.fields {
505        meta.fields.extend(values.iter().cloned());
506        keys.push("fields".into());
507    }
508    if let Some(attributes) = &patch.custom_attributes {
509        for (key, value) in attributes {
510            let converted = canonical_yaml_value(yaml_serde::to_value(value).map_err(|e| {
511                overlay_error(
512                    name,
513                    origin,
514                    format!("cannot convert custom attribute '{key}': {e}"),
515                )
516            })?);
517            let Value::Sequence(items) = converted else {
518                return Err(overlay_error(
519                    name,
520                    origin,
521                    format!("append custom_attributes.{key} must be a sequence"),
522                ));
523            };
524            match meta.custom_attributes.entry(key.clone()) {
525                std::collections::hash_map::Entry::Vacant(slot) => {
526                    slot.insert(Value::Sequence(items));
527                }
528                std::collections::hash_map::Entry::Occupied(mut slot) => match slot.get_mut() {
529                    Value::Sequence(existing) => existing.extend(items),
530                    _ => {
531                        return Err(overlay_error(
532                            name,
533                            origin,
534                            format!(
535                                "append custom_attributes.{key} must target an existing sequence"
536                            ),
537                        ));
538                    }
539                },
540            }
541            keys.push(format!("custom_attributes.{key}"));
542        }
543    }
544    Ok(())
545}
546
547fn validate_touched(
548    name: &str,
549    origin: &OverlayOrigin,
550    doc: &CandidateDoc,
551    set: &[String],
552    appended: &[String],
553) -> Result<(), RulesetError> {
554    let exemplar_path = format!("custom_attributes.{EXEMPLARS_KEY}");
555    let touched_exemplars = set.iter().chain(appended).any(|key| key == &exemplar_path);
556
557    let attributes = match doc {
558        CandidateDoc::Detection(rule) => &rule.custom_attributes,
559        CandidateDoc::Correlation(rule) => &rule.custom_attributes,
560        CandidateDoc::Filter(rule) => &rule.custom_attributes,
561    };
562
563    if touched_exemplars {
564        let kind = match doc {
565            CandidateDoc::Detection(_) => ExemplarRuleKind::Detection,
566            CandidateDoc::Correlation(_) => ExemplarRuleKind::Correlation,
567            CandidateDoc::Filter(_) => ExemplarRuleKind::Filter,
568        };
569        if let Err(errors) = exemplars_from_attrs(attributes, kind) {
570            let detail = errors
571                .iter()
572                .map(ToString::to_string)
573                .collect::<Vec<_>>()
574                .join("; ");
575            return Err(overlay_error(
576                name,
577                origin,
578                format!("{EXEMPLARS_KEY} is invalid: {detail}"),
579            ));
580        }
581    }
582
583    for key in set.iter().chain(appended) {
584        let Some(attribute) = key.strip_prefix("custom_attributes.") else {
585            continue;
586        };
587        let Some(value) = attributes.get(attribute) else {
588            continue;
589        };
590        if attribute == EXEMPT_KEY {
591            if value.as_bool().is_none() {
592                return Err(overlay_error(
593                    name,
594                    origin,
595                    format!("{EXEMPT_KEY} must be a boolean"),
596                ));
597            }
598        } else if attribute.starts_with(ADS_PREFIX) && AdsContent::from_yaml(value).is_none() {
599            return Err(overlay_error(
600                name,
601                origin,
602                format!("{attribute} must be text or a list of text"),
603            ));
604        }
605    }
606    Ok(())
607}
608
609fn overlay_error(name: &str, origin: &OverlayOrigin, detail: impl fmt::Display) -> RulesetError {
610    RulesetError::Overlay(format!("ruleset '{name}': overlay {origin}: {detail}"))
611}
612
613/// Sort mapping keys recursively so overlay-derived YAML does not depend on
614/// whether the build enabled `serde_json`'s `preserve_order` feature.
615fn canonical_yaml_value(value: Value) -> Value {
616    match value {
617        Value::Mapping(map) => {
618            let mut entries: Vec<(String, Value)> = map
619                .into_iter()
620                .map(|(key, value)| {
621                    let key = match key {
622                        Value::String(text) => text,
623                        other => format!("{other:?}"),
624                    };
625                    (key, canonical_yaml_value(value))
626                })
627                .collect();
628            entries.sort_by(|a, b| a.0.cmp(&b.0));
629            let mut sorted = yaml_serde::Mapping::new();
630            for (key, value) in entries {
631                sorted.insert(Value::String(key), value);
632            }
633            Value::Mapping(sorted)
634        }
635        Value::Sequence(items) => {
636            Value::Sequence(items.into_iter().map(canonical_yaml_value).collect())
637        }
638        other => other,
639    }
640}
641
642fn validate_expanded(
643    name: &str,
644    origin: &OverlayOrigin,
645    entry: &OverlayEntry,
646) -> Result<(), RulesetError> {
647    let mut problems = Vec::new();
648    let file_entry = matches!(origin, OverlayOrigin::File { .. });
649    let at = format!("overlay {origin}");
650
651    for key in entry.unknown.keys() {
652        problems.push(format!(
653            "ruleset '{name}': {at} has unknown key '{key}'{}",
654            suggestion(key, &["id", "file", "dir", "set", "append"])
655        ));
656    }
657    if file_entry {
658        if entry.file.is_some() || entry.dir.is_some() {
659            problems.push(format!(
660                "ruleset '{name}': {at} must not use file or dir inside an overlay file"
661            ));
662        }
663    } else {
664        let forms = [
665            entry.id.is_some(),
666            entry.file.is_some(),
667            entry.dir.is_some(),
668        ]
669        .into_iter()
670        .filter(|set| *set)
671        .count();
672        if forms != 1 {
673            problems.push(format!(
674                "ruleset '{name}': {at} must set exactly one of id, file, or dir"
675            ));
676        }
677    }
678    if entry.id.is_none() {
679        problems.push(format!("ruleset '{name}': {at} needs an id"));
680    }
681    if entry.set.is_none() && entry.append.is_none() {
682        problems.push(format!(
683            "ruleset '{name}': {at} needs at least one of set or append"
684        ));
685    }
686    if let Some(patch) = &entry.set {
687        validate_patch(name, patch, &at, "set", SET_KEYS, &mut problems);
688        for value in patch.level.iter() {
689            if value.parse::<Level>().is_err() {
690                problems.push(format!(
691                    "ruleset '{name}': {at}.set has unknown level '{value}'"
692                ));
693            }
694        }
695        for value in patch.status.iter() {
696            if value.parse::<Status>().is_err() {
697                problems.push(format!(
698                    "ruleset '{name}': {at}.set has unknown status '{value}'"
699                ));
700            }
701        }
702    }
703    if let Some(patch) = &entry.append {
704        validate_patch(name, patch, &at, "append", APPEND_KEYS, &mut problems);
705        for (key, value) in [
706            ("level", patch.level.is_some()),
707            ("status", patch.status.is_some()),
708            ("description", patch.description.is_some()),
709            ("author", patch.author.is_some()),
710        ] {
711            if value {
712                problems.push(format!(
713                    "ruleset '{name}': {at}.append cannot set '{key}'; use set"
714                ));
715            }
716        }
717    }
718
719    if problems.is_empty() {
720        Ok(())
721    } else {
722        Err(RulesetError::InvalidSpec(problems))
723    }
724}
725
726#[cfg(test)]
727mod tests {
728    use super::*;
729    use crate::ruleset::ResolvedRuleset;
730    use crate::ruleset::source::RuleOrigin;
731    use crate::ruleset::spec::RuleSelector;
732
733    fn origin(id: &str) -> RuleOrigin {
734        RuleOrigin {
735            source: 0,
736            root: PathBuf::from("."),
737            file: PathBuf::from(format!("{id}.yml")),
738            ordinal: 0,
739        }
740    }
741
742    fn detection(id: &str) -> Candidate {
743        let collection = crate::parse_sigma_yaml(&format!(
744            "title: Rule {id}\nid: {id}\nlogsource:\n    product: linux\ndetection:\n    selection:\n        Field: value\n    condition: selection\n"
745        ))
746        .unwrap();
747        Candidate {
748            doc: CandidateDoc::Detection(collection.rules.into_iter().next().unwrap()),
749            origin: origin(id),
750        }
751    }
752
753    fn correlation(id: &str) -> Candidate {
754        let collection = crate::parse_sigma_yaml(&format!(
755            "title: Correlation {id}\nid: {id}\ncorrelation:\n    type: event_count\n    rules:\n        - base\n    timespan: 5m\n    condition:\n        gte: 2\n"
756        ))
757        .unwrap();
758        Candidate {
759            doc: CandidateDoc::Correlation(collection.correlations.into_iter().next().unwrap()),
760            origin: origin(id),
761        }
762    }
763
764    fn with_attr(candidate: &mut Candidate, key: &str, value: Value) {
765        match &mut candidate.doc {
766            CandidateDoc::Detection(rule) => {
767                rule.custom_attributes.insert(key.to_string(), value);
768            }
769            CandidateDoc::Correlation(rule) => {
770                rule.custom_attributes.insert(key.to_string(), value);
771            }
772            CandidateDoc::Filter(rule) => {
773                rule.custom_attributes.insert(key.to_string(), value);
774            }
775        }
776    }
777
778    fn spec_with_overlays(overlays: Vec<OverlayEntry>) -> RulesetSpec {
779        RulesetSpec {
780            sources: vec![PathBuf::from("rules")],
781            overlays,
782            ..Default::default()
783        }
784    }
785
786    fn resolve_with(
787        name: &str,
788        spec: &RulesetSpec,
789        candidates: Vec<Candidate>,
790    ) -> Result<ResolvedRuleset, RulesetError> {
791        crate::ruleset::resolve_loaded(
792            name,
793            spec,
794            crate::ruleset::LoadedSources {
795                candidates,
796                ..Default::default()
797            },
798            &InlineOnlyOverlayLoader,
799        )
800    }
801
802    fn exemplar_value() -> Value {
803        yaml_serde::to_value(serde_json::json!([{
804            "name": "one",
805            "expect": "match",
806            "event": {"Field": "value"}
807        }]))
808        .unwrap()
809    }
810
811    fn inline(id: &str, set: Option<OverlayPatch>, append: Option<OverlayPatch>) -> OverlayEntry {
812        OverlayEntry {
813            id: Some(id.into()),
814            set,
815            append,
816            ..Default::default()
817        }
818    }
819
820    fn level_patch(value: &str) -> OverlayPatch {
821        OverlayPatch {
822            level: Some(value.into()),
823            ..Default::default()
824        }
825    }
826
827    #[test]
828    fn set_replaces_level() {
829        let spec = spec_with_overlays(vec![inline("d", Some(level_patch("critical")), None)]);
830        let resolved = resolve_with("test", &spec, vec![detection("d")]).unwrap();
831        assert_eq!(resolved.collection.rules[0].level, Some(Level::Critical));
832        assert_eq!(resolved.entries[0].overlays.len(), 1);
833        assert_eq!(resolved.entries[0].overlays[0].set, ["level"]);
834    }
835
836    #[test]
837    fn invalid_level_errors() {
838        let spec = spec_with_overlays(vec![inline("d", Some(level_patch("severe")), None)]);
839        let error = resolve_with("test", &spec, vec![detection("d")]).unwrap_err();
840        assert_eq!(
841            error.to_string(),
842            "ruleset 'test': overlays[0].set has unknown level 'severe'"
843        );
844    }
845
846    #[test]
847    fn custom_attributes_merge_per_key_and_keep_exemplars() {
848        let mut rule = detection("d");
849        with_attr(&mut rule, "rsigma.exemplars", exemplar_value());
850        with_attr(
851            &mut rule,
852            "rsigma.foo",
853            yaml_serde::to_value("old").unwrap(),
854        );
855        let patch = OverlayPatch {
856            custom_attributes: Some(
857                [(
858                    "rsigma.foo".to_string(),
859                    serde_json::Value::String("new".into()),
860                )]
861                .into_iter()
862                .collect(),
863            ),
864            ..Default::default()
865        };
866        let spec = spec_with_overlays(vec![inline("d", Some(patch), None)]);
867        let resolved = resolve_with("test", &spec, vec![rule]).unwrap();
868        let attrs = &resolved.collection.rules[0].custom_attributes;
869        assert_eq!(
870            attrs.get("rsigma.foo"),
871            Some(&yaml_serde::to_value("new").unwrap())
872        );
873        assert!(attrs.contains_key("rsigma.exemplars"));
874    }
875
876    #[test]
877    fn null_removes_a_key() {
878        let mut rule = detection("d");
879        with_attr(&mut rule, "rsigma.foo", yaml_serde::to_value("x").unwrap());
880        let patch = OverlayPatch {
881            custom_attributes: Some(
882                [("rsigma.foo".to_string(), serde_json::Value::Null)]
883                    .into_iter()
884                    .collect(),
885            ),
886            ..Default::default()
887        };
888        let spec = spec_with_overlays(vec![inline("d", Some(patch), None)]);
889        let resolved = resolve_with("test", &spec, vec![rule]).unwrap();
890        assert!(
891            !resolved.collection.rules[0]
892                .custom_attributes
893                .contains_key("rsigma.foo")
894        );
895    }
896
897    #[test]
898    fn append_creates_absent_exemplars() {
899        let patch = OverlayPatch {
900            custom_attributes: Some(
901                [(
902                    "rsigma.exemplars".to_string(),
903                    serde_json::json!([{
904                        "name": "one",
905                        "expect": "match",
906                        "event": {"Field": "value"}
907                    }]),
908                )]
909                .into_iter()
910                .collect(),
911            ),
912            ..Default::default()
913        };
914        let spec = spec_with_overlays(vec![inline("d", None, Some(patch))]);
915        let resolved = resolve_with("test", &spec, vec![detection("d")]).unwrap();
916        assert!(
917            resolved.collection.rules[0]
918                .custom_attributes
919                .contains_key("rsigma.exemplars")
920        );
921        assert_eq!(
922            resolved.entries[0].overlays[0].appended,
923            ["custom_attributes.rsigma.exemplars"]
924        );
925    }
926
927    #[test]
928    fn append_onto_a_mapping_errors() {
929        let mut rule = detection("d");
930        with_attr(
931            &mut rule,
932            "rsigma.foo",
933            yaml_serde::from_str("a: b").unwrap(),
934        );
935        let patch = OverlayPatch {
936            custom_attributes: Some(
937                [("rsigma.foo".to_string(), serde_json::json!(["x"]))]
938                    .into_iter()
939                    .collect(),
940            ),
941            ..Default::default()
942        };
943        let spec = spec_with_overlays(vec![inline("d", None, Some(patch))]);
944        let error = resolve_with("test", &spec, vec![rule]).unwrap_err();
945        assert!(error.to_string().contains("existing sequence"), "{error}");
946    }
947
948    #[test]
949    fn tags_are_deduplicated() {
950        let mut rule = detection("d");
951        if let CandidateDoc::Detection(rule) = &mut rule.doc {
952            rule.tags = vec!["attack.t1059".into()];
953        }
954        let patch = OverlayPatch {
955            tags: Some(vec![
956                "attack.t1059".into(),
957                "attack.t1071".into(),
958                "attack.t1071".into(),
959            ]),
960            ..Default::default()
961        };
962        let spec = spec_with_overlays(vec![inline("d", None, Some(patch))]);
963        let resolved = resolve_with("test", &spec, vec![rule]).unwrap();
964        assert_eq!(
965            resolved.collection.rules[0].tags,
966            ["attack.t1059", "attack.t1071"]
967        );
968    }
969
970    #[test]
971    fn set_then_append_within_one_entry() {
972        let entry = inline(
973            "d",
974            Some(OverlayPatch {
975                tags: Some(vec!["a".into()]),
976                ..Default::default()
977            }),
978            Some(OverlayPatch {
979                tags: Some(vec!["b".into()]),
980                ..Default::default()
981            }),
982        );
983        let spec = spec_with_overlays(vec![entry]);
984        let resolved = resolve_with("test", &spec, vec![detection("d")]).unwrap();
985        assert_eq!(resolved.collection.rules[0].tags, ["a", "b"]);
986        assert_eq!(resolved.entries[0].overlays[0].set, ["tags"]);
987        assert_eq!(resolved.entries[0].overlays[0].appended, ["tags"]);
988    }
989
990    #[test]
991    fn two_entries_apply_in_order() {
992        let spec = spec_with_overlays(vec![
993            inline("d", Some(level_patch("low")), None),
994            inline("d", Some(level_patch("high")), None),
995        ]);
996        let resolved = resolve_with("test", &spec, vec![detection("d")]).unwrap();
997        assert_eq!(resolved.collection.rules[0].level, Some(Level::High));
998        let origins: Vec<String> = resolved.entries[0]
999            .overlays
1000            .iter()
1001            .map(|o| o.origin.to_string())
1002            .collect();
1003        assert_eq!(origins, ["inline:0", "inline:1"]);
1004    }
1005
1006    #[test]
1007    fn directory_entries_expand_in_sorted_order_at_their_position() {
1008        let dir = tempfile::tempdir().unwrap();
1009        let overlays = dir.path().join("overlays");
1010        std::fs::create_dir_all(&overlays).unwrap();
1011        std::fs::write(overlays.join("b.yml"), "- id: d\n  set:\n    level: high\n").unwrap();
1012        std::fs::write(
1013            overlays.join("a.yml"),
1014            "- id: d\n  set:\n    level: medium\n",
1015        )
1016        .unwrap();
1017
1018        let spec = RulesetSpec {
1019            sources: vec![PathBuf::from("rules")],
1020            overlays: vec![
1021                inline("d", Some(level_patch("low")), None),
1022                OverlayEntry {
1023                    dir: Some(overlays.clone()),
1024                    ..Default::default()
1025                },
1026                inline("d", Some(level_patch("critical")), None),
1027            ],
1028            ..Default::default()
1029        };
1030        let loader = FsOverlayLoader::new(None);
1031        let resolved = crate::ruleset::resolve_loaded(
1032            "test",
1033            &spec,
1034            crate::ruleset::LoadedSources {
1035                candidates: vec![detection("d")],
1036                ..Default::default()
1037            },
1038            &loader,
1039        )
1040        .unwrap();
1041        assert_eq!(resolved.collection.rules[0].level, Some(Level::Critical));
1042        let origins: Vec<String> = resolved.entries[0]
1043            .overlays
1044            .iter()
1045            .map(|o| o.origin.to_string())
1046            .collect();
1047        assert_eq!(
1048            origins,
1049            [
1050                "inline:0".to_string(),
1051                format!("{}:0", overlays.join("a.yml").display()),
1052                format!("{}:0", overlays.join("b.yml").display()),
1053                "inline:2".to_string(),
1054            ]
1055        );
1056        assert_eq!(resolved.overlay_files.len(), 2);
1057        let files: Vec<String> = resolved
1058            .overlay_files
1059            .iter()
1060            .map(|f| f.path.file_name().unwrap().to_string_lossy().into_owned())
1061            .collect();
1062        assert_eq!(files, ["a.yml", "b.yml"]);
1063    }
1064
1065    #[test]
1066    fn empty_and_null_overlay_files_contribute_nothing() {
1067        let dir = tempfile::tempdir().unwrap();
1068        let empty = dir.path().join("empty.yml");
1069        std::fs::write(&empty, "").unwrap();
1070        let null = dir.path().join("null.yml");
1071        std::fs::write(&null, "null\n").unwrap();
1072        let spec = spec_with_overlays(vec![
1073            OverlayEntry {
1074                file: Some(empty),
1075                ..Default::default()
1076            },
1077            OverlayEntry {
1078                file: Some(null),
1079                ..Default::default()
1080            },
1081        ]);
1082        let loader = FsOverlayLoader::new(None);
1083        let resolved = crate::ruleset::resolve_loaded(
1084            "test",
1085            &spec,
1086            crate::ruleset::LoadedSources {
1087                candidates: vec![detection("d")],
1088                ..Default::default()
1089            },
1090            &loader,
1091        )
1092        .unwrap();
1093        assert!(resolved.entries[0].overlays.is_empty());
1094        assert_eq!(resolved.overlay_files.len(), 2);
1095    }
1096
1097    #[test]
1098    fn unknown_keys_in_a_file_error() {
1099        let dir = tempfile::tempdir().unwrap();
1100        let path = dir.path().join("overlay.yml");
1101        std::fs::write(&path, "- id: d\n  set:\n    level: low\n    tagz: [x]\n").unwrap();
1102        let spec = RulesetSpec {
1103            sources: vec![PathBuf::from("rules")],
1104            overlays: vec![OverlayEntry {
1105                file: Some(path),
1106                ..Default::default()
1107            }],
1108            ..Default::default()
1109        };
1110        let loader = FsOverlayLoader::new(None);
1111        let error = crate::ruleset::resolve_loaded(
1112            "test",
1113            &spec,
1114            crate::ruleset::LoadedSources {
1115                candidates: vec![detection("d")],
1116                ..Default::default()
1117            },
1118            &loader,
1119        )
1120        .unwrap_err();
1121        let message = error.to_string();
1122        assert!(message.contains("unknown key 'tagz'"), "{message}");
1123        assert!(message.contains("did you mean 'tags'"), "{message}");
1124    }
1125
1126    #[test]
1127    fn a_file_overlay_cannot_shadow_a_standard_key_or_be_empty() {
1128        for (body, expected) in [
1129            (
1130                "- id: d\n  set:\n    custom_attributes:\n      title: Renamed\n",
1131                "overlay.yml:0.set.custom_attributes cannot set 'title'",
1132            ),
1133            ("- id: d\n  append: {}\n", "overlay.yml:0.append is empty"),
1134        ] {
1135            let dir = tempfile::tempdir().unwrap();
1136            let path = dir.path().join("overlay.yml");
1137            std::fs::write(&path, body).unwrap();
1138            let spec = RulesetSpec {
1139                sources: vec![PathBuf::from("rules")],
1140                overlays: vec![OverlayEntry {
1141                    file: Some(path),
1142                    ..Default::default()
1143                }],
1144                ..Default::default()
1145            };
1146            let error = crate::ruleset::resolve_loaded(
1147                "test",
1148                &spec,
1149                crate::ruleset::LoadedSources {
1150                    candidates: vec![detection("d")],
1151                    ..Default::default()
1152                },
1153                &FsOverlayLoader::new(None),
1154            )
1155            .unwrap_err();
1156            let message = error.to_string();
1157            assert!(message.contains(expected), "{message}");
1158        }
1159    }
1160
1161    #[test]
1162    fn filter_target_errors() {
1163        let filter = crate::parse_sigma_yaml(
1164            "title: Filter\nid: f\nlogsource:\n    product: linux\nfilter:\n    rules: any\n    selection:\n        Field: value\n    condition: selection\n",
1165        )
1166        .unwrap()
1167        .filters
1168        .remove(0);
1169        let candidate = Candidate {
1170            doc: CandidateDoc::Filter(filter),
1171            origin: origin("f"),
1172        };
1173        let spec = spec_with_overlays(vec![inline("f", Some(level_patch("low")), None)]);
1174        let error = resolve_with("test", &spec, vec![candidate]).unwrap_err();
1175        assert!(error.to_string().contains("which is a filter"), "{error}");
1176    }
1177
1178    #[test]
1179    fn stale_absent_and_excluded_are_errors() {
1180        let spec = spec_with_overlays(vec![inline("missing", Some(level_patch("low")), None)]);
1181        let error = resolve_with("test", &spec, vec![detection("d")]).unwrap_err();
1182        assert!(error.to_string().contains("exists in no source"), "{error}");
1183
1184        let mut spec = spec_with_overlays(vec![inline("d", Some(level_patch("low")), None)]);
1185        spec.exclude = vec![RuleSelector {
1186            id: vec!["d".into()],
1187            ..Default::default()
1188        }];
1189        let error = resolve_with("test", &spec, vec![detection("d")]).unwrap_err();
1190        assert!(
1191            error.to_string().contains("excluded by exclude selector 0"),
1192            "{error}"
1193        );
1194    }
1195
1196    #[test]
1197    fn stale_warn_records_a_warning() {
1198        let mut spec = spec_with_overlays(vec![inline("missing", Some(level_patch("low")), None)]);
1199        spec.stale_overlays = Some("warn".into());
1200        let resolved = resolve_with("test", &spec, vec![detection("d")]).unwrap();
1201        assert_eq!(resolved.warnings.len(), 1);
1202        assert!(
1203            resolved.warnings[0].contains("exists in no source"),
1204            "{:?}",
1205            resolved.warnings
1206        );
1207    }
1208
1209    #[test]
1210    fn appended_exemplar_with_duplicate_name_errors() {
1211        let mut rule = detection("d");
1212        with_attr(&mut rule, "rsigma.exemplars", exemplar_value());
1213        let patch = OverlayPatch {
1214            custom_attributes: Some(
1215                [(
1216                    "rsigma.exemplars".to_string(),
1217                    serde_json::json!([{
1218                        "name": "one",
1219                        "expect": "no-match",
1220                        "event": {"Field": "other"}
1221                    }]),
1222                )]
1223                .into_iter()
1224                .collect(),
1225            ),
1226            ..Default::default()
1227        };
1228        let spec = spec_with_overlays(vec![inline("d", None, Some(patch))]);
1229        let error = resolve_with("test", &spec, vec![rule]).unwrap_err();
1230        assert!(
1231            error.to_string().contains("duplicate exemplar name"),
1232            "{error}"
1233        );
1234    }
1235
1236    #[test]
1237    fn correlation_exemplars_are_validated_as_correlations() {
1238        let patch = OverlayPatch {
1239            custom_attributes: Some(
1240                [(
1241                    "rsigma.exemplars".to_string(),
1242                    serde_json::json!([{
1243                        "name": "burst",
1244                        "expect": "match",
1245                        "events": [{"offset": "0s", "event": {"Field": "value"}}]
1246                    }]),
1247                )]
1248                .into_iter()
1249                .collect(),
1250            ),
1251            ..Default::default()
1252        };
1253        let spec = spec_with_overlays(vec![inline("c", Some(patch.clone()), None)]);
1254        let resolved =
1255            resolve_with("test", &spec, vec![detection("base"), correlation("c")]).unwrap();
1256        assert!(
1257            resolved.collection.correlations[0]
1258                .custom_attributes
1259                .contains_key("rsigma.exemplars")
1260        );
1261
1262        let detection_patch = OverlayPatch {
1263            custom_attributes: Some(
1264                [(
1265                    "rsigma.exemplars".to_string(),
1266                    serde_json::json!([{
1267                        "name": "burst",
1268                        "expect": "match",
1269                        "event": {"Field": "value"}
1270                    }]),
1271                )]
1272                .into_iter()
1273                .collect(),
1274            ),
1275            ..Default::default()
1276        };
1277        let spec = spec_with_overlays(vec![inline("c", Some(detection_patch), None)]);
1278        let error =
1279            resolve_with("test", &spec, vec![detection("base"), correlation("c")]).unwrap_err();
1280        assert!(error.to_string().contains("must use 'events'"), "{error}");
1281    }
1282
1283    #[test]
1284    fn ads_values_are_validated() {
1285        let list = OverlayPatch {
1286            custom_attributes: Some(
1287                [(
1288                    "rsigma.ads.blind_spots".to_string(),
1289                    serde_json::json!(["one", "two"]),
1290                )]
1291                .into_iter()
1292                .collect(),
1293            ),
1294            ..Default::default()
1295        };
1296        let spec = spec_with_overlays(vec![inline("d", Some(list), None)]);
1297        resolve_with("test", &spec, vec![detection("d")]).unwrap();
1298
1299        let mapping = OverlayPatch {
1300            custom_attributes: Some(
1301                [(
1302                    "rsigma.ads.blind_spots".to_string(),
1303                    serde_json::json!({"one": "two"}),
1304                )]
1305                .into_iter()
1306                .collect(),
1307            ),
1308            ..Default::default()
1309        };
1310        let spec = spec_with_overlays(vec![inline("d", Some(mapping), None)]);
1311        let error = resolve_with("test", &spec, vec![detection("d")]).unwrap_err();
1312        assert!(
1313            error.to_string().contains("must be text or a list"),
1314            "{error}"
1315        );
1316    }
1317
1318    #[test]
1319    fn provenance_records_set_and_appended_keys() {
1320        let entry = inline(
1321            "d",
1322            Some(OverlayPatch {
1323                level: Some("high".into()),
1324                ..Default::default()
1325            }),
1326            Some(OverlayPatch {
1327                tags: Some(vec!["attack.t1059".into()]),
1328                ..Default::default()
1329            }),
1330        );
1331        let spec = spec_with_overlays(vec![entry]);
1332        let resolved = resolve_with("test", &spec, vec![detection("d")]).unwrap();
1333        let overlay = &resolved.entries[0].overlays[0];
1334        assert_eq!(overlay.origin, OverlayOrigin::Inline { index: 0 });
1335        assert_eq!(overlay.set, ["level"]);
1336        assert_eq!(overlay.appended, ["tags"]);
1337    }
1338
1339    fn attr_patch(key: &str, value: serde_json::Value) -> OverlayPatch {
1340        OverlayPatch {
1341            custom_attributes: Some([(key.to_string(), value)].into_iter().collect()),
1342            ..Default::default()
1343        }
1344    }
1345
1346    /// Resolve `detection("d")` with one file or dir overlay entry through the
1347    /// filesystem loader, optionally confined to `root`.
1348    fn resolve_fs(
1349        entry: OverlayEntry,
1350        root: Option<&Path>,
1351    ) -> Result<ResolvedRuleset, RulesetError> {
1352        let spec = spec_with_overlays(vec![entry]);
1353        crate::ruleset::resolve_loaded(
1354            "test",
1355            &spec,
1356            crate::ruleset::LoadedSources {
1357                candidates: vec![detection("d")],
1358                ..Default::default()
1359            },
1360            &FsOverlayLoader::new(root.map(Path::to_path_buf)),
1361        )
1362    }
1363
1364    fn file_entry(path: PathBuf) -> OverlayEntry {
1365        OverlayEntry {
1366            file: Some(path),
1367            ..Default::default()
1368        }
1369    }
1370
1371    fn dir_entry(path: PathBuf) -> OverlayEntry {
1372        OverlayEntry {
1373            dir: Some(path),
1374            ..Default::default()
1375        }
1376    }
1377
1378    #[test]
1379    fn ads_exempt_must_be_a_boolean() {
1380        let patch = attr_patch("rsigma.ads.exempt", serde_json::json!("yes"));
1381        let spec = spec_with_overlays(vec![inline("d", Some(patch), None)]);
1382        let error = resolve_with("test", &spec, vec![detection("d")]).unwrap_err();
1383        assert!(
1384            error
1385                .to_string()
1386                .contains("rsigma.ads.exempt must be a boolean"),
1387            "{error}"
1388        );
1389    }
1390
1391    #[test]
1392    fn appending_a_non_sequence_errors() {
1393        let patch = attr_patch("team", serde_json::json!("blue"));
1394        let spec = spec_with_overlays(vec![inline("d", None, Some(patch))]);
1395        let error = resolve_with("test", &spec, vec![detection("d")]).unwrap_err();
1396        assert!(
1397            error
1398                .to_string()
1399                .contains("append custom_attributes.team must be a sequence"),
1400            "{error}"
1401        );
1402    }
1403
1404    #[test]
1405    fn file_or_dir_inside_an_overlay_file_errors() {
1406        let dir = tempfile::tempdir().unwrap();
1407        let path = dir.path().join("overlay.yml");
1408        std::fs::write(
1409            &path,
1410            "- id: d\n  file: other.yml\n  set:\n    level: low\n",
1411        )
1412        .unwrap();
1413        let error = resolve_fs(file_entry(path), None).unwrap_err();
1414        assert!(
1415            error
1416                .to_string()
1417                .contains("must not use file or dir inside an overlay file"),
1418            "{error}"
1419        );
1420    }
1421
1422    #[test]
1423    fn a_missing_overlay_directory_errors() {
1424        let dir = tempfile::tempdir().unwrap();
1425        let missing = dir.path().join("missing");
1426        let error = resolve_fs(dir_entry(missing.clone()), None).unwrap_err();
1427        assert!(
1428            matches!(&error, RulesetError::Io { path, .. } if *path == missing),
1429            "{error}"
1430        );
1431        assert!(
1432            error
1433                .to_string()
1434                .contains("overlay directory does not exist"),
1435            "{error}"
1436        );
1437    }
1438
1439    #[test]
1440    fn an_unparseable_overlay_file_errors() {
1441        let dir = tempfile::tempdir().unwrap();
1442        let path = dir.path().join("overlay.yml");
1443        std::fs::write(&path, "- id: [unclosed\n").unwrap();
1444        let error = resolve_fs(file_entry(path), None).unwrap_err();
1445        assert!(
1446            error.to_string().contains("cannot parse overlay file"),
1447            "{error}"
1448        );
1449    }
1450
1451    #[test]
1452    fn the_filesystem_loader_confines_overlay_files_and_dirs() {
1453        let root = tempfile::tempdir().unwrap();
1454        let outside = tempfile::tempdir().unwrap();
1455        let outside_file = outside.path().join("overlay.yml");
1456        std::fs::write(&outside_file, "- id: d\n  set:\n    level: low\n").unwrap();
1457
1458        let error = resolve_fs(file_entry(outside_file.clone()), Some(root.path())).unwrap_err();
1459        assert!(matches!(error, RulesetError::Confinement { .. }), "{error}");
1460
1461        #[cfg(unix)]
1462        {
1463            let overlays = root.path().join("overlays");
1464            std::fs::create_dir(&overlays).unwrap();
1465            std::os::unix::fs::symlink(&outside_file, overlays.join("link.yml")).unwrap();
1466            let error = resolve_fs(dir_entry(overlays), Some(root.path())).unwrap_err();
1467            assert!(matches!(error, RulesetError::Confinement { .. }), "{error}");
1468        }
1469    }
1470
1471    #[test]
1472    fn stale_overlays_name_unselected_and_dropped_targets() {
1473        let mut spec = spec_with_overlays(vec![inline("d", Some(level_patch("low")), None)]);
1474        spec.include = vec![RuleSelector {
1475            id: vec!["other".into()],
1476            ..Default::default()
1477        }];
1478        let error =
1479            resolve_with("test", &spec, vec![detection("d"), detection("other")]).unwrap_err();
1480        assert!(
1481            error.to_string().contains("is not matched by include"),
1482            "{error}"
1483        );
1484
1485        let mut spec = spec_with_overlays(vec![inline("c", Some(level_patch("low")), None)]);
1486        spec.dependencies = Some("drop".into());
1487        spec.exclude = vec![RuleSelector {
1488            id: vec!["base".into()],
1489            ..Default::default()
1490        }];
1491        let error =
1492            resolve_with("test", &spec, vec![detection("base"), correlation("c")]).unwrap_err();
1493        assert!(error.to_string().contains("was dropped"), "{error}");
1494    }
1495}