rsigma-convert 0.15.0

Sigma rule conversion engine — convert rules to backend-native query strings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
//! End-to-end unit tests for the Fibratus backend.
//!
//! These exercise the full `convert_rule` path through the public
//! `Backend` trait so each test pins a representative Sigma -> Fibratus
//! mapping (case-insensitive default, `|cased` switch, wildcards, IN
//! lists, regex, CIDR, comparisons, exists/null, `|fieldref`, `not`,
//! grouping precedence, output formats).
//!
//! Per the project workflow: unit tests live next to the code they
//! exercise; this file does not duplicate coverage shared by the
//! cross-crate golden suite under `tests/golden_fibratus.rs`.
//!
//! The `#[cfg(test)]` gate is applied at the `mod tests;` declaration
//! in [`super`](super) so this file omits its own to avoid the
//! `duplicated_attributes` lint.

use rsigma_eval::pipeline::state::PipelineState;
use rsigma_parser::parse_sigma_yaml;

use super::FibratusBackend;
use crate::backend::Backend;

fn convert(yaml: &str) -> Vec<String> {
    let backend = FibratusBackend::new();
    convert_with(yaml, &backend, "expr")
}

fn convert_with(yaml: &str, backend: &FibratusBackend, format: &str) -> Vec<String> {
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut results = Vec::new();
    for rule in &collection.rules {
        let queries = backend
            .convert_rule(rule, format, &PipelineState::default())
            .unwrap();
        results.extend(queries);
    }
    results
}

// ---------------------------------------------------------------------
// Basic field equality
// ---------------------------------------------------------------------

#[test]
fn field_eq_string_default_case_insensitive() {
    // Sigma defaults to case-insensitive string matching, and Fibratus's
    // bare `=` is case-sensitive. A literal without wildcards therefore
    // uses `~=`, Fibratus's case-insensitive string-equality operator
    // (matches `cmd.exe` and `CMD.EXE`), which is cheaper than a glob
    // match.
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name: cmd.exe
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name ~= 'cmd.exe'"]);
}

#[test]
fn field_eq_string_cased_modifier_uses_exact_equality() {
    // The `|cased` modifier flips to the case-sensitive exact-equality
    // operator `=` (no wildcards in the value).
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name|cased: Cmd.exe
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name = 'Cmd.exe'"]);
}

#[test]
fn field_eq_string_contains_uses_icontains() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name|contains: cmd
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name icontains 'cmd'"]);
}

#[test]
fn field_eq_string_cased_modifier_switches_to_contains() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name|contains|cased: Cmd
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name contains 'Cmd'"]);
}

#[test]
fn field_eq_string_startswith() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name|startswith: cmd
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name istartswith 'cmd'"]);
}

#[test]
fn field_eq_string_endswith() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.exe|endswith: '.exe'
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.exe iendswith '.exe'"]);
}

// ---------------------------------------------------------------------
// Wildcards (lower to imatches)
// ---------------------------------------------------------------------

#[test]
fn wildcard_multi_lowers_to_imatches() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline: '*whoami*'
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.cmdline imatches '*whoami*'"]);
}

#[test]
fn wildcard_single_lowers_to_imatches() {
    let q = convert(
        r#"
title: T
detection:
  s:
    file.name: 'a?c.exe'
  condition: s
"#,
    );
    assert_eq!(q, vec!["file.name imatches 'a?c.exe'"]);
}

#[test]
fn wildcard_cased_lowers_to_matches() {
    let q = convert(
        r#"
title: T
detection:
  s:
    file.name|cased: '*Cmd*'
  condition: s
"#,
    );
    assert_eq!(q, vec!["file.name matches '*Cmd*'"]);
}

// ---------------------------------------------------------------------
// Boolean logic and grouping
// ---------------------------------------------------------------------

#[test]
fn condition_and() {
    let q = convert(
        r#"
title: T
detection:
  a:
    ps.name: cmd.exe
  b:
    ps.parent.name: explorer.exe
  condition: a and b
"#,
    );
    assert_eq!(
        q,
        vec!["ps.name ~= 'cmd.exe' and ps.parent.name ~= 'explorer.exe'"]
    );
}

#[test]
fn condition_or() {
    let q = convert(
        r#"
title: T
detection:
  a:
    ps.name: cmd.exe
  b:
    ps.name: pwsh.exe
  condition: a or b
"#,
    );
    // Multi-child OR groups are always parenthesized so the standard
    // Sigma precedence (AND binds tighter than OR) survives any
    // surrounding AND context. Harmless at top level.
    assert_eq!(q, vec!["(ps.name ~= 'cmd.exe' or ps.name ~= 'pwsh.exe')"]);
}

#[test]
fn condition_not_uses_native_not() {
    let q = convert(
        r#"
title: T
detection:
  a:
    ps.name: cmd.exe
  f:
    ps.parent.name: explorer.exe
  condition: a and not f
"#,
    );
    assert_eq!(
        q,
        vec!["ps.name ~= 'cmd.exe' and not (ps.parent.name ~= 'explorer.exe')"]
    );
}

#[test]
fn grouping_for_or_inside_and() {
    let q = convert(
        r#"
title: T
detection:
  a:
    ps.name: cmd.exe
  b:
    ps.parent.name: explorer.exe
  c:
    ps.parent.name: services.exe
  condition: a and (b or c)
"#,
    );
    assert_eq!(
        q,
        vec![
            "ps.name ~= 'cmd.exe' and (ps.parent.name ~= 'explorer.exe' or ps.parent.name ~= 'services.exe')"
        ]
    );
}

// ---------------------------------------------------------------------
// Multi-value lists
// ---------------------------------------------------------------------

#[test]
fn multi_value_string_eq_collapses_to_iin() {
    // A multi-value OR list of plain literals collapses to a single
    // `iin (...)` clause (case-insensitive IN), the idiomatic Fibratus
    // form, rather than OR'd `~=` comparisons.
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name:
      - cmd.exe
      - pwsh.exe
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name iin ('cmd.exe', 'pwsh.exe')"]);
}

#[test]
fn multi_value_string_eq_with_wildcards_uses_imatches_list() {
    // When any value carries a glob, the list uses `imatches (...)`
    // so the wildcards are honored.
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.name:
      - '*cmd*'
      - 'power?hell'
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.name imatches ('*cmd*', 'power?hell')"]);
}

#[test]
fn multi_value_contains_collapses_to_icontains_list() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline|contains:
      - whoami
      - localgroup
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.cmdline icontains ('whoami', 'localgroup')"]);
}

#[test]
fn convert_condition_as_in_expression_emits_iin_for_or() {
    // Exercise the IN-list helper directly to lock in the iin/in
    // formatting since the auto-dispatch path doesn't currently call
    // it. Used by future optimization passes and the macro recognizer.
    use crate::state::ConversionState;
    use rsigma_parser::{SigmaString, SigmaValue};
    let backend = FibratusBackend::new();
    let a = SigmaValue::String(SigmaString::new("cmd.exe"));
    let b = SigmaValue::String(SigmaString::new("pwsh.exe"));
    let mut state = ConversionState::default();
    let out = backend
        .convert_condition_as_in_expression("ps.name", &[&a, &b], true, &mut state)
        .unwrap();
    assert_eq!(out, "ps.name iin ('cmd.exe', 'pwsh.exe')");
}

#[test]
fn multi_value_string_with_all_modifier_joins_with_and() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline|contains|all:
      - whoami
      - localgroup
  condition: s
"#,
    );
    assert_eq!(
        q,
        vec!["ps.cmdline icontains 'whoami' and ps.cmdline icontains 'localgroup'"]
    );
}

// ---------------------------------------------------------------------
// Numeric, boolean, null
// ---------------------------------------------------------------------

#[test]
fn field_eq_integer() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.pid: 4
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.pid = 4"]);
}

#[test]
fn field_eq_boolean() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.is_protected: true
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.is_protected = true"]);
}

#[test]
fn field_eq_null_compares_to_empty_string() {
    // Fibratus has no `null` token; a Sigma `field: null` lowers to an
    // empty-string comparison.
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.username: null
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.username = ''"]);
}

// ---------------------------------------------------------------------
// Numeric comparison
// ---------------------------------------------------------------------

#[test]
fn compare_gte() {
    let q = convert(
        r#"
title: T
detection:
  s:
    file.io.size|gte: 1024
  condition: s
"#,
    );
    assert_eq!(q, vec!["file.io.size >= 1024"]);
}

#[test]
fn compare_lt() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.handles|lt: 10
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.handles < 10"]);
}

// ---------------------------------------------------------------------
// Regex via regex() function call
// ---------------------------------------------------------------------

#[test]
fn regex_lowers_to_function_call() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline|re: 'power.*(shell|hell)\.dll'
  condition: s
"#,
    );
    // Fibratus single-quoted string literals use `\\` for a literal
    // backslash, so the regex `\.` becomes `\\.` in the rendered
    // literal. The RE2 engine receives the unescaped `\.` and treats
    // it as a literal period (matching upstream rules library style:
    // `file.path imatches '?:\\Windows\\System32\\lsass.exe'`).
    assert_eq!(
        q,
        vec![r"regex(ps.cmdline, 'power.*(shell|hell)\\.dll') = true"]
    );
}

#[test]
fn regex_negated_uses_native_not() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline|re: '^safe'
  f:
    ps.name: cmd.exe
  condition: f and not s
"#,
    );
    assert_eq!(
        q,
        vec!["ps.name ~= 'cmd.exe' and not (regex(ps.cmdline, '^safe') = true)"]
    );
}

#[test]
fn condition_or_inside_and_uses_explicit_grouping() {
    // Regression for precedence: OR sub-expressions inside AND must
    // be wrapped or `a and b or c` would be parsed as `(a and b) or c`
    // by Fibratus's standard (NOT > AND > OR) precedence.
    let q = convert(
        r#"
title: T
detection:
  a:
    ps.name: a.exe
  b:
    ps.name: b.exe
  c:
    ps.name: c.exe
  condition: a and (b or c)
"#,
    );
    assert_eq!(
        q,
        vec!["ps.name ~= 'a.exe' and (ps.name ~= 'b.exe' or ps.name ~= 'c.exe')"]
    );
}

#[test]
fn regex_rejects_lookarounds() {
    let yaml = r#"
title: T
detection:
  s:
    ps.cmdline|re: 'foo(?=bar)'
  condition: s
"#;
    let backend = FibratusBackend::new();
    let collection = parse_sigma_yaml(yaml).unwrap();
    let err = backend
        .convert_rule(&collection.rules[0], "expr", &PipelineState::default())
        .unwrap_err();
    assert!(
        format!("{err}").contains("lookaround"),
        "expected lookaround error, got: {err}",
    );
}

// ---------------------------------------------------------------------
// Multi-value |re and |cidr (generic-dispatch OR/AND fold)
// ---------------------------------------------------------------------

#[test]
fn multi_value_re_collapses_to_single_regex_call() {
    // Fibratus's `regex()` filter function takes a variadic pattern
    // list and returns true if any pattern matches, so multi-value
    // `|re` collapses to a single call rather than OR'd separate
    // calls (the idiomatic Fibratus form).
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline|re:
      - '^safe'
      - '^trusted'
  condition: s
"#,
    );
    assert_eq!(q, vec!["regex(ps.cmdline, '^safe', '^trusted') = true"]);
}

#[test]
fn multi_value_re_with_all_modifier_uses_and() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.cmdline|re|all:
      - '\bwhoami\b'
      - '\bnet user\b'
  condition: s
"#,
    );
    assert_eq!(
        q,
        vec![
            r"regex(ps.cmdline, '\\bwhoami\\b') = true and regex(ps.cmdline, '\\bnet user\\b') = true"
        ],
    );
}

#[test]
fn multi_value_cidr_collapses_to_single_call() {
    // `cidr_contains()` accepts a variadic list of CIDR masks and
    // returns true if the address is in any of them, so a multi-value
    // `|cidr` (OR) collapses to one call.
    let q = convert(
        r#"
title: T
detection:
  s:
    net.dip|cidr:
      - '10.0.0.0/8'
      - '172.16.0.0/12'
      - '192.168.0.0/16'
  condition: s
"#,
    );
    assert_eq!(
        q,
        vec!["cidr_contains(net.dip, '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16')"],
    );
}

// ---------------------------------------------------------------------
// CIDR via cidr_contains() function call
// ---------------------------------------------------------------------

#[test]
fn cidr_lowers_to_function_call() {
    let q = convert(
        r#"
title: T
detection:
  s:
    net.dip|cidr: '10.0.0.0/8'
  condition: s
"#,
    );
    assert_eq!(q, vec!["cidr_contains(net.dip, '10.0.0.0/8')"]);
}

// ---------------------------------------------------------------------
// Exists / fieldref
// ---------------------------------------------------------------------

#[test]
fn field_exists_true() {
    // Fibratus has no `null`; field presence is expressed against the
    // zero value (`!= false` set, `= false` absent).
    let q = convert(
        r#"
title: T
detection:
  s:
    thread.callstack.is_unbacked|exists: true
  condition: s
"#,
    );
    assert_eq!(q, vec!["thread.callstack.is_unbacked != false"]);
}

#[test]
fn field_exists_false() {
    let q = convert(
        r#"
title: T
detection:
  s:
    thread.callstack.is_unbacked|exists: false
  condition: s
"#,
    );
    assert_eq!(q, vec!["thread.callstack.is_unbacked = false"]);
}

#[test]
fn fieldref_renders_as_native_equality() {
    let q = convert(
        r#"
title: T
detection:
  s:
    ps.pid|fieldref: thread.pid
  condition: s
"#,
    );
    assert_eq!(q, vec!["ps.pid = thread.pid"]);
}

// ---------------------------------------------------------------------
// Keyword (unsupported)
// ---------------------------------------------------------------------

#[test]
fn keyword_returns_unsupported_keyword_error() {
    let yaml = r#"
title: T
detection:
  keywords:
    - whoami
    - ipconfig
  condition: keywords
"#;
    let backend = FibratusBackend::new();
    let collection = parse_sigma_yaml(yaml).unwrap();
    let err = backend
        .convert_rule(&collection.rules[0], "expr", &PipelineState::default())
        .unwrap_err();
    assert!(
        format!("{err}").contains("keyword"),
        "expected keyword error, got: {err}"
    );
}

// ---------------------------------------------------------------------
// Output formats
// ---------------------------------------------------------------------

#[test]
fn default_format_emits_yaml_envelope() {
    let backend = FibratusBackend::new();
    let q = convert_with(
        r#"
title: Cmd via Explorer
id: 11111111-2222-3333-4444-555555555555
description: Detect cmd.exe spawned by explorer.
tags:
  - attack.execution
detection:
  s:
    ps.name: cmd.exe
    ps.parent.name: explorer.exe
  condition: s
"#,
        &backend,
        "default",
    );
    assert_eq!(q.len(), 1);
    let doc = &q[0];
    assert!(doc.starts_with("name: Cmd via Explorer\n"));
    assert!(doc.contains("id: 11111111-2222-3333-4444-555555555555\n"));
    assert!(doc.contains("description: |\n  Detect cmd.exe spawned by explorer.\n"));
    assert!(doc.contains("tactic.id: TA0002\n"));
    assert!(
        doc.contains("condition: >\n  ps.name ~= 'cmd.exe' and ps.parent.name ~= 'explorer.exe'\n")
    );
    assert!(doc.contains("min-engine-version: 3.0.0\n"));
}

#[test]
fn yaml_format_is_alias_of_default() {
    let backend = FibratusBackend::new();
    let yaml = r#"
title: T
detection:
  s:
    ps.name: cmd.exe
  condition: s
"#;
    let default = convert_with(yaml, &backend, "default");
    let aliased = convert_with(yaml, &backend, "yaml");
    let rule_aliased = convert_with(yaml, &backend, "rule");
    assert_eq!(default, aliased);
    assert_eq!(default, rule_aliased);
}

#[test]
fn multi_doc_default_format_joins_with_separator() {
    let yaml = r#"
title: First
detection:
  s:
    ps.name: a.exe
  condition: s
---
title: Second
detection:
  s:
    ps.name: b.exe
  condition: s
"#;
    let backend = FibratusBackend::new();
    let collection = parse_sigma_yaml(yaml).unwrap();
    assert_eq!(collection.rules.len(), 2);

    let mut all_queries = Vec::new();
    for rule in &collection.rules {
        let q = backend
            .convert_rule(rule, "default", &PipelineState::default())
            .unwrap();
        all_queries.extend(q);
    }
    let joined = backend.finalize_output(all_queries, "default").unwrap();
    assert!(joined.contains("name: First\n"));
    assert!(joined.contains("\n---\nname: Second\n"));
}

// ---------------------------------------------------------------------
// Backend metadata
// ---------------------------------------------------------------------

#[test]
fn backend_advertises_expected_formats() {
    let backend = FibratusBackend::new();
    let names: Vec<&str> = backend.formats().iter().map(|(n, _)| *n).collect();
    assert_eq!(names, vec!["default", "expr", "yaml", "rule"]);
}

#[test]
fn backend_name_is_fibratus() {
    assert_eq!(FibratusBackend::new().name(), "fibratus");
}

#[test]
fn backend_does_not_require_pipeline() {
    assert!(!FibratusBackend::new().requires_pipeline());
}

// ---------------------------------------------------------------------
// `-O case_sensitive=true` forces bare operators globally
// ---------------------------------------------------------------------

// ---------------------------------------------------------------------
// fibratus_windows builtin pipeline integration
// ---------------------------------------------------------------------

#[test]
fn pipeline_renames_sigma_fields_and_adds_evt_name() {
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: Suspicious cmd via Explorer
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\cmd.exe'
    ParentImage|endswith: '\explorer.exe'
    CommandLine|contains: 'whoami'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();

    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();

    assert_eq!(q.len(), 1);
    let out = &q[0];
    assert!(out.contains("spawn_process"), "got: {out}");
    // The event predicate is emitted first (the pipeline prepends it)
    // so Fibratus short-circuits on the cheapest discriminator.
    assert!(
        out.starts_with("spawn_process"),
        "event predicate must come first, got: {out}",
    );
    // On a Fibratus 3.0.0 `CreateProcess` event `ps.*` is the created
    // (child) process (Sigma `Image` -> `ps.exe`, Sigma `CommandLine`
    // -> `ps.cmdline`) and the spawning process is `ps.parent.*`. The
    // Sigma source `'\cmd.exe'` parses as the literal `\cmd.exe`;
    // Fibratus single-quoted strings need `\\` for a literal `\`, so
    // the rendered value carries the double-escape.
    assert!(out.contains(r"ps.exe iendswith '\\cmd.exe'"), "got: {out}",);
    assert!(
        out.contains(r"ps.parent.exe iendswith '\\explorer.exe'"),
        "got: {out}"
    );
    assert!(out.contains("ps.cmdline icontains 'whoami'"), "got: {out}",);
}

#[test]
fn pipeline_routes_network_connection_to_connect_event() {
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: Outbound to RFC1918
logsource:
  category: network_connection
  product: windows
detection:
  selection:
    DestinationIp|cidr: '10.0.0.0/8'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();

    let out = &q[0];
    // `evt.name: Connect` injected by the pipeline matches the
    // `connect_socket` macro after recognition.
    assert!(out.contains("connect_socket"), "got: {out}");
    assert!(
        out.contains("cidr_contains(net.dip, '10.0.0.0/8')"),
        "got: {out}",
    );
}

#[test]
fn pipeline_file_event_excludes_open_disposition() {
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: File creation
logsource:
  category: file_event
  product: windows
detection:
  selection:
    TargetFilename|endswith: '\evil.exe'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();

    let out = &q[0];
    // Sigma file_event is file creation: the `CreateFile` event is led
    // with, the path is renamed, and the OPEN disposition is excluded so
    // it does not fire on plain file access (the `create_file` macro
    // semantics).
    assert!(out.starts_with("evt.name = 'CreateFile'"), "got: {out}");
    assert!(
        out.contains(r"file.path iendswith '\\evil.exe'"),
        "got: {out}"
    );
    assert!(
        out.contains("not (file.operation ~= 'OPEN')"),
        "expected OPEN disposition excluded, got: {out}",
    );
}

#[test]
fn pipeline_routes_dns_query_with_dns_namespace() {
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: Suspicious DNS
logsource:
  category: dns_query
  product: windows
detection:
  selection:
    QueryName|endswith: '.evil.test'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();

    let out = &q[0];
    // `QueryName` maps to the `dns.name` field (not the invalid
    // `net.dns.*`), and the `QueryDns` event is recognized as the
    // `query_dns` macro and emitted first.
    assert!(out.starts_with("query_dns"), "got: {out}");
    assert!(
        out.contains("dns.name iendswith '.evil.test'"),
        "got: {out}"
    );
}

#[test]
fn pipeline_routes_image_load_with_module_namespace() {
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: Unsigned module load
logsource:
  category: image_load
  product: windows
detection:
  selection:
    ImageLoaded|endswith: '\evil.dll'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();

    let out = &q[0];
    // `image.*` is deprecated; `ImageLoaded` maps to `module.path`.
    assert!(
        out.contains(r"module.path iendswith '\\evil.dll'"),
        "got: {out}",
    );
}

#[test]
fn pipeline_routes_registry_set_with_target_object_rename() {
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: Run-key persistence
logsource:
  category: registry_set
  product: windows
detection:
  selection:
    TargetObject|contains: '\CurrentVersion\Run\'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();

    let out = &q[0];
    // `evt.name: RegSetValue` is the single-clause `set_value` macro
    // body but the registry status guard is not added by the
    // pipeline, so the standalone clause stays as the raw form. The
    // `evt.name` discriminator uses the exact `=` operator.
    assert!(out.contains("evt.name = 'RegSetValue'"), "got: {out}");
    assert!(
        out.contains(r"registry.path icontains '\\CurrentVersion\\Run\\'"),
        "got: {out}",
    );
}

// ---------------------------------------------------------------------
// Macro recognition (use_macros, default on)
// ---------------------------------------------------------------------

#[test]
fn macros_recognize_spawn_process_via_pipeline() {
    // The fibratus_windows pipeline injects `evt.name: CreateProcess`;
    // the backend then renders it as `evt.name = 'CreateProcess'`,
    // which the macro recognizer must rewrite to `spawn_process`.
    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};

    let yaml = r#"
title: cmd.exe with whoami
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\cmd.exe'
    CommandLine|contains: 'whoami'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let backend = FibratusBackend::new();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();
    assert_eq!(q.len(), 1);
    let out = &q[0];
    assert!(
        out.contains("spawn_process"),
        "expected spawn_process, got: {out}"
    );
    assert!(
        !out.contains("evt.name = 'CreateProcess'"),
        "macro should have replaced the raw clause, got: {out}",
    );
}

#[test]
fn macros_disabled_emits_raw_clauses() {
    use std::collections::HashMap;
    let mut opts: HashMap<String, String> = HashMap::new();
    opts.insert("use_macros".to_string(), "false".to_string());
    let backend = FibratusBackend::from_options(&opts);

    use rsigma_eval::pipeline::{apply_pipelines_with_state, builtin::resolve_builtin};
    let yaml = r#"
title: t
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\cmd.exe'
  condition: selection
"#;
    let mut collection = rsigma_parser::parse_sigma_yaml(yaml).unwrap();
    let pipeline = resolve_builtin("fibratus_windows").unwrap().unwrap();
    let rule = &mut collection.rules[0];
    let state = apply_pipelines_with_state(&[pipeline], rule).unwrap();
    let q = backend.convert_rule(rule, "expr", &state).unwrap();
    assert!(
        q[0].contains("evt.name = 'CreateProcess'"),
        "expected raw evt.name clause with use_macros=false, got: {}",
        q[0],
    );
    assert!(!q[0].contains("spawn_process"));
}

#[test]
fn option_case_sensitive_forces_bare_operators() {
    use std::collections::HashMap;
    let mut opts: HashMap<String, String> = HashMap::new();
    opts.insert("case_sensitive".to_string(), "true".to_string());
    let backend = FibratusBackend::from_options(&opts);
    let q = convert_with(
        r#"
title: T
detection:
  s:
    ps.cmdline|contains: Whoami
  condition: s
"#,
        &backend,
        "expr",
    );
    assert_eq!(q, vec!["ps.cmdline contains 'Whoami'"]);
}