Skip to main content

rsigma_eval/
rule_draft.rs

1//! Rule drafting: turn exemplar events into a draft Sigma detection rule.
2//!
3//! The operator feeds exemplar events (the malicious or noteworthy ones),
4//! optionally contrasted against a baseline corpus of normal traffic. This
5//! module profiles every field across the exemplars, drops volatile fields
6//! (timestamps, GUIDs, counters, high-entropy uniques), scores the rest by
7//! stability across exemplars times rarity in the baseline, infers a value
8//! form and a small Sigma modifier vocabulary per field, assembles a minimal
9//! selection, and emits a complete draft rule as standard Sigma YAML.
10//!
11//! The draft is verified end-to-end before it is returned: the emitted YAML is
12//! parsed via [`rsigma_parser::parse_sigma_yaml`] and compiled into the real
13//! [`Engine`], every exemplar must match (with a bounded
14//! predicate-drop relaxation and a minimum-field floor that errors instead of
15//! emitting an over-broad draft), and the baseline hit count and rate are
16//! recorded as the draft's estimated false-positive rate.
17//!
18//! The core is pure and deterministic: no randomness (the rule `id` is
19//! caller-supplied; the CLI generates a UUIDv4 for event drafts and a UUID v5
20//! for indicator drafts), and repeated runs over the same input yield
21//! byte-identical YAML. [`draft_rule`] uses the exemplars' native field names,
22//! so that draft must be evaluated without a mapping pipeline.
23//! [`draft_rule_from_values`] emits a rule from field values the caller already
24//! chose. It does not read events.
25//!
26//! This is the detection-authoring sibling of
27//! [`schema_discovery`](crate::schema_discovery): discovery mines unrecognized
28//! events into schema signatures, drafting mines exemplar events into a
29//! detection rule. Both follow the same contract: the tool proposes, a human
30//! reviews and commits.
31
32use 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// =============================================================================
46// Configuration
47// =============================================================================
48
49/// Tunables for a draft run. [`Default`] is a sensible starting point; the CLI
50/// exposes each as a flag.
51#[derive(Debug, Clone)]
52pub struct DraftConfig {
53    /// Maximum fields in a selection. Kept small so drafts stay readable.
54    pub max_fields: usize,
55    /// Relaxation floor: verification may drop failing fields down to this
56    /// count, below it drafting errors instead of emitting an over-broad rule.
57    pub min_fields: usize,
58    /// Fraction (0.0-1.0) of exemplars a field must appear in to be a
59    /// candidate. The default 1.0 keeps AND-selections sound.
60    pub min_prevalence: f64,
61    /// A field whose distinct exemplar values do not exceed this cap is
62    /// "enumerable" and emitted as an OR value list.
63    pub max_value_cardinality: usize,
64    /// Minimum length of a shared prefix/suffix/token before it becomes a
65    /// `startswith`/`endswith`/`contains` pattern, so short generic fragments
66    /// are never chosen.
67    pub min_token_len: usize,
68    /// A `contains` token matching more than this fraction of baseline events
69    /// is rejected as too generic.
70    pub max_baseline_token_prevalence: f64,
71    /// Force these fields into the selection (a warning is recorded when a
72    /// forced field is absent from some exemplars).
73    pub include_fields: Vec<String>,
74    /// Never consider these fields.
75    pub exclude_fields: Vec<String>,
76    /// Rule title override; derived from the dominant marker when unset.
77    pub title: Option<String>,
78    /// Rule `id`. The core is deterministic and never generates one; the CLI
79    /// passes a fresh UUIDv4. Unset omits the `id` key (lint reports it).
80    pub rule_id: Option<String>,
81    /// Rule `date` (YYYY-MM-DD). Defaults to today (UTC) when unset; tests
82    /// pass a fixed date for byte-identical output.
83    pub date: Option<String>,
84    /// Logsource overrides; each set dimension wins over inference.
85    pub logsource_category: Option<String>,
86    pub logsource_product: Option<String>,
87    pub logsource_service: Option<String>,
88    /// Evaluate the final draft against the baseline (the baseline is still
89    /// used for contrastive scoring when this is off).
90    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// =============================================================================
116// Errors
117// =============================================================================
118
119/// Why a draft could not be produced.
120#[derive(Debug, thiserror::Error)]
121pub enum DraftError {
122    /// No exemplar events were provided.
123    #[error("no exemplar events to draft from")]
124    NoExemplars,
125    /// No field survived profiling (all volatile, excluded, or below the
126    /// prevalence threshold).
127    #[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    /// Even after relaxing to the minimum-field floor the draft does not match
133    /// every exemplar, so an honest rule cannot be emitted.
134    #[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    /// A field forced via `include_fields` is absent from some exemplars, so
145    /// no draft containing it can match them. Forced fields are user intent
146    /// and are never dropped by relaxation.
147    #[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    /// The emitted YAML failed to parse or compile (a bug, surfaced honestly).
156    #[error("internal error: emitted draft failed to {stage}: {message}")]
157    Internal { stage: String, message: String },
158    /// [`draft_rule_from_values`] was called with no selections.
159    #[error("no selections to draft from")]
160    NoSelections,
161    /// A selection passed to [`draft_rule_from_values`] cannot be emitted.
162    #[error("selection {name:?} needs a selection_<ident> name, a field, and at least one value")]
163    BadSelection { name: String },
164    /// [`draft_rule_from_values`] was called with an empty title.
165    #[error("draft title is empty")]
166    EmptyTitle,
167}
168
169/// One detection selection in a value draft.
170///
171/// `name` must start with `selection_` so the emitted condition
172/// `1 of selection_*` covers it. `modifiers` are Sigma modifiers without the
173/// leading `|`.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct ValueSelection {
176    /// Detection item name, such as `selection_destination_ip`.
177    pub name: String,
178    /// Event field, such as `DestinationIp`.
179    pub field: String,
180    /// Sigma modifiers, such as `cidr` or `contains`.
181    pub modifiers: Vec<String>,
182    /// Literal values. `*`, `?`, and wildcard-adjacent backslashes are escaped.
183    pub values: Vec<String>,
184}
185
186/// Input for [`draft_rule_from_values`].
187///
188/// Every string is the caller's. This crate does not parse STIX.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct ValueDraftSpec {
191    /// Rule title. Empty titles are refused.
192    pub title: String,
193    /// Rule description. `None` or blank text emits the shared TODO placeholder.
194    pub description: Option<String>,
195    /// External references. Empty lists are omitted.
196    pub references: Vec<String>,
197    /// Sigma tags. Empty lists are omitted.
198    pub tags: Vec<String>,
199    /// Rule id. The caller owns how it is chosen.
200    pub rule_id: Option<String>,
201    /// `YYYY-MM-DD`. `None` uses today's UTC date.
202    pub date: Option<String>,
203    /// Logsource category.
204    pub logsource_category: Option<String>,
205    /// Logsource product.
206    pub logsource_product: Option<String>,
207    /// Logsource service.
208    pub logsource_service: Option<String>,
209    /// Sigma level. `None` emits `medium`.
210    pub level: Option<String>,
211    /// Selections combined with `1 of selection_*`.
212    pub selections: Vec<ValueSelection>,
213}
214
215/// Placeholders the event draft and the value draft both emit.
216const 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// =============================================================================
221// Public report types
222// =============================================================================
223
224/// How a field's values behave across the exemplars.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
226#[serde(rename_all = "snake_case")]
227pub enum Stability {
228    /// The same value in every exemplar.
229    Constant,
230    /// A small distinct value set (an OR list).
231    Enumerable,
232    /// Differing values sharing a prefix, suffix, or token.
233    Patterned,
234    /// No usable structure; never selected.
235    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/// One profiled field in the report, ranked.
251#[derive(Debug, Clone, Serialize)]
252pub struct DraftFieldReport {
253    /// Dot-joined field path.
254    pub field: String,
255    /// Contrastive score used for ranking (higher is better).
256    pub score: f64,
257    /// Value-stability class across the exemplars.
258    pub stability: Stability,
259    /// Sigma modifier chain chosen for the field (empty for a plain match).
260    pub modifier: String,
261    /// Display values or derived pattern, capped.
262    pub values: Vec<String>,
263    /// Fraction of baseline events this field's value form matches, when a
264    /// baseline was provided.
265    pub baseline_prevalence: Option<f64>,
266    /// Whether the field made it into the final selection.
267    pub selected: bool,
268}
269
270/// The result of a draft run: the rule plus the evidence behind it.
271#[derive(Debug, Clone)]
272pub struct DraftReport {
273    /// The complete draft rule, standard Sigma YAML, parse- and lint-checked.
274    pub rule_yaml: String,
275    /// Profiled candidate fields, ranked (selected fields first).
276    pub fields: Vec<DraftFieldReport>,
277    /// Number of exemplar events.
278    pub exemplar_total: usize,
279    /// Exemplars the final draft matches (always equals `exemplar_total`; a
280    /// draft that cannot match every exemplar is an error, not a result).
281    pub exemplar_matched: usize,
282    /// Number of baseline events provided.
283    pub baseline_total: usize,
284    /// Baseline events the draft matches (its estimated false-positive count),
285    /// when the baseline evaluation ran.
286    pub baseline_hits: Option<usize>,
287    /// `baseline_hits / baseline_total` (0.0-1.0), when computed.
288    pub baseline_hit_rate: Option<f64>,
289    /// Advisory notes: lint findings, relaxation drops, inference caveats.
290    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
407// =============================================================================
408// Entry point
409// =============================================================================
410
411/// Draft a Sigma detection rule from exemplar events, optionally contrasted
412/// against a baseline corpus (pass an empty slice for no baseline).
413///
414/// The returned draft is guaranteed to parse, compile, and match every
415/// exemplar; drafting errors instead of emitting a rule that does not.
416pub 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    // ---- Emit + verify (bounded relaxation) --------------------------------
425    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        // A field is a provable culprit when it is absent from a failing
439        // exemplar (the common case: partial-prevalence fields admitted by
440        // `min_prevalence`).
441        let absent_in_failing = |i: usize| {
442            failing
443                .iter()
444                .any(|&idx| candidate.profiles[i].values[idx].is_none())
445        };
446
447        // A forced field that provably breaks the match is a user decision we
448        // refuse to override; dropping other fields could never fix it, so
449        // error out immediately with the culprit named.
450        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        // Drop the lowest-ranked non-forced culprit; when no field is provably
473        // at fault (a value-form edge case), shed the weakest non-forced field.
474        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    // ---- Baseline hits ------------------------------------------------------
490    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    // ---- Lint ----------------------------------------------------------------
510    for w in rsigma_parser::lint_yaml_str(&yaml) {
511        candidate
512            .warnings
513            .push(format!("lint {}: {}", w.rule, w.message));
514    }
515
516    // ---- Report ---------------------------------------------------------------
517    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
559// =============================================================================
560// Selection assembly and grouping
561// =============================================================================
562
563/// One named selection: field, modifier chain, and values in emission order.
564struct 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    // Try a value-group split: partition exemplars by the highest-ranked
581    // selected field with a small distinct value set, and split only when it
582    // makes another multi-valued field single-valued in every partition.
583    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    // Splitter: first selected field (rank order) with 2..=MAX_VALUE_GROUPS
616    // distinct string values.
617    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    // Partition exemplar indexes by the splitter value, in first-seen order.
629    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    // Every group needs real support; splitting one exemplar per selection
641    // would just memorize the input.
642    if groups.iter().any(|(_, members)| members.len() < 2) {
643        return None;
644    }
645
646    // The split must earn its keep: some other selected field is multi-valued
647    // globally but single-valued within every partition.
648    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    // Build one selection per group, deriving per-group forms.
667    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
704/// A short selection-name suffix from a splitter value: the first token of the
705/// last path segment's stem (`C:\W\vssadmin.exe` and `vssadmin delete shadows`
706/// both slug to `vssadmin`), lowercased.
707fn 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// =============================================================================
726// Logsource inference
727// =============================================================================
728
729#[derive(Debug, Clone, Default)]
730struct DraftLogsource {
731    category: Option<String>,
732    product: Option<String>,
733    service: Option<String>,
734    inferred: bool,
735}
736
737/// Sysmon EventID to Sigma category, for the unambiguous mappings only.
738fn 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    // Majority schema over the exemplars.
761    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            // One shared EventID across all exemplars maps to a category and
777            // drops the service (Sigma sysmon rules use category + product).
778            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    // Overrides win per dimension.
805    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
829/// A short human marker for the title, from the dominant (first selected)
830/// field's form.
831fn 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
901/// Emit one Sigma rule from explicit field values and compile it.
902///
903/// Selections are OR-ed with `condition: 1 of selection_*`. A missing
904/// description uses the same placeholder as [`draft_rule`]. Newlines in text
905/// fields become spaces so each scalar stays on one line. `*`, `?`, and
906/// wildcard-adjacent backslashes in values are escaped before quoting.
907///
908/// # Examples
909///
910/// ```
911/// use rsigma_eval::{ValueDraftSpec, ValueSelection, draft_rule_from_values};
912///
913/// let yaml = draft_rule_from_values(&ValueDraftSpec {
914///     title: "Beacon address".into(),
915///     description: None,
916///     references: vec!["https://example.com/report".into()],
917///     tags: vec!["attack.command_and_control".into()],
918///     rule_id: Some("00000000-0000-4000-8000-000000000001".into()),
919///     date: Some("2026-06-01".into()),
920///     logsource_category: Some("network_connection".into()),
921///     logsource_product: None,
922///     logsource_service: None,
923///     level: Some("high".into()),
924///     selections: vec![ValueSelection {
925///         name: "selection_destination_ip".into(),
926///         field: "DestinationIp".into(),
927///         modifiers: Vec::new(),
928///         values: vec!["198.51.100.7".into()],
929///     }],
930/// })
931/// .expect("draft");
932/// assert!(yaml.contains("DestinationIp: 198.51.100.7"));
933/// ```
934pub 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
1106// =============================================================================
1107// Verification
1108// =============================================================================
1109
1110fn 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    // ---- Volatility heuristics ---------------------------------------------
1152
1153    #[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)); // seconds
1179        assert!(is_epoch_number(1_751_500_000_000.0)); // milliseconds
1180        assert!(!is_epoch_number(4688.0)); // an EventID is not an epoch
1181    }
1182
1183    #[test]
1184    fn time_date_name_match_is_word_bounded() {
1185        // Real timestamp fields are volatile...
1186        assert!(is_volatile_name("EventTime"));
1187        assert!(is_volatile_name("event_date"));
1188        assert!(is_volatile_name("datetime"));
1189        // ...but content fields that merely contain "time"/"date" as a
1190        // substring are not (regression: substring matching dropped these).
1191        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        // The common byte run ends inside 'é' (both é and è start 0xC3), so the
1201        // prefix must snap to a char boundary rather than panic on the slice.
1202        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        // Suffix: 'Ω' and 'é' both end in the continuation byte 0xA9, so the
1208        // overlap starts mid-character; snapping up yields no suffix and no panic.
1209        assert_eq!(shared_suffix(&["x\u{03a9}", "y\u{00e9}"], 1), None);
1210        // A fully-shared multibyte affix is preserved intact.
1211        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    // ---- Scoring -------------------------------------------------------------
1235
1236    #[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        // proto: tcp is ubiquitous in the baseline; action: exfil never occurs.
1242        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    // ---- Modifier inference ---------------------------------------------------
1330
1331    #[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        // The only shared token is 3 chars ("run"), below min_token_len 4.
1374        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        // "powershell" is a stable exemplar token but ubiquitous in baseline.
1390        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        // And the escaped rule still matches the exemplars end-to-end (the
1421        // verification loop enforces this; assert the report agrees).
1422        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    // ---- Grouping ----------------------------------------------------------------
1436
1437    #[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    // ---- Logsource -------------------------------------------------------------
1466
1467    #[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    // ---- Emission, round-trip, verification -----------------------------------
1528
1529    #[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        // Parses and compiles (draft_rule already enforced it; do it again
1536        // from the public surface).
1537        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        // Two baseline events the draft will also match.
1577        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    // ---- Relaxation and error paths ------------------------------------------
1610
1611    #[test]
1612    fn relaxation_drops_partial_prevalence_fields() {
1613        // "extra" appears in half the exemplars; selecting it breaks the AND
1614        // selection, so verification must drop it and still succeed.
1615        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        // Two disjoint half-prevalence fields and nothing else: no 2-field AND
1632        // can match every exemplar, and the floor forbids going below 2.
1633        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        // "extra" is forced but absent from half the exemplars: relaxation
1653        // must not strip the useful fields around it, it must name the
1654        // culprit and stop.
1655        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    // ---- Flags -------------------------------------------------------------------
1695
1696    #[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}