1use std::collections::{BTreeMap, BTreeSet};
33use std::fmt;
34
35use serde::Serialize;
36
37use crate::engine::Engine;
38use crate::event::Event;
39use crate::schema::SchemaClassifier;
40
41pub mod correlation;
42pub(crate) mod draft_core;
43use draft_core::*;
44
45#[derive(Debug, Clone)]
52pub struct DraftConfig {
53 pub max_fields: usize,
55 pub min_fields: usize,
58 pub min_prevalence: f64,
61 pub max_value_cardinality: usize,
64 pub min_token_len: usize,
68 pub max_baseline_token_prevalence: f64,
71 pub include_fields: Vec<String>,
74 pub exclude_fields: Vec<String>,
76 pub title: Option<String>,
78 pub rule_id: Option<String>,
81 pub date: Option<String>,
84 pub logsource_category: Option<String>,
86 pub logsource_product: Option<String>,
87 pub logsource_service: Option<String>,
88 pub evaluate_baseline: bool,
91}
92
93impl Default for DraftConfig {
94 fn default() -> Self {
95 Self {
96 max_fields: 4,
97 min_fields: 2,
98 min_prevalence: 1.0,
99 max_value_cardinality: 4,
100 min_token_len: 4,
101 max_baseline_token_prevalence: 0.05,
102 include_fields: Vec::new(),
103 exclude_fields: Vec::new(),
104 title: None,
105 rule_id: None,
106 date: None,
107 logsource_category: None,
108 logsource_product: None,
109 logsource_service: None,
110 evaluate_baseline: true,
111 }
112 }
113}
114
115#[derive(Debug, thiserror::Error)]
121pub enum DraftError {
122 #[error("no exemplar events to draft from")]
124 NoExemplars,
125 #[error(
128 "no candidate fields: every field was volatile (timestamps, ids, unique values), \
129 excluded, or below the prevalence threshold ({0} exemplars profiled)"
130 )]
131 NoCandidateFields(usize),
132 #[error(
135 "draft cannot match all exemplars: {matched}/{total} match at the {floor}-field floor; \
136 exemplars may be too heterogeneous for one rule (failing exemplar indexes: {failing:?})"
137 )]
138 CannotMatchExemplars {
139 matched: usize,
140 total: usize,
141 floor: usize,
142 failing: Vec<usize>,
143 },
144 #[error(
148 "forced field(s) {fields:?} are absent from exemplar(s) {failing:?}; \
149 remove the --include-field or drop those exemplars"
150 )]
151 ForcedFieldMismatch {
152 fields: Vec<String>,
153 failing: Vec<usize>,
154 },
155 #[error("internal error: emitted draft failed to {stage}: {message}")]
157 Internal { stage: String, message: String },
158 #[error("no selections to draft from")]
160 NoSelections,
161 #[error("selection {name:?} needs a selection_<ident> name, a field, and at least one value")]
163 BadSelection { name: String },
164 #[error("draft title is empty")]
166 EmptyTitle,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct ValueSelection {
176 pub name: String,
178 pub field: String,
180 pub modifiers: Vec<String>,
182 pub values: Vec<String>,
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct ValueDraftSpec {
191 pub title: String,
193 pub description: Option<String>,
195 pub references: Vec<String>,
197 pub tags: Vec<String>,
199 pub rule_id: Option<String>,
201 pub date: Option<String>,
203 pub logsource_category: Option<String>,
205 pub logsource_product: Option<String>,
207 pub logsource_service: Option<String>,
209 pub level: Option<String>,
211 pub selections: Vec<ValueSelection>,
213}
214
215const DESCRIPTION_PLACEHOLDER: &str = "TODO: describe what this rule detects and why it matters.";
217const AUTHOR_PLACEHOLDER: &str = "TODO: your name";
218const FALSE_POSITIVE_PLACEHOLDER: &str = "TODO: list known benign triggers.";
219
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
226#[serde(rename_all = "snake_case")]
227pub enum Stability {
228 Constant,
230 Enumerable,
232 Patterned,
234 Volatile,
236}
237
238impl fmt::Display for Stability {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 let s = match self {
241 Stability::Constant => "constant",
242 Stability::Enumerable => "enumerable",
243 Stability::Patterned => "patterned",
244 Stability::Volatile => "volatile",
245 };
246 f.write_str(s)
247 }
248}
249
250#[derive(Debug, Clone, Serialize)]
252pub struct DraftFieldReport {
253 pub field: String,
255 pub score: f64,
257 pub stability: Stability,
259 pub modifier: String,
261 pub values: Vec<String>,
263 pub baseline_prevalence: Option<f64>,
266 pub selected: bool,
268}
269
270#[derive(Debug, Clone)]
272pub struct DraftReport {
273 pub rule_yaml: String,
275 pub fields: Vec<DraftFieldReport>,
277 pub exemplar_total: usize,
279 pub exemplar_matched: usize,
282 pub baseline_total: usize,
284 pub baseline_hits: Option<usize>,
287 pub baseline_hit_rate: Option<f64>,
289 pub warnings: Vec<String>,
291}
292
293#[derive(Debug, Clone)]
294pub(crate) struct DraftCandidate {
295 pub(crate) profiles: Vec<DraftFieldProfile>,
296 pub(crate) selected: Vec<usize>,
297 logsource: DraftLogsource,
298 pub(crate) warnings: Vec<String>,
299}
300
301impl DraftCandidate {
302 pub(crate) fn build<E: Event>(
303 exemplars: &[E],
304 baseline: &[E],
305 config: &DraftConfig,
306 ) -> Result<Self, DraftError> {
307 if exemplars.is_empty() {
308 return Err(DraftError::NoExemplars);
309 }
310 let mut warnings = Vec::new();
311 let mut profiles = profile_fields(exemplars, config, &mut warnings);
312 if profiles.is_empty() {
313 return Err(DraftError::NoCandidateFields(exemplars.len()));
314 }
315 for profile in &mut profiles {
316 infer_form(profile, config);
317 }
318 if !baseline.is_empty() {
319 for profile in &mut profiles {
320 apply_baseline(profile, baseline, config);
321 }
322 }
323 let has_baseline = !baseline.is_empty();
324 for profile in &mut profiles {
325 profile.score = score_field(profile, has_baseline);
326 }
327 profiles.sort_by(|a, b| {
328 b.forced
329 .cmp(&a.forced)
330 .then_with(|| {
331 b.score
332 .partial_cmp(&a.score)
333 .unwrap_or(std::cmp::Ordering::Equal)
334 })
335 .then_with(|| a.field().cmp(b.field()))
336 });
337 let usable: Vec<usize> = profiles
338 .iter()
339 .enumerate()
340 .filter(|(_, profile)| {
341 profile.form.is_some() && profile.stability != Stability::Volatile
342 })
343 .map(|(index, _)| index)
344 .collect();
345 if usable.is_empty() {
346 return Err(DraftError::NoCandidateFields(exemplars.len()));
347 }
348 let selected: Vec<usize> = usable.iter().copied().take(config.max_fields).collect();
349 if selected.len() < config.min_fields {
350 warnings.push(format!(
351 "only {} usable field(s) found (floor is {}); the draft may be broad",
352 selected.len(),
353 config.min_fields
354 ));
355 }
356 let logsource = infer_logsource(exemplars, config, &mut warnings);
357 Ok(Self {
358 profiles,
359 selected,
360 logsource,
361 warnings,
362 })
363 }
364
365 pub(crate) fn emit<E: Event>(&self, exemplars: &[E], config: &DraftConfig) -> String {
366 self.emit_named(exemplars, config, None)
367 }
368
369 pub(crate) fn emit_named<E: Event>(
370 &self,
371 exemplars: &[E],
372 config: &DraftConfig,
373 name: Option<&str>,
374 ) -> String {
375 let detection = build_detection(&self.profiles, &self.selected, exemplars, config);
376 emit_rule_yaml(
377 &self.profiles,
378 &self.selected,
379 &detection,
380 &self.logsource,
381 config,
382 name,
383 )
384 }
385
386 pub(crate) fn drop_lowest_eligible(&mut self, failing: Option<&[usize]>) -> Option<usize> {
387 let absent_in_failing = |index: usize| {
388 failing.is_some_and(|indexes| {
389 indexes
390 .iter()
391 .any(|&event| self.profiles[index].values[event].is_none())
392 })
393 };
394 let position = self
395 .selected
396 .iter()
397 .rposition(|&index| !self.profiles[index].forced && absent_in_failing(index))
398 .or_else(|| {
399 self.selected
400 .iter()
401 .rposition(|&index| !self.profiles[index].forced)
402 })?;
403 Some(self.selected.remove(position))
404 }
405}
406
407pub fn draft_rule<E: Event>(
417 exemplars: &[E],
418 baseline: &[E],
419 config: &DraftConfig,
420) -> Result<DraftReport, DraftError> {
421 let mut candidate = DraftCandidate::build(exemplars, baseline, config)?;
422 let floor = config.min_fields.min(candidate.selected.len()).max(1);
423
424 let (yaml, matched, failing) = loop {
426 let yaml = candidate.emit(exemplars, config);
427 let engine = compile_draft(&yaml)?;
428 let failing: Vec<usize> = exemplars
429 .iter()
430 .enumerate()
431 .filter(|(_, e)| engine.evaluate(e).is_empty())
432 .map(|(i, _)| i)
433 .collect();
434 if failing.is_empty() {
435 break (yaml, exemplars.len(), failing);
436 }
437
438 let absent_in_failing = |i: usize| {
442 failing
443 .iter()
444 .any(|&idx| candidate.profiles[i].values[idx].is_none())
445 };
446
447 let forced_culprits: Vec<String> = candidate
451 .selected
452 .iter()
453 .filter(|&&i| candidate.profiles[i].forced && absent_in_failing(i))
454 .map(|&i| candidate.profiles[i].field().to_string())
455 .collect();
456 if !forced_culprits.is_empty() {
457 return Err(DraftError::ForcedFieldMismatch {
458 fields: forced_culprits,
459 failing,
460 });
461 }
462
463 if candidate.selected.len() <= floor {
464 return Err(DraftError::CannotMatchExemplars {
465 matched: exemplars.len() - failing.len(),
466 total: exemplars.len(),
467 floor,
468 failing,
469 });
470 }
471
472 let Some(dropped) = candidate.drop_lowest_eligible(Some(&failing)) else {
475 return Err(DraftError::CannotMatchExemplars {
476 matched: exemplars.len() - failing.len(),
477 total: exemplars.len(),
478 floor,
479 failing,
480 });
481 };
482 candidate.warnings.push(format!(
483 "relaxed: dropped field '{}' because the draft did not match every exemplar with it",
484 candidate.profiles[dropped].field()
485 ));
486 };
487 debug_assert!(failing.is_empty());
488
489 let (baseline_hits, baseline_hit_rate) = if !baseline.is_empty() && config.evaluate_baseline {
491 let engine = compile_draft(&yaml)?;
492 let hits = baseline
493 .iter()
494 .filter(|e| !engine.evaluate(e).is_empty())
495 .count();
496 let rate = hits as f64 / baseline.len() as f64;
497 if hits > 0 {
498 candidate.warnings.push(format!(
499 "draft matches {hits}/{} baseline events ({:.1}%); consider a tighter field",
500 baseline.len(),
501 rate * 100.0
502 ));
503 }
504 (Some(hits), Some(rate))
505 } else {
506 (None, None)
507 };
508
509 for w in rsigma_parser::lint_yaml_str(&yaml) {
511 candidate
512 .warnings
513 .push(format!("lint {}: {}", w.rule, w.message));
514 }
515
516 let selected_set: BTreeSet<usize> = candidate.selected.iter().copied().collect();
518 let fields = candidate
519 .profiles
520 .iter()
521 .enumerate()
522 .map(|(i, p)| DraftFieldReport {
523 field: p.field().to_string(),
524 score: p.score,
525 stability: p.stability,
526 modifier: p
527 .form
528 .as_ref()
529 .map(|f| f.modifier().trim_start_matches('|').to_string())
530 .unwrap_or_default(),
531 values: p
532 .form
533 .as_ref()
534 .map(|f| f.display_values())
535 .unwrap_or_else(|| {
536 p.distinct()
537 .into_iter()
538 .take(4)
539 .map(|v| v.as_display())
540 .collect()
541 }),
542 baseline_prevalence: p.baseline_prevalence,
543 selected: selected_set.contains(&i),
544 })
545 .collect();
546
547 Ok(DraftReport {
548 rule_yaml: yaml,
549 fields,
550 exemplar_total: exemplars.len(),
551 exemplar_matched: matched,
552 baseline_total: baseline.len(),
553 baseline_hits,
554 baseline_hit_rate,
555 warnings: candidate.warnings,
556 })
557}
558
559struct Selection {
565 name: String,
566 entries: Vec<(String, ValueForm)>,
567}
568
569struct DetectionBlock {
570 selections: Vec<Selection>,
571 condition: String,
572}
573
574fn build_detection<E: Event>(
575 profiles: &[DraftFieldProfile],
576 selected: &[usize],
577 exemplars: &[E],
578 config: &DraftConfig,
579) -> DetectionBlock {
580 if let Some(block) = try_group_split(profiles, selected, exemplars, config) {
584 return block;
585 }
586 let entries: Vec<(String, ValueForm)> = selected
587 .iter()
588 .filter_map(|&i| {
589 profiles[i]
590 .form
591 .clone()
592 .map(|f| (profiles[i].field().to_string(), f))
593 })
594 .collect();
595 DetectionBlock {
596 selections: vec![Selection {
597 name: "selection".to_string(),
598 entries,
599 }],
600 condition: "selection".to_string(),
601 }
602}
603
604const MAX_VALUE_GROUPS: usize = 3;
605
606fn try_group_split<E: Event>(
607 profiles: &[DraftFieldProfile],
608 selected: &[usize],
609 exemplars: &[E],
610 config: &DraftConfig,
611) -> Option<DetectionBlock> {
612 if selected.len() < 2 || exemplars.len() < 2 {
613 return None;
614 }
615 let (splitter_pos, splitter) = selected.iter().enumerate().find_map(|(pos, &i)| {
618 let p = &profiles[i];
619 let d = p.distinct();
620 let all_str = d.iter().all(|v| matches!(v, DraftValue::Str(_)));
621 if all_str && d.len() >= 2 && d.len() <= MAX_VALUE_GROUPS {
622 Some((pos, i))
623 } else {
624 None
625 }
626 })?;
627
628 let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
630 for (idx, v) in profiles[splitter].values.iter().enumerate() {
631 let key = v.as_ref()?.as_display();
632 match groups.iter_mut().find(|(k, _)| *k == key) {
633 Some((_, members)) => members.push(idx),
634 None => groups.push((key, vec![idx])),
635 }
636 }
637 if groups.len() < 2 {
638 return None;
639 }
640 if groups.iter().any(|(_, members)| members.len() < 2) {
643 return None;
644 }
645
646 let improves = selected.iter().enumerate().any(|(pos, &i)| {
649 if pos == splitter_pos {
650 return false;
651 }
652 let p = &profiles[i];
653 if p.distinct().len() < 2 {
654 return false;
655 }
656 groups.iter().all(|(_, members)| {
657 let mut vals = members.iter().filter_map(|&m| p.values[m].as_ref());
658 let first = vals.next();
659 first.is_some() && vals.all(|v| Some(v) == first)
660 })
661 });
662 if !improves {
663 return None;
664 }
665
666 let mut used_names: BTreeMap<String, u32> = BTreeMap::new();
668 let selections: Vec<Selection> = groups
669 .iter()
670 .map(|(key, members)| {
671 let entries: Vec<(String, ValueForm)> = selected
672 .iter()
673 .filter_map(|&i| {
674 let p = &profiles[i];
675 let mut distinct: Vec<DraftValue> = Vec::new();
676 for &m in members {
677 if let Some(v) = &p.values[m]
678 && !distinct.contains(v)
679 {
680 distinct.push(v.clone());
681 }
682 }
683 derive_form(&distinct, config).map(|f| (p.field().to_string(), f))
684 })
685 .collect();
686 let base = selection_slug(key);
687 let n = used_names.entry(base.clone()).or_insert(0);
688 *n += 1;
689 let name = if *n == 1 {
690 format!("selection_{base}")
691 } else {
692 format!("selection_{base}_{n}")
693 };
694 Selection { name, entries }
695 })
696 .collect();
697
698 Some(DetectionBlock {
699 selections,
700 condition: "1 of selection_*".to_string(),
701 })
702}
703
704fn selection_slug(value: &str) -> String {
708 let last_segment = value.rsplit(['\\', '/']).next().unwrap_or(value);
709 let stem = last_segment
710 .split_once('.')
711 .map(|(stem, _)| stem)
712 .unwrap_or(last_segment);
713 let first_token = stem
714 .split(|c: char| !c.is_ascii_alphanumeric())
715 .find(|t| !t.is_empty())
716 .unwrap_or("");
717 let out: String = first_token.to_ascii_lowercase();
718 if out.is_empty() {
719 "group".to_string()
720 } else {
721 out
722 }
723}
724
725#[derive(Debug, Clone, Default)]
730struct DraftLogsource {
731 category: Option<String>,
732 product: Option<String>,
733 service: Option<String>,
734 inferred: bool,
735}
736
737fn sysmon_category(event_id: i64) -> Option<&'static str> {
739 Some(match event_id {
740 1 => "process_creation",
741 3 => "network_connection",
742 6 => "driver_load",
743 7 => "image_load",
744 8 => "create_remote_thread",
745 10 => "process_access",
746 11 => "file_event",
747 22 => "dns_query",
748 23 => "file_delete",
749 _ => return None,
750 })
751}
752
753fn infer_logsource<E: Event>(
754 exemplars: &[E],
755 config: &DraftConfig,
756 warnings: &mut Vec<String>,
757) -> DraftLogsource {
758 let mut out = DraftLogsource::default();
759
760 let classifier = SchemaClassifier::builtin();
762 let mut counts: BTreeMap<String, usize> = BTreeMap::new();
763 for e in exemplars {
764 if let Some(m) = classifier.classify(e) {
765 *counts.entry(m.name).or_insert(0) += 1;
766 }
767 }
768 let majority = counts
769 .iter()
770 .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
771 .map(|(name, _)| name.as_str());
772
773 match majority {
774 Some("sysmon") => {
775 out.product = Some("windows".to_string());
776 let ids: BTreeSet<i64> = exemplars
779 .iter()
780 .filter_map(|e| e.get_field("EventID").and_then(|v| v.as_i64()))
781 .collect();
782 let category = if ids.len() == 1 {
783 ids.first().copied().and_then(sysmon_category)
784 } else {
785 None
786 };
787 match category {
788 Some(c) => out.category = Some(c.to_string()),
789 None => out.service = Some("sysmon".to_string()),
790 }
791 out.inferred = true;
792 }
793 Some("windows_eventlog") | Some("ecs_windows") => {
794 out.product = Some("windows".to_string());
795 out.inferred = true;
796 }
797 Some("ecs_linux") => {
798 out.product = Some("linux".to_string());
799 out.inferred = true;
800 }
801 _ => {}
802 }
803
804 if config.logsource_category.is_some() {
806 out.category = config.logsource_category.clone();
807 out.inferred = true;
808 }
809 if config.logsource_product.is_some() {
810 out.product = config.logsource_product.clone();
811 out.inferred = true;
812 }
813 if config.logsource_service.is_some() {
814 out.service = config.logsource_service.clone();
815 out.inferred = true;
816 }
817
818 if !out.inferred {
819 warnings.push(
820 "logsource could not be inferred from the exemplars; \
821 replace the 'todo' placeholder before committing"
822 .to_string(),
823 );
824 out.product = Some("todo".to_string());
825 }
826 out
827}
828
829fn title_marker(profiles: &[DraftFieldProfile], selected: &[usize]) -> Option<String> {
832 let first = selected.first().map(|&i| &profiles[i])?;
833 let form = first.form.as_ref()?;
834 let raw = match form {
835 ValueForm::Exact(v) => v.as_display(),
836 ValueForm::OneOf(vs) => vs.first().map(|v| v.as_display()).unwrap_or_default(),
837 ValueForm::EndsWith(s) | ValueForm::StartsWith(s) | ValueForm::Contains(s) => s.clone(),
838 ValueForm::ContainsAll(ts) => ts.first().cloned().unwrap_or_default(),
839 };
840 let trimmed = raw.trim_matches(|c: char| !c.is_ascii_alphanumeric());
841 if trimmed.is_empty() {
842 None
843 } else {
844 Some(format!("{trimmed} ({})", first.field()))
845 }
846}
847
848fn emit_rule_yaml(
849 profiles: &[DraftFieldProfile],
850 selected: &[usize],
851 detection: &DetectionBlock,
852 logsource: &DraftLogsource,
853 config: &DraftConfig,
854 name: Option<&str>,
855) -> String {
856 let title = config.title.clone().unwrap_or_else(|| {
857 title_marker(profiles, selected)
858 .map(|m| format!("Draft: {m}"))
859 .unwrap_or_else(|| "Draft rule".to_string())
860 });
861 let date = config
862 .date
863 .clone()
864 .unwrap_or_else(|| chrono::Utc::now().format("%Y-%m-%d").to_string());
865
866 let mut out = String::new();
867 out.push_str(&format!("title: {}\n", yaml_title_str(&title)));
868 if let Some(name) = name {
869 out.push_str(&format!("name: {}\n", yaml_str(name)));
870 }
871 if let Some(id) = &config.rule_id {
872 out.push_str(&format!("id: {id}\n"));
873 }
874 out.push_str("status: experimental\n");
875 push_description(&mut out, None);
876 push_author(&mut out);
877 out.push_str(&format!("date: {}\n", yaml_str(&date)));
878 out.push_str("logsource:\n");
879 if let Some(c) = &logsource.category {
880 out.push_str(&format!(" category: {}\n", yaml_str(c)));
881 }
882 if let Some(p) = &logsource.product {
883 out.push_str(&format!(" product: {}\n", yaml_str(p)));
884 }
885 if let Some(s) = &logsource.service {
886 out.push_str(&format!(" service: {}\n", yaml_str(s)));
887 }
888 out.push_str("detection:\n");
889 for sel in &detection.selections {
890 out.push_str(&format!(" {}:\n", sel.name));
891 for (field, form) in &sel.entries {
892 emit_form(&mut out, field, form, " ");
893 }
894 }
895 out.push_str(&format!(" condition: {}\n", detection.condition));
896 push_falsepositives(&mut out);
897 push_level(&mut out, "medium");
898 out
899}
900
901pub fn draft_rule_from_values(spec: &ValueDraftSpec) -> Result<String, DraftError> {
935 let title = one_line(&spec.title);
936 if title.trim().is_empty() {
937 return Err(DraftError::EmptyTitle);
938 }
939 if spec.selections.is_empty() {
940 return Err(DraftError::NoSelections);
941 }
942 for selection in &spec.selections {
943 if !valid_selection(selection) {
944 return Err(DraftError::BadSelection {
945 name: selection.name.clone(),
946 });
947 }
948 }
949
950 let date = spec
951 .date
952 .as_deref()
953 .map(one_line)
954 .filter(|date| !date.trim().is_empty())
955 .unwrap_or_else(|| chrono::Utc::now().format("%Y-%m-%d").to_string());
956 let level = spec
957 .level
958 .as_deref()
959 .map(one_line)
960 .filter(|level| !level.trim().is_empty())
961 .unwrap_or_else(|| "medium".to_string());
962 let description = spec.description.as_deref().map(one_line);
963
964 let mut out = String::new();
965 out.push_str(&format!("title: {}\n", yaml_title_str(title.trim())));
966 if let Some(id) = &spec.rule_id {
967 let id = one_line(id);
968 if !id.trim().is_empty() {
969 out.push_str(&format!("id: {}\n", yaml_str(id.trim())));
970 }
971 }
972 out.push_str("status: experimental\n");
973 push_description(&mut out, description.as_deref());
974 push_string_list(&mut out, "references", &spec.references);
975 push_author(&mut out);
976 out.push_str(&format!("date: {}\n", yaml_str(date.trim())));
977 push_string_list(&mut out, "tags", &spec.tags);
978 out.push_str("logsource:\n");
979 if let Some(category) = &spec.logsource_category {
980 push_logsource_field(&mut out, "category", category);
981 }
982 if let Some(product) = &spec.logsource_product {
983 push_logsource_field(&mut out, "product", product);
984 }
985 if let Some(service) = &spec.logsource_service {
986 push_logsource_field(&mut out, "service", service);
987 }
988 out.push_str("detection:\n");
989 for selection in &spec.selections {
990 out.push_str(&format!(" {}:\n", selection.name));
991 let key = selection_key(selection);
992 let values: Vec<String> = selection
993 .values
994 .iter()
995 .map(|value| one_line(value))
996 .collect();
997 if values.len() == 1 {
998 out.push_str(&format!(
999 " {key}: {}\n",
1000 yaml_str(&escape_sigma_value(&values[0]))
1001 ));
1002 } else {
1003 out.push_str(&format!(" {key}:\n"));
1004 for value in &values {
1005 out.push_str(&format!(
1006 " - {}\n",
1007 yaml_str(&escape_sigma_value(value))
1008 ));
1009 }
1010 }
1011 }
1012 out.push_str(" condition: 1 of selection_*\n");
1013 push_falsepositives(&mut out);
1014 push_level(&mut out, level.trim());
1015
1016 compile_draft(&out)?;
1017 Ok(out)
1018}
1019
1020fn push_description(out: &mut String, description: Option<&str>) {
1021 let text = description
1022 .map(str::trim)
1023 .filter(|text| !text.is_empty())
1024 .unwrap_or(DESCRIPTION_PLACEHOLDER);
1025 out.push_str(&format!("description: {}\n", yaml_str(text)));
1026}
1027
1028fn push_author(out: &mut String) {
1029 out.push_str(&format!("author: {}\n", yaml_str(AUTHOR_PLACEHOLDER)));
1030}
1031
1032fn push_falsepositives(out: &mut String) {
1033 out.push_str("falsepositives:\n");
1034 out.push_str(&format!(" - {}\n", yaml_str(FALSE_POSITIVE_PLACEHOLDER)));
1035}
1036
1037fn push_level(out: &mut String, level: &str) {
1038 out.push_str(&format!("level: {}\n", yaml_str(level)));
1039}
1040
1041fn push_logsource_field(out: &mut String, key: &str, value: &str) {
1042 let value = one_line(value);
1043 if value.trim().is_empty() {
1044 return;
1045 }
1046 out.push_str(&format!(" {key}: {}\n", yaml_str(value.trim())));
1047}
1048
1049fn push_string_list(out: &mut String, key: &str, values: &[String]) {
1050 let values: Vec<String> = values
1051 .iter()
1052 .map(|value| one_line(value).trim().to_string())
1053 .filter(|value| !value.is_empty())
1054 .collect();
1055 if values.is_empty() {
1056 return;
1057 }
1058 out.push_str(key);
1059 out.push_str(":\n");
1060 for value in values {
1061 out.push_str(&format!(" - {}\n", yaml_str(&value)));
1062 }
1063}
1064
1065fn one_line(value: &str) -> String {
1066 value.replace(['\n', '\r'], " ")
1067}
1068
1069fn valid_selection(selection: &ValueSelection) -> bool {
1070 ident_like(&selection.name)
1071 && selection.name.starts_with("selection_")
1072 && field_like(&selection.field)
1073 && selection
1074 .modifiers
1075 .iter()
1076 .all(|modifier| ident_like(modifier))
1077 && !selection.values.is_empty()
1078}
1079
1080fn selection_key(selection: &ValueSelection) -> String {
1081 if selection.modifiers.is_empty() {
1082 selection.field.clone()
1083 } else {
1084 format!("{}|{}", selection.field, selection.modifiers.join("|"))
1085 }
1086}
1087
1088fn ident_like(value: &str) -> bool {
1089 let mut chars = value.chars();
1090 match chars.next() {
1091 Some(first) if first.is_ascii_alphabetic() || first == '_' => {}
1092 _ => return false,
1093 }
1094 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1095}
1096
1097fn field_like(value: &str) -> bool {
1098 let mut chars = value.chars();
1099 match chars.next() {
1100 Some(first) if first.is_ascii_alphabetic() || first == '_' => {}
1101 _ => return false,
1102 }
1103 chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
1104}
1105
1106fn compile_draft(yaml: &str) -> Result<Engine, DraftError> {
1111 let collection = rsigma_parser::parse_sigma_yaml(yaml).map_err(|e| DraftError::Internal {
1112 stage: "parse".to_string(),
1113 message: e.to_string(),
1114 })?;
1115 let mut engine = Engine::new();
1116 engine
1117 .add_collection(&collection)
1118 .map_err(|e| DraftError::Internal {
1119 stage: "compile".to_string(),
1120 message: e.to_string(),
1121 })?;
1122 Ok(engine)
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127 use super::*;
1128 use crate::event::JsonEvent;
1129 use serde_json::{Value, json};
1130
1131 fn events(values: &[Value]) -> Vec<JsonEvent<'_>> {
1132 values.iter().map(JsonEvent::borrow).collect()
1133 }
1134
1135 fn fixed_config() -> DraftConfig {
1136 DraftConfig {
1137 rule_id: Some("00000000-0000-4000-8000-000000000000".to_string()),
1138 date: Some("2026-07-03".to_string()),
1139 ..DraftConfig::default()
1140 }
1141 }
1142
1143 fn draft(
1144 exemplars: &[Value],
1145 baseline: &[Value],
1146 config: &DraftConfig,
1147 ) -> Result<DraftReport, DraftError> {
1148 draft_rule(&events(exemplars), &events(baseline), config)
1149 }
1150
1151 #[test]
1154 fn timestamp_names_and_values_are_volatile() {
1155 assert!(is_volatile_name("UtcTime"));
1156 assert!(is_volatile_name("@timestamp"));
1157 assert!(is_volatile_name("event.created_date"));
1158 assert!(is_volatile_value(&DraftValue::Str(
1159 "2026-07-03T12:00:00Z".into()
1160 )));
1161 assert!(is_volatile_value(&DraftValue::Str("2026-07-03".into())));
1162 assert!(!is_volatile_value(&DraftValue::Str("whoami.exe".into())));
1163 }
1164
1165 #[test]
1166 fn uuid_values_and_guid_names_are_volatile() {
1167 assert!(is_volatile_name("ProcessGuid"));
1168 assert!(is_uuid_string("6bde842e-a2f4-441e-b027-3aa79b1b2fc2"));
1169 assert!(is_uuid_string("{6bde842e-a2f4-441e-b027-3aa79b1b2fc2}"));
1170 assert!(!is_uuid_string("not-a-uuid"));
1171 }
1172
1173 #[test]
1174 fn counter_names_and_epoch_values_are_volatile() {
1175 assert!(is_volatile_name("ProcessId"));
1176 assert!(is_volatile_name("Event.System.EventRecordID"));
1177 assert!(is_volatile_name("logon_id"));
1178 assert!(is_epoch_number(1_751_500_000.0)); assert!(is_epoch_number(1_751_500_000_000.0)); assert!(!is_epoch_number(4688.0)); }
1182
1183 #[test]
1184 fn time_date_name_match_is_word_bounded() {
1185 assert!(is_volatile_name("EventTime"));
1187 assert!(is_volatile_name("event_date"));
1188 assert!(is_volatile_name("datetime"));
1189 assert!(!is_volatile_name("runtime"));
1192 assert!(!is_volatile_name("update"));
1193 assert!(!is_volatile_name("candidate"));
1194 assert!(!is_volatile_name("CommandLine"));
1195 assert!(!is_volatile_name("validate_action"));
1196 }
1197
1198 #[test]
1199 fn shared_affix_never_splits_a_multibyte_char() {
1200 assert_eq!(
1203 shared_prefix(&["abcé1", "abcè2"], 3).as_deref(),
1204 Some("abc")
1205 );
1206 assert_eq!(shared_prefix(&["abcé1", "abcè2"], 4), None);
1207 assert_eq!(shared_suffix(&["x\u{03a9}", "y\u{00e9}"], 1), None);
1210 assert_eq!(
1212 shared_suffix(&["1éabc", "2éabc"], 3).as_deref(),
1213 Some("éabc")
1214 );
1215 }
1216
1217 #[test]
1218 fn random_unique_values_are_volatile() {
1219 let exemplars: Vec<Value> = (0..4)
1220 .map(|i| {
1221 json!({
1222 "tool": "runner",
1223 "task": "sync",
1224 "token": format!("a9f{i}c2d4e6b8a0f1c3d5e7f9b1a3c5d{i}"),
1225 })
1226 })
1227 .collect();
1228 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1229 let token = report.fields.iter().find(|f| f.field == "token").unwrap();
1230 assert_eq!(token.stability, Stability::Volatile);
1231 assert!(!token.selected);
1232 }
1233
1234 #[test]
1237 fn baseline_contrast_prefers_rare_fields() {
1238 let exemplars: Vec<Value> = (0..3)
1239 .map(|_| json!({"action": "exfil", "proto": "tcp"}))
1240 .collect();
1241 let baseline: Vec<Value> = (0..20)
1243 .map(|i| json!({"action": format!("browse{i}"), "proto": "tcp"}))
1244 .collect();
1245 let report = draft(&exemplars, &baseline, &fixed_config()).unwrap();
1246 let action = report.fields.iter().find(|f| f.field == "action").unwrap();
1247 let proto = report.fields.iter().find(|f| f.field == "proto").unwrap();
1248 assert!(
1249 action.score > proto.score,
1250 "baseline-rare field must outrank the ubiquitous one"
1251 );
1252 assert_eq!(proto.baseline_prevalence, Some(1.0));
1253 assert_eq!(action.baseline_prevalence, Some(0.0));
1254 }
1255
1256 #[test]
1257 fn structural_fields_are_demoted_without_baseline() {
1258 let exemplars: Vec<Value> = (0..3)
1259 .map(|_| json!({"hostname": "web-01", "action": "exfil"}))
1260 .collect();
1261 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1262 let host = report
1263 .fields
1264 .iter()
1265 .find(|f| f.field == "hostname")
1266 .unwrap();
1267 let action = report.fields.iter().find(|f| f.field == "action").unwrap();
1268 assert!(action.score > host.score);
1269 }
1270
1271 #[test]
1272 fn deterministic_output_across_runs() {
1273 let exemplars: Vec<Value> = (0..3)
1274 .map(|_| json!({"vendor": "acme", "action": "alert", "sig": "S-1001"}))
1275 .collect();
1276 let a = draft(&exemplars, &[], &fixed_config()).unwrap().rule_yaml;
1277 let b = draft(&exemplars, &[], &fixed_config()).unwrap().rule_yaml;
1278 assert_eq!(a, b, "draft output must be byte-identical across runs");
1279 }
1280
1281 #[test]
1282 fn structured_candidate_reemits_deterministically_after_drop() {
1283 let exemplars: Vec<Value> = (0..3)
1284 .map(|_| json!({"vendor": "acme", "action": "alert", "kind": "auth"}))
1285 .collect();
1286 let events = events(&exemplars);
1287 let mut candidate = DraftCandidate::build(&events, &[], &fixed_config()).unwrap();
1288 assert!(candidate.drop_lowest_eligible(None).is_some());
1289 let first = candidate.emit(&events, &fixed_config());
1290 let second = candidate.emit(&events, &fixed_config());
1291 assert_eq!(first, second);
1292 }
1293
1294 #[test]
1295 fn structured_candidate_never_drops_forced_fields() {
1296 let exemplars: Vec<Value> = (0..3)
1297 .map(|_| json!({"forced": "keep", "action": "alert"}))
1298 .collect();
1299 let events = events(&exemplars);
1300 let config = DraftConfig {
1301 include_fields: vec!["forced".to_string()],
1302 max_fields: 1,
1303 ..fixed_config()
1304 };
1305 let mut candidate = DraftCandidate::build(&events, &[], &config).unwrap();
1306 assert!(candidate.drop_lowest_eligible(None).is_none());
1307 assert_eq!(candidate.profiles[candidate.selected[0]].field(), "forced");
1308 }
1309
1310 #[test]
1311 fn structured_candidate_excludes_all_grouping_fields() {
1312 let exemplars: Vec<Value> = (0..3)
1313 .map(|_| json!({"tenant": "one", "user": "alice", "action": "alert"}))
1314 .collect();
1315 let events = events(&exemplars);
1316 let config = DraftConfig {
1317 exclude_fields: vec!["tenant".to_string(), "user".to_string()],
1318 ..fixed_config()
1319 };
1320 let candidate = DraftCandidate::build(&events, &[], &config).unwrap();
1321 assert!(
1322 candidate
1323 .profiles
1324 .iter()
1325 .all(|profile| !matches!(profile.field(), "tenant" | "user"))
1326 );
1327 }
1328
1329 #[test]
1332 fn shared_path_tail_becomes_endswith() {
1333 let exemplars = vec![
1334 json!({"Image": "C:\\Tools\\whoami.exe", "kind": "proc"}),
1335 json!({"Image": "C:\\Windows\\System32\\whoami.exe", "kind": "proc"}),
1336 json!({"Image": "D:\\stage\\whoami.exe", "kind": "proc"}),
1337 json!({"Image": "E:\\x\\whoami.exe", "kind": "proc"}),
1338 json!({"Image": "F:\\y\\whoami.exe", "kind": "proc"}),
1339 ];
1340 let cfg = DraftConfig {
1341 max_value_cardinality: 3,
1342 ..fixed_config()
1343 };
1344 let report = draft(&exemplars, &[], &cfg).unwrap();
1345 assert!(
1346 report.rule_yaml.contains("Image|endswith: '\\whoami.exe'"),
1347 "expected endswith derivation, got:\n{}",
1348 report.rule_yaml
1349 );
1350 }
1351
1352 #[test]
1353 fn shared_prefix_becomes_startswith() {
1354 let exemplars: Vec<Value> = (0..5)
1355 .map(|i| json!({"url": format!("https://evil.example/payload{i}"), "verb": "GET"}))
1356 .collect();
1357 let cfg = DraftConfig {
1358 max_value_cardinality: 3,
1359 ..fixed_config()
1360 };
1361 let report = draft(&exemplars, &[], &cfg).unwrap();
1362 assert!(
1363 report
1364 .rule_yaml
1365 .contains("url|startswith: 'https://evil.example/payload'"),
1366 "expected startswith derivation, got:\n{}",
1367 report.rule_yaml
1368 );
1369 }
1370
1371 #[test]
1372 fn short_generic_tokens_are_never_chosen() {
1373 let exemplars: Vec<Value> = (0..5)
1375 .map(|i| json!({"cmd": format!("{i}zz run q{i}"), "kind": "x"}))
1376 .collect();
1377 let cfg = DraftConfig {
1378 max_value_cardinality: 3,
1379 ..fixed_config()
1380 };
1381 let report = draft(&exemplars, &[], &cfg).unwrap();
1382 let cmd = report.fields.iter().find(|f| f.field == "cmd").unwrap();
1383 assert_eq!(cmd.stability, Stability::Volatile);
1384 assert!(!report.rule_yaml.contains("cmd|contains"));
1385 }
1386
1387 #[test]
1388 fn baseline_generic_token_is_rejected() {
1389 let exemplars: Vec<Value> = (0..5)
1391 .map(|i| json!({"proc": format!("powershell -x {i}q{i}w{i}"), "kind": "spawn"}))
1392 .collect();
1393 let baseline: Vec<Value> = (0..20)
1394 .map(|i| json!({"proc": format!("powershell -File login{i}.ps1"), "kind": "spawn"}))
1395 .collect();
1396 let cfg = DraftConfig {
1397 max_value_cardinality: 3,
1398 min_fields: 1,
1399 ..fixed_config()
1400 };
1401 let report = draft(&exemplars, &baseline, &cfg).unwrap();
1402 assert!(
1403 !report.rule_yaml.contains("proc|contains: powershell"),
1404 "generic baseline token must be rejected, got:\n{}",
1405 report.rule_yaml
1406 );
1407 }
1408
1409 #[test]
1410 fn wildcard_specials_in_values_are_escaped() {
1411 let exemplars: Vec<Value> = (0..3)
1412 .map(|_| json!({"query": "SELECT * FROM users?", "app": "dbd"}))
1413 .collect();
1414 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1415 assert!(
1416 report.rule_yaml.contains(r"SELECT \* FROM users\?"),
1417 "wildcards must be escaped, got:\n{}",
1418 report.rule_yaml
1419 );
1420 assert_eq!(report.exemplar_matched, 3);
1423 }
1424
1425 #[test]
1426 fn escape_sigma_value_handles_backslash_adjacency() {
1427 assert_eq!(escape_sigma_value(r"C:\Windows"), r"C:\Windows");
1428 assert_eq!(escape_sigma_value("a*b"), r"a\*b");
1429 assert_eq!(escape_sigma_value("a?b"), r"a\?b");
1430 assert_eq!(escape_sigma_value(r"a\*b"), r"a\\\*b");
1431 assert_eq!(escape_sigma_value(r"a\\b"), r"a\\\\b");
1432 assert_eq!(escape_sigma_value(r"trailing\"), r"trailing\\");
1433 }
1434
1435 #[test]
1438 fn distinct_value_groups_split_into_selections() {
1439 let exemplars = vec![
1440 json!({"Image": "C:\\W\\vssadmin.exe", "CommandLine": "vssadmin delete shadows", "k": "p"}),
1441 json!({"Image": "C:\\W\\vssadmin.exe", "CommandLine": "vssadmin delete shadows", "k": "p"}),
1442 json!({"Image": "C:\\W\\wmic.exe", "CommandLine": "wmic shadowcopy delete", "k": "p"}),
1443 json!({"Image": "C:\\W\\wmic.exe", "CommandLine": "wmic shadowcopy delete", "k": "p"}),
1444 ];
1445 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1446 assert!(
1447 report.rule_yaml.contains("condition: 1 of selection_*"),
1448 "expected a group split, got:\n{}",
1449 report.rule_yaml
1450 );
1451 assert!(report.rule_yaml.contains("selection_vssadmin:"));
1452 assert!(report.rule_yaml.contains("selection_wmic:"));
1453 assert_eq!(report.exemplar_matched, 4);
1454 }
1455
1456 #[test]
1457 fn no_split_when_values_do_not_partition() {
1458 let exemplars: Vec<Value> = (0..4)
1459 .map(|_| json!({"vendor": "acme", "action": "alert"}))
1460 .collect();
1461 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1462 assert!(report.rule_yaml.contains("condition: selection\n"));
1463 }
1464
1465 #[test]
1468 fn sysmon_event_id_maps_to_category() {
1469 let exemplars: Vec<Value> = (0..3)
1470 .map(|_| {
1471 json!({
1472 "Channel": "Microsoft-Windows-Sysmon/Operational",
1473 "EventID": 1,
1474 "Image": "C:\\W\\evil.exe",
1475 "CommandLine": "evil.exe --run",
1476 })
1477 })
1478 .collect();
1479 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1480 assert!(report.rule_yaml.contains("category: process_creation"));
1481 assert!(report.rule_yaml.contains("product: windows"));
1482 assert!(!report.rule_yaml.contains("service: sysmon"));
1483 }
1484
1485 #[test]
1486 fn sysmon_without_shared_event_id_keeps_service() {
1487 let exemplars = vec![
1488 json!({"Channel": "Microsoft-Windows-Sysmon/Operational", "EventID": 1, "Image": "C:\\W\\a.exe", "RuleName": "t"}),
1489 json!({"Channel": "Microsoft-Windows-Sysmon/Operational", "EventID": 3, "Image": "C:\\W\\a.exe", "RuleName": "t"}),
1490 ];
1491 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1492 assert!(report.rule_yaml.contains("service: sysmon"));
1493 assert!(report.rule_yaml.contains("product: windows"));
1494 }
1495
1496 #[test]
1497 fn logsource_overrides_win() {
1498 let exemplars: Vec<Value> = (0..3)
1499 .map(|_| json!({"vendor": "acme", "action": "alert"}))
1500 .collect();
1501 let cfg = DraftConfig {
1502 logsource_product: Some("acme_fw".to_string()),
1503 logsource_category: Some("firewall".to_string()),
1504 ..fixed_config()
1505 };
1506 let report = draft(&exemplars, &[], &cfg).unwrap();
1507 assert!(report.rule_yaml.contains("product: acme_fw"));
1508 assert!(report.rule_yaml.contains("category: firewall"));
1509 assert!(!report.rule_yaml.contains("todo"));
1510 }
1511
1512 #[test]
1513 fn unknown_schema_gets_todo_placeholder() {
1514 let exemplars: Vec<Value> = (0..3)
1515 .map(|_| json!({"vendor": "acme", "action": "alert"}))
1516 .collect();
1517 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1518 assert!(report.rule_yaml.contains("product: todo"));
1519 assert!(
1520 report
1521 .warnings
1522 .iter()
1523 .any(|w| w.contains("logsource could not be inferred"))
1524 );
1525 }
1526
1527 #[test]
1530 fn draft_round_trips_and_matches_exemplars() {
1531 let exemplars: Vec<Value> = (0..4)
1532 .map(|_| json!({"vendor": "acme", "action": "exfil", "dst_port": 443}))
1533 .collect();
1534 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1535 let collection =
1538 rsigma_parser::parse_sigma_yaml(&report.rule_yaml).expect("emitted draft must parse");
1539 let mut engine = Engine::new();
1540 engine.add_collection(&collection).unwrap();
1541 for e in &events(&exemplars) {
1542 assert!(!engine.evaluate(e).is_empty(), "exemplar must match");
1543 }
1544 assert_eq!(report.exemplar_matched, report.exemplar_total);
1545 assert!(
1546 report
1547 .rule_yaml
1548 .contains("id: 00000000-0000-4000-8000-000000000000")
1549 );
1550 assert!(report.rule_yaml.contains("status: experimental"));
1551 assert!(report.rule_yaml.contains("level: medium"));
1552 assert!(report.rule_yaml.contains("date: 2026-07-03"));
1553 }
1554
1555 #[test]
1556 fn typed_values_emit_as_numbers() {
1557 let exemplars: Vec<Value> = (0..3)
1558 .map(|_| json!({"vendor": "acme", "code": 4688}))
1559 .collect();
1560 let report = draft(&exemplars, &[], &fixed_config()).unwrap();
1561 assert!(
1562 report.rule_yaml.contains("code: 4688"),
1563 "integers must emit bare, got:\n{}",
1564 report.rule_yaml
1565 );
1566 }
1567
1568 #[test]
1569 fn baseline_hits_are_counted_with_rate() {
1570 let exemplars: Vec<Value> = (0..3)
1571 .map(|_| json!({"vendor": "acme", "action": "alert"}))
1572 .collect();
1573 let mut baseline: Vec<Value> = (0..8)
1574 .map(|i| json!({"vendor": "other", "action": format!("a{i}")}))
1575 .collect();
1576 baseline.push(json!({"vendor": "acme", "action": "alert"}));
1578 baseline.push(json!({"vendor": "acme", "action": "alert"}));
1579 let report = draft(&exemplars, &baseline, &fixed_config()).unwrap();
1580 assert_eq!(report.baseline_total, 10);
1581 assert_eq!(report.baseline_hits, Some(2));
1582 assert!((report.baseline_hit_rate.unwrap() - 0.2).abs() < 1e-9);
1583 assert!(report.warnings.iter().any(|w| w.contains("baseline")));
1584 }
1585
1586 #[test]
1587 fn skip_baseline_eval_keeps_scoring_but_not_hits() {
1588 let exemplars: Vec<Value> = (0..3)
1589 .map(|_| json!({"vendor": "acme", "action": "alert"}))
1590 .collect();
1591 let baseline: Vec<Value> = (0..5)
1592 .map(|i| json!({"vendor": "other", "action": format!("a{i}")}))
1593 .collect();
1594 let cfg = DraftConfig {
1595 evaluate_baseline: false,
1596 ..fixed_config()
1597 };
1598 let report = draft(&exemplars, &baseline, &cfg).unwrap();
1599 assert_eq!(report.baseline_hits, None);
1600 assert!(
1601 report
1602 .fields
1603 .iter()
1604 .any(|f| f.baseline_prevalence.is_some()),
1605 "contrastive scoring still uses the baseline"
1606 );
1607 }
1608
1609 #[test]
1612 fn relaxation_drops_partial_prevalence_fields() {
1613 let mut exemplars: Vec<Value> = (0..2)
1616 .map(|_| json!({"vendor": "acme", "action": "alert", "extra": "x"}))
1617 .collect();
1618 exemplars.extend((0..2).map(|_| json!({"vendor": "acme", "action": "alert"})));
1619 let cfg = DraftConfig {
1620 min_prevalence: 0.4,
1621 ..fixed_config()
1622 };
1623 let report = draft(&exemplars, &[], &cfg).unwrap();
1624 assert_eq!(report.exemplar_matched, 4);
1625 assert!(!report.rule_yaml.contains("extra"));
1626 assert!(report.warnings.iter().any(|w| w.contains("relaxed")));
1627 }
1628
1629 #[test]
1630 fn floor_errors_instead_of_emitting_overbroad_draft() {
1631 let mut exemplars: Vec<Value> = (0..2)
1634 .map(|_| json!({"alpha": "one", "beta": "x"}))
1635 .collect();
1636 exemplars.extend((0..2).map(|_| json!({"alpha": "two", "gamma": "y"})));
1637 let cfg = DraftConfig {
1638 min_prevalence: 0.4,
1639 min_fields: 2,
1640 max_value_cardinality: 1,
1641 ..fixed_config()
1642 };
1643 let err = draft(&exemplars, &[], &cfg).unwrap_err();
1644 assert!(
1645 matches!(err, DraftError::CannotMatchExemplars { floor: 2, .. }),
1646 "expected the floor error, got: {err}"
1647 );
1648 }
1649
1650 #[test]
1651 fn forced_field_absent_from_exemplars_errors_immediately() {
1652 let mut exemplars: Vec<Value> = (0..2)
1656 .map(|_| json!({"vendor": "acme", "action": "alert", "extra": "x"}))
1657 .collect();
1658 exemplars.extend((0..2).map(|_| json!({"vendor": "acme", "action": "alert"})));
1659 let cfg = DraftConfig {
1660 include_fields: vec!["extra".to_string()],
1661 min_prevalence: 0.4,
1662 ..fixed_config()
1663 };
1664 let err = draft(&exemplars, &[], &cfg).unwrap_err();
1665 match err {
1666 DraftError::ForcedFieldMismatch { fields, failing } => {
1667 assert_eq!(fields, vec!["extra".to_string()]);
1668 assert_eq!(failing, vec![2, 3]);
1669 }
1670 other => panic!("expected ForcedFieldMismatch, got: {other}"),
1671 }
1672 }
1673
1674 #[test]
1675 fn no_exemplars_is_an_error() {
1676 let err = draft(&[], &[], &fixed_config()).unwrap_err();
1677 assert!(matches!(err, DraftError::NoExemplars));
1678 }
1679
1680 #[test]
1681 fn all_volatile_fields_is_an_error() {
1682 let exemplars: Vec<Value> = (0..3)
1683 .map(|i| {
1684 json!({
1685 "UtcTime": format!("2026-07-03T12:00:0{i}Z"),
1686 "ProcessGuid": format!("6bde842e-a2f4-441e-b027-3aa79b1b2fc{i}"),
1687 })
1688 })
1689 .collect();
1690 let err = draft(&exemplars, &[], &fixed_config()).unwrap_err();
1691 assert!(matches!(err, DraftError::NoCandidateFields(3)));
1692 }
1693
1694 #[test]
1697 fn include_and_exclude_fields_are_honored() {
1698 let exemplars: Vec<Value> = (0..3)
1699 .map(|_| json!({"vendor": "acme", "action": "alert", "noise": "same"}))
1700 .collect();
1701 let cfg = DraftConfig {
1702 include_fields: vec!["noise".to_string()],
1703 exclude_fields: vec!["vendor".to_string()],
1704 max_fields: 2,
1705 ..fixed_config()
1706 };
1707 let report = draft(&exemplars, &[], &cfg).unwrap();
1708 assert!(report.rule_yaml.contains("noise: same"));
1709 assert!(!report.rule_yaml.contains("vendor"));
1710 }
1711
1712 #[test]
1713 fn title_override_and_derived_title() {
1714 let exemplars: Vec<Value> = (0..3)
1715 .map(|_| json!({"vendor": "acme", "action": "alert"}))
1716 .collect();
1717 let derived = draft(&exemplars, &[], &fixed_config()).unwrap();
1718 assert!(
1719 derived.rule_yaml.starts_with("title: 'Draft:")
1720 || derived.rule_yaml.starts_with("title: Draft"),
1721 "derived title expected, got:\n{}",
1722 derived.rule_yaml
1723 );
1724 let cfg = DraftConfig {
1725 title: Some("Acme Exfil Detection".to_string()),
1726 ..fixed_config()
1727 };
1728 let titled = draft(&exemplars, &[], &cfg).unwrap();
1729 assert!(titled.rule_yaml.starts_with("title: Acme Exfil Detection"));
1730 }
1731
1732 #[test]
1733 fn value_draft_escapes_hostile_text_and_compiles() {
1734 let yaml = draft_rule_from_values(&ValueDraftSpec {
1735 title: "Bad: # 'quote'".into(),
1736 description: Some("line\nwith 'quotes'".into()),
1737 references: vec!["https://example.com/a'b".into()],
1738 tags: vec!["attack.command_and_control".into()],
1739 rule_id: Some("00000000-0000-4000-8000-000000000002".into()),
1740 date: Some("2026-06-01".into()),
1741 logsource_category: Some("network_connection".into()),
1742 logsource_product: Some("windows".into()),
1743 logsource_service: Some("sysmon".into()),
1744 level: Some("high".into()),
1745 selections: vec![
1746 ValueSelection {
1747 name: "selection_destination_ip".into(),
1748 field: "DestinationIp".into(),
1749 modifiers: Vec::new(),
1750 values: vec!["a'b*c\nd".into(), "198.51.100.8".into()],
1751 },
1752 ValueSelection {
1753 name: "selection_destination_ip_cidr".into(),
1754 field: "DestinationIp".into(),
1755 modifiers: vec!["cidr".into()],
1756 values: vec!["198.51.100.0/24".into()],
1757 },
1758 ],
1759 })
1760 .unwrap();
1761 assert!(yaml.contains("title: 'Bad: # ''quote'''"));
1762 assert!(yaml.contains("description: 'line with ''quotes'''"));
1763 assert!(yaml.contains("'a''b\\*c d'"));
1764 assert!(yaml.contains("198.51.100.8"));
1765 assert!(yaml.contains("DestinationIp|cidr"));
1766 assert!(yaml.contains("condition: 1 of selection_*"));
1767 assert!(yaml.contains("product: windows"));
1768 assert!(yaml.contains("service: sysmon"));
1769 assert!(yaml.contains("level: high"));
1770 assert!(!yaml.contains(&format!(
1771 "description: {}",
1772 yaml_str(DESCRIPTION_PLACEHOLDER)
1773 )));
1774 assert!(yaml.contains(&format!("author: {}", yaml_str(AUTHOR_PLACEHOLDER))));
1775 rsigma_parser::parse_sigma_yaml(&yaml).expect("hostile draft parses");
1776 }
1777
1778 #[test]
1779 fn value_draft_uses_the_shared_placeholders() {
1780 let yaml = draft_rule_from_values(&ValueDraftSpec {
1781 title: "Placeholder".into(),
1782 description: Some(" ".into()),
1783 references: Vec::new(),
1784 tags: Vec::new(),
1785 rule_id: None,
1786 date: Some("2026-06-01".into()),
1787 logsource_category: Some("dns_query".into()),
1788 logsource_product: None,
1789 logsource_service: None,
1790 level: None,
1791 selections: vec![ValueSelection {
1792 name: "selection_query_name".into(),
1793 field: "QueryName".into(),
1794 modifiers: Vec::new(),
1795 values: vec!["bad.example".into()],
1796 }],
1797 })
1798 .unwrap();
1799 assert!(yaml.contains(&format!(
1800 "description: {}",
1801 yaml_str(DESCRIPTION_PLACEHOLDER)
1802 )));
1803 assert!(yaml.contains(&format!(" - {}", yaml_str(FALSE_POSITIVE_PLACEHOLDER))));
1804 assert!(yaml.contains("level: medium"));
1805 assert!(!yaml.contains("references:"));
1806 assert!(!yaml.contains("tags:"));
1807 assert!(!yaml.contains("id:"));
1808 }
1809
1810 #[test]
1811 fn value_draft_escapes_a_single_value() {
1812 let yaml = draft_rule_from_values(&ValueDraftSpec {
1813 title: "Callback URL".into(),
1814 description: None,
1815 references: Vec::new(),
1816 tags: Vec::new(),
1817 rule_id: None,
1818 date: Some("2026-06-01".into()),
1819 logsource_category: Some("proxy".into()),
1820 logsource_product: None,
1821 logsource_service: None,
1822 level: None,
1823 selections: vec![ValueSelection {
1824 name: "selection_c_uri".into(),
1825 field: "c-uri".into(),
1826 modifiers: Vec::new(),
1827 values: vec!["http://bad.example/a.php?id=1".into()],
1828 }],
1829 })
1830 .unwrap();
1831 assert!(
1832 yaml.contains(r"c-uri: 'http://bad.example/a.php\?id=1'"),
1833 "{yaml}"
1834 );
1835 assert!(!yaml.contains("a.php?id=1"), "{yaml}");
1836 }
1837
1838 #[test]
1839 fn value_draft_rejects_empty_input() {
1840 let empty = ValueDraftSpec {
1841 title: " ".into(),
1842 description: None,
1843 references: Vec::new(),
1844 tags: Vec::new(),
1845 rule_id: None,
1846 date: None,
1847 logsource_category: None,
1848 logsource_product: None,
1849 logsource_service: None,
1850 level: None,
1851 selections: vec![ValueSelection {
1852 name: "selection_query_name".into(),
1853 field: "QueryName".into(),
1854 modifiers: Vec::new(),
1855 values: vec!["bad.example".into()],
1856 }],
1857 };
1858 assert!(matches!(
1859 draft_rule_from_values(&empty),
1860 Err(DraftError::EmptyTitle)
1861 ));
1862 let no_selections = ValueDraftSpec {
1863 title: "Named".into(),
1864 selections: Vec::new(),
1865 ..empty.clone()
1866 };
1867 assert!(matches!(
1868 draft_rule_from_values(&no_selections),
1869 Err(DraftError::NoSelections)
1870 ));
1871 let bad_name = ValueDraftSpec {
1872 title: "Named".into(),
1873 selections: vec![ValueSelection {
1874 name: "ip".into(),
1875 field: "DestinationIp".into(),
1876 modifiers: Vec::new(),
1877 values: vec!["198.51.100.7".into()],
1878 }],
1879 ..empty
1880 };
1881 assert!(matches!(
1882 draft_rule_from_values(&bad_name),
1883 Err(DraftError::BadSelection { .. })
1884 ));
1885 }
1886}