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 lint_directory_impl(
1000 dir: &Path,
1001 config: Option<&LintConfig>,
1002) -> crate::error::Result<Vec<FileLintResult>> {
1003 let exclude_set = config.and_then(LintConfig::build_exclude_set);
1004 let mut files = Vec::new();
1005 let mut visited = HashSet::new();
1006 crate::walk::collect_yaml_files(dir, dir, exclude_set.as_ref(), &mut files, &mut visited)?;
1007
1008 let mut index = RuleIndex::new(true);
1010 let mut contents: Vec<(std::path::PathBuf, std::result::Result<String, String>)> =
1011 Vec::with_capacity(files.len());
1012 for path in files {
1013 match std::fs::read_to_string(&path) {
1014 Ok(text) => {
1015 index.add_text(&text);
1016 contents.push((path, Ok(text)));
1017 }
1018 Err(e) => contents.push((path, Err(format!("error reading file: {e}")))),
1019 }
1020 }
1021
1022 let mut results = Vec::with_capacity(contents.len());
1023 for (path, content) in contents {
1024 match content {
1025 Ok(text) => {
1026 let warnings = match config {
1027 Some(cfg) => {
1028 let w = lint_yaml_str_indexed(
1029 &text,
1030 &cfg.tag_namespaces,
1031 cfg.ads.as_ref(),
1032 Some(&index),
1033 );
1034 apply_suppressions(w, cfg, &parse_inline_suppressions(&text))
1035 }
1036 None => lint_yaml_str_indexed(&text, &[], None, Some(&index)),
1037 };
1038 results.push(FileLintResult { path, warnings });
1039 }
1040 Err(msg) => results.push(FileLintResult {
1041 path,
1042 warnings: vec![err(LintRule::FileReadError, msg, "/")],
1043 }),
1044 }
1045 }
1046 Ok(results)
1047}
1048
1049pub fn lint_yaml_directory(dir: &Path) -> crate::error::Result<Vec<FileLintResult>> {
1051 lint_directory_impl(dir, None)
1052}
1053
1054#[derive(Debug, Clone, Default, Serialize)]
1060pub struct LintConfig {
1061 pub disabled_rules: HashSet<String>,
1062 pub severity_overrides: HashMap<String, Severity>,
1063 pub exclude_patterns: Vec<String>,
1064 pub tag_namespaces: Vec<String>,
1066 #[serde(skip_serializing_if = "Option::is_none")]
1069 pub ads: Option<AdsConfig>,
1070}
1071
1072#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1079pub struct AdsConfig {
1080 pub enforce_status: Vec<String>,
1082 pub required: Vec<String>,
1084 #[serde(skip_serializing_if = "Option::is_none")]
1087 pub severity: Option<Severity>,
1088}
1089
1090impl Default for AdsConfig {
1091 fn default() -> Self {
1092 AdsConfig {
1093 enforce_status: vec!["stable".to_string()],
1094 required: AdsSection::all()
1095 .iter()
1096 .map(|s| s.id().to_string())
1097 .collect(),
1098 severity: None,
1099 }
1100 }
1101}
1102
1103impl AdsConfig {
1104 pub fn enforces_status(&self, status: Option<&str>) -> bool {
1107 match status {
1108 Some(s) => self.enforce_status.iter().any(|e| e == s),
1109 None => false,
1110 }
1111 }
1112
1113 pub fn requires(&self, section_id: &str) -> bool {
1115 self.required.iter().any(|r| r == section_id)
1116 }
1117}
1118
1119#[derive(Debug, Deserialize)]
1120struct RawLintConfig {
1121 #[serde(default)]
1122 disabled_rules: Vec<String>,
1123 #[serde(default)]
1124 severity_overrides: HashMap<String, String>,
1125 #[serde(default)]
1126 exclude: Vec<String>,
1127 #[serde(default)]
1128 tag_namespaces: Vec<String>,
1129 #[serde(default)]
1130 ads: Option<RawAdsConfig>,
1131}
1132
1133#[derive(Debug, Deserialize)]
1134struct RawAdsConfig {
1135 #[serde(default)]
1136 enforce_status: Option<Vec<String>>,
1137 #[serde(default)]
1138 required: Option<Vec<String>>,
1139 #[serde(default)]
1140 severity: Option<String>,
1141}
1142
1143fn parse_severity(s: &str) -> Option<Severity> {
1145 match s {
1146 "error" => Some(Severity::Error),
1147 "warning" => Some(Severity::Warning),
1148 "info" => Some(Severity::Info),
1149 "hint" => Some(Severity::Hint),
1150 _ => None,
1151 }
1152}
1153
1154fn ads_config_from_raw(raw: RawAdsConfig) -> crate::error::Result<AdsConfig> {
1157 let mut config = AdsConfig::default();
1158
1159 if let Some(statuses) = raw.enforce_status {
1160 const VALID_STATUSES: &[&str] = &[
1161 "stable",
1162 "test",
1163 "experimental",
1164 "deprecated",
1165 "unsupported",
1166 ];
1167 let mut normalised = Vec::with_capacity(statuses.len());
1168 for s in statuses {
1169 let lower = s.to_lowercase();
1170 if !VALID_STATUSES.contains(&lower.as_str()) {
1171 return Err(crate::error::SigmaParserError::InvalidRule(format!(
1172 "invalid ads.enforce_status '{s}'; expected one of: {}",
1173 VALID_STATUSES.join(", ")
1174 )));
1175 }
1176 normalised.push(lower);
1177 }
1178 dedup_preserving_order(&mut normalised);
1179 config.enforce_status = normalised;
1180 }
1181
1182 if let Some(required) = raw.required {
1183 let mut ids = Vec::with_capacity(required.len());
1184 for id in required {
1185 let lower = id.to_lowercase();
1186 if AdsSection::from_id(&lower).is_none() {
1187 return Err(crate::error::SigmaParserError::InvalidRule(format!(
1188 "invalid ads.required section '{id}'; expected one of: {}",
1189 AdsSection::all()
1190 .iter()
1191 .map(|s| s.id())
1192 .collect::<Vec<_>>()
1193 .join(", ")
1194 )));
1195 }
1196 ids.push(lower);
1197 }
1198 dedup_preserving_order(&mut ids);
1199 config.required = ids;
1200 }
1201
1202 if let Some(sev) = raw.severity {
1203 config.severity = Some(parse_severity(&sev).ok_or_else(|| {
1204 crate::error::SigmaParserError::InvalidRule(format!(
1205 "invalid ads.severity '{sev}'; expected error, warning, info, or hint"
1206 ))
1207 })?);
1208 }
1209
1210 Ok(config)
1211}
1212
1213fn dedup_preserving_order(items: &mut Vec<String>) {
1217 let mut seen = HashSet::new();
1218 items.retain(|item| seen.insert(item.clone()));
1219}
1220
1221impl LintConfig {
1222 pub fn load(path: &Path) -> crate::error::Result<Self> {
1223 let content = std::fs::read_to_string(path)?;
1224 let raw: RawLintConfig = yaml_serde::from_str(&content)?;
1225
1226 let disabled_rules: HashSet<String> = raw.disabled_rules.into_iter().collect();
1227 let mut severity_overrides = HashMap::new();
1228 for (rule, sev_str) in &raw.severity_overrides {
1229 let sev = parse_severity(sev_str).ok_or_else(|| {
1230 crate::error::SigmaParserError::InvalidRule(format!(
1231 "invalid severity '{sev_str}' for rule '{rule}' in lint config"
1232 ))
1233 })?;
1234 severity_overrides.insert(rule.clone(), sev);
1235 }
1236
1237 let mut exclude_patterns = raw.exclude;
1238 dedup_preserving_order(&mut exclude_patterns);
1239
1240 let mut tag_namespaces: Vec<String> = raw
1241 .tag_namespaces
1242 .into_iter()
1243 .map(|s| s.to_lowercase())
1244 .collect();
1245 dedup_preserving_order(&mut tag_namespaces);
1246
1247 let ads = raw.ads.map(ads_config_from_raw).transpose()?;
1248
1249 Ok(LintConfig {
1250 disabled_rules,
1251 severity_overrides,
1252 exclude_patterns,
1253 tag_namespaces,
1254 ads,
1255 })
1256 }
1257
1258 pub fn find_in_ancestors(start_path: &Path) -> Option<std::path::PathBuf> {
1259 let dir = if start_path.is_file() {
1260 start_path.parent()?
1261 } else {
1262 start_path
1263 };
1264
1265 let mut current = dir;
1266 loop {
1267 let candidate = current.join(".rsigma-lint.yml");
1268 if candidate.is_file() {
1269 return Some(candidate);
1270 }
1271 let candidate_yaml = current.join(".rsigma-lint.yaml");
1272 if candidate_yaml.is_file() {
1273 return Some(candidate_yaml);
1274 }
1275 current = current.parent()?;
1276 }
1277 }
1278
1279 pub fn merge(&mut self, other: &LintConfig) {
1280 self.disabled_rules
1281 .extend(other.disabled_rules.iter().cloned());
1282 for (rule, sev) in &other.severity_overrides {
1283 self.severity_overrides.insert(rule.clone(), *sev);
1284 }
1285 self.exclude_patterns
1286 .extend(other.exclude_patterns.iter().cloned());
1287 dedup_preserving_order(&mut self.exclude_patterns);
1288 self.tag_namespaces
1289 .extend(other.tag_namespaces.iter().cloned());
1290 dedup_preserving_order(&mut self.tag_namespaces);
1291 if other.ads.is_some() {
1294 self.ads = other.ads.clone();
1295 }
1296 }
1297
1298 pub fn is_disabled(&self, rule: &LintRule) -> bool {
1299 self.disabled_rules.contains(&rule.to_string())
1300 }
1301
1302 pub fn build_exclude_set(&self) -> Option<globset::GlobSet> {
1303 if self.exclude_patterns.is_empty() {
1304 return None;
1305 }
1306 let mut builder = globset::GlobSetBuilder::new();
1307 for pat in &self.exclude_patterns {
1308 if let Ok(glob) = globset::GlobBuilder::new(pat)
1309 .literal_separator(false)
1310 .build()
1311 {
1312 builder.add(glob);
1313 }
1314 }
1315 builder.build().ok()
1316 }
1317}
1318
1319#[derive(Debug, Clone, Default)]
1324pub struct InlineSuppressions {
1325 pub disable_all: bool,
1326 pub file_disabled: HashSet<String>,
1327 pub line_disabled: HashMap<u32, Option<HashSet<String>>>,
1328}
1329
1330pub fn parse_inline_suppressions(text: &str) -> InlineSuppressions {
1331 let mut result = InlineSuppressions::default();
1332
1333 for (i, line) in text.lines().enumerate() {
1334 let trimmed = line.trim();
1335
1336 let comment = if let Some(pos) = find_yaml_comment(trimmed) {
1337 trimmed[pos + 1..].trim()
1338 } else {
1339 continue;
1340 };
1341
1342 if let Some(rest) = comment.strip_prefix("rsigma-disable-next-line") {
1343 let rest = rest.trim();
1344 let next_line = (i + 1) as u32;
1345 if rest.is_empty() {
1346 result.line_disabled.insert(next_line, None);
1347 } else {
1348 let rules: HashSet<String> = rest
1349 .split(',')
1350 .map(|s| s.trim().to_string())
1351 .filter(|s| !s.is_empty())
1352 .collect();
1353 if !rules.is_empty() {
1354 result
1355 .line_disabled
1356 .entry(next_line)
1357 .and_modify(|existing| {
1358 if let Some(existing_set) = existing {
1359 existing_set.extend(rules.iter().cloned());
1360 }
1361 })
1362 .or_insert(Some(rules));
1363 }
1364 }
1365 } else if let Some(rest) = comment.strip_prefix("rsigma-disable") {
1366 let rest = rest.trim();
1367 if rest.is_empty() {
1368 result.disable_all = true;
1369 } else {
1370 for rule in rest.split(',') {
1371 let rule = rule.trim();
1372 if !rule.is_empty() {
1373 result.file_disabled.insert(rule.to_string());
1374 }
1375 }
1376 }
1377 }
1378 }
1379
1380 result
1381}
1382
1383fn find_yaml_comment(line: &str) -> Option<usize> {
1384 let mut in_single = false;
1385 let mut in_double = false;
1386 for (i, c) in line.char_indices() {
1387 match c {
1388 '\'' if !in_double => in_single = !in_single,
1389 '"' if !in_single => in_double = !in_double,
1390 '#' if !in_single && !in_double => return Some(i),
1391 _ => {}
1392 }
1393 }
1394 None
1395}
1396
1397impl InlineSuppressions {
1398 pub fn is_suppressed(&self, warning: &LintWarning) -> bool {
1399 if self.disable_all {
1400 return true;
1401 }
1402
1403 let rule_name = warning.rule.to_string();
1404 if self.file_disabled.contains(&rule_name) {
1405 return true;
1406 }
1407
1408 if let Some(span) = &warning.span
1409 && let Some(line_rules) = self.line_disabled.get(&span.start_line)
1410 {
1411 return match line_rules {
1412 None => true,
1413 Some(rules) => rules.contains(&rule_name),
1414 };
1415 }
1416
1417 false
1418 }
1419}
1420
1421pub fn apply_suppressions(
1426 warnings: Vec<LintWarning>,
1427 config: &LintConfig,
1428 inline: &InlineSuppressions,
1429) -> Vec<LintWarning> {
1430 warnings
1431 .into_iter()
1432 .filter(|w| !config.is_disabled(&w.rule))
1433 .filter(|w| !inline.is_suppressed(w))
1434 .map(|mut w| {
1435 let rule_name = w.rule.to_string();
1436 if let Some(sev) = config.severity_overrides.get(&rule_name) {
1437 w.severity = *sev;
1438 }
1439 w
1440 })
1441 .collect()
1442}
1443
1444pub fn lint_yaml_str_with_config(text: &str, config: &LintConfig) -> Vec<LintWarning> {
1445 let warnings = lint_yaml_str_ext(text, &config.tag_namespaces, config.ads.as_ref());
1446 let inline = parse_inline_suppressions(text);
1447 apply_suppressions(warnings, config, &inline)
1448}
1449
1450pub fn lint_yaml_file_with_config(
1451 path: &Path,
1452 config: &LintConfig,
1453) -> crate::error::Result<FileLintResult> {
1454 let content = std::fs::read_to_string(path)?;
1455 let warnings = lint_yaml_str_with_config(&content, config);
1456 Ok(FileLintResult {
1457 path: path.to_path_buf(),
1458 warnings,
1459 })
1460}
1461
1462pub fn lint_yaml_directory_with_config(
1463 dir: &Path,
1464 config: &LintConfig,
1465) -> crate::error::Result<Vec<FileLintResult>> {
1466 lint_directory_impl(dir, Some(config))
1467}
1468
1469#[cfg(test)]
1474mod tests {
1475 use super::*;
1476
1477 fn yaml_value(yaml: &str) -> Value {
1478 yaml_serde::from_str(yaml).unwrap()
1479 }
1480
1481 fn lint(yaml: &str) -> Vec<LintWarning> {
1482 lint_yaml_value(&yaml_value(yaml))
1483 }
1484
1485 fn has_rule(warnings: &[LintWarning], rule: LintRule) -> bool {
1486 warnings.iter().any(|w| w.rule == rule)
1487 }
1488
1489 fn has_no_rule(warnings: &[LintWarning], rule: LintRule) -> bool {
1490 !has_rule(warnings, rule)
1491 }
1492
1493 #[test]
1494 fn valid_detection_rule_no_errors() {
1495 let w = lint(
1496 r#"
1497title: Test Rule
1498id: 929a690e-bef0-4204-a928-ef5e620d6fcc
1499status: test
1500logsource:
1501 category: process_creation
1502 product: windows
1503detection:
1504 selection:
1505 CommandLine|contains: 'whoami'
1506 condition: selection
1507level: medium
1508tags:
1509 - attack.execution
1510 - attack.t1059
1511"#,
1512 );
1513 let errors: Vec<_> = w.iter().filter(|w| w.severity == Severity::Error).collect();
1514 assert!(errors.is_empty(), "unexpected errors: {errors:?}");
1515 }
1516
1517 #[test]
1518 fn not_a_mapping() {
1519 let v: yaml_serde::Value = yaml_serde::from_str("- item1\n- item2").unwrap();
1520 let w = lint_yaml_value(&v);
1521 assert!(has_rule(&w, LintRule::NotAMapping));
1522 }
1523
1524 #[test]
1525 fn lint_yaml_str_produces_spans() {
1526 let text = r#"title: Test
1527status: invalid_status
1528logsource:
1529 category: test
1530detection:
1531 selection:
1532 field: value
1533 condition: selection
1534level: medium
1535"#;
1536 let warnings = lint_yaml_str(text);
1537 let invalid_status = warnings.iter().find(|w| w.rule == LintRule::InvalidStatus);
1538 assert!(invalid_status.is_some(), "expected InvalidStatus warning");
1539 let span = invalid_status.unwrap().span;
1540 assert!(span.is_some(), "expected span to be resolved");
1541 assert_eq!(span.unwrap().start_line, 1);
1542 }
1543
1544 #[test]
1545 fn yaml_parse_error_uses_correct_rule() {
1546 let text = "title: [unclosed";
1547 let warnings = lint_yaml_str(text);
1548 assert!(has_rule(&warnings, LintRule::YamlParseError));
1549 assert!(has_no_rule(&warnings, LintRule::MissingTitle));
1550 }
1551
1552 #[test]
1553 fn action_global_skipped() {
1554 let w = lint(
1555 r#"
1556action: global
1557title: Global Template
1558logsource:
1559 product: windows
1560"#,
1561 );
1562 assert!(w.is_empty());
1563 }
1564
1565 #[test]
1566 fn action_reset_skipped() {
1567 let w = lint(
1568 r#"
1569action: reset
1570"#,
1571 );
1572 assert!(w.is_empty());
1573 }
1574
1575 #[test]
1576 fn resolve_path_to_span_root() {
1577 let text = "title: Test\nstatus: test\n";
1578 let span = resolve_path_to_span(text, "/");
1579 assert!(span.is_some());
1580 assert_eq!(span.unwrap().start_line, 0);
1581 }
1582
1583 #[test]
1584 fn resolve_path_to_span_top_level_key() {
1585 let text = "title: Test\nstatus: test\nlevel: high\n";
1586 let span = resolve_path_to_span(text, "/status");
1587 assert!(span.is_some());
1588 assert_eq!(span.unwrap().start_line, 1);
1589 }
1590
1591 #[test]
1592 fn resolve_path_to_span_nested_key() {
1593 let text = "title: Test\nlogsource:\n category: test\n product: windows\n";
1594 let span = resolve_path_to_span(text, "/logsource/product");
1595 assert!(span.is_some());
1596 assert_eq!(span.unwrap().start_line, 3);
1597 }
1598
1599 #[test]
1600 fn resolve_path_to_span_missing_key() {
1601 let text = "title: Test\nstatus: test\n";
1602 let span = resolve_path_to_span(text, "/nonexistent");
1603 assert!(span.is_none());
1604 }
1605
1606 #[test]
1607 fn multi_doc_yaml_lints_all_documents() {
1608 let text = r#"title: Rule 1
1609logsource:
1610 category: test
1611detection:
1612 selection:
1613 field: value
1614 condition: selection
1615level: medium
1616---
1617title: Rule 2
1618status: bad_status
1619logsource:
1620 category: test
1621detection:
1622 selection:
1623 field: value
1624 condition: selection
1625level: medium
1626"#;
1627 let warnings = lint_yaml_str(text);
1628 assert!(has_rule(&warnings, LintRule::InvalidStatus));
1629 }
1630
1631 #[test]
1632 fn severity_display() {
1633 assert_eq!(format!("{}", Severity::Error), "error");
1634 assert_eq!(format!("{}", Severity::Warning), "warning");
1635 assert_eq!(format!("{}", Severity::Info), "info");
1636 assert_eq!(format!("{}", Severity::Hint), "hint");
1637 }
1638
1639 #[test]
1640 fn file_lint_result_has_errors() {
1641 let result = FileLintResult {
1642 path: std::path::PathBuf::from("test.yml"),
1643 warnings: vec![
1644 warning(LintRule::TitleTooLong, "too long", "/title"),
1645 err(
1646 LintRule::MissingCondition,
1647 "missing",
1648 "/detection/condition",
1649 ),
1650 ],
1651 };
1652 assert!(result.has_errors());
1653 assert_eq!(result.error_count(), 1);
1654 assert_eq!(result.warning_count(), 1);
1655 }
1656
1657 #[test]
1658 fn file_lint_result_no_errors() {
1659 let result = FileLintResult {
1660 path: std::path::PathBuf::from("test.yml"),
1661 warnings: vec![warning(LintRule::TitleTooLong, "too long", "/title")],
1662 };
1663 assert!(!result.has_errors());
1664 assert_eq!(result.error_count(), 0);
1665 assert_eq!(result.warning_count(), 1);
1666 }
1667
1668 #[test]
1669 fn file_lint_result_empty() {
1670 let result = FileLintResult {
1671 path: std::path::PathBuf::from("test.yml"),
1672 warnings: vec![],
1673 };
1674 assert!(!result.has_errors());
1675 assert_eq!(result.error_count(), 0);
1676 assert_eq!(result.warning_count(), 0);
1677 }
1678
1679 #[test]
1680 fn lint_warning_display() {
1681 let w = err(
1682 LintRule::MissingTitle,
1683 "missing required field 'title'",
1684 "/title",
1685 );
1686 let display = format!("{w}");
1687 assert!(display.contains("error"));
1688 assert!(display.contains("missing_title"));
1689 assert!(display.contains("/title"));
1690 }
1691
1692 #[test]
1693 fn file_lint_result_info_count() {
1694 let result = FileLintResult {
1695 path: std::path::PathBuf::from("test.yml"),
1696 warnings: vec![
1697 info(LintRule::MissingDescription, "missing desc", "/description"),
1698 info(LintRule::MissingAuthor, "missing author", "/author"),
1699 warning(LintRule::TitleTooLong, "too long", "/title"),
1700 ],
1701 };
1702 assert_eq!(result.info_count(), 2);
1703 assert_eq!(result.warning_count(), 1);
1704 assert_eq!(result.error_count(), 0);
1705 assert!(!result.has_errors());
1706 }
1707
1708 #[test]
1709 fn parse_inline_disable_all() {
1710 let text = "# rsigma-disable\ntitle: Test\n";
1711 let sup = parse_inline_suppressions(text);
1712 assert!(sup.disable_all);
1713 }
1714
1715 #[test]
1716 fn parse_inline_disable_specific_rules() {
1717 let text = "# rsigma-disable missing_description, missing_author\ntitle: Test\n";
1718 let sup = parse_inline_suppressions(text);
1719 assert!(!sup.disable_all);
1720 assert!(sup.file_disabled.contains("missing_description"));
1721 assert!(sup.file_disabled.contains("missing_author"));
1722 }
1723
1724 #[test]
1725 fn parse_inline_disable_next_line_all() {
1726 let text = "# rsigma-disable-next-line\ntitle: Test\n";
1727 let sup = parse_inline_suppressions(text);
1728 assert!(!sup.disable_all);
1729 assert!(sup.line_disabled.contains_key(&1));
1730 assert!(sup.line_disabled[&1].is_none());
1731 }
1732
1733 #[test]
1734 fn parse_inline_disable_next_line_specific() {
1735 let text = "title: Test\n# rsigma-disable-next-line missing_level\nlevel: medium\n";
1736 let sup = parse_inline_suppressions(text);
1737 assert!(sup.line_disabled.contains_key(&2));
1738 let rules = sup.line_disabled[&2].as_ref().unwrap();
1739 assert!(rules.contains("missing_level"));
1740 }
1741
1742 #[test]
1743 fn parse_inline_no_comments() {
1744 let text = "title: Test\nstatus: test\n";
1745 let sup = parse_inline_suppressions(text);
1746 assert!(!sup.disable_all);
1747 assert!(sup.file_disabled.is_empty());
1748 assert!(sup.line_disabled.is_empty());
1749 }
1750
1751 #[test]
1752 fn parse_inline_comment_in_quoted_string() {
1753 let text = "description: 'no # rsigma-disable here'\ntitle: Test\n";
1754 let sup = parse_inline_suppressions(text);
1755 assert!(!sup.disable_all);
1756 assert!(sup.file_disabled.is_empty());
1757 }
1758
1759 #[test]
1760 fn apply_suppressions_disables_rule() {
1761 let warnings = vec![
1762 info(LintRule::MissingDescription, "desc", "/description"),
1763 info(LintRule::MissingAuthor, "author", "/author"),
1764 warning(LintRule::TitleTooLong, "title", "/title"),
1765 ];
1766 let mut config = LintConfig::default();
1767 config
1768 .disabled_rules
1769 .insert("missing_description".to_string());
1770 let inline = InlineSuppressions::default();
1771
1772 let result = apply_suppressions(warnings, &config, &inline);
1773 assert_eq!(result.len(), 2);
1774 assert!(
1775 result
1776 .iter()
1777 .all(|w| w.rule != LintRule::MissingDescription)
1778 );
1779 }
1780
1781 #[test]
1782 fn apply_suppressions_severity_override() {
1783 let warnings = vec![warning(LintRule::TitleTooLong, "title too long", "/title")];
1784 let mut config = LintConfig::default();
1785 config
1786 .severity_overrides
1787 .insert("title_too_long".to_string(), Severity::Info);
1788 let inline = InlineSuppressions::default();
1789
1790 let result = apply_suppressions(warnings, &config, &inline);
1791 assert_eq!(result.len(), 1);
1792 assert_eq!(result[0].severity, Severity::Info);
1793 }
1794
1795 #[test]
1796 fn apply_suppressions_inline_file_disable() {
1797 let warnings = vec![
1798 info(LintRule::MissingDescription, "desc", "/description"),
1799 info(LintRule::MissingAuthor, "author", "/author"),
1800 ];
1801 let config = LintConfig::default();
1802 let mut inline = InlineSuppressions::default();
1803 inline.file_disabled.insert("missing_author".to_string());
1804
1805 let result = apply_suppressions(warnings, &config, &inline);
1806 assert_eq!(result.len(), 1);
1807 assert_eq!(result[0].rule, LintRule::MissingDescription);
1808 }
1809
1810 #[test]
1811 fn apply_suppressions_inline_disable_all() {
1812 let warnings = vec![
1813 err(LintRule::MissingTitle, "title", "/title"),
1814 warning(LintRule::TitleTooLong, "long", "/title"),
1815 ];
1816 let config = LintConfig::default();
1817 let inline = InlineSuppressions {
1818 disable_all: true,
1819 ..Default::default()
1820 };
1821
1822 let result = apply_suppressions(warnings, &config, &inline);
1823 assert!(result.is_empty());
1824 }
1825
1826 #[test]
1827 fn apply_suppressions_inline_next_line() {
1828 let mut w1 = warning(LintRule::TitleTooLong, "long", "/title");
1829 w1.span = Some(Span {
1830 start_line: 5,
1831 start_col: 0,
1832 end_line: 5,
1833 end_col: 10,
1834 });
1835 let mut w2 = err(LintRule::InvalidStatus, "bad", "/status");
1836 w2.span = Some(Span {
1837 start_line: 6,
1838 start_col: 0,
1839 end_line: 6,
1840 end_col: 10,
1841 });
1842
1843 let config = LintConfig::default();
1844 let mut inline = InlineSuppressions::default();
1845 inline.line_disabled.insert(5, None);
1846
1847 let result = apply_suppressions(vec![w1, w2], &config, &inline);
1848 assert_eq!(result.len(), 1);
1849 assert_eq!(result[0].rule, LintRule::InvalidStatus);
1850 }
1851
1852 #[test]
1853 fn lint_with_config_disables_rules() {
1854 let text = r#"title: Test
1855logsource:
1856 category: test
1857detection:
1858 selection:
1859 field: value
1860 condition: selection
1861level: medium
1862"#;
1863 let mut config = LintConfig::default();
1864 config
1865 .disabled_rules
1866 .insert("missing_description".to_string());
1867 config.disabled_rules.insert("missing_author".to_string());
1868
1869 let warnings = lint_yaml_str_with_config(text, &config);
1870 assert!(
1871 !warnings
1872 .iter()
1873 .any(|w| w.rule == LintRule::MissingDescription)
1874 );
1875 assert!(!warnings.iter().any(|w| w.rule == LintRule::MissingAuthor));
1876 }
1877
1878 #[test]
1879 fn lint_with_inline_disable_next_line() {
1880 let text = r#"title: Test
1881# rsigma-disable-next-line missing_level
1882logsource:
1883 category: test
1884detection:
1885 selection:
1886 field: value
1887 condition: selection
1888"#;
1889 let config = LintConfig::default();
1890 let warnings = lint_yaml_str_with_config(text, &config);
1891 assert!(warnings.iter().any(|w| w.rule == LintRule::MissingLevel));
1892 }
1893
1894 #[test]
1895 fn lint_with_inline_file_disable() {
1896 let text = r#"# rsigma-disable missing_description, missing_author
1897title: Test
1898logsource:
1899 category: test
1900detection:
1901 selection:
1902 field: value
1903 condition: selection
1904level: medium
1905"#;
1906 let config = LintConfig::default();
1907 let warnings = lint_yaml_str_with_config(text, &config);
1908 assert!(
1909 !warnings
1910 .iter()
1911 .any(|w| w.rule == LintRule::MissingDescription)
1912 );
1913 assert!(!warnings.iter().any(|w| w.rule == LintRule::MissingAuthor));
1914 }
1915
1916 #[test]
1917 fn lint_with_inline_disable_all() {
1918 let text = r#"# rsigma-disable
1919title: Test
1920status: invalid_status
1921logsource:
1922 category: test
1923detection:
1924 selection:
1925 field: value
1926 condition: selection
1927"#;
1928 let config = LintConfig::default();
1929 let warnings = lint_yaml_str_with_config(text, &config);
1930 assert!(warnings.is_empty());
1931 }
1932
1933 #[test]
1934 fn lint_config_merge() {
1935 let mut base = LintConfig::default();
1936 base.disabled_rules.insert("rule_a".to_string());
1937 base.severity_overrides
1938 .insert("rule_b".to_string(), Severity::Info);
1939
1940 let other = LintConfig {
1941 disabled_rules: ["rule_c".to_string()].into_iter().collect(),
1942 severity_overrides: [("rule_d".to_string(), Severity::Hint)]
1943 .into_iter()
1944 .collect(),
1945 exclude_patterns: vec!["test/**".to_string()],
1946 tag_namespaces: vec!["myns".to_string()],
1947 ads: None,
1948 };
1949
1950 base.merge(&other);
1951 assert!(base.disabled_rules.contains("rule_a"));
1952 assert!(base.disabled_rules.contains("rule_c"));
1953 assert_eq!(base.severity_overrides.get("rule_b"), Some(&Severity::Info));
1954 assert_eq!(base.severity_overrides.get("rule_d"), Some(&Severity::Hint));
1955 assert_eq!(base.exclude_patterns, vec!["test/**".to_string()]);
1956 assert!(base.tag_namespaces.contains(&"myns".to_string()));
1957 }
1958
1959 #[test]
1960 fn lint_config_merge_dedups_lists() {
1961 let mut base = LintConfig {
1962 exclude_patterns: vec!["config/**".to_string(), "shared/**".to_string()],
1963 tag_namespaces: vec!["myorg".to_string(), "shared".to_string()],
1964 ..Default::default()
1965 };
1966 let other = LintConfig {
1967 exclude_patterns: vec!["shared/**".to_string(), "extra/**".to_string()],
1969 tag_namespaces: vec!["shared".to_string(), "internal".to_string()],
1970 ..Default::default()
1971 };
1972
1973 base.merge(&other);
1974
1975 assert_eq!(
1976 base.exclude_patterns,
1977 vec![
1978 "config/**".to_string(),
1979 "shared/**".to_string(),
1980 "extra/**".to_string()
1981 ]
1982 );
1983 assert_eq!(
1984 base.tag_namespaces,
1985 vec![
1986 "myorg".to_string(),
1987 "shared".to_string(),
1988 "internal".to_string()
1989 ]
1990 );
1991 }
1992
1993 #[test]
1994 fn lint_config_load_dedups_and_normalises() {
1995 let yaml = r#"
1996exclude:
1997 - "config/**"
1998 - "config/**"
1999tag_namespaces:
2000 - MyOrg
2001 - myorg
2002 - internal
2003"#;
2004 let mut tmp = tempfile::NamedTempFile::with_suffix(".yml").unwrap();
2005 std::io::Write::write_all(&mut tmp, yaml.as_bytes()).unwrap();
2006 let config = LintConfig::load(tmp.path()).unwrap();
2007
2008 assert_eq!(config.exclude_patterns, vec!["config/**".to_string()]);
2009 assert_eq!(
2011 config.tag_namespaces,
2012 vec!["myorg".to_string(), "internal".to_string()]
2013 );
2014 }
2015
2016 #[test]
2017 fn lint_config_is_disabled() {
2018 let mut config = LintConfig::default();
2019 config.disabled_rules.insert("missing_title".to_string());
2020 assert!(config.is_disabled(&LintRule::MissingTitle));
2021 assert!(!config.is_disabled(&LintRule::EmptyTitle));
2022 }
2023
2024 #[test]
2025 fn find_yaml_comment_basic() {
2026 assert_eq!(find_yaml_comment("# comment"), Some(0));
2027 assert_eq!(find_yaml_comment("key: value # comment"), Some(11));
2028 assert_eq!(find_yaml_comment("key: 'value # not comment'"), None);
2029 assert_eq!(find_yaml_comment("key: \"value # not comment\""), None);
2030 assert_eq!(find_yaml_comment("key: value"), None);
2031 }
2032
2033 #[test]
2034 fn no_fix_for_unfixable_rule() {
2035 let w = lint(
2036 r#"
2037title: Test
2038logsource:
2039 category: test
2040"#,
2041 );
2042 assert!(has_rule(&w, LintRule::MissingDetection));
2043 let fix = w
2044 .iter()
2045 .find(|w| w.rule == LintRule::MissingDetection)
2046 .and_then(|w| w.fix.as_ref());
2047 assert!(fix.is_none());
2048 }
2049
2050 #[test]
2051 fn lint_config_exclude_from_yaml() {
2052 let yaml = r#"
2053disabled_rules:
2054 - missing_description
2055exclude:
2056 - "config/**"
2057 - "**/unsupported/**"
2058"#;
2059 let tmp = std::env::temp_dir().join("rsigma_test_exclude.yml");
2060 std::fs::write(&tmp, yaml).unwrap();
2061 let config = LintConfig::load(&tmp).unwrap();
2062 std::fs::remove_file(&tmp).ok();
2063
2064 assert!(config.disabled_rules.contains("missing_description"));
2065 assert_eq!(config.exclude_patterns.len(), 2);
2066 assert_eq!(config.exclude_patterns[0], "config/**");
2067 assert_eq!(config.exclude_patterns[1], "**/unsupported/**");
2068 }
2069
2070 #[test]
2071 fn lint_config_build_exclude_set_empty() {
2072 let config = LintConfig::default();
2073 assert!(config.build_exclude_set().is_none());
2074 }
2075
2076 #[test]
2077 fn lint_config_build_exclude_set_matches() {
2078 let config = LintConfig {
2079 exclude_patterns: vec!["config/**".to_string()],
2080 ..Default::default()
2081 };
2082 let gs = config.build_exclude_set().expect("should build");
2083 assert!(gs.is_match("config/data_mapping/foo.yaml"));
2084 assert!(gs.is_match("config/nested/deep/bar.yml"));
2085 assert!(!gs.is_match("rules/windows/test.yml"));
2086 }
2087
2088 #[test]
2089 fn cross_ref_version_mismatch_within_file() {
2090 let yaml = r#"
2094title: Base Rule
2095name: base_rule
2096sigma-version: 2
2097logsource:
2098 category: test
2099detection:
2100 selection:
2101 EventID: 1
2102 condition: selection
2103---
2104title: Brute Force
2105sigma-version: 3
2106correlation:
2107 type: event_count
2108 rules:
2109 - base_rule
2110 group-by:
2111 - SourceIP
2112 timespan: 5m
2113 condition:
2114 gte: 10
2115"#;
2116 let w = lint_yaml_str(yaml);
2117 assert!(has_rule(&w, LintRule::SigmaVersionMismatch));
2118 assert!(has_no_rule(&w, LintRule::UnknownRuleReference));
2119 }
2120
2121 #[test]
2122 fn cross_ref_matching_version_no_mismatch() {
2123 let yaml = r#"
2124title: Base Rule
2125name: base_rule
2126sigma-version: 3
2127logsource:
2128 category: test
2129detection:
2130 selection:
2131 EventID: 1
2132 condition: selection
2133---
2134title: Brute Force
2135sigma-version: 3
2136correlation:
2137 type: event_count
2138 rules:
2139 - base_rule
2140 group-by:
2141 - SourceIP
2142 timespan: 5m
2143 condition:
2144 gte: 10
2145"#;
2146 assert!(has_no_rule(
2147 &lint_yaml_str(yaml),
2148 LintRule::SigmaVersionMismatch
2149 ));
2150 }
2151
2152 #[test]
2153 fn filter_reference_by_title_is_deprecated() {
2154 let yaml = r#"
2155title: Base Rule
2156id: 00000000-0000-4000-8000-000000000001
2157name: base_rule
2158logsource:
2159 category: test
2160detection:
2161 selection:
2162 EventID: 1
2163 condition: selection
2164---
2165title: Filter by Title
2166logsource:
2167 category: test
2168filter:
2169 rules: [Base Rule]
2170 selection:
2171 User: admin
2172 condition: not selection
2173"#;
2174 assert!(has_rule(
2175 &lint_yaml_str(yaml),
2176 LintRule::FilterReferenceByTitle
2177 ));
2178 }
2179
2180 #[test]
2181 fn filter_reference_by_name_is_not_deprecated() {
2182 let yaml = r#"
2183title: Base Rule
2184name: base_rule
2185logsource:
2186 category: test
2187detection:
2188 selection:
2189 EventID: 1
2190 condition: selection
2191---
2192title: Filter by Name
2193logsource:
2194 category: test
2195filter:
2196 rules: [base_rule]
2197 selection:
2198 User: admin
2199 condition: not selection
2200"#;
2201 assert!(has_no_rule(
2202 &lint_yaml_str(yaml),
2203 LintRule::FilterReferenceByTitle
2204 ));
2205 }
2206
2207 #[test]
2208 fn filter_reference_by_name_wins_over_another_rules_title() {
2209 let yaml = r#"
2210title: Stable Target
2211name: target
2212logsource:
2213 category: test
2214detection:
2215 selection:
2216 EventID: 1
2217 condition: selection
2218---
2219title: target
2220logsource:
2221 category: test
2222detection:
2223 selection:
2224 EventID: 2
2225 condition: selection
2226---
2227title: Filter by Name
2228logsource:
2229 category: test
2230filter:
2231 rules: [target]
2232 selection:
2233 User: admin
2234 condition: not selection
2235"#;
2236 assert!(has_no_rule(
2237 &lint_yaml_str(yaml),
2238 LintRule::FilterReferenceByTitle
2239 ));
2240 }
2241
2242 #[test]
2243 fn filter_reference_ignores_correlation_identities() {
2244 let yaml = r#"
2245title: brute_force
2246logsource:
2247 category: test
2248detection:
2249 selection:
2250 EventID: 4625
2251 condition: selection
2252---
2253title: Brute Force Correlation
2254name: brute_force
2255correlation:
2256 type: event_count
2257 rules: [brute_force]
2258 group-by: [User]
2259 timespan: 5m
2260 condition:
2261 gte: 10
2262---
2263title: Filter Brute Force
2264logsource:
2265 category: test
2266filter:
2267 rules: [brute_force]
2268 selection:
2269 User: admin
2270 condition: not selection
2271"#;
2272 let warnings = lint_yaml_str(yaml);
2273 let filter_title_refs = warnings
2274 .iter()
2275 .filter(|w| w.rule == LintRule::FilterReferenceByTitle)
2276 .count();
2277 assert_eq!(filter_title_refs, 1);
2278 }
2279
2280 #[test]
2281 fn cross_ref_unknown_only_with_complete_index() {
2282 let yaml = r#"
2283title: Brute Force
2284correlation:
2285 type: event_count
2286 rules:
2287 - nonexistent_rule
2288 group-by:
2289 - SourceIP
2290 timespan: 5m
2291 condition:
2292 gte: 10
2293"#;
2294 assert!(has_no_rule(
2297 &lint_yaml_str(yaml),
2298 LintRule::UnknownRuleReference
2299 ));
2300
2301 let tmp = tempfile::tempdir().unwrap();
2303 std::fs::write(tmp.path().join("corr.yml"), yaml).unwrap();
2304 let results = lint_yaml_directory(tmp.path()).unwrap();
2305 assert!(
2306 results
2307 .iter()
2308 .flat_map(|r| &r.warnings)
2309 .any(|w| w.rule == LintRule::UnknownRuleReference)
2310 );
2311 }
2312
2313 #[test]
2314 fn cross_ref_resolves_across_files() {
2315 let tmp = tempfile::tempdir().unwrap();
2318 std::fs::write(
2319 tmp.path().join("base.yml"),
2320 r#"
2321title: Base Rule
2322name: base_rule
2323sigma-version: 2
2324logsource:
2325 category: test
2326detection:
2327 selection:
2328 EventID: 1
2329 condition: selection
2330"#,
2331 )
2332 .unwrap();
2333 std::fs::write(
2334 tmp.path().join("corr.yml"),
2335 r#"
2336title: Brute Force
2337sigma-version: 3
2338correlation:
2339 type: event_count
2340 rules:
2341 - base_rule
2342 group-by:
2343 - SourceIP
2344 timespan: 5m
2345 condition:
2346 gte: 10
2347"#,
2348 )
2349 .unwrap();
2350 let results = lint_yaml_directory(tmp.path()).unwrap();
2351 let all: Vec<_> = results.iter().flat_map(|r| &r.warnings).collect();
2352 assert!(all.iter().any(|w| w.rule == LintRule::SigmaVersionMismatch));
2353 assert!(!all.iter().any(|w| w.rule == LintRule::UnknownRuleReference));
2354 }
2355
2356 #[test]
2357 fn lint_directory_with_excludes() {
2358 let tmp = tempfile::tempdir().unwrap();
2359 let rules_dir = tmp.path().join("rules");
2360 let config_dir = tmp.path().join("config");
2361 std::fs::create_dir_all(&rules_dir).unwrap();
2362 std::fs::create_dir_all(&config_dir).unwrap();
2363
2364 std::fs::write(
2365 rules_dir.join("good.yml"),
2366 r#"
2367title: Good Rule
2368logsource:
2369 category: test
2370detection:
2371 sel:
2372 field: value
2373 condition: sel
2374level: medium
2375"#,
2376 )
2377 .unwrap();
2378
2379 std::fs::write(
2380 config_dir.join("mapping.yaml"),
2381 r#"
2382Title: Logon
2383Channel: Security
2384EventID: 4624
2385"#,
2386 )
2387 .unwrap();
2388
2389 let no_exclude = LintConfig::default();
2390 let results = lint_yaml_directory_with_config(tmp.path(), &no_exclude).unwrap();
2391 let config_warnings: Vec<_> = results
2392 .iter()
2393 .filter(|r| r.path.to_string_lossy().contains("config"))
2394 .flat_map(|r| &r.warnings)
2395 .collect();
2396 assert!(
2397 !config_warnings.is_empty(),
2398 "config file should produce warnings without excludes"
2399 );
2400
2401 let with_exclude = LintConfig {
2402 exclude_patterns: vec!["config/**".to_string()],
2403 ..Default::default()
2404 };
2405 let results = lint_yaml_directory_with_config(tmp.path(), &with_exclude).unwrap();
2406 let config_results: Vec<_> = results
2407 .iter()
2408 .filter(|r| r.path.to_string_lossy().contains("config"))
2409 .collect();
2410 assert!(config_results.is_empty(), "config file should be excluded");
2411
2412 let rule_results: Vec<_> = results
2413 .iter()
2414 .filter(|r| r.path.to_string_lossy().contains("good.yml"))
2415 .collect();
2416 assert_eq!(rule_results.len(), 1);
2417 }
2418
2419 #[test]
2420 fn all_lint_keys_are_cached() {
2421 const ALL_LINT_KEYS: &[&str] = &[
2422 "action",
2423 "author",
2424 "condition",
2425 "correlation",
2426 "date",
2427 "description",
2428 "detection",
2429 "field",
2430 "filter",
2431 "generate",
2432 "group-by",
2433 "id",
2434 "level",
2435 "logsource",
2436 "modified",
2437 "name",
2438 "rules",
2439 "selection",
2440 "status",
2441 "tags",
2442 "taxonomy",
2443 "timeframe",
2444 "timespan",
2445 "title",
2446 "type",
2447 ];
2448 for key_str in ALL_LINT_KEYS {
2449 assert!(KEY_CACHE.contains_key(key_str), "key not cached: {key_str}");
2450 }
2451 }
2452
2453 #[test]
2454 fn extra_tag_namespace_suppresses_warning() {
2455 let text = r#"title: Test
2456logsource:
2457 category: test
2458detection:
2459 selection:
2460 field: value
2461 condition: selection
2462level: medium
2463tags:
2464 - myorg.custom_tag
2465"#;
2466 let warnings = lint_yaml_str(text);
2468 assert!(has_rule(&warnings, LintRule::UnknownTagNamespace));
2469
2470 let config = LintConfig {
2472 tag_namespaces: vec!["myorg".to_string()],
2473 ..Default::default()
2474 };
2475 let warnings = lint_yaml_str_with_config(text, &config);
2476 assert!(has_no_rule(&warnings, LintRule::UnknownTagNamespace));
2477 }
2478
2479 #[test]
2480 fn extra_tag_namespace_from_config_file() {
2481 let yaml = r#"
2482tag_namespaces:
2483 - myorg
2484 - internal
2485"#;
2486 let mut tmp = tempfile::NamedTempFile::with_suffix(".yml").unwrap();
2487 std::io::Write::write_all(&mut tmp, yaml.as_bytes()).unwrap();
2488 let config = LintConfig::load(tmp.path()).unwrap();
2489
2490 assert!(config.tag_namespaces.contains(&"myorg".to_string()));
2491 assert!(config.tag_namespaces.contains(&"internal".to_string()));
2492 }
2493}