Skip to main content

rsigma_parser/
emit.rs

1//! Emit a parsed Sigma rule back to canonical Sigma YAML.
2//!
3//! This is the inverse of [`parse_sigma_yaml`](crate::parse_sigma_yaml): it
4//! turns a [`SigmaRule`] (or a [`SigmaCollection`] of detection rules) back
5//! into standard Sigma YAML. Parsing then emitting then parsing again yields an
6//! equal AST for the detection-rule shapes the parser produces (field matching
7//! with modifiers, value lists, keyword blocks, `field[any]`/`field[all]` array
8//! blocks, boolean and quantified conditions, and all standard metadata).
9//!
10//! The emitter is deterministic: mapping-shaped collections (named detections,
11//! logsource custom fields, custom attributes) are emitted in sorted key order,
12//! so the same rule always produces byte-identical YAML. Detection value order
13//! and condition order are preserved as-is.
14//!
15//! Value scalars are rendered in Sigma's canonical quoting: a string stays
16//! plain only when YAML would read it back as exactly that string, and literal
17//! `*`, `?`, and `\` are escaped so a re-parse reproduces the same
18//! [`SigmaString`] wildcard structure.
19
20use std::collections::{BTreeMap, HashMap};
21use std::fmt::Write as _;
22
23use crate::ast::{
24    ArrayQuantifier, ConditionExpr, ConditionOperator, CorrelationCondition, CorrelationRule,
25    Detection, DetectionItem, Detections, FieldAlias, FilterRule, FilterRuleTarget, LogSource,
26    Modifier, Related, RelationType, SigmaCollection, SigmaRule, Status, WindowMode,
27};
28use crate::style::{KeyCtx, Lead, RSIGMA_ORDER, STEP, ScalarCtx, encode_key, push_scalar};
29use crate::value::{SigmaString, SigmaValue, SpecialChar, StringPart};
30
31/// Emit a single detection [`SigmaRule`] as canonical Sigma YAML.
32///
33/// The output always ends with a trailing newline and re-parses to an equal
34/// [`SigmaRule`].
35pub fn emit_rule_yaml(rule: &SigmaRule) -> String {
36    let mut out = String::new();
37
38    push_scalar(
39        &mut out,
40        "",
41        Lead::Key("title"),
42        &rule.title,
43        ScalarCtx::Prose,
44    );
45    if let Some(id) = &rule.id {
46        push_scalar(&mut out, "", Lead::Key("id"), id, ScalarCtx::Value);
47    }
48    if let Some(name) = &rule.name {
49        push_scalar(&mut out, "", Lead::Key("name"), name, ScalarCtx::Value);
50    }
51    if let Some(status) = &rule.status {
52        push_line(&mut out, "status", status_str(*status));
53    }
54    if let Some(description) = &rule.description {
55        push_scalar(
56            &mut out,
57            "",
58            Lead::Key("description"),
59            description,
60            ScalarCtx::Prose,
61        );
62    }
63    emit_string_list(&mut out, "references", &rule.references, ScalarCtx::Prose);
64    if let Some(author) = &rule.author {
65        push_scalar(&mut out, "", Lead::Key("author"), author, ScalarCtx::Prose);
66    }
67    if let Some(date) = &rule.date {
68        push_scalar(&mut out, "", Lead::Key("date"), date, ScalarCtx::Value);
69    }
70    if let Some(modified) = &rule.modified {
71        push_scalar(
72            &mut out,
73            "",
74            Lead::Key("modified"),
75            modified,
76            ScalarCtx::Value,
77        );
78    }
79    emit_related(&mut out, &rule.related);
80    emit_string_list(&mut out, "tags", &rule.tags, ScalarCtx::Prose);
81    if let Some(version) = rule.sigma_version {
82        push_line(&mut out, "sigma-version", &version.to_string());
83    }
84    emit_logsource(&mut out, &rule.logsource);
85    emit_detection(&mut out, &rule.detection);
86    emit_string_list(&mut out, "fields", &rule.fields, ScalarCtx::Prose);
87    emit_string_list(
88        &mut out,
89        "falsepositives",
90        &rule.falsepositives,
91        ScalarCtx::Prose,
92    );
93    if let Some(level) = &rule.level {
94        push_line(&mut out, "level", level.as_str());
95    }
96    emit_string_list(&mut out, "scope", &rule.scope, ScalarCtx::Prose);
97    if let Some(license) = &rule.license {
98        push_scalar(
99            &mut out,
100            "",
101            Lead::Key("license"),
102            license,
103            ScalarCtx::Prose,
104        );
105    }
106    if let Some(taxonomy) = &rule.taxonomy {
107        push_scalar(
108            &mut out,
109            "",
110            Lead::Key("taxonomy"),
111            taxonomy,
112            ScalarCtx::Value,
113        );
114    }
115    emit_custom_attributes(&mut out, &rule.custom_attributes);
116
117    out
118}
119
120/// Emit a single [`CorrelationRule`] as canonical Sigma YAML.
121///
122/// The output always ends with a trailing newline and re-parses to an equal
123/// [`CorrelationRule`]. Correlation bodies are emitted in the key order the
124/// parser accepts, `window` only when it is not the default sliding mode, and
125/// `generate` only when true.
126///
127/// ```rust
128/// use rsigma_parser::{emit_correlation_yaml, parse_sigma_yaml};
129///
130/// let yaml = r#"
131/// title: Burst of failed logins
132/// correlation:
133///     type: event_count
134///     rules:
135///         - failed_login
136///     group-by:
137///         - User
138///     timespan: 5m
139///     condition:
140///         gte: 10
141/// "#;
142/// let collection = parse_sigma_yaml(yaml).unwrap();
143/// let emitted = emit_correlation_yaml(&collection.correlations[0]);
144/// assert!(emitted.contains("type: event_count"));
145/// assert!(emitted.contains("gte: 10"));
146/// ```
147pub fn emit_correlation_yaml(rule: &CorrelationRule) -> String {
148    let mut out = String::new();
149
150    push_scalar(
151        &mut out,
152        "",
153        Lead::Key("title"),
154        &rule.title,
155        ScalarCtx::Prose,
156    );
157    if let Some(id) = &rule.id {
158        push_scalar(&mut out, "", Lead::Key("id"), id, ScalarCtx::Value);
159    }
160    if let Some(name) = &rule.name {
161        push_scalar(&mut out, "", Lead::Key("name"), name, ScalarCtx::Value);
162    }
163    if let Some(status) = &rule.status {
164        push_line(&mut out, "status", status_str(*status));
165    }
166    if let Some(description) = &rule.description {
167        push_scalar(
168            &mut out,
169            "",
170            Lead::Key("description"),
171            description,
172            ScalarCtx::Prose,
173        );
174    }
175    emit_string_list(&mut out, "references", &rule.references, ScalarCtx::Prose);
176    if let Some(author) = &rule.author {
177        push_scalar(&mut out, "", Lead::Key("author"), author, ScalarCtx::Prose);
178    }
179    if let Some(date) = &rule.date {
180        push_scalar(&mut out, "", Lead::Key("date"), date, ScalarCtx::Value);
181    }
182    if let Some(modified) = &rule.modified {
183        push_scalar(
184            &mut out,
185            "",
186            Lead::Key("modified"),
187            modified,
188            ScalarCtx::Value,
189        );
190    }
191    emit_related(&mut out, &rule.related);
192    emit_string_list(&mut out, "tags", &rule.tags, ScalarCtx::Prose);
193    if let Some(version) = rule.sigma_version {
194        push_line(&mut out, "sigma-version", &version.to_string());
195    }
196
197    let _ = writeln!(out, "correlation:");
198    push_line(&mut out, "    type", rule.correlation_type.as_str());
199    emit_string_list_at(&mut out, "    rules", &rule.rules, ScalarCtx::Value);
200    emit_string_list_at(&mut out, "    group-by", &rule.group_by, ScalarCtx::Value);
201    push_line(&mut out, "    timespan", &rule.timespan.to_string());
202    if rule.window != WindowMode::Sliding {
203        push_line(&mut out, "    window", rule.window.as_str());
204    }
205    if let Some(gap) = &rule.gap {
206        push_line(&mut out, "    gap", &gap.to_string());
207    }
208    emit_correlation_condition(&mut out, "    ", &rule.condition);
209    emit_correlation_aliases(&mut out, &rule.aliases);
210    if rule.generate {
211        push_line(&mut out, "    generate", "true");
212    }
213
214    emit_string_list(&mut out, "fields", &rule.fields, ScalarCtx::Prose);
215    emit_string_list(
216        &mut out,
217        "falsepositives",
218        &rule.falsepositives,
219        ScalarCtx::Prose,
220    );
221    if let Some(level) = &rule.level {
222        push_line(&mut out, "level", level.as_str());
223    }
224    emit_string_list(&mut out, "scope", &rule.scope, ScalarCtx::Prose);
225    if let Some(license) = &rule.license {
226        push_scalar(
227            &mut out,
228            "",
229            Lead::Key("license"),
230            license,
231            ScalarCtx::Prose,
232        );
233    }
234    if let Some(taxonomy) = &rule.taxonomy {
235        push_scalar(
236            &mut out,
237            "",
238            Lead::Key("taxonomy"),
239            taxonomy,
240            ScalarCtx::Value,
241        );
242    }
243    emit_custom_attributes(&mut out, &rule.custom_attributes);
244
245    out
246}
247
248/// Emit a single [`FilterRule`] as canonical Sigma YAML.
249///
250/// The output always ends with a trailing newline and re-parses to an equal
251/// [`FilterRule`]. The `filter:` block carries the detection items and
252/// condition; `rules` is omitted when the filter applies to every rule.
253///
254/// ```rust
255/// use rsigma_parser::{emit_filter_yaml, parse_sigma_yaml};
256///
257/// let yaml = r#"
258/// title: Drop system accounts
259/// logsource:
260///     product: windows
261/// filter:
262///     rules:
263///         - failed_login
264///     selection:
265///         User|endswith: '$'
266///     condition: selection
267/// "#;
268/// let collection = parse_sigma_yaml(yaml).unwrap();
269/// let emitted = emit_filter_yaml(&collection.filters[0]);
270/// assert!(emitted.contains("filter:"));
271/// assert!(emitted.contains("User|endswith"));
272/// ```
273pub fn emit_filter_yaml(rule: &FilterRule) -> String {
274    let mut out = String::new();
275
276    push_scalar(
277        &mut out,
278        "",
279        Lead::Key("title"),
280        &rule.title,
281        ScalarCtx::Prose,
282    );
283    if let Some(id) = &rule.id {
284        push_scalar(&mut out, "", Lead::Key("id"), id, ScalarCtx::Value);
285    }
286    if let Some(name) = &rule.name {
287        push_scalar(&mut out, "", Lead::Key("name"), name, ScalarCtx::Value);
288    }
289    if let Some(status) = &rule.status {
290        push_line(&mut out, "status", status_str(*status));
291    }
292    if let Some(description) = &rule.description {
293        push_scalar(
294            &mut out,
295            "",
296            Lead::Key("description"),
297            description,
298            ScalarCtx::Prose,
299        );
300    }
301    emit_string_list(&mut out, "references", &rule.references, ScalarCtx::Prose);
302    if let Some(author) = &rule.author {
303        push_scalar(&mut out, "", Lead::Key("author"), author, ScalarCtx::Prose);
304    }
305    if let Some(date) = &rule.date {
306        push_scalar(&mut out, "", Lead::Key("date"), date, ScalarCtx::Value);
307    }
308    if let Some(modified) = &rule.modified {
309        push_scalar(
310            &mut out,
311            "",
312            Lead::Key("modified"),
313            modified,
314            ScalarCtx::Value,
315        );
316    }
317    emit_related(&mut out, &rule.related);
318    emit_string_list(&mut out, "tags", &rule.tags, ScalarCtx::Prose);
319    if let Some(version) = rule.sigma_version {
320        push_line(&mut out, "sigma-version", &version.to_string());
321    }
322    match &rule.logsource {
323        Some(logsource) => emit_logsource(&mut out, logsource),
324        None => {
325            let _ = writeln!(out, "logsource: {{}}");
326        }
327    }
328
329    let _ = writeln!(out, "filter:");
330    if let FilterRuleTarget::Specific(targets) = &rule.rules {
331        emit_string_list_at(&mut out, "    rules", targets, ScalarCtx::Value);
332    }
333    for (name, det) in sorted_named(&rule.detection.named) {
334        emit_named_detection(&mut out, name, det, "    ");
335    }
336    emit_timeframe(&mut out, "    ", &rule.detection);
337    emit_condition_at(&mut out, "    ", &rule.detection.conditions);
338
339    emit_string_list(&mut out, "fields", &rule.fields, ScalarCtx::Prose);
340    emit_string_list(
341        &mut out,
342        "falsepositives",
343        &rule.falsepositives,
344        ScalarCtx::Prose,
345    );
346    if let Some(level) = &rule.level {
347        push_line(&mut out, "level", level.as_str());
348    }
349    emit_string_list(&mut out, "scope", &rule.scope, ScalarCtx::Prose);
350    if let Some(license) = &rule.license {
351        push_scalar(
352            &mut out,
353            "",
354            Lead::Key("license"),
355            license,
356            ScalarCtx::Prose,
357        );
358    }
359    if let Some(taxonomy) = &rule.taxonomy {
360        push_scalar(
361            &mut out,
362            "",
363            Lead::Key("taxonomy"),
364            taxonomy,
365            ScalarCtx::Value,
366        );
367    }
368    emit_custom_attributes(&mut out, &rule.custom_attributes);
369
370    out
371}
372
373/// Emit every detection rule in a collection, separated by `---` documents.
374///
375/// Correlation and filter documents are not part of the reverse-conversion
376/// surface and are skipped; only [`SigmaCollection::rules`] are emitted.
377pub fn emit_collection_yaml(collection: &SigmaCollection) -> String {
378    collection
379        .rules
380        .iter()
381        .map(emit_rule_yaml)
382        .collect::<Vec<_>>()
383        .join("---\n")
384}
385
386// =============================================================================
387// Metadata sections
388// =============================================================================
389
390fn push_line(out: &mut String, key: &str, value: &str) {
391    let _ = writeln!(out, "{key}: {value}");
392}
393
394fn emit_string_list(out: &mut String, key: &str, items: &[String], ctx: ScalarCtx) {
395    emit_string_list_at(out, key, items, ctx);
396}
397
398/// Emit a list whose key may carry leading indentation (for nested blocks).
399fn emit_string_list_at(out: &mut String, key: &str, items: &[String], ctx: ScalarCtx) {
400    if items.is_empty() {
401        return;
402    }
403    let _ = writeln!(out, "{key}:");
404    let indent = format!("{}{STEP}", leading_whitespace(key));
405    for item in items {
406        push_scalar(out, &indent, Lead::Dash, item, ctx);
407    }
408}
409
410fn leading_whitespace(s: &str) -> &str {
411    &s[..s.len() - s.trim_start().len()]
412}
413
414fn emit_related(out: &mut String, related: &[Related]) {
415    if related.is_empty() {
416        return;
417    }
418    let _ = writeln!(out, "related:");
419    for entry in related {
420        push_scalar(
421            out,
422            &format!("{STEP}- "),
423            Lead::Key("id"),
424            &entry.id,
425            ScalarCtx::Value,
426        );
427        let _ = writeln!(out, "{STEP}  type: {}", relation_str(entry.relation_type));
428    }
429}
430
431fn emit_logsource(out: &mut String, logsource: &LogSource) {
432    // An empty `logsource:` key parses as null, which the parser reports as
433    // not being a mapping; an explicit empty mapping gets the clearer error
434    // that no log source field is set.
435    if logsource.category.is_none()
436        && logsource.product.is_none()
437        && logsource.service.is_none()
438        && logsource.definition.is_none()
439        && logsource.custom.is_empty()
440    {
441        let _ = writeln!(out, "logsource: {{}}");
442        return;
443    }
444    let _ = writeln!(out, "logsource:");
445    if let Some(category) = &logsource.category {
446        push_scalar(out, STEP, Lead::Key("category"), category, ScalarCtx::Value);
447    }
448    if let Some(product) = &logsource.product {
449        push_scalar(out, STEP, Lead::Key("product"), product, ScalarCtx::Value);
450    }
451    if let Some(service) = &logsource.service {
452        push_scalar(out, STEP, Lead::Key("service"), service, ScalarCtx::Value);
453    }
454    if let Some(definition) = &logsource.definition {
455        push_scalar(
456            out,
457            STEP,
458            Lead::Key("definition"),
459            definition,
460            ScalarCtx::Prose,
461        );
462    }
463    for (key, value) in sorted(&logsource.custom) {
464        push_scalar(
465            out,
466            STEP,
467            Lead::Key(&encode_key(key, KeyCtx::Key)),
468            value,
469            ScalarCtx::Value,
470        );
471    }
472}
473
474fn emit_custom_attributes(out: &mut String, attrs: &HashMap<String, yaml_serde::Value>) {
475    let mut keys: Vec<&str> = attrs.keys().map(String::as_str).collect();
476    let mut ordered: Vec<&str> = RSIGMA_ORDER
477        .iter()
478        .copied()
479        .filter(|key| attrs.contains_key(*key))
480        .collect();
481    keys.sort_unstable();
482    ordered.extend(keys.into_iter().filter(|key| !RSIGMA_ORDER.contains(key)));
483    for key in ordered {
484        let value = &attrs[key];
485        emit_yaml_value(out, &encode_key(key, KeyCtx::Key), value, "");
486    }
487}
488
489// =============================================================================
490// Detection section
491// =============================================================================
492
493fn emit_detection(out: &mut String, detection: &Detections) {
494    let _ = writeln!(out, "detection:");
495    for (name, det) in sorted_named(&detection.named) {
496        emit_named_detection(out, name, det, STEP);
497    }
498    emit_timeframe(out, STEP, detection);
499    emit_condition(out, &detection.conditions);
500}
501
502fn emit_timeframe(out: &mut String, indent: &str, detection: &Detections) {
503    if let Some(timeframe) = &detection.timeframe {
504        push_scalar(
505            out,
506            indent,
507            Lead::Key("timeframe"),
508            timeframe,
509            ScalarCtx::Value,
510        );
511    }
512}
513
514fn emit_condition(out: &mut String, conditions: &[ConditionExpr]) {
515    emit_condition_at(out, STEP, conditions);
516}
517
518fn emit_condition_at(out: &mut String, indent: &str, conditions: &[ConditionExpr]) {
519    match conditions {
520        [] => {}
521        [single] => {
522            push_scalar(
523                out,
524                indent,
525                Lead::Key("condition"),
526                &condition_source(single),
527                ScalarCtx::Condition,
528            );
529        }
530        many => {
531            let _ = writeln!(out, "{indent}condition:");
532            let nested = deeper(indent);
533            for cond in many {
534                push_scalar(
535                    out,
536                    &nested,
537                    Lead::Dash,
538                    &condition_source(cond),
539                    ScalarCtx::Condition,
540                );
541            }
542        }
543    }
544}
545
546/// Render a condition expression as a Sigma condition string, without the
547/// redundant outer parentheses [`ConditionExpr`]'s `Display` adds around a
548/// top-level `and`/`or`.
549fn condition_source(expr: &ConditionExpr) -> String {
550    match expr {
551        ConditionExpr::And(parts) => parts
552            .iter()
553            .map(|p| p.to_string())
554            .collect::<Vec<_>>()
555            .join(" and "),
556        ConditionExpr::Or(parts) => parts
557            .iter()
558            .map(|p| p.to_string())
559            .collect::<Vec<_>>()
560            .join(" or "),
561        other => other.to_string(),
562    }
563}
564
565/// Emit a correlation `condition:` block at `indent` (including the key).
566fn emit_correlation_condition(out: &mut String, indent: &str, condition: &CorrelationCondition) {
567    match condition {
568        CorrelationCondition::Threshold {
569            predicates,
570            field,
571            percentile,
572        } => {
573            let _ = writeln!(out, "{indent}condition:");
574            let nested = deeper(indent);
575            let mut ordered: Vec<&(ConditionOperator, u64)> = predicates.iter().collect();
576            ordered.sort_by_key(|(op, _)| operator_rank(*op));
577            for (op, value) in ordered {
578                push_line(
579                    out,
580                    &format!("{nested}{}", operator_str(*op)),
581                    &value.to_string(),
582                );
583            }
584            if let Some(field) = field {
585                match field.as_slice() {
586                    [single] => {
587                        push_scalar(out, &nested, Lead::Key("field"), single, ScalarCtx::Value)
588                    }
589                    many => {
590                        emit_string_list_at(out, &format!("{nested}field"), many, ScalarCtx::Value)
591                    }
592                }
593            }
594            if let Some(percentile) = percentile {
595                push_line(out, &format!("{nested}percentile"), &percentile.to_string());
596            }
597        }
598        CorrelationCondition::Extended(expr) => {
599            push_scalar(
600                out,
601                indent,
602                Lead::Key("condition"),
603                &condition_source(expr),
604                ScalarCtx::Condition,
605            );
606        }
607    }
608}
609
610/// Emit the `aliases:` mapping of a correlation, with sorted per-rule keys.
611fn emit_correlation_aliases(out: &mut String, aliases: &[FieldAlias]) {
612    if aliases.is_empty() {
613        return;
614    }
615    let _ = writeln!(out, "{STEP}aliases:");
616    for alias in aliases {
617        let _ = writeln!(
618            out,
619            "{STEP}{STEP}{}:",
620            encode_key(&alias.alias, KeyCtx::Key)
621        );
622        let mut mapping: Vec<(&String, &String)> = alias.mapping.iter().collect();
623        mapping.sort_by(|a, b| a.0.cmp(b.0));
624        for (rule, field) in mapping {
625            push_scalar(
626                out,
627                &format!("{STEP}{STEP}{STEP}"),
628                Lead::Key(&encode_key(rule, KeyCtx::Key)),
629                field,
630                ScalarCtx::Value,
631            );
632        }
633    }
634}
635
636fn emit_named_detection(out: &mut String, name: &str, det: &Detection, indent: &str) {
637    let _ = writeln!(out, "{indent}{}:", encode_key(name, KeyCtx::Key));
638    emit_detection_value(out, det, &deeper(indent));
639}
640
641/// Emit the body of a detection at `indent` (a mapping of items, a YAML list,
642/// or a keyword list depending on the detection shape).
643fn emit_detection_value(out: &mut String, det: &Detection, indent: &str) {
644    match det {
645        Detection::AnyOf(subs) => {
646            for sub in subs {
647                emit_list_item(out, sub, indent);
648            }
649        }
650        Detection::Keywords(values) => {
651            for value in values {
652                push_value(out, indent, Lead::Dash, value, false, false);
653            }
654        }
655        map_shaped => emit_map_entries(out, map_shaped, indent),
656    }
657}
658
659/// Emit the `key: value` entries of a mapping-shaped detection.
660fn emit_map_entries(out: &mut String, det: &Detection, indent: &str) {
661    match det {
662        Detection::AllOf(items) => {
663            for item in items {
664                emit_item(out, item, indent);
665            }
666        }
667        Detection::And(subs) => {
668            for sub in subs {
669                emit_map_entries(out, sub, indent);
670            }
671        }
672        Detection::ArrayMatch {
673            field,
674            quantifier,
675            body,
676        } => {
677            let key = format!("{}[{}]", field, array_str(*quantifier));
678            let _ = writeln!(out, "{indent}{}:", encode_key(&key, KeyCtx::FieldKey));
679            emit_detection_value(out, body, &deeper(indent));
680        }
681        Detection::Conditional { named, condition } => {
682            for (name, sub) in sorted_named(named) {
683                emit_named_detection(out, name, sub, indent);
684            }
685            push_scalar(
686                out,
687                indent,
688                Lead::Key("condition"),
689                &condition_source(condition),
690                ScalarCtx::Condition,
691            );
692        }
693        // List-shaped detections cannot appear as bare map entries; render them
694        // under a synthetic block so nothing is silently dropped.
695        Detection::AnyOf(_) | Detection::Keywords(_) => {
696            emit_detection_value(out, det, indent);
697        }
698    }
699}
700
701/// Emit one YAML list item (`- ...`) for an `AnyOf` sub-detection.
702fn emit_list_item(out: &mut String, det: &Detection, indent: &str) {
703    let mut buf = String::new();
704    emit_detection_value(&mut buf, det, "");
705    for (i, line) in buf.lines().enumerate() {
706        if i == 0 {
707            let _ = writeln!(out, "{indent}- {line}");
708        } else {
709            let _ = writeln!(out, "{indent}  {line}");
710        }
711    }
712}
713
714/// Emit a single detection item (`field|mods: value` or a value list).
715fn emit_item(out: &mut String, item: &DetectionItem, indent: &str) {
716    let base = item.field.name.as_deref().unwrap_or(".");
717    let key = field_key(base, &item.field.modifiers);
718    // `re`, `cidr`, and `fieldref` values are raw strings (the parser reads them
719    // without wildcard interpretation), so they must be emitted verbatim rather
720    // than wildcard-escaped, or a regex like `ab.*c` would gain a stray `\`.
721    let raw = item
722        .field
723        .modifiers
724        .iter()
725        .any(|m| matches!(m, Modifier::Re | Modifier::Cidr | Modifier::FieldRef));
726    let expand = item.field.modifiers.contains(&Modifier::Expand);
727    match item.values.as_slice() {
728        [single] => {
729            push_value(out, indent, Lead::Key(&key), single, raw, expand);
730        }
731        values => {
732            let _ = writeln!(out, "{indent}{key}:");
733            for value in values {
734                push_value(out, &deeper(indent), Lead::Dash, value, raw, expand);
735            }
736        }
737    }
738}
739
740/// Write a [`SigmaValue`]: strings go through [`push_scalar`] in the value
741/// context, while non-string scalars are copied verbatim.
742fn push_value(
743    out: &mut String,
744    indent: &str,
745    lead: Lead<'_>,
746    value: &SigmaValue,
747    raw: bool,
748    expand: bool,
749) {
750    match value {
751        SigmaValue::String(s) => {
752            let source = if expand {
753                s.original.clone()
754            } else if raw {
755                s.as_plain().unwrap_or_else(|| s.original.clone())
756            } else {
757                sigma_string_source(s)
758            };
759            push_scalar(out, indent, lead, &source, ScalarCtx::Value);
760        }
761        other => {
762            let token = match other {
763                SigmaValue::Integer(n) => n.to_string(),
764                SigmaValue::Float(f) => float_token(*f),
765                SigmaValue::Bool(b) => b.to_string(),
766                SigmaValue::Null => "null".to_string(),
767                SigmaValue::String(_) => unreachable!("string handled above"),
768            };
769            let prefix = match lead {
770                Lead::Key(key) => format!("{indent}{key}:"),
771                Lead::Dash => format!("{indent}-"),
772            };
773            let _ = writeln!(out, "{prefix} {token}");
774        }
775    }
776}
777
778// =============================================================================
779// yaml_serde value emission (custom attributes)
780// =============================================================================
781
782fn emit_yaml_value(out: &mut String, key: &str, value: &yaml_serde::Value, indent: &str) {
783    match value {
784        yaml_serde::Value::Mapping(map) if !map.is_empty() => {
785            let _ = writeln!(out, "{indent}{key}:");
786            for (k, v) in map {
787                let child_key = yaml_key(k);
788                emit_yaml_value(out, &child_key, v, &deeper(indent));
789            }
790        }
791        yaml_serde::Value::Mapping(_) => {
792            let _ = writeln!(out, "{indent}{key}: {{}}");
793        }
794        yaml_serde::Value::Sequence(seq) if !seq.is_empty() => {
795            let _ = writeln!(out, "{indent}{key}:");
796            for v in seq {
797                emit_yaml_seq_item(out, v, &deeper(indent));
798            }
799        }
800        yaml_serde::Value::Sequence(_) => {
801            let _ = writeln!(out, "{indent}{key}: []");
802        }
803        yaml_serde::Value::String(s) => {
804            push_scalar(out, indent, Lead::Key(key), s, ScalarCtx::Value);
805        }
806        scalar => {
807            let _ = writeln!(out, "{indent}{key}: {}", yaml_scalar(scalar));
808        }
809    }
810}
811
812/// Emit one YAML sequence item, including nested mappings and sequences.
813fn emit_yaml_seq_item(out: &mut String, value: &yaml_serde::Value, indent: &str) {
814    match value {
815        yaml_serde::Value::Mapping(map) if !map.is_empty() => {
816            let mut buf = String::new();
817            for (k, v) in map {
818                let child_key = yaml_key(k);
819                emit_yaml_value(&mut buf, &child_key, v, "");
820            }
821            for (i, line) in buf.lines().enumerate() {
822                if i == 0 {
823                    let _ = writeln!(out, "{indent}- {line}");
824                } else {
825                    let _ = writeln!(out, "{indent}  {line}");
826                }
827            }
828        }
829        yaml_serde::Value::Mapping(_) => {
830            let _ = writeln!(out, "{indent}- {{}}");
831        }
832        yaml_serde::Value::Sequence(seq) if !seq.is_empty() => {
833            let _ = writeln!(out, "{indent}-");
834            for v in seq {
835                emit_yaml_seq_item(out, v, &deeper(indent));
836            }
837        }
838        yaml_serde::Value::Sequence(_) => {
839            let _ = writeln!(out, "{indent}- []");
840        }
841        yaml_serde::Value::String(s) => {
842            push_scalar(out, indent, Lead::Dash, s, ScalarCtx::Value);
843        }
844        scalar => {
845            let _ = writeln!(out, "{indent}- {}", yaml_scalar(scalar));
846        }
847    }
848}
849
850fn yaml_key(value: &yaml_serde::Value) -> String {
851    match value {
852        yaml_serde::Value::String(s) => encode_key(s, KeyCtx::Key),
853        other => yaml_scalar(other),
854    }
855}
856
857fn yaml_scalar(value: &yaml_serde::Value) -> String {
858    match value {
859        yaml_serde::Value::Null => "null".to_string(),
860        yaml_serde::Value::Bool(b) => b.to_string(),
861        yaml_serde::Value::Number(n) if n.is_f64() => float_token(n.as_f64().unwrap_or_default()),
862        yaml_serde::Value::Number(n) => n.to_string(),
863        yaml_serde::Value::String(s) => encode_key(s, KeyCtx::Key),
864        // Nested collections are handled by emit_yaml_value; an inline fallback
865        // keeps the emitter total for unexpected placements.
866        other => format!("{other:?}"),
867    }
868}
869
870// =============================================================================
871// Scalars, keys, and value tokens
872// =============================================================================
873
874/// Format a float so it re-parses as a float (never collapses `3.0` to `3`).
875fn float_token(f: f64) -> String {
876    if f.is_nan() {
877        return ".nan".to_string();
878    }
879    if f == f64::INFINITY {
880        return ".inf".to_string();
881    }
882    if f == f64::NEG_INFINITY {
883        return "-.inf".to_string();
884    }
885    let s = f.to_string();
886    if s.contains(['.', 'e', 'E']) {
887        s
888    } else {
889        format!("{s}.0")
890    }
891}
892
893/// Reconstruct the Sigma source text of a [`SigmaString`], escaping literal
894/// wildcard and backslash characters so the value round-trips through the
895/// parser unchanged.
896fn sigma_string_source(value: &SigmaString) -> String {
897    let mut out = String::with_capacity(value.original.len());
898    for part in &value.parts {
899        match part {
900            StringPart::Plain(text) => push_escaped_literal(&mut out, text),
901            StringPart::Special(SpecialChar::WildcardMulti) => out.push('*'),
902            StringPart::Special(SpecialChar::WildcardSingle) => out.push('?'),
903        }
904    }
905    out
906}
907
908/// Escape a literal segment: `*`/`?` always gain a backslash; a run of
909/// backslashes is doubled only when it would otherwise bind to a following
910/// wildcard or end the value (keeping plain Windows paths readable).
911fn push_escaped_literal(out: &mut String, text: &str) {
912    let chars: Vec<char> = text.chars().collect();
913    let mut i = 0;
914    while i < chars.len() {
915        match chars[i] {
916            '*' => out.push_str("\\*"),
917            '?' => out.push_str("\\?"),
918            '\\' => {
919                let mut j = i;
920                while j < chars.len() && chars[j] == '\\' {
921                    j += 1;
922                }
923                let run = j - i;
924                let next = chars.get(j);
925                let must_escape = run > 1 || matches!(next, Some('*') | Some('?') | None);
926                for _ in 0..run {
927                    out.push_str(if must_escape { "\\\\" } else { "\\" });
928                }
929                i = j;
930                continue;
931            }
932            other => out.push(other),
933        }
934        i += 1;
935    }
936}
937
938/// Build a detection key from a field name and its ordered modifiers.
939fn field_key(field: &str, modifiers: &[Modifier]) -> String {
940    let mut key = String::new();
941    key.push_str(field);
942    for modifier in modifiers {
943        key.push('|');
944        key.push_str(modifier_str(*modifier));
945    }
946    encode_key(&key, KeyCtx::FieldKey)
947}
948
949pub(crate) fn modifier_str(modifier: Modifier) -> &'static str {
950    match modifier {
951        Modifier::Contains => "contains",
952        Modifier::StartsWith => "startswith",
953        Modifier::EndsWith => "endswith",
954        Modifier::All => "all",
955        Modifier::Base64 => "base64",
956        Modifier::Base64Offset => "base64offset",
957        Modifier::Wide => "wide",
958        Modifier::Utf16be => "utf16be",
959        Modifier::Utf16 => "utf16",
960        Modifier::WindAsh => "windash",
961        Modifier::Re => "re",
962        Modifier::Cidr => "cidr",
963        Modifier::Cased => "cased",
964        Modifier::Exists => "exists",
965        Modifier::Expand => "expand",
966        Modifier::FieldRef => "fieldref",
967        Modifier::Gt => "gt",
968        Modifier::Gte => "gte",
969        Modifier::Lt => "lt",
970        Modifier::Lte => "lte",
971        Modifier::Neq => "neq",
972        Modifier::IgnoreCase => "i",
973        Modifier::Multiline => "m",
974        Modifier::DotAll => "s",
975        Modifier::Minute => "minute",
976        Modifier::Hour => "hour",
977        Modifier::Day => "day",
978        Modifier::Week => "week",
979        Modifier::Month => "month",
980        Modifier::Year => "year",
981    }
982}
983
984fn status_str(status: Status) -> &'static str {
985    match status {
986        Status::Stable => "stable",
987        Status::Test => "test",
988        Status::Experimental => "experimental",
989        Status::Deprecated => "deprecated",
990        Status::Unsupported => "unsupported",
991    }
992}
993
994fn operator_str(op: ConditionOperator) -> &'static str {
995    match op {
996        ConditionOperator::Lt => "lt",
997        ConditionOperator::Lte => "lte",
998        ConditionOperator::Gt => "gt",
999        ConditionOperator::Gte => "gte",
1000        ConditionOperator::Eq => "eq",
1001        ConditionOperator::Neq => "neq",
1002    }
1003}
1004
1005fn operator_rank(op: ConditionOperator) -> u8 {
1006    match op {
1007        ConditionOperator::Lt => 0,
1008        ConditionOperator::Lte => 1,
1009        ConditionOperator::Gt => 2,
1010        ConditionOperator::Gte => 3,
1011        ConditionOperator::Eq => 4,
1012        ConditionOperator::Neq => 5,
1013    }
1014}
1015
1016fn relation_str(relation: RelationType) -> &'static str {
1017    match relation {
1018        RelationType::Correlation => "correlation",
1019        RelationType::Derived => "derived",
1020        RelationType::Obsolete => "obsolete",
1021        RelationType::Merged => "merged",
1022        RelationType::Renamed => "renamed",
1023        RelationType::Similar => "similar",
1024    }
1025}
1026
1027fn array_str(quantifier: ArrayQuantifier) -> &'static str {
1028    match quantifier {
1029        ArrayQuantifier::Any => "any",
1030        ArrayQuantifier::All => "all",
1031        ArrayQuantifier::AllOrEmpty => "all_or_empty",
1032        ArrayQuantifier::None => "none",
1033    }
1034}
1035
1036// =============================================================================
1037// Small helpers
1038// =============================================================================
1039
1040fn deeper(indent: &str) -> String {
1041    format!("{indent}{STEP}")
1042}
1043
1044fn sorted(map: &std::collections::HashMap<String, String>) -> Vec<(&str, &str)> {
1045    let mut entries: Vec<(&str, &str)> =
1046        map.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
1047    entries.sort_by(|a, b| a.0.cmp(b.0));
1048    entries
1049}
1050
1051fn sorted_named(map: &std::collections::HashMap<String, Detection>) -> Vec<(&str, &Detection)> {
1052    let mut entries: BTreeMap<&str, &Detection> = BTreeMap::new();
1053    for (k, v) in map {
1054        entries.insert(k.as_str(), v);
1055    }
1056    entries.into_iter().collect()
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061    use super::*;
1062    use crate::parse_sigma_yaml;
1063
1064    /// Assert the emitter is a stable canonical form: `emit(parse(x))` re-parses
1065    /// to one rule and re-emits to a byte-identical string. This is the correct
1066    /// round-trip criterion; it does not depend on the raw source spelling a
1067    /// [`SigmaString`] preserves in its `original` field.
1068    fn assert_round_trips(yaml: &str) -> String {
1069        let first = parse_sigma_yaml(yaml).expect("input parses");
1070        assert_eq!(first.rules.len(), 1, "expected one input rule");
1071        let emitted = emit_rule_yaml(&first.rules[0]);
1072
1073        let reparsed = parse_sigma_yaml(&emitted)
1074            .unwrap_or_else(|e| panic!("emitted YAML must re-parse: {e}\n---\n{emitted}"));
1075        assert_eq!(
1076            reparsed.rules.len(),
1077            1,
1078            "expected one rule, got:\n{emitted}"
1079        );
1080
1081        let reemitted = emit_rule_yaml(&reparsed.rules[0]);
1082        assert_eq!(emitted, reemitted, "emit is not idempotent:\n{emitted}");
1083        emitted
1084    }
1085
1086    #[test]
1087    fn round_trips_minimal_rule() {
1088        assert_round_trips(
1089            "title: Whoami\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection:\n        CommandLine|contains: whoami\n    condition: selection\nlevel: medium\n",
1090        );
1091    }
1092
1093    #[test]
1094    fn round_trips_modifiers_and_value_lists() {
1095        assert_round_trips(
1096            "title: Modifiers\nlogsource:\n    product: windows\ndetection:\n    selection:\n        Image|endswith:\n            - '\\\\cmd.exe'\n            - '\\\\powershell.exe'\n        CommandLine|contains|all:\n            - foo\n            - bar\n        Field|re: 'ab.*c'\n        Port|gt: 1024\n        User|cased: Admin\n    filter:\n        Image|startswith: 'C:\\\\Windows\\\\'\n    condition: selection and not filter\nlevel: high\n",
1097        );
1098    }
1099
1100    #[test]
1101    fn round_trips_keywords_and_anyof() {
1102        assert_round_trips(
1103            "title: Keywords\nlogsource:\n    product: linux\ndetection:\n    keywords:\n        - mimikatz\n        - sekurlsa\n    selection:\n        - EventID: 1\n        - EventID: 4688\n    condition: keywords and selection\n",
1104        );
1105    }
1106
1107    #[test]
1108    fn round_trips_metadata_and_selector_condition() {
1109        assert_round_trips(
1110            "title: Full Metadata\nid: 11111111-2222-3333-4444-555555555555\nstatus: experimental\ndescription: A single line description.\nreferences:\n    - https://example.com/a\nauthor: Jane Doe\ndate: 2026-01-01\ntags:\n    - attack.execution\n    - attack.t1059\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection_a:\n        Image|endswith: '\\\\a.exe'\n    selection_b:\n        Image|endswith: '\\\\b.exe'\n    condition: 1 of selection_*\nfalsepositives:\n    - Legitimate admin use\nlevel: low\n",
1111        );
1112    }
1113
1114    #[test]
1115    fn escapes_wildcards_in_literal_values() {
1116        // A literal asterisk in the value must survive as a literal, not a wildcard.
1117        let yaml = "title: Escapes\nlogsource:\n    product: test\ndetection:\n    selection:\n        Field: 'a\\*b'\n    condition: selection\n";
1118        let emitted = assert_round_trips(yaml);
1119        assert!(
1120            emitted.contains(r"a\*b"),
1121            "expected escaped glob, got:\n{emitted}"
1122        );
1123    }
1124
1125    #[test]
1126    fn empty_logsource_emits_a_mapping_the_parser_rejects() {
1127        let mut rule = parse_sigma_yaml(
1128            "title: No Logsource\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n",
1129        )
1130        .unwrap()
1131        .rules
1132        .remove(0);
1133        rule.logsource = LogSource::default();
1134        let emitted = emit_rule_yaml(&rule);
1135        assert!(emitted.contains("logsource: {}"), "{emitted}");
1136        let errors = parse_sigma_yaml(&emitted).unwrap().diagnostics;
1137        assert!(
1138            errors[0]
1139                .message
1140                .contains("at least one of category, product, or service"),
1141            "{errors:?}"
1142        );
1143    }
1144
1145    #[test]
1146    fn round_trips_detection_exemplars() {
1147        let emitted = assert_round_trips(
1148            "title: Whoami\nid: 11111111-2222-3333-4444-555555555555\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection:\n        CommandLine|contains: whoami\n    condition: selection\ncustom_attributes:\n    rsigma.exemplars:\n        - name: whoami fires\n          expect: match\n          event:\n              CommandLine: whoami /all\n        - name: benign hostname\n          expect: no-match\n          event:\n              CommandLine: hostname\n",
1149        );
1150        assert!(
1151            emitted.contains("rsigma.exemplars:"),
1152            "expected exemplars in emit:\n{emitted}"
1153        );
1154        assert!(
1155            emitted.contains("whoami fires"),
1156            "expected exemplar name:\n{emitted}"
1157        );
1158        let reparsed = parse_sigma_yaml(&emitted).unwrap();
1159        let attrs = &reparsed.rules[0].custom_attributes;
1160        let list = crate::exemplar::exemplars_from_attrs(
1161            attrs,
1162            crate::exemplar::ExemplarRuleKind::Detection,
1163        )
1164        .expect("emitted exemplars re-parse");
1165        assert_eq!(list.len(), 2);
1166        assert_eq!(list[0].expect, crate::exemplar::Expect::Match);
1167        assert_eq!(list[1].expect, crate::exemplar::Expect::NoMatch);
1168    }
1169
1170    #[test]
1171    fn emit_preserves_correlation_shaped_exemplar_sequence() {
1172        let emitted = assert_round_trips(
1173            "title: Burst host\nlogsource:\n    category: auth\ndetection:\n    selection:\n        EventType: login\n    condition: selection\ncustom_attributes:\n    rsigma.exemplars:\n        - name: burst\n          expect: match\n          event:\n              EventType: login\n              User: alice\n",
1174        );
1175        assert!(emitted.contains("User:"), "{emitted}");
1176    }
1177
1178    #[test]
1179    fn round_trips_array_object_scope_block() {
1180        assert_round_trips(
1181            "title: Array\nsigma-version: 3\nlogsource:\n    category: test\ndetection:\n    selection:\n        connections[any]:\n            protocol: TCP\n            port: 445\n    condition: selection\n",
1182        );
1183    }
1184
1185    #[test]
1186    fn quotes_strings_that_yaml_would_read_as_another_type() {
1187        assert_round_trips(
1188            "title: 'True'\nid: '123'\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: '0x1F'\n        Other: '1_000'\n        Third: '1:30'\n    condition: selection\n",
1189        );
1190    }
1191
1192    #[test]
1193    fn emits_reference_urls_plain() {
1194        let emitted = assert_round_trips(
1195            "title: URL\nreferences:\n    - https://example.com/a?b=c\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\n",
1196        );
1197        assert!(
1198            emitted.contains("- https://example.com/a?b=c\n"),
1199            "expected a plain URL:\n{emitted}"
1200        );
1201    }
1202
1203    #[test]
1204    fn emits_multi_line_values_as_literal_blocks() {
1205        let emitted = assert_round_trips(
1206            "title: Multiline\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: |-\n            first line\n            second line\n    condition: selection\n",
1207        );
1208        assert!(emitted.contains("Field: |-"), "{emitted}");
1209    }
1210
1211    #[test]
1212    fn quotes_a_field_name_with_a_space_as_one_key() {
1213        let emitted = assert_round_trips(
1214            "title: Space\nlogsource:\n    category: test\ndetection:\n    selection:\n        'Product Name|contains': thing\n    condition: selection\n",
1215        );
1216        assert!(
1217            emitted.contains("'Product Name|contains': thing"),
1218            "{emitted}"
1219        );
1220    }
1221
1222    #[test]
1223    fn emits_empty_custom_attribute_collections() {
1224        let emitted = assert_round_trips(
1225            "title: Empty\nlogsource:\n    category: test\ndetection:\n    selection:\n        Field: value\n    condition: selection\nempty_map: {}\nempty_seq: []\n",
1226        );
1227        assert!(emitted.contains("empty_map: {}"), "{emitted}");
1228        assert!(emitted.contains("empty_seq: []"), "{emitted}");
1229    }
1230
1231    #[test]
1232    fn quotes_a_condition_that_would_read_as_another_type() {
1233        let emitted = assert_round_trips(
1234            "title: Condition\nlogsource:\n    category: test\ndetection:\n    '1e3':\n        Field: value\n    condition: '1e3'\n",
1235        );
1236        assert!(emitted.contains("condition: '1e3'"), "{emitted}");
1237    }
1238
1239    #[test]
1240    fn emits_root_keys_in_canonical_order() {
1241        let yaml = "\
1242zzz: last
1243title: Order
1244aaa: first
1245id: 11111111-2222-3333-4444-555555555555
1246name: order
1247status: experimental
1248description: Order test.
1249references:
1250    - https://example.com
1251author: Jane Doe
1252date: 2026-01-01
1253modified: 2026-02-01
1254related:
1255    - id: 22222222-3333-4444-5555-666666666666
1256      type: derived
1257tags:
1258    - attack.execution
1259sigma-version: 3
1260logsource:
1261    product: windows
1262    category: process_creation
1263detection:
1264    selection:
1265        Field: value
1266    condition: selection
1267fields:
1268    - Field
1269falsepositives:
1270    - None known
1271level: medium
1272scope:
1273    - endpoint
1274license: MIT
1275taxonomy: attack
1276rsigma.exemplars:
1277    - name: example
1278      expect: match
1279      event:
1280          Field: value
1281rsigma.suppress:
1282    - reason: noisy
1283";
1284        let rule = parse_sigma_yaml(yaml)
1285            .expect("input parses")
1286            .rules
1287            .remove(0);
1288        let emitted = emit_rule_yaml(&rule);
1289        let root_keys: Vec<&str> = emitted
1290            .lines()
1291            .filter(|line| !line.starts_with(' ') && line.contains(':'))
1292            .map(|line| line.split(':').next().unwrap_or_default())
1293            .collect();
1294        let expected = [
1295            "title",
1296            "id",
1297            "name",
1298            "status",
1299            "description",
1300            "references",
1301            "author",
1302            "date",
1303            "modified",
1304            "related",
1305            "tags",
1306            "sigma-version",
1307            "logsource",
1308            "detection",
1309            "fields",
1310            "falsepositives",
1311            "level",
1312            "scope",
1313            "license",
1314            "taxonomy",
1315            "rsigma.suppress",
1316            "rsigma.exemplars",
1317            "aaa",
1318            "zzz",
1319        ];
1320        assert_eq!(root_keys, expected, "{emitted}");
1321    }
1322
1323    fn assert_correlation_round_trips(yaml: &str) -> String {
1324        let first = parse_sigma_yaml(yaml).expect("input parses");
1325        assert_eq!(first.correlations.len(), 1, "expected one correlation");
1326        let emitted = emit_correlation_yaml(&first.correlations[0]);
1327        let reparsed = parse_sigma_yaml(&emitted)
1328            .unwrap_or_else(|e| panic!("emitted YAML must re-parse: {e}\n---\n{emitted}"));
1329        assert_eq!(reparsed.correlations.len(), 1, "{emitted}");
1330        assert_eq!(first.correlations[0], reparsed.correlations[0]);
1331        assert_eq!(emitted, emit_correlation_yaml(&reparsed.correlations[0]));
1332        emitted
1333    }
1334
1335    fn assert_filter_round_trips(yaml: &str) -> String {
1336        let first = parse_sigma_yaml(yaml).expect("input parses");
1337        assert_eq!(first.filters.len(), 1, "expected one filter");
1338        let emitted = emit_filter_yaml(&first.filters[0]);
1339        let reparsed = parse_sigma_yaml(&emitted)
1340            .unwrap_or_else(|e| panic!("emitted YAML must re-parse: {e}\n---\n{emitted}"));
1341        assert_eq!(reparsed.filters.len(), 1, "{emitted}");
1342        assert_eq!(first.filters[0], reparsed.filters[0]);
1343        assert_eq!(emitted, emit_filter_yaml(&reparsed.filters[0]));
1344        emitted
1345    }
1346
1347    #[test]
1348    fn round_trips_event_count_session_gap_aliases() {
1349        let emitted = assert_correlation_round_trips(
1350            "title: Session burst\nid: 11111111-2222-3333-4444-555555555555\ndescription: Too many logins.\ntags:\n    - attack.credential_access\ncorrelation:\n    type: event_count\n    rules:\n        - failed_login\n        - failed_ssh\n    group-by:\n        - User\n    timespan: 1h\n    window: session\n    gap: 5m\n    condition:\n        gte: 10\n    aliases:\n        user:\n            failed_login: User\n            failed_ssh: Username\n    generate: true\nlevel: high\n",
1351        );
1352        assert!(emitted.contains("window: session"), "{emitted}");
1353        assert!(emitted.contains("gap: 5m"), "{emitted}");
1354        assert!(emitted.contains("generate: true"), "{emitted}");
1355        assert!(emitted.contains("failed_login: User"), "{emitted}");
1356    }
1357
1358    #[test]
1359    fn round_trips_value_count_range_and_field() {
1360        let emitted = assert_correlation_round_trips(
1361            "title: Port scan\ncorrelation:\n    type: value_count\n    rules:\n        - connection\n    group-by:\n        - SourceIp\n    timespan: 5m\n    condition:\n        gt: 100\n        lte: 200\n        field:\n            - DestPort\n",
1362        );
1363        assert!(emitted.contains("gt: 100"), "{emitted}");
1364        assert!(emitted.contains("lte: 200"), "{emitted}");
1365        assert!(emitted.contains("DestPort"), "{emitted}");
1366    }
1367
1368    #[test]
1369    fn round_trips_value_percentile() {
1370        assert_correlation_round_trips(
1371            "title: Slow tail\ncorrelation:\n    type: value_percentile\n    rules:\n        - latency\n    group-by:\n        - Service\n    timespan: 10m\n    condition:\n        gte: 95\n        field: LatencyMs\n        percentile: 99\n",
1372        );
1373    }
1374
1375    #[test]
1376    fn round_trips_value_sum_avg_median() {
1377        assert_correlation_round_trips(
1378            "title: Sum\ncorrelation:\n    type: value_sum\n    rules:\n        - transfer\n    group-by:\n        - User\n    timespan: 1h\n    condition:\n        gte: 1000\n        field: Bytes\n",
1379        );
1380        assert_correlation_round_trips(
1381            "title: Avg\ncorrelation:\n    type: value_avg\n    rules:\n        - transfer\n    group-by:\n        - User\n    timespan: 1h\n    condition:\n        gte: 1000\n        field: Bytes\n",
1382        );
1383        assert_correlation_round_trips(
1384            "title: Median\ncorrelation:\n    type: value_median\n    rules:\n        - transfer\n    group-by:\n        - User\n    timespan: 1h\n    condition:\n        gte: 1000\n        field: Bytes\n",
1385        );
1386    }
1387
1388    #[test]
1389    fn round_trips_temporal_extended_and_ordered() {
1390        assert_correlation_round_trips(
1391            "title: Login then process\ncorrelation:\n    type: temporal\n    rules:\n        - login\n        - process_start\n    group-by:\n        - User\n    timespan: 10m\n    condition: login and process_start\n",
1392        );
1393        assert_correlation_round_trips(
1394            "title: Ordered\ncorrelation:\n    type: temporal_ordered\n    rules:\n        - login\n        - process_start\n    group-by:\n        - User\n    timespan: 10m\n    condition: login and process_start\n",
1395        );
1396    }
1397
1398    #[test]
1399    fn round_trips_tumbling_window() {
1400        assert_correlation_round_trips(
1401            "title: Tumbling\ncorrelation:\n    type: event_count\n    rules:\n        - login\n    group-by:\n        - User\n    timespan: 1h\n    window: tumbling\n    condition:\n        gte: 5\n",
1402        );
1403    }
1404
1405    #[test]
1406    fn round_trips_filter_any() {
1407        let emitted = assert_filter_round_trips(
1408            "title: Drop system accounts\nlogsource:\n    product: windows\n    category: process_creation\nfilter:\n    selection:\n        User|endswith: '$'\n    condition: selection\n",
1409        );
1410        assert!(!emitted.contains("rules:"), "{emitted}");
1411    }
1412
1413    #[test]
1414    fn round_trips_filter_specific_logsource() {
1415        let emitted = assert_filter_round_trips(
1416            "title: Drop admin whoami\nid: 22222222-3333-4444-5555-666666666666\nlogsource:\n    product: windows\n    service: security\nfilter:\n    rules:\n        - 11111111-2222-3333-4444-555555555555\n        - whoami_rule\n    selection:\n        Image|endswith: '\\whoami.exe'\n    filter_main_system:\n        User: SYSTEM\n    condition: selection and not filter_main_system\n",
1417        );
1418        assert!(emitted.contains("rules:"), "{emitted}");
1419        assert!(emitted.contains("whoami_rule"), "{emitted}");
1420        assert!(emitted.contains("filter_main_system"), "{emitted}");
1421    }
1422
1423    #[test]
1424    fn round_trips_a_detection_timeframe() {
1425        let emitted = assert_round_trips(
1426            "title: Burst\nlogsource:\n    product: windows\ndetection:\n    selection:\n        EventID: 4625\n    condition: selection\n    timeframe: 5m\n",
1427        );
1428        assert!(emitted.contains("    timeframe: 5m\n"), "{emitted}");
1429    }
1430
1431    #[test]
1432    fn round_trips_a_filter_timeframe() {
1433        let emitted = assert_filter_round_trips(
1434            "title: Drop bursts\nlogsource:\n    product: windows\nfilter:\n    selection:\n        User: SYSTEM\n    condition: selection\n    timeframe: 5m\n",
1435        );
1436        assert!(emitted.contains("    timeframe: 5m\n"), "{emitted}");
1437    }
1438}