1pub mod catalogue;
23#[cfg(feature = "fix")]
24pub mod fix;
25mod rules;
26
27use std::collections::{HashMap, HashSet};
28use std::fmt;
29use std::path::Path;
30use std::sync::LazyLock;
31
32use serde::{Deserialize, Serialize};
33use yaml_serde::Value;
34
35use crate::ads::AdsSection;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
43pub enum Severity {
44 Error,
46 Warning,
48 Info,
50 Hint,
52}
53
54impl fmt::Display for Severity {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Severity::Error => write!(f, "error"),
58 Severity::Warning => write!(f, "warning"),
59 Severity::Info => write!(f, "info"),
60 Severity::Hint => write!(f, "hint"),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
67pub enum LintRule {
68 YamlParseError,
70 NotAMapping,
71 FileReadError,
72 SchemaViolation,
73
74 MissingTitle,
76 EmptyTitle,
77 TitleTooLong,
78 MissingDescription,
79 MissingAuthor,
80 InvalidId,
81 InvalidStatus,
82 MissingLevel,
83 InvalidLevel,
84 InvalidDate,
85 InvalidModified,
86 ModifiedBeforeDate,
87 DescriptionTooLong,
88 NameTooLong,
89 TaxonomyTooLong,
90 NonLowercaseKey,
91
92 MissingLogsource,
94 MissingDetection,
95 MissingCondition,
96 EmptyDetection,
97 InvalidRelatedType,
98 InvalidRelatedId,
99 RelatedMissingRequired,
100 DeprecatedWithoutRelated,
101 InvalidTag,
102 UnknownTagNamespace,
103 DuplicateTags,
104 DuplicateReferences,
105 DuplicateFields,
106 FalsepositiveTooShort,
107 ScopeTooShort,
108 LogsourceValueNotLowercase,
109 ConditionReferencesUnknown,
110 InvalidCondition,
111 DeprecatedAggregationSyntax,
112 DeprecatedDetectionTimeframe,
113
114 MissingCorrelation,
116 MissingCorrelationType,
117 InvalidCorrelationType,
118 MissingCorrelationRules,
119 EmptyCorrelationRules,
120 MissingCorrelationTimespan,
121 InvalidTimespanFormat,
122 InvalidWindowMode,
123 MissingSessionGap,
124 GapWithoutSession,
125 InvalidGapFormat,
126 MissingGroupBy,
127 MissingCorrelationCondition,
128 MissingConditionField,
129 InvalidConditionOperator,
130 ConditionValueNotNumeric,
131 GenerateNotBoolean,
132 CorrelationOnlyReferences,
133
134 MissingFilter,
136 MissingFilterRules,
137 EmptyFilterRules,
138 MissingFilterSelection,
139 MissingFilterCondition,
140 FilterHasLevel,
141 FilterHasStatus,
142 MissingFilterLogsource,
143 FilterReferenceByTitle,
144
145 NullInValueList,
147 SingleValueAllModifier,
148 AllWithRe,
149 IncompatibleModifiers,
150 EmptyValueList,
151 WildcardOnlyValue,
152 FlattenedArrayCorrelation,
153 UnsupportedSigmaVersion,
154 ArrayMatchingWithoutVersion,
155 SigmaVersionMismatch,
156 UnknownRuleReference,
157 UnknownKey,
158
159 AdsMissingGoal,
161 AdsMissingCategorization,
162 AdsMissingStrategy,
163 AdsMissingTechnicalContext,
164 AdsMissingBlindSpots,
165 AdsMissingFalsePositives,
166 AdsMissingValidation,
167 AdsMissingPriority,
168 AdsMissingResponse,
169 AdsEmptySection,
170 AdsUnknownSection,
171
172 ExemplarShape,
174 ExemplarWrongRuleKind,
175}
176
177impl fmt::Display for LintRule {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 let s = match self {
180 LintRule::YamlParseError => "yaml_parse_error",
181 LintRule::NotAMapping => "not_a_mapping",
182 LintRule::FileReadError => "file_read_error",
183 LintRule::SchemaViolation => "schema_violation",
184 LintRule::MissingTitle => "missing_title",
185 LintRule::EmptyTitle => "empty_title",
186 LintRule::TitleTooLong => "title_too_long",
187 LintRule::MissingDescription => "missing_description",
188 LintRule::MissingAuthor => "missing_author",
189 LintRule::InvalidId => "invalid_id",
190 LintRule::InvalidStatus => "invalid_status",
191 LintRule::MissingLevel => "missing_level",
192 LintRule::InvalidLevel => "invalid_level",
193 LintRule::InvalidDate => "invalid_date",
194 LintRule::InvalidModified => "invalid_modified",
195 LintRule::ModifiedBeforeDate => "modified_before_date",
196 LintRule::DescriptionTooLong => "description_too_long",
197 LintRule::NameTooLong => "name_too_long",
198 LintRule::TaxonomyTooLong => "taxonomy_too_long",
199 LintRule::NonLowercaseKey => "non_lowercase_key",
200 LintRule::MissingLogsource => "missing_logsource",
201 LintRule::MissingDetection => "missing_detection",
202 LintRule::MissingCondition => "missing_condition",
203 LintRule::EmptyDetection => "empty_detection",
204 LintRule::InvalidRelatedType => "invalid_related_type",
205 LintRule::InvalidRelatedId => "invalid_related_id",
206 LintRule::RelatedMissingRequired => "related_missing_required",
207 LintRule::DeprecatedWithoutRelated => "deprecated_without_related",
208 LintRule::InvalidTag => "invalid_tag",
209 LintRule::UnknownTagNamespace => "unknown_tag_namespace",
210 LintRule::DuplicateTags => "duplicate_tags",
211 LintRule::DuplicateReferences => "duplicate_references",
212 LintRule::DuplicateFields => "duplicate_fields",
213 LintRule::FalsepositiveTooShort => "falsepositive_too_short",
214 LintRule::ScopeTooShort => "scope_too_short",
215 LintRule::LogsourceValueNotLowercase => "logsource_value_not_lowercase",
216 LintRule::ConditionReferencesUnknown => "condition_references_unknown",
217 LintRule::InvalidCondition => "invalid_condition",
218 LintRule::DeprecatedAggregationSyntax => "deprecated_aggregation_syntax",
219 LintRule::DeprecatedDetectionTimeframe => "deprecated_detection_timeframe",
220 LintRule::MissingCorrelation => "missing_correlation",
221 LintRule::MissingCorrelationType => "missing_correlation_type",
222 LintRule::InvalidCorrelationType => "invalid_correlation_type",
223 LintRule::MissingCorrelationRules => "missing_correlation_rules",
224 LintRule::EmptyCorrelationRules => "empty_correlation_rules",
225 LintRule::MissingCorrelationTimespan => "missing_correlation_timespan",
226 LintRule::InvalidTimespanFormat => "invalid_timespan_format",
227 LintRule::InvalidWindowMode => "invalid_window_mode",
228 LintRule::MissingSessionGap => "missing_session_gap",
229 LintRule::GapWithoutSession => "gap_without_session",
230 LintRule::InvalidGapFormat => "invalid_gap_format",
231 LintRule::MissingGroupBy => "missing_group_by",
232 LintRule::MissingCorrelationCondition => "missing_correlation_condition",
233 LintRule::MissingConditionField => "missing_condition_field",
234 LintRule::InvalidConditionOperator => "invalid_condition_operator",
235 LintRule::ConditionValueNotNumeric => "condition_value_not_numeric",
236 LintRule::GenerateNotBoolean => "generate_not_boolean",
237 LintRule::CorrelationOnlyReferences => "correlation_only_references",
238 LintRule::MissingFilter => "missing_filter",
239 LintRule::MissingFilterRules => "missing_filter_rules",
240 LintRule::EmptyFilterRules => "empty_filter_rules",
241 LintRule::MissingFilterSelection => "missing_filter_selection",
242 LintRule::MissingFilterCondition => "missing_filter_condition",
243 LintRule::FilterHasLevel => "filter_has_level",
244 LintRule::FilterHasStatus => "filter_has_status",
245 LintRule::MissingFilterLogsource => "missing_filter_logsource",
246 LintRule::FilterReferenceByTitle => "filter_reference_by_title",
247 LintRule::NullInValueList => "null_in_value_list",
248 LintRule::SingleValueAllModifier => "single_value_all_modifier",
249 LintRule::AllWithRe => "all_with_re",
250 LintRule::IncompatibleModifiers => "incompatible_modifiers",
251 LintRule::EmptyValueList => "empty_value_list",
252 LintRule::WildcardOnlyValue => "wildcard_only_value",
253 LintRule::FlattenedArrayCorrelation => "flattened_array_correlation",
254 LintRule::UnsupportedSigmaVersion => "unsupported_sigma_version",
255 LintRule::ArrayMatchingWithoutVersion => "array_matching_without_version",
256 LintRule::SigmaVersionMismatch => "sigma_version_mismatch",
257 LintRule::UnknownRuleReference => "unknown_rule_reference",
258 LintRule::UnknownKey => "unknown_key",
259 LintRule::AdsMissingGoal => "ads_missing_goal",
260 LintRule::AdsMissingCategorization => "ads_missing_categorization",
261 LintRule::AdsMissingStrategy => "ads_missing_strategy",
262 LintRule::AdsMissingTechnicalContext => "ads_missing_technical_context",
263 LintRule::AdsMissingBlindSpots => "ads_missing_blind_spots",
264 LintRule::AdsMissingFalsePositives => "ads_missing_false_positives",
265 LintRule::AdsMissingValidation => "ads_missing_validation",
266 LintRule::AdsMissingPriority => "ads_missing_priority",
267 LintRule::AdsMissingResponse => "ads_missing_response",
268 LintRule::AdsEmptySection => "ads_empty_section",
269 LintRule::AdsUnknownSection => "ads_unknown_section",
270 LintRule::ExemplarShape => "exemplar_shape",
271 LintRule::ExemplarWrongRuleKind => "exemplar_wrong_rule_kind",
272 };
273 write!(f, "{s}")
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
279pub struct Span {
280 pub start_line: u32,
281 pub start_col: u32,
282 pub end_line: u32,
283 pub end_col: u32,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
292pub enum FixDisposition {
293 Safe,
294 Unsafe,
295}
296
297#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
299pub enum FixPatch {
300 ReplaceValue { path: String, new_value: String },
301 ReplaceKey { path: String, new_key: String },
302 Remove { path: String },
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
307pub struct Fix {
308 pub title: String,
309 pub disposition: FixDisposition,
310 pub patches: Vec<FixPatch>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
315pub struct LintWarning {
316 pub rule: LintRule,
317 pub severity: Severity,
318 pub message: String,
319 pub path: String,
320 pub span: Option<Span>,
321 pub fix: Option<Fix>,
322}
323
324impl fmt::Display for LintWarning {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 write!(
327 f,
328 "{}[{}]: {}\n --> {}",
329 self.severity, self.rule, self.message, self.path
330 )
331 }
332}
333
334#[derive(Debug, Clone, Serialize)]
336pub struct FileLintResult {
337 pub path: std::path::PathBuf,
338 pub warnings: Vec<LintWarning>,
339}
340
341impl FileLintResult {
342 pub fn has_errors(&self) -> bool {
343 self.warnings.iter().any(|w| w.severity == Severity::Error)
344 }
345
346 pub fn error_count(&self) -> usize {
347 self.warnings
348 .iter()
349 .filter(|w| w.severity == Severity::Error)
350 .count()
351 }
352
353 pub fn warning_count(&self) -> usize {
354 self.warnings
355 .iter()
356 .filter(|w| w.severity == Severity::Warning)
357 .count()
358 }
359
360 pub fn info_count(&self) -> usize {
361 self.warnings
362 .iter()
363 .filter(|w| w.severity == Severity::Info)
364 .count()
365 }
366
367 pub fn hint_count(&self) -> usize {
368 self.warnings
369 .iter()
370 .filter(|w| w.severity == Severity::Hint)
371 .count()
372 }
373}
374
375static KEY_CACHE: LazyLock<HashMap<&'static str, Value>> = LazyLock::new(|| {
380 [
381 "action",
382 "author",
383 "category",
384 "condition",
385 "correlation",
386 "custom_attributes",
387 "date",
388 "description",
389 "detection",
390 "falsepositives",
391 "field",
392 "fields",
393 "filter",
394 "gap",
395 "generate",
396 "group-by",
397 "id",
398 "level",
399 "logsource",
400 "modified",
401 "name",
402 "product",
403 "references",
404 "related",
405 "rsigma.gap",
406 "rsigma.window",
407 "rules",
408 "scope",
409 "selection",
410 "service",
411 "sigma-version",
412 "status",
413 "tags",
414 "taxonomy",
415 "timeframe",
416 "timespan",
417 "title",
418 "type",
419 "window",
420 ]
421 .into_iter()
422 .map(|n| (n, Value::String(n.into())))
423 .collect()
424});
425
426pub(crate) fn key(s: &str) -> &'static Value {
427 KEY_CACHE
428 .get(s)
429 .unwrap_or_else(|| panic!("lint key not pre-cached: \"{s}\" — add it to KEY_CACHE"))
430}
431
432pub(crate) fn get_str<'a>(m: &'a yaml_serde::Mapping, k: &str) -> Option<&'a str> {
433 m.get(key(k)).and_then(|v| v.as_str())
434}
435
436pub(crate) fn get_mapping<'a>(
437 m: &'a yaml_serde::Mapping,
438 k: &str,
439) -> Option<&'a yaml_serde::Mapping> {
440 m.get(key(k)).and_then(|v| v.as_mapping())
441}
442
443pub(crate) fn get_seq<'a>(m: &'a yaml_serde::Mapping, k: &str) -> Option<&'a yaml_serde::Sequence> {
444 m.get(key(k)).and_then(|v| v.as_sequence())
445}
446
447pub(crate) fn warn(
448 rule: LintRule,
449 severity: Severity,
450 message: impl Into<String>,
451 path: impl Into<String>,
452) -> LintWarning {
453 LintWarning {
454 rule,
455 severity,
456 message: message.into(),
457 path: path.into(),
458 span: None,
459 fix: None,
460 }
461}
462
463pub(crate) fn err(
464 rule: LintRule,
465 message: impl Into<String>,
466 path: impl Into<String>,
467) -> LintWarning {
468 warn(rule, Severity::Error, message, path)
469}
470
471pub(crate) fn warning(
472 rule: LintRule,
473 message: impl Into<String>,
474 path: impl Into<String>,
475) -> LintWarning {
476 warn(rule, Severity::Warning, message, path)
477}
478
479pub(crate) fn info(
480 rule: LintRule,
481 message: impl Into<String>,
482 path: impl Into<String>,
483) -> LintWarning {
484 warn(rule, Severity::Info, message, path)
485}
486
487pub(crate) fn safe_fix(title: impl Into<String>, patches: Vec<FixPatch>) -> Option<Fix> {
488 Some(Fix {
489 title: title.into(),
490 disposition: FixDisposition::Safe,
491 patches,
492 })
493}
494
495pub(crate) fn closest_match<'a>(
497 input: &str,
498 candidates: &[&'a str],
499 max_distance: usize,
500) -> Option<&'a str> {
501 candidates
502 .iter()
503 .filter(|c| edit_distance(input, c) <= max_distance)
504 .min_by_key(|c| edit_distance(input, c))
505 .copied()
506}
507
508pub(crate) fn edit_distance(a: &str, b: &str) -> usize {
510 let (a_len, b_len) = (a.len(), b.len());
511 if a_len == 0 {
512 return b_len;
513 }
514 if b_len == 0 {
515 return a_len;
516 }
517 let mut prev: Vec<usize> = (0..=b_len).collect();
518 let mut curr = vec![0; b_len + 1];
519 for (i, ca) in a.bytes().enumerate() {
520 curr[0] = i + 1;
521 for (j, cb) in b.bytes().enumerate() {
522 let cost = if ca == cb { 0 } else { 1 };
523 curr[j + 1] = (prev[j] + cost).min(prev[j + 1] + 1).min(curr[j] + 1);
524 }
525 std::mem::swap(&mut prev, &mut curr);
526 }
527 prev[b_len]
528}
529
530pub(crate) const TYPO_MAX_EDIT_DISTANCE: usize = 2;
531
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
537pub(crate) enum DocType {
538 Detection,
539 Correlation,
540 Filter,
541}
542
543impl DocType {
544 pub(crate) fn known_keys(&self) -> &'static [&'static str] {
545 match self {
546 DocType::Detection => rules::shared::KNOWN_KEYS_DETECTION,
547 DocType::Correlation => rules::shared::KNOWN_KEYS_CORRELATION,
548 DocType::Filter => rules::shared::KNOWN_KEYS_FILTER,
549 }
550 }
551}
552
553fn detect_doc_type(m: &yaml_serde::Mapping) -> DocType {
554 if m.contains_key(key("correlation")) {
555 DocType::Correlation
556 } else if m.contains_key(key("filter")) {
557 DocType::Filter
558 } else {
559 DocType::Detection
560 }
561}
562
563fn is_action_fragment(m: &yaml_serde::Mapping) -> bool {
564 matches!(get_str(m, "action"), Some("global" | "reset" | "repeat"))
565}
566
567struct RuleIndex {
576 majors: HashMap<String, u32>,
577 detection_identities: HashMap<String, u32>,
580 detection_titles: HashMap<String, u32>,
581 complete: bool,
585}
586
587impl RuleIndex {
588 fn new(complete: bool) -> Self {
589 Self {
590 majors: HashMap::new(),
591 detection_identities: HashMap::new(),
592 detection_titles: HashMap::new(),
593 complete,
594 }
595 }
596
597 fn add_text(&mut self, text: &str) {
599 for doc in yaml_serde::Deserializer::from_str(text) {
600 let Ok(value) = Value::deserialize(doc) else {
601 break;
602 };
603 self.add_value(&value);
604 }
605 }
606
607 fn add_value(&mut self, value: &Value) {
608 let Some(m) = value.as_mapping() else {
609 return;
610 };
611 if is_action_fragment(m) {
612 return;
613 }
614 let doc_type = detect_doc_type(m);
616 if matches!(doc_type, DocType::Detection | DocType::Correlation) {
617 let major = crate::version::resolve_major(
618 m.get(key("sigma-version"))
619 .and_then(crate::version::major_from_value),
620 );
621 for id_key in ["id", "name"] {
622 if let Some(v) = get_str(m, id_key) {
623 self.majors.insert(v.to_string(), major);
624 if doc_type == DocType::Detection {
625 self.detection_identities.insert(v.to_string(), major);
626 }
627 }
628 }
629 if doc_type == DocType::Detection
630 && let Some(title) = get_str(m, "title")
631 {
632 self.detection_titles.insert(title.to_string(), major);
633 }
634 }
635 }
636}
637
638fn reference_list(v: Option<&Value>) -> Vec<String> {
640 match v {
641 Some(Value::String(s)) => vec![s.clone()],
642 Some(Value::Sequence(seq)) => seq
643 .iter()
644 .filter_map(|x| x.as_str().map(str::to_string))
645 .collect(),
646 _ => Vec::new(),
647 }
648}
649
650fn correlation_rule_refs(m: &yaml_serde::Mapping) -> Vec<String> {
652 m.get(key("correlation"))
653 .and_then(|c| c.as_mapping())
654 .map(|c| reference_list(c.get(key("rules"))))
655 .unwrap_or_default()
656}
657
658fn filter_rule_refs(m: &yaml_serde::Mapping) -> Option<Vec<String>> {
661 let f = m.get(key("filter"))?.as_mapping()?;
662 let rules = f.get(key("rules"))?;
663 if let Some(s) = rules.as_str()
664 && s.eq_ignore_ascii_case("any")
665 {
666 return None;
667 }
668 Some(reference_list(Some(rules)))
669}
670
671fn lint_cross_references(docs: &[Value], index: &RuleIndex, warnings: &mut Vec<LintWarning>) {
679 for value in docs {
680 let Some(m) = value.as_mapping() else {
681 continue;
682 };
683 if is_action_fragment(m) {
684 continue;
685 }
686 let doc_type = detect_doc_type(m);
687 let (refs, path) = match doc_type {
688 DocType::Correlation => (correlation_rule_refs(m), "/correlation/rules"),
689 DocType::Filter => match filter_rule_refs(m) {
690 Some(refs) => (refs, "/filter/rules"),
691 None => continue,
692 },
693 DocType::Detection => continue,
694 };
695 if refs.is_empty() {
696 continue;
697 }
698 let self_major = crate::version::resolve_major(
699 m.get(key("sigma-version"))
700 .and_then(crate::version::major_from_value),
701 );
702 let label = get_str(m, "title")
703 .or_else(|| get_str(m, "name"))
704 .unwrap_or("<rule>");
705 for r in refs {
706 let identities = if doc_type == DocType::Filter {
707 &index.detection_identities
708 } else {
709 &index.majors
710 };
711 let mut target = identities.get(&r).copied();
712 if target.is_none()
713 && doc_type == DocType::Filter
714 && let Some(title_target) = index.detection_titles.get(&r).copied()
715 {
716 warnings.push(warning(
717 LintRule::FilterReferenceByTitle,
718 format!(
719 "'{label}' references rule title '{r}'; title references are deprecated, \
720 use the rule id or name"
721 ),
722 path,
723 ));
724 target = Some(title_target);
725 }
726 match target {
727 Some(target) if target != self_major => warnings.push(warning(
728 LintRule::SigmaVersionMismatch,
729 format!(
730 "'{label}' targets sigma-version major {self_major} but references rule \
731 '{r}' which targets major {target}; cross-referencing rules must share a \
732 specification major"
733 ),
734 path,
735 )),
736 Some(_) => {}
737 None if index.complete => warnings.push(warning(
738 LintRule::UnknownRuleReference,
739 format!(
740 "'{label}' references rule '{r}', which was not found among the linted \
741 rules (matched by id or name)"
742 ),
743 path,
744 )),
745 None => {}
746 }
747 }
748 }
749}
750
751fn lint_yaml_value_ext(
756 value: &Value,
757 extra_ns: &[String],
758 ads: Option<&AdsConfig>,
759) -> Vec<LintWarning> {
760 let Some(m) = value.as_mapping() else {
761 return vec![err(
762 LintRule::NotAMapping,
763 "document is not a YAML mapping",
764 "/",
765 )];
766 };
767
768 if is_action_fragment(m) {
769 let mut warnings = Vec::new();
770 rules::exemplar::lint_exemplars(m, None, &mut warnings);
771 return warnings;
772 }
773
774 let mut warnings = Vec::new();
775
776 rules::metadata::lint_shared(m, &mut warnings);
777
778 let doc_type = detect_doc_type(m);
779 match doc_type {
780 DocType::Detection => rules::detection::lint_detection_rule(m, &mut warnings, extra_ns),
781 DocType::Correlation => rules::correlation::lint_correlation_rule(m, &mut warnings),
782 DocType::Filter => rules::filter::lint_filter_rule(m, &mut warnings),
783 }
784
785 rules::version::lint_sigma_version(m, doc_type, &mut warnings);
786 rules::shared::lint_unknown_keys(m, doc_type, &mut warnings);
787 rules::exemplar::lint_exemplars(m, Some(doc_type), &mut warnings);
788
789 if let Some(ads_cfg) = ads
792 && doc_type == DocType::Detection
793 {
794 rules::ads::lint_ads(m, ads_cfg, extra_ns, &mut warnings);
795 }
796
797 warnings
798}
799
800pub fn lint_yaml_value(value: &Value) -> Vec<LintWarning> {
802 lint_yaml_value_ext(value, &[], None)
803}
804
805fn lint_yaml_str_ext(text: &str, extra_ns: &[String], ads: Option<&AdsConfig>) -> Vec<LintWarning> {
806 lint_yaml_str_indexed(text, extra_ns, ads, None)
807}
808
809fn lint_yaml_str_indexed(
814 text: &str,
815 extra_ns: &[String],
816 ads: Option<&AdsConfig>,
817 external_index: Option<&RuleIndex>,
818) -> Vec<LintWarning> {
819 let mut all_warnings = Vec::new();
820 let mut docs: Vec<Value> = Vec::new();
821
822 for doc in yaml_serde::Deserializer::from_str(text) {
823 let value: Value = match Value::deserialize(doc) {
824 Ok(v) => v,
825 Err(e) => {
826 let mut w = err(
827 LintRule::YamlParseError,
828 format!("YAML parse error: {e}"),
829 "/",
830 );
831 if let Some(loc) = e.location() {
832 w.span = Some(Span {
833 start_line: loc.line().saturating_sub(1) as u32,
834 start_col: loc.column() as u32,
835 end_line: loc.line().saturating_sub(1) as u32,
836 end_col: loc.column() as u32 + 1,
837 });
838 }
839 all_warnings.push(w);
840 break;
841 }
842 };
843
844 for mut w in lint_yaml_value_ext(&value, extra_ns, ads) {
845 w.span = resolve_path_to_span(text, &w.path);
846 all_warnings.push(w);
847 }
848 docs.push(value);
849 }
850
851 let local_index;
854 let index = match external_index {
855 Some(idx) => idx,
856 None => {
857 let mut idx = RuleIndex::new(false);
858 for v in &docs {
859 idx.add_value(v);
860 }
861 local_index = idx;
862 &local_index
863 }
864 };
865 let mut xref = Vec::new();
866 lint_cross_references(&docs, index, &mut xref);
867 for mut w in xref {
868 w.span = resolve_path_to_span(text, &w.path);
869 all_warnings.push(w);
870 }
871
872 all_warnings
873}
874
875pub fn lint_yaml_str(text: &str) -> Vec<LintWarning> {
877 lint_yaml_str_ext(text, &[], None)
878}
879
880fn resolve_path_to_span(text: &str, path: &str) -> Option<Span> {
881 if path == "/" || path.is_empty() {
882 for (i, line) in text.lines().enumerate() {
883 let trimmed = line.trim();
884 if !trimmed.is_empty() && !trimmed.starts_with('#') && trimmed != "---" {
885 return Some(Span {
886 start_line: i as u32,
887 start_col: 0,
888 end_line: i as u32,
889 end_col: line.len() as u32,
890 });
891 }
892 }
893 return None;
894 }
895
896 let segments: Vec<&str> = path.strip_prefix('/').unwrap_or(path).split('/').collect();
897
898 if segments.is_empty() {
899 return None;
900 }
901
902 let lines: Vec<&str> = text.lines().collect();
903 let mut current_indent: i32 = -1;
904 let mut search_start = 0usize;
905 let mut last_matched_line: Option<usize> = None;
906
907 for segment in &segments {
908 let array_index: Option<usize> = segment.parse().ok();
909 let mut found = false;
910
911 let mut line_num = search_start;
912 while line_num < lines.len() {
913 let line = lines[line_num];
914 let trimmed = line.trim();
915 if trimmed.is_empty() || trimmed.starts_with('#') {
916 line_num += 1;
917 continue;
918 }
919
920 let indent = (line.len() - trimmed.len()) as i32;
921
922 if indent <= current_indent && found {
923 break;
924 }
925 if indent <= current_indent {
926 line_num += 1;
927 continue;
928 }
929
930 if let Some(idx) = array_index {
931 if trimmed.starts_with("- ") && indent > current_indent {
932 let mut count = 0usize;
933 for (offset, sl) in lines[search_start..].iter().enumerate() {
934 let scan = search_start + offset;
935 let st = sl.trim();
936 if st.is_empty() || st.starts_with('#') {
937 continue;
938 }
939 let si = (sl.len() - st.len()) as i32;
940 if si == indent && st.starts_with("- ") {
941 if count == idx {
942 last_matched_line = Some(scan);
943 search_start = scan + 1;
944 current_indent = indent;
945 found = true;
946 break;
947 }
948 count += 1;
949 }
950 if si < indent && count > 0 {
951 break;
952 }
953 }
954 break;
955 }
956 } else {
957 let key_pattern = format!("{segment}:");
958 if trimmed.starts_with(&key_pattern) || trimmed == *segment {
959 last_matched_line = Some(line_num);
960 search_start = line_num + 1;
961 current_indent = indent;
962 found = true;
963 break;
964 }
965 }
966
967 line_num += 1;
968 }
969
970 if !found && last_matched_line.is_none() {
971 break;
972 }
973 }
974
975 last_matched_line.map(|line_num| {
976 let line = lines[line_num];
977 Span {
978 start_line: line_num as u32,
979 start_col: 0,
980 end_line: line_num as u32,
981 end_col: line.len() as u32,
982 }
983 })
984}
985
986pub fn lint_yaml_file(path: &Path) -> crate::error::Result<FileLintResult> {
988 let content = std::fs::read_to_string(path)?;
989 let warnings = lint_yaml_str(&content);
990 Ok(FileLintResult {
991 path: path.to_path_buf(),
992 warnings,
993 })
994}
995
996fn collect_yaml_files(
1000 dir: &Path,
1001 base: &Path,
1002 exclude_set: Option<&globset::GlobSet>,
1003 files: &mut Vec<std::path::PathBuf>,
1004 visited: &mut HashSet<std::path::PathBuf>,
1005) -> crate::error::Result<()> {
1006 let canonical = match dir.canonicalize() {
1007 Ok(p) => p,
1008 Err(_) => return Ok(()),
1009 };
1010 if !visited.insert(canonical) {
1011 return Ok(());
1012 }
1013
1014 let mut entries: Vec<_> = std::fs::read_dir(dir)?.filter_map(|e| e.ok()).collect();
1015 entries.sort_by_key(|e| e.path());
1016
1017 for entry in entries {
1018 let path = entry.path();
1019
1020 if let Some(gs) = exclude_set
1021 && let Ok(rel) = path.strip_prefix(base)
1022 && gs.is_match(rel)
1023 {
1024 continue;
1025 }
1026
1027 if path.is_dir() {
1028 if path
1029 .file_name()
1030 .and_then(|n| n.to_str())
1031 .is_some_and(|n| n.starts_with('.'))
1032 {
1033 continue;
1034 }
1035 collect_yaml_files(&path, base, exclude_set, files, visited)?;
1036 } else if matches!(
1037 path.extension().and_then(|e| e.to_str()),
1038 Some("yml" | "yaml")
1039 ) {
1040 files.push(path);
1041 }
1042 }
1043 Ok(())
1044}
1045
1046fn lint_directory_impl(
1050 dir: &Path,
1051 config: Option<&LintConfig>,
1052) -> crate::error::Result<Vec<FileLintResult>> {
1053 let exclude_set = config.and_then(LintConfig::build_exclude_set);
1054 let mut files = Vec::new();
1055 let mut visited = HashSet::new();
1056 collect_yaml_files(dir, dir, exclude_set.as_ref(), &mut files, &mut visited)?;
1057
1058 let mut index = RuleIndex::new(true);
1060 let mut contents: Vec<(std::path::PathBuf, std::result::Result<String, String>)> =
1061 Vec::with_capacity(files.len());
1062 for path in files {
1063 match std::fs::read_to_string(&path) {
1064 Ok(text) => {
1065 index.add_text(&text);
1066 contents.push((path, Ok(text)));
1067 }
1068 Err(e) => contents.push((path, Err(format!("error reading file: {e}")))),
1069 }
1070 }
1071
1072 let mut results = Vec::with_capacity(contents.len());
1073 for (path, content) in contents {
1074 match content {
1075 Ok(text) => {
1076 let warnings = match config {
1077 Some(cfg) => {
1078 let w = lint_yaml_str_indexed(
1079 &text,
1080 &cfg.tag_namespaces,
1081 cfg.ads.as_ref(),
1082 Some(&index),
1083 );
1084 apply_suppressions(w, cfg, &parse_inline_suppressions(&text))
1085 }
1086 None => lint_yaml_str_indexed(&text, &[], None, Some(&index)),
1087 };
1088 results.push(FileLintResult { path, warnings });
1089 }
1090 Err(msg) => results.push(FileLintResult {
1091 path,
1092 warnings: vec![err(LintRule::FileReadError, msg, "/")],
1093 }),
1094 }
1095 }
1096 Ok(results)
1097}
1098
1099pub fn lint_yaml_directory(dir: &Path) -> crate::error::Result<Vec<FileLintResult>> {
1101 lint_directory_impl(dir, None)
1102}
1103
1104#[derive(Debug, Clone, Default, Serialize)]
1110pub struct LintConfig {
1111 pub disabled_rules: HashSet<String>,
1112 pub severity_overrides: HashMap<String, Severity>,
1113 pub exclude_patterns: Vec<String>,
1114 pub tag_namespaces: Vec<String>,
1116 #[serde(skip_serializing_if = "Option::is_none")]
1119 pub ads: Option<AdsConfig>,
1120}
1121
1122#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1129pub struct AdsConfig {
1130 pub enforce_status: Vec<String>,
1132 pub required: Vec<String>,
1134 #[serde(skip_serializing_if = "Option::is_none")]
1137 pub severity: Option<Severity>,
1138}
1139
1140impl Default for AdsConfig {
1141 fn default() -> Self {
1142 AdsConfig {
1143 enforce_status: vec!["stable".to_string()],
1144 required: AdsSection::all()
1145 .iter()
1146 .map(|s| s.id().to_string())
1147 .collect(),
1148 severity: None,
1149 }
1150 }
1151}
1152
1153impl AdsConfig {
1154 pub fn enforces_status(&self, status: Option<&str>) -> bool {
1157 match status {
1158 Some(s) => self.enforce_status.iter().any(|e| e == s),
1159 None => false,
1160 }
1161 }
1162
1163 pub fn requires(&self, section_id: &str) -> bool {
1165 self.required.iter().any(|r| r == section_id)
1166 }
1167}
1168
1169#[derive(Debug, Deserialize)]
1170struct RawLintConfig {
1171 #[serde(default)]
1172 disabled_rules: Vec<String>,
1173 #[serde(default)]
1174 severity_overrides: HashMap<String, String>,
1175 #[serde(default)]
1176 exclude: Vec<String>,
1177 #[serde(default)]
1178 tag_namespaces: Vec<String>,
1179 #[serde(default)]
1180 ads: Option<RawAdsConfig>,
1181}
1182
1183#[derive(Debug, Deserialize)]
1184struct RawAdsConfig {
1185 #[serde(default)]
1186 enforce_status: Option<Vec<String>>,
1187 #[serde(default)]
1188 required: Option<Vec<String>>,
1189 #[serde(default)]
1190 severity: Option<String>,
1191}
1192
1193fn parse_severity(s: &str) -> Option<Severity> {
1195 match s {
1196 "error" => Some(Severity::Error),
1197 "warning" => Some(Severity::Warning),
1198 "info" => Some(Severity::Info),
1199 "hint" => Some(Severity::Hint),
1200 _ => None,
1201 }
1202}
1203
1204fn ads_config_from_raw(raw: RawAdsConfig) -> crate::error::Result<AdsConfig> {
1207 let mut config = AdsConfig::default();
1208
1209 if let Some(statuses) = raw.enforce_status {
1210 const VALID_STATUSES: &[&str] = &[
1211 "stable",
1212 "test",
1213 "experimental",
1214 "deprecated",
1215 "unsupported",
1216 ];
1217 let mut normalised = Vec::with_capacity(statuses.len());
1218 for s in statuses {
1219 let lower = s.to_lowercase();
1220 if !VALID_STATUSES.contains(&lower.as_str()) {
1221 return Err(crate::error::SigmaParserError::InvalidRule(format!(
1222 "invalid ads.enforce_status '{s}'; expected one of: {}",
1223 VALID_STATUSES.join(", ")
1224 )));
1225 }
1226 normalised.push(lower);
1227 }
1228 dedup_preserving_order(&mut normalised);
1229 config.enforce_status = normalised;
1230 }
1231
1232 if let Some(required) = raw.required {
1233 let mut ids = Vec::with_capacity(required.len());
1234 for id in required {
1235 let lower = id.to_lowercase();
1236 if AdsSection::from_id(&lower).is_none() {
1237 return Err(crate::error::SigmaParserError::InvalidRule(format!(
1238 "invalid ads.required section '{id}'; expected one of: {}",
1239 AdsSection::all()
1240 .iter()
1241 .map(|s| s.id())
1242 .collect::<Vec<_>>()
1243 .join(", ")
1244 )));
1245 }
1246 ids.push(lower);
1247 }
1248 dedup_preserving_order(&mut ids);
1249 config.required = ids;
1250 }
1251
1252 if let Some(sev) = raw.severity {
1253 config.severity = Some(parse_severity(&sev).ok_or_else(|| {
1254 crate::error::SigmaParserError::InvalidRule(format!(
1255 "invalid ads.severity '{sev}'; expected error, warning, info, or hint"
1256 ))
1257 })?);
1258 }
1259
1260 Ok(config)
1261}
1262
1263fn dedup_preserving_order(items: &mut Vec<String>) {
1267 let mut seen = HashSet::new();
1268 items.retain(|item| seen.insert(item.clone()));
1269}
1270
1271impl LintConfig {
1272 pub fn load(path: &Path) -> crate::error::Result<Self> {
1273 let content = std::fs::read_to_string(path)?;
1274 let raw: RawLintConfig = yaml_serde::from_str(&content)?;
1275
1276 let disabled_rules: HashSet<String> = raw.disabled_rules.into_iter().collect();
1277 let mut severity_overrides = HashMap::new();
1278 for (rule, sev_str) in &raw.severity_overrides {
1279 let sev = parse_severity(sev_str).ok_or_else(|| {
1280 crate::error::SigmaParserError::InvalidRule(format!(
1281 "invalid severity '{sev_str}' for rule '{rule}' in lint config"
1282 ))
1283 })?;
1284 severity_overrides.insert(rule.clone(), sev);
1285 }
1286
1287 let mut exclude_patterns = raw.exclude;
1288 dedup_preserving_order(&mut exclude_patterns);
1289
1290 let mut tag_namespaces: Vec<String> = raw
1291 .tag_namespaces
1292 .into_iter()
1293 .map(|s| s.to_lowercase())
1294 .collect();
1295 dedup_preserving_order(&mut tag_namespaces);
1296
1297 let ads = raw.ads.map(ads_config_from_raw).transpose()?;
1298
1299 Ok(LintConfig {
1300 disabled_rules,
1301 severity_overrides,
1302 exclude_patterns,
1303 tag_namespaces,
1304 ads,
1305 })
1306 }
1307
1308 pub fn find_in_ancestors(start_path: &Path) -> Option<std::path::PathBuf> {
1309 let dir = if start_path.is_file() {
1310 start_path.parent()?
1311 } else {
1312 start_path
1313 };
1314
1315 let mut current = dir;
1316 loop {
1317 let candidate = current.join(".rsigma-lint.yml");
1318 if candidate.is_file() {
1319 return Some(candidate);
1320 }
1321 let candidate_yaml = current.join(".rsigma-lint.yaml");
1322 if candidate_yaml.is_file() {
1323 return Some(candidate_yaml);
1324 }
1325 current = current.parent()?;
1326 }
1327 }
1328
1329 pub fn merge(&mut self, other: &LintConfig) {
1330 self.disabled_rules
1331 .extend(other.disabled_rules.iter().cloned());
1332 for (rule, sev) in &other.severity_overrides {
1333 self.severity_overrides.insert(rule.clone(), *sev);
1334 }
1335 self.exclude_patterns
1336 .extend(other.exclude_patterns.iter().cloned());
1337 dedup_preserving_order(&mut self.exclude_patterns);
1338 self.tag_namespaces
1339 .extend(other.tag_namespaces.iter().cloned());
1340 dedup_preserving_order(&mut self.tag_namespaces);
1341 if other.ads.is_some() {
1344 self.ads = other.ads.clone();
1345 }
1346 }
1347
1348 pub fn is_disabled(&self, rule: &LintRule) -> bool {
1349 self.disabled_rules.contains(&rule.to_string())
1350 }
1351
1352 pub fn build_exclude_set(&self) -> Option<globset::GlobSet> {
1353 if self.exclude_patterns.is_empty() {
1354 return None;
1355 }
1356 let mut builder = globset::GlobSetBuilder::new();
1357 for pat in &self.exclude_patterns {
1358 if let Ok(glob) = globset::GlobBuilder::new(pat)
1359 .literal_separator(false)
1360 .build()
1361 {
1362 builder.add(glob);
1363 }
1364 }
1365 builder.build().ok()
1366 }
1367}
1368
1369#[derive(Debug, Clone, Default)]
1374pub struct InlineSuppressions {
1375 pub disable_all: bool,
1376 pub file_disabled: HashSet<String>,
1377 pub line_disabled: HashMap<u32, Option<HashSet<String>>>,
1378}
1379
1380pub fn parse_inline_suppressions(text: &str) -> InlineSuppressions {
1381 let mut result = InlineSuppressions::default();
1382
1383 for (i, line) in text.lines().enumerate() {
1384 let trimmed = line.trim();
1385
1386 let comment = if let Some(pos) = find_yaml_comment(trimmed) {
1387 trimmed[pos + 1..].trim()
1388 } else {
1389 continue;
1390 };
1391
1392 if let Some(rest) = comment.strip_prefix("rsigma-disable-next-line") {
1393 let rest = rest.trim();
1394 let next_line = (i + 1) as u32;
1395 if rest.is_empty() {
1396 result.line_disabled.insert(next_line, None);
1397 } else {
1398 let rules: HashSet<String> = rest
1399 .split(',')
1400 .map(|s| s.trim().to_string())
1401 .filter(|s| !s.is_empty())
1402 .collect();
1403 if !rules.is_empty() {
1404 result
1405 .line_disabled
1406 .entry(next_line)
1407 .and_modify(|existing| {
1408 if let Some(existing_set) = existing {
1409 existing_set.extend(rules.iter().cloned());
1410 }
1411 })
1412 .or_insert(Some(rules));
1413 }
1414 }
1415 } else if let Some(rest) = comment.strip_prefix("rsigma-disable") {
1416 let rest = rest.trim();
1417 if rest.is_empty() {
1418 result.disable_all = true;
1419 } else {
1420 for rule in rest.split(',') {
1421 let rule = rule.trim();
1422 if !rule.is_empty() {
1423 result.file_disabled.insert(rule.to_string());
1424 }
1425 }
1426 }
1427 }
1428 }
1429
1430 result
1431}
1432
1433fn find_yaml_comment(line: &str) -> Option<usize> {
1434 let mut in_single = false;
1435 let mut in_double = false;
1436 for (i, c) in line.char_indices() {
1437 match c {
1438 '\'' if !in_double => in_single = !in_single,
1439 '"' if !in_single => in_double = !in_double,
1440 '#' if !in_single && !in_double => return Some(i),
1441 _ => {}
1442 }
1443 }
1444 None
1445}
1446
1447impl InlineSuppressions {
1448 pub fn is_suppressed(&self, warning: &LintWarning) -> bool {
1449 if self.disable_all {
1450 return true;
1451 }
1452
1453 let rule_name = warning.rule.to_string();
1454 if self.file_disabled.contains(&rule_name) {
1455 return true;
1456 }
1457
1458 if let Some(span) = &warning.span
1459 && let Some(line_rules) = self.line_disabled.get(&span.start_line)
1460 {
1461 return match line_rules {
1462 None => true,
1463 Some(rules) => rules.contains(&rule_name),
1464 };
1465 }
1466
1467 false
1468 }
1469}
1470
1471pub fn apply_suppressions(
1476 warnings: Vec<LintWarning>,
1477 config: &LintConfig,
1478 inline: &InlineSuppressions,
1479) -> Vec<LintWarning> {
1480 warnings
1481 .into_iter()
1482 .filter(|w| !config.is_disabled(&w.rule))
1483 .filter(|w| !inline.is_suppressed(w))
1484 .map(|mut w| {
1485 let rule_name = w.rule.to_string();
1486 if let Some(sev) = config.severity_overrides.get(&rule_name) {
1487 w.severity = *sev;
1488 }
1489 w
1490 })
1491 .collect()
1492}
1493
1494pub fn lint_yaml_str_with_config(text: &str, config: &LintConfig) -> Vec<LintWarning> {
1495 let warnings = lint_yaml_str_ext(text, &config.tag_namespaces, config.ads.as_ref());
1496 let inline = parse_inline_suppressions(text);
1497 apply_suppressions(warnings, config, &inline)
1498}
1499
1500pub fn lint_yaml_file_with_config(
1501 path: &Path,
1502 config: &LintConfig,
1503) -> crate::error::Result<FileLintResult> {
1504 let content = std::fs::read_to_string(path)?;
1505 let warnings = lint_yaml_str_with_config(&content, config);
1506 Ok(FileLintResult {
1507 path: path.to_path_buf(),
1508 warnings,
1509 })
1510}
1511
1512pub fn lint_yaml_directory_with_config(
1513 dir: &Path,
1514 config: &LintConfig,
1515) -> crate::error::Result<Vec<FileLintResult>> {
1516 lint_directory_impl(dir, Some(config))
1517}
1518
1519#[cfg(test)]
1524mod tests {
1525 use super::*;
1526
1527 fn yaml_value(yaml: &str) -> Value {
1528 yaml_serde::from_str(yaml).unwrap()
1529 }
1530
1531 fn lint(yaml: &str) -> Vec<LintWarning> {
1532 lint_yaml_value(&yaml_value(yaml))
1533 }
1534
1535 fn has_rule(warnings: &[LintWarning], rule: LintRule) -> bool {
1536 warnings.iter().any(|w| w.rule == rule)
1537 }
1538
1539 fn has_no_rule(warnings: &[LintWarning], rule: LintRule) -> bool {
1540 !has_rule(warnings, rule)
1541 }
1542
1543 #[test]
1544 fn valid_detection_rule_no_errors() {
1545 let w = lint(
1546 r#"
1547title: Test Rule
1548id: 929a690e-bef0-4204-a928-ef5e620d6fcc
1549status: test
1550logsource:
1551 category: process_creation
1552 product: windows
1553detection:
1554 selection:
1555 CommandLine|contains: 'whoami'
1556 condition: selection
1557level: medium
1558tags:
1559 - attack.execution
1560 - attack.t1059
1561"#,
1562 );
1563 let errors: Vec<_> = w.iter().filter(|w| w.severity == Severity::Error).collect();
1564 assert!(errors.is_empty(), "unexpected errors: {errors:?}");
1565 }
1566
1567 #[test]
1568 fn not_a_mapping() {
1569 let v: yaml_serde::Value = yaml_serde::from_str("- item1\n- item2").unwrap();
1570 let w = lint_yaml_value(&v);
1571 assert!(has_rule(&w, LintRule::NotAMapping));
1572 }
1573
1574 #[test]
1575 fn lint_yaml_str_produces_spans() {
1576 let text = r#"title: Test
1577status: invalid_status
1578logsource:
1579 category: test
1580detection:
1581 selection:
1582 field: value
1583 condition: selection
1584level: medium
1585"#;
1586 let warnings = lint_yaml_str(text);
1587 let invalid_status = warnings.iter().find(|w| w.rule == LintRule::InvalidStatus);
1588 assert!(invalid_status.is_some(), "expected InvalidStatus warning");
1589 let span = invalid_status.unwrap().span;
1590 assert!(span.is_some(), "expected span to be resolved");
1591 assert_eq!(span.unwrap().start_line, 1);
1592 }
1593
1594 #[test]
1595 fn yaml_parse_error_uses_correct_rule() {
1596 let text = "title: [unclosed";
1597 let warnings = lint_yaml_str(text);
1598 assert!(has_rule(&warnings, LintRule::YamlParseError));
1599 assert!(has_no_rule(&warnings, LintRule::MissingTitle));
1600 }
1601
1602 #[test]
1603 fn action_global_skipped() {
1604 let w = lint(
1605 r#"
1606action: global
1607title: Global Template
1608logsource:
1609 product: windows
1610"#,
1611 );
1612 assert!(w.is_empty());
1613 }
1614
1615 #[test]
1616 fn action_reset_skipped() {
1617 let w = lint(
1618 r#"
1619action: reset
1620"#,
1621 );
1622 assert!(w.is_empty());
1623 }
1624
1625 #[test]
1626 fn resolve_path_to_span_root() {
1627 let text = "title: Test\nstatus: test\n";
1628 let span = resolve_path_to_span(text, "/");
1629 assert!(span.is_some());
1630 assert_eq!(span.unwrap().start_line, 0);
1631 }
1632
1633 #[test]
1634 fn resolve_path_to_span_top_level_key() {
1635 let text = "title: Test\nstatus: test\nlevel: high\n";
1636 let span = resolve_path_to_span(text, "/status");
1637 assert!(span.is_some());
1638 assert_eq!(span.unwrap().start_line, 1);
1639 }
1640
1641 #[test]
1642 fn resolve_path_to_span_nested_key() {
1643 let text = "title: Test\nlogsource:\n category: test\n product: windows\n";
1644 let span = resolve_path_to_span(text, "/logsource/product");
1645 assert!(span.is_some());
1646 assert_eq!(span.unwrap().start_line, 3);
1647 }
1648
1649 #[test]
1650 fn resolve_path_to_span_missing_key() {
1651 let text = "title: Test\nstatus: test\n";
1652 let span = resolve_path_to_span(text, "/nonexistent");
1653 assert!(span.is_none());
1654 }
1655
1656 #[test]
1657 fn multi_doc_yaml_lints_all_documents() {
1658 let text = r#"title: Rule 1
1659logsource:
1660 category: test
1661detection:
1662 selection:
1663 field: value
1664 condition: selection
1665level: medium
1666---
1667title: Rule 2
1668status: bad_status
1669logsource:
1670 category: test
1671detection:
1672 selection:
1673 field: value
1674 condition: selection
1675level: medium
1676"#;
1677 let warnings = lint_yaml_str(text);
1678 assert!(has_rule(&warnings, LintRule::InvalidStatus));
1679 }
1680
1681 #[test]
1682 fn severity_display() {
1683 assert_eq!(format!("{}", Severity::Error), "error");
1684 assert_eq!(format!("{}", Severity::Warning), "warning");
1685 assert_eq!(format!("{}", Severity::Info), "info");
1686 assert_eq!(format!("{}", Severity::Hint), "hint");
1687 }
1688
1689 #[test]
1690 fn file_lint_result_has_errors() {
1691 let result = FileLintResult {
1692 path: std::path::PathBuf::from("test.yml"),
1693 warnings: vec![
1694 warning(LintRule::TitleTooLong, "too long", "/title"),
1695 err(
1696 LintRule::MissingCondition,
1697 "missing",
1698 "/detection/condition",
1699 ),
1700 ],
1701 };
1702 assert!(result.has_errors());
1703 assert_eq!(result.error_count(), 1);
1704 assert_eq!(result.warning_count(), 1);
1705 }
1706
1707 #[test]
1708 fn file_lint_result_no_errors() {
1709 let result = FileLintResult {
1710 path: std::path::PathBuf::from("test.yml"),
1711 warnings: vec![warning(LintRule::TitleTooLong, "too long", "/title")],
1712 };
1713 assert!(!result.has_errors());
1714 assert_eq!(result.error_count(), 0);
1715 assert_eq!(result.warning_count(), 1);
1716 }
1717
1718 #[test]
1719 fn file_lint_result_empty() {
1720 let result = FileLintResult {
1721 path: std::path::PathBuf::from("test.yml"),
1722 warnings: vec![],
1723 };
1724 assert!(!result.has_errors());
1725 assert_eq!(result.error_count(), 0);
1726 assert_eq!(result.warning_count(), 0);
1727 }
1728
1729 #[test]
1730 fn lint_warning_display() {
1731 let w = err(
1732 LintRule::MissingTitle,
1733 "missing required field 'title'",
1734 "/title",
1735 );
1736 let display = format!("{w}");
1737 assert!(display.contains("error"));
1738 assert!(display.contains("missing_title"));
1739 assert!(display.contains("/title"));
1740 }
1741
1742 #[test]
1743 fn file_lint_result_info_count() {
1744 let result = FileLintResult {
1745 path: std::path::PathBuf::from("test.yml"),
1746 warnings: vec![
1747 info(LintRule::MissingDescription, "missing desc", "/description"),
1748 info(LintRule::MissingAuthor, "missing author", "/author"),
1749 warning(LintRule::TitleTooLong, "too long", "/title"),
1750 ],
1751 };
1752 assert_eq!(result.info_count(), 2);
1753 assert_eq!(result.warning_count(), 1);
1754 assert_eq!(result.error_count(), 0);
1755 assert!(!result.has_errors());
1756 }
1757
1758 #[test]
1759 fn parse_inline_disable_all() {
1760 let text = "# rsigma-disable\ntitle: Test\n";
1761 let sup = parse_inline_suppressions(text);
1762 assert!(sup.disable_all);
1763 }
1764
1765 #[test]
1766 fn parse_inline_disable_specific_rules() {
1767 let text = "# rsigma-disable missing_description, missing_author\ntitle: Test\n";
1768 let sup = parse_inline_suppressions(text);
1769 assert!(!sup.disable_all);
1770 assert!(sup.file_disabled.contains("missing_description"));
1771 assert!(sup.file_disabled.contains("missing_author"));
1772 }
1773
1774 #[test]
1775 fn parse_inline_disable_next_line_all() {
1776 let text = "# rsigma-disable-next-line\ntitle: Test\n";
1777 let sup = parse_inline_suppressions(text);
1778 assert!(!sup.disable_all);
1779 assert!(sup.line_disabled.contains_key(&1));
1780 assert!(sup.line_disabled[&1].is_none());
1781 }
1782
1783 #[test]
1784 fn parse_inline_disable_next_line_specific() {
1785 let text = "title: Test\n# rsigma-disable-next-line missing_level\nlevel: medium\n";
1786 let sup = parse_inline_suppressions(text);
1787 assert!(sup.line_disabled.contains_key(&2));
1788 let rules = sup.line_disabled[&2].as_ref().unwrap();
1789 assert!(rules.contains("missing_level"));
1790 }
1791
1792 #[test]
1793 fn parse_inline_no_comments() {
1794 let text = "title: Test\nstatus: test\n";
1795 let sup = parse_inline_suppressions(text);
1796 assert!(!sup.disable_all);
1797 assert!(sup.file_disabled.is_empty());
1798 assert!(sup.line_disabled.is_empty());
1799 }
1800
1801 #[test]
1802 fn parse_inline_comment_in_quoted_string() {
1803 let text = "description: 'no # rsigma-disable here'\ntitle: Test\n";
1804 let sup = parse_inline_suppressions(text);
1805 assert!(!sup.disable_all);
1806 assert!(sup.file_disabled.is_empty());
1807 }
1808
1809 #[test]
1810 fn apply_suppressions_disables_rule() {
1811 let warnings = vec![
1812 info(LintRule::MissingDescription, "desc", "/description"),
1813 info(LintRule::MissingAuthor, "author", "/author"),
1814 warning(LintRule::TitleTooLong, "title", "/title"),
1815 ];
1816 let mut config = LintConfig::default();
1817 config
1818 .disabled_rules
1819 .insert("missing_description".to_string());
1820 let inline = InlineSuppressions::default();
1821
1822 let result = apply_suppressions(warnings, &config, &inline);
1823 assert_eq!(result.len(), 2);
1824 assert!(
1825 result
1826 .iter()
1827 .all(|w| w.rule != LintRule::MissingDescription)
1828 );
1829 }
1830
1831 #[test]
1832 fn apply_suppressions_severity_override() {
1833 let warnings = vec![warning(LintRule::TitleTooLong, "title too long", "/title")];
1834 let mut config = LintConfig::default();
1835 config
1836 .severity_overrides
1837 .insert("title_too_long".to_string(), Severity::Info);
1838 let inline = InlineSuppressions::default();
1839
1840 let result = apply_suppressions(warnings, &config, &inline);
1841 assert_eq!(result.len(), 1);
1842 assert_eq!(result[0].severity, Severity::Info);
1843 }
1844
1845 #[test]
1846 fn apply_suppressions_inline_file_disable() {
1847 let warnings = vec![
1848 info(LintRule::MissingDescription, "desc", "/description"),
1849 info(LintRule::MissingAuthor, "author", "/author"),
1850 ];
1851 let config = LintConfig::default();
1852 let mut inline = InlineSuppressions::default();
1853 inline.file_disabled.insert("missing_author".to_string());
1854
1855 let result = apply_suppressions(warnings, &config, &inline);
1856 assert_eq!(result.len(), 1);
1857 assert_eq!(result[0].rule, LintRule::MissingDescription);
1858 }
1859
1860 #[test]
1861 fn apply_suppressions_inline_disable_all() {
1862 let warnings = vec![
1863 err(LintRule::MissingTitle, "title", "/title"),
1864 warning(LintRule::TitleTooLong, "long", "/title"),
1865 ];
1866 let config = LintConfig::default();
1867 let inline = InlineSuppressions {
1868 disable_all: true,
1869 ..Default::default()
1870 };
1871
1872 let result = apply_suppressions(warnings, &config, &inline);
1873 assert!(result.is_empty());
1874 }
1875
1876 #[test]
1877 fn apply_suppressions_inline_next_line() {
1878 let mut w1 = warning(LintRule::TitleTooLong, "long", "/title");
1879 w1.span = Some(Span {
1880 start_line: 5,
1881 start_col: 0,
1882 end_line: 5,
1883 end_col: 10,
1884 });
1885 let mut w2 = err(LintRule::InvalidStatus, "bad", "/status");
1886 w2.span = Some(Span {
1887 start_line: 6,
1888 start_col: 0,
1889 end_line: 6,
1890 end_col: 10,
1891 });
1892
1893 let config = LintConfig::default();
1894 let mut inline = InlineSuppressions::default();
1895 inline.line_disabled.insert(5, None);
1896
1897 let result = apply_suppressions(vec![w1, w2], &config, &inline);
1898 assert_eq!(result.len(), 1);
1899 assert_eq!(result[0].rule, LintRule::InvalidStatus);
1900 }
1901
1902 #[test]
1903 fn lint_with_config_disables_rules() {
1904 let text = r#"title: Test
1905logsource:
1906 category: test
1907detection:
1908 selection:
1909 field: value
1910 condition: selection
1911level: medium
1912"#;
1913 let mut config = LintConfig::default();
1914 config
1915 .disabled_rules
1916 .insert("missing_description".to_string());
1917 config.disabled_rules.insert("missing_author".to_string());
1918
1919 let warnings = lint_yaml_str_with_config(text, &config);
1920 assert!(
1921 !warnings
1922 .iter()
1923 .any(|w| w.rule == LintRule::MissingDescription)
1924 );
1925 assert!(!warnings.iter().any(|w| w.rule == LintRule::MissingAuthor));
1926 }
1927
1928 #[test]
1929 fn lint_with_inline_disable_next_line() {
1930 let text = r#"title: Test
1931# rsigma-disable-next-line missing_level
1932logsource:
1933 category: test
1934detection:
1935 selection:
1936 field: value
1937 condition: selection
1938"#;
1939 let config = LintConfig::default();
1940 let warnings = lint_yaml_str_with_config(text, &config);
1941 assert!(warnings.iter().any(|w| w.rule == LintRule::MissingLevel));
1942 }
1943
1944 #[test]
1945 fn lint_with_inline_file_disable() {
1946 let text = r#"# rsigma-disable missing_description, missing_author
1947title: Test
1948logsource:
1949 category: test
1950detection:
1951 selection:
1952 field: value
1953 condition: selection
1954level: medium
1955"#;
1956 let config = LintConfig::default();
1957 let warnings = lint_yaml_str_with_config(text, &config);
1958 assert!(
1959 !warnings
1960 .iter()
1961 .any(|w| w.rule == LintRule::MissingDescription)
1962 );
1963 assert!(!warnings.iter().any(|w| w.rule == LintRule::MissingAuthor));
1964 }
1965
1966 #[test]
1967 fn lint_with_inline_disable_all() {
1968 let text = r#"# rsigma-disable
1969title: Test
1970status: invalid_status
1971logsource:
1972 category: test
1973detection:
1974 selection:
1975 field: value
1976 condition: selection
1977"#;
1978 let config = LintConfig::default();
1979 let warnings = lint_yaml_str_with_config(text, &config);
1980 assert!(warnings.is_empty());
1981 }
1982
1983 #[test]
1984 fn lint_config_merge() {
1985 let mut base = LintConfig::default();
1986 base.disabled_rules.insert("rule_a".to_string());
1987 base.severity_overrides
1988 .insert("rule_b".to_string(), Severity::Info);
1989
1990 let other = LintConfig {
1991 disabled_rules: ["rule_c".to_string()].into_iter().collect(),
1992 severity_overrides: [("rule_d".to_string(), Severity::Hint)]
1993 .into_iter()
1994 .collect(),
1995 exclude_patterns: vec!["test/**".to_string()],
1996 tag_namespaces: vec!["myns".to_string()],
1997 ads: None,
1998 };
1999
2000 base.merge(&other);
2001 assert!(base.disabled_rules.contains("rule_a"));
2002 assert!(base.disabled_rules.contains("rule_c"));
2003 assert_eq!(base.severity_overrides.get("rule_b"), Some(&Severity::Info));
2004 assert_eq!(base.severity_overrides.get("rule_d"), Some(&Severity::Hint));
2005 assert_eq!(base.exclude_patterns, vec!["test/**".to_string()]);
2006 assert!(base.tag_namespaces.contains(&"myns".to_string()));
2007 }
2008
2009 #[test]
2010 fn lint_config_merge_dedups_lists() {
2011 let mut base = LintConfig {
2012 exclude_patterns: vec!["config/**".to_string(), "shared/**".to_string()],
2013 tag_namespaces: vec!["myorg".to_string(), "shared".to_string()],
2014 ..Default::default()
2015 };
2016 let other = LintConfig {
2017 exclude_patterns: vec!["shared/**".to_string(), "extra/**".to_string()],
2019 tag_namespaces: vec!["shared".to_string(), "internal".to_string()],
2020 ..Default::default()
2021 };
2022
2023 base.merge(&other);
2024
2025 assert_eq!(
2026 base.exclude_patterns,
2027 vec![
2028 "config/**".to_string(),
2029 "shared/**".to_string(),
2030 "extra/**".to_string()
2031 ]
2032 );
2033 assert_eq!(
2034 base.tag_namespaces,
2035 vec![
2036 "myorg".to_string(),
2037 "shared".to_string(),
2038 "internal".to_string()
2039 ]
2040 );
2041 }
2042
2043 #[test]
2044 fn lint_config_load_dedups_and_normalises() {
2045 let yaml = r#"
2046exclude:
2047 - "config/**"
2048 - "config/**"
2049tag_namespaces:
2050 - MyOrg
2051 - myorg
2052 - internal
2053"#;
2054 let mut tmp = tempfile::NamedTempFile::with_suffix(".yml").unwrap();
2055 std::io::Write::write_all(&mut tmp, yaml.as_bytes()).unwrap();
2056 let config = LintConfig::load(tmp.path()).unwrap();
2057
2058 assert_eq!(config.exclude_patterns, vec!["config/**".to_string()]);
2059 assert_eq!(
2061 config.tag_namespaces,
2062 vec!["myorg".to_string(), "internal".to_string()]
2063 );
2064 }
2065
2066 #[test]
2067 fn lint_config_is_disabled() {
2068 let mut config = LintConfig::default();
2069 config.disabled_rules.insert("missing_title".to_string());
2070 assert!(config.is_disabled(&LintRule::MissingTitle));
2071 assert!(!config.is_disabled(&LintRule::EmptyTitle));
2072 }
2073
2074 #[test]
2075 fn find_yaml_comment_basic() {
2076 assert_eq!(find_yaml_comment("# comment"), Some(0));
2077 assert_eq!(find_yaml_comment("key: value # comment"), Some(11));
2078 assert_eq!(find_yaml_comment("key: 'value # not comment'"), None);
2079 assert_eq!(find_yaml_comment("key: \"value # not comment\""), None);
2080 assert_eq!(find_yaml_comment("key: value"), None);
2081 }
2082
2083 #[test]
2084 fn no_fix_for_unfixable_rule() {
2085 let w = lint(
2086 r#"
2087title: Test
2088logsource:
2089 category: test
2090"#,
2091 );
2092 assert!(has_rule(&w, LintRule::MissingDetection));
2093 let fix = w
2094 .iter()
2095 .find(|w| w.rule == LintRule::MissingDetection)
2096 .and_then(|w| w.fix.as_ref());
2097 assert!(fix.is_none());
2098 }
2099
2100 #[test]
2101 fn lint_config_exclude_from_yaml() {
2102 let yaml = r#"
2103disabled_rules:
2104 - missing_description
2105exclude:
2106 - "config/**"
2107 - "**/unsupported/**"
2108"#;
2109 let tmp = std::env::temp_dir().join("rsigma_test_exclude.yml");
2110 std::fs::write(&tmp, yaml).unwrap();
2111 let config = LintConfig::load(&tmp).unwrap();
2112 std::fs::remove_file(&tmp).ok();
2113
2114 assert!(config.disabled_rules.contains("missing_description"));
2115 assert_eq!(config.exclude_patterns.len(), 2);
2116 assert_eq!(config.exclude_patterns[0], "config/**");
2117 assert_eq!(config.exclude_patterns[1], "**/unsupported/**");
2118 }
2119
2120 #[test]
2121 fn lint_config_build_exclude_set_empty() {
2122 let config = LintConfig::default();
2123 assert!(config.build_exclude_set().is_none());
2124 }
2125
2126 #[test]
2127 fn lint_config_build_exclude_set_matches() {
2128 let config = LintConfig {
2129 exclude_patterns: vec!["config/**".to_string()],
2130 ..Default::default()
2131 };
2132 let gs = config.build_exclude_set().expect("should build");
2133 assert!(gs.is_match("config/data_mapping/foo.yaml"));
2134 assert!(gs.is_match("config/nested/deep/bar.yml"));
2135 assert!(!gs.is_match("rules/windows/test.yml"));
2136 }
2137
2138 #[test]
2139 fn cross_ref_version_mismatch_within_file() {
2140 let yaml = r#"
2144title: Base Rule
2145name: base_rule
2146sigma-version: 2
2147logsource:
2148 category: test
2149detection:
2150 selection:
2151 EventID: 1
2152 condition: selection
2153---
2154title: Brute Force
2155sigma-version: 3
2156correlation:
2157 type: event_count
2158 rules:
2159 - base_rule
2160 group-by:
2161 - SourceIP
2162 timespan: 5m
2163 condition:
2164 gte: 10
2165"#;
2166 let w = lint_yaml_str(yaml);
2167 assert!(has_rule(&w, LintRule::SigmaVersionMismatch));
2168 assert!(has_no_rule(&w, LintRule::UnknownRuleReference));
2169 }
2170
2171 #[test]
2172 fn cross_ref_matching_version_no_mismatch() {
2173 let yaml = r#"
2174title: Base Rule
2175name: base_rule
2176sigma-version: 3
2177logsource:
2178 category: test
2179detection:
2180 selection:
2181 EventID: 1
2182 condition: selection
2183---
2184title: Brute Force
2185sigma-version: 3
2186correlation:
2187 type: event_count
2188 rules:
2189 - base_rule
2190 group-by:
2191 - SourceIP
2192 timespan: 5m
2193 condition:
2194 gte: 10
2195"#;
2196 assert!(has_no_rule(
2197 &lint_yaml_str(yaml),
2198 LintRule::SigmaVersionMismatch
2199 ));
2200 }
2201
2202 #[test]
2203 fn filter_reference_by_title_is_deprecated() {
2204 let yaml = r#"
2205title: Base Rule
2206id: 00000000-0000-4000-8000-000000000001
2207name: base_rule
2208logsource:
2209 category: test
2210detection:
2211 selection:
2212 EventID: 1
2213 condition: selection
2214---
2215title: Filter by Title
2216logsource:
2217 category: test
2218filter:
2219 rules: [Base Rule]
2220 selection:
2221 User: admin
2222 condition: not selection
2223"#;
2224 assert!(has_rule(
2225 &lint_yaml_str(yaml),
2226 LintRule::FilterReferenceByTitle
2227 ));
2228 }
2229
2230 #[test]
2231 fn filter_reference_by_name_is_not_deprecated() {
2232 let yaml = r#"
2233title: Base Rule
2234name: base_rule
2235logsource:
2236 category: test
2237detection:
2238 selection:
2239 EventID: 1
2240 condition: selection
2241---
2242title: Filter by Name
2243logsource:
2244 category: test
2245filter:
2246 rules: [base_rule]
2247 selection:
2248 User: admin
2249 condition: not selection
2250"#;
2251 assert!(has_no_rule(
2252 &lint_yaml_str(yaml),
2253 LintRule::FilterReferenceByTitle
2254 ));
2255 }
2256
2257 #[test]
2258 fn filter_reference_by_name_wins_over_another_rules_title() {
2259 let yaml = r#"
2260title: Stable Target
2261name: target
2262logsource:
2263 category: test
2264detection:
2265 selection:
2266 EventID: 1
2267 condition: selection
2268---
2269title: target
2270logsource:
2271 category: test
2272detection:
2273 selection:
2274 EventID: 2
2275 condition: selection
2276---
2277title: Filter by Name
2278logsource:
2279 category: test
2280filter:
2281 rules: [target]
2282 selection:
2283 User: admin
2284 condition: not selection
2285"#;
2286 assert!(has_no_rule(
2287 &lint_yaml_str(yaml),
2288 LintRule::FilterReferenceByTitle
2289 ));
2290 }
2291
2292 #[test]
2293 fn filter_reference_ignores_correlation_identities() {
2294 let yaml = r#"
2295title: brute_force
2296logsource:
2297 category: test
2298detection:
2299 selection:
2300 EventID: 4625
2301 condition: selection
2302---
2303title: Brute Force Correlation
2304name: brute_force
2305correlation:
2306 type: event_count
2307 rules: [brute_force]
2308 group-by: [User]
2309 timespan: 5m
2310 condition:
2311 gte: 10
2312---
2313title: Filter Brute Force
2314logsource:
2315 category: test
2316filter:
2317 rules: [brute_force]
2318 selection:
2319 User: admin
2320 condition: not selection
2321"#;
2322 let warnings = lint_yaml_str(yaml);
2323 let filter_title_refs = warnings
2324 .iter()
2325 .filter(|w| w.rule == LintRule::FilterReferenceByTitle)
2326 .count();
2327 assert_eq!(filter_title_refs, 1);
2328 }
2329
2330 #[test]
2331 fn cross_ref_unknown_only_with_complete_index() {
2332 let yaml = r#"
2333title: Brute Force
2334correlation:
2335 type: event_count
2336 rules:
2337 - nonexistent_rule
2338 group-by:
2339 - SourceIP
2340 timespan: 5m
2341 condition:
2342 gte: 10
2343"#;
2344 assert!(has_no_rule(
2347 &lint_yaml_str(yaml),
2348 LintRule::UnknownRuleReference
2349 ));
2350
2351 let tmp = tempfile::tempdir().unwrap();
2353 std::fs::write(tmp.path().join("corr.yml"), yaml).unwrap();
2354 let results = lint_yaml_directory(tmp.path()).unwrap();
2355 assert!(
2356 results
2357 .iter()
2358 .flat_map(|r| &r.warnings)
2359 .any(|w| w.rule == LintRule::UnknownRuleReference)
2360 );
2361 }
2362
2363 #[test]
2364 fn cross_ref_resolves_across_files() {
2365 let tmp = tempfile::tempdir().unwrap();
2368 std::fs::write(
2369 tmp.path().join("base.yml"),
2370 r#"
2371title: Base Rule
2372name: base_rule
2373sigma-version: 2
2374logsource:
2375 category: test
2376detection:
2377 selection:
2378 EventID: 1
2379 condition: selection
2380"#,
2381 )
2382 .unwrap();
2383 std::fs::write(
2384 tmp.path().join("corr.yml"),
2385 r#"
2386title: Brute Force
2387sigma-version: 3
2388correlation:
2389 type: event_count
2390 rules:
2391 - base_rule
2392 group-by:
2393 - SourceIP
2394 timespan: 5m
2395 condition:
2396 gte: 10
2397"#,
2398 )
2399 .unwrap();
2400 let results = lint_yaml_directory(tmp.path()).unwrap();
2401 let all: Vec<_> = results.iter().flat_map(|r| &r.warnings).collect();
2402 assert!(all.iter().any(|w| w.rule == LintRule::SigmaVersionMismatch));
2403 assert!(!all.iter().any(|w| w.rule == LintRule::UnknownRuleReference));
2404 }
2405
2406 #[test]
2407 fn lint_directory_with_excludes() {
2408 let tmp = tempfile::tempdir().unwrap();
2409 let rules_dir = tmp.path().join("rules");
2410 let config_dir = tmp.path().join("config");
2411 std::fs::create_dir_all(&rules_dir).unwrap();
2412 std::fs::create_dir_all(&config_dir).unwrap();
2413
2414 std::fs::write(
2415 rules_dir.join("good.yml"),
2416 r#"
2417title: Good Rule
2418logsource:
2419 category: test
2420detection:
2421 sel:
2422 field: value
2423 condition: sel
2424level: medium
2425"#,
2426 )
2427 .unwrap();
2428
2429 std::fs::write(
2430 config_dir.join("mapping.yaml"),
2431 r#"
2432Title: Logon
2433Channel: Security
2434EventID: 4624
2435"#,
2436 )
2437 .unwrap();
2438
2439 let no_exclude = LintConfig::default();
2440 let results = lint_yaml_directory_with_config(tmp.path(), &no_exclude).unwrap();
2441 let config_warnings: Vec<_> = results
2442 .iter()
2443 .filter(|r| r.path.to_string_lossy().contains("config"))
2444 .flat_map(|r| &r.warnings)
2445 .collect();
2446 assert!(
2447 !config_warnings.is_empty(),
2448 "config file should produce warnings without excludes"
2449 );
2450
2451 let with_exclude = LintConfig {
2452 exclude_patterns: vec!["config/**".to_string()],
2453 ..Default::default()
2454 };
2455 let results = lint_yaml_directory_with_config(tmp.path(), &with_exclude).unwrap();
2456 let config_results: Vec<_> = results
2457 .iter()
2458 .filter(|r| r.path.to_string_lossy().contains("config"))
2459 .collect();
2460 assert!(config_results.is_empty(), "config file should be excluded");
2461
2462 let rule_results: Vec<_> = results
2463 .iter()
2464 .filter(|r| r.path.to_string_lossy().contains("good.yml"))
2465 .collect();
2466 assert_eq!(rule_results.len(), 1);
2467 }
2468
2469 #[test]
2470 fn all_lint_keys_are_cached() {
2471 const ALL_LINT_KEYS: &[&str] = &[
2472 "action",
2473 "author",
2474 "condition",
2475 "correlation",
2476 "date",
2477 "description",
2478 "detection",
2479 "field",
2480 "filter",
2481 "generate",
2482 "group-by",
2483 "id",
2484 "level",
2485 "logsource",
2486 "modified",
2487 "name",
2488 "rules",
2489 "selection",
2490 "status",
2491 "tags",
2492 "taxonomy",
2493 "timeframe",
2494 "timespan",
2495 "title",
2496 "type",
2497 ];
2498 for key_str in ALL_LINT_KEYS {
2499 assert!(KEY_CACHE.contains_key(key_str), "key not cached: {key_str}");
2500 }
2501 }
2502
2503 #[test]
2504 fn extra_tag_namespace_suppresses_warning() {
2505 let text = r#"title: Test
2506logsource:
2507 category: test
2508detection:
2509 selection:
2510 field: value
2511 condition: selection
2512level: medium
2513tags:
2514 - myorg.custom_tag
2515"#;
2516 let warnings = lint_yaml_str(text);
2518 assert!(has_rule(&warnings, LintRule::UnknownTagNamespace));
2519
2520 let config = LintConfig {
2522 tag_namespaces: vec!["myorg".to_string()],
2523 ..Default::default()
2524 };
2525 let warnings = lint_yaml_str_with_config(text, &config);
2526 assert!(has_no_rule(&warnings, LintRule::UnknownTagNamespace));
2527 }
2528
2529 #[test]
2530 fn extra_tag_namespace_from_config_file() {
2531 let yaml = r#"
2532tag_namespaces:
2533 - myorg
2534 - internal
2535"#;
2536 let mut tmp = tempfile::NamedTempFile::with_suffix(".yml").unwrap();
2537 std::io::Write::write_all(&mut tmp, yaml.as_bytes()).unwrap();
2538 let config = LintConfig::load(tmp.path()).unwrap();
2539
2540 assert!(config.tag_namespaces.contains(&"myorg".to_string()));
2541 assert!(config.tag_namespaces.contains(&"internal".to_string()));
2542 }
2543}