rsigma-eval 0.15.0

Evaluator for Sigma detection and correlation rules — match rules against events
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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
use super::*;
use crate::event::JsonEvent;
use rsigma_parser::parse_sigma_yaml;
use serde_json::json;

fn make_engine_with_rule(yaml: &str) -> Engine {
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();
    engine
}

#[test]
fn test_simple_match() {
    let engine = make_engine_with_rule(
        r#"
title: Detect Whoami
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: medium
"#,
    );

    let ev = json!({"CommandLine": "cmd /c whoami /all"});
    let event = JsonEvent::borrow(&ev);
    let matches = engine.evaluate(&event);
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].header.rule_title, "Detect Whoami");
}

#[test]
fn test_no_match() {
    let engine = make_engine_with_rule(
        r#"
title: Detect Whoami
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: medium
"#,
    );

    let ev = json!({"CommandLine": "ipconfig /all"});
    let event = JsonEvent::borrow(&ev);
    let matches = engine.evaluate(&event);
    assert!(matches.is_empty());
}

#[test]
fn test_and_not_filter() {
    let engine = make_engine_with_rule(
        r#"
title: Suspicious Process
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'whoami'
    filter:
        User: 'SYSTEM'
    condition: selection and not filter
level: high
"#,
    );

    // Match: whoami by non-SYSTEM user
    let ev = json!({"CommandLine": "whoami", "User": "admin"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);

    // No match: whoami by SYSTEM
    let ev2 = json!({"CommandLine": "whoami", "User": "SYSTEM"});
    let event2 = JsonEvent::borrow(&ev2);
    assert!(engine.evaluate(&event2).is_empty());
}

#[test]
fn test_multiple_values_or() {
    let engine = make_engine_with_rule(
        r#"
title: Recon Commands
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains:
            - 'whoami'
            - 'ipconfig'
            - 'net user'
    condition: selection
level: medium
"#,
    );

    let ev = json!({"CommandLine": "ipconfig /all"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);

    let ev2 = json!({"CommandLine": "dir"});
    let event2 = JsonEvent::borrow(&ev2);
    assert!(engine.evaluate(&event2).is_empty());
}

#[test]
fn test_logsource_routing() {
    let engine = make_engine_with_rule(
        r#"
title: Windows Process
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: medium
"#,
    );

    let ev = json!({"CommandLine": "whoami"});
    let event = JsonEvent::borrow(&ev);

    // Matching logsource
    let ls_match = LogSource {
        product: Some("windows".into()),
        category: Some("process_creation".into()),
        ..Default::default()
    };
    assert_eq!(engine.evaluate_with_logsource(&event, &ls_match).len(), 1);

    // Non-matching logsource
    let ls_nomatch = LogSource {
        product: Some("linux".into()),
        category: Some("process_creation".into()),
        ..Default::default()
    };
    assert!(
        engine
            .evaluate_with_logsource(&event, &ls_nomatch)
            .is_empty()
    );
}

#[test]
fn test_selector_1_of() {
    let engine = make_engine_with_rule(
        r#"
title: Multiple Selections
logsource:
    product: windows
detection:
    selection_cmd:
        CommandLine|contains: 'cmd'
    selection_ps:
        CommandLine|contains: 'powershell'
    condition: 1 of selection_*
level: medium
"#,
    );

    let ev = json!({"CommandLine": "powershell.exe -enc"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);
}

#[test]
fn test_filter_rule_application() {
    // A filter rule that excludes SYSTEM user from the detection
    let yaml = r#"
title: Suspicious Process
id: rule-001
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: high
---
title: Filter SYSTEM
filter:
    rules:
        - rule-001
    selection:
        User: 'SYSTEM'
    condition: not selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    assert_eq!(collection.rules.len(), 1);
    assert_eq!(collection.filters.len(), 1);

    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    // Match: whoami by non-SYSTEM user
    let ev = json!({"CommandLine": "whoami", "User": "admin"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);

    // No match: whoami by SYSTEM (filtered out)
    let ev2 = json!({"CommandLine": "whoami", "User": "SYSTEM"});
    let event2 = JsonEvent::borrow(&ev2);
    assert!(engine.evaluate(&event2).is_empty());
}

#[test]
fn test_filter_rule_no_ref_applies_to_all() {
    // A filter rule with empty `rules` applies to all rules
    let yaml = r#"
title: Detection A
id: det-a
logsource:
    product: windows
detection:
    sel:
        EventType: alert
    condition: sel
---
title: Filter Out Test Env
filter:
    rules: []
    selection:
        Environment: 'test'
    condition: not selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    let ev = json!({"EventType": "alert", "Environment": "prod"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);

    let ev2 = json!({"EventType": "alert", "Environment": "test"});
    let event2 = JsonEvent::borrow(&ev2);
    assert!(engine.evaluate(&event2).is_empty());
}

#[test]
fn test_multiple_rules() {
    let yaml = r#"
title: Rule A
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: low
---
title: Rule B
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'ipconfig'
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();
    assert_eq!(engine.rule_count(), 2);

    // Only Rule A matches
    let ev = json!({"CommandLine": "whoami"});
    let event = JsonEvent::borrow(&ev);
    let matches = engine.evaluate(&event);
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].header.rule_title, "Rule A");
}

// =========================================================================
// Filter rule edge cases
// =========================================================================

#[test]
fn test_filter_by_rule_name() {
    // Filter that references a rule by title (not ID)
    let yaml = r#"
title: Detect Mimikatz
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'mimikatz'
    condition: selection
level: critical
---
title: Exclude Admin Tools
filter:
    rules:
        - Detect Mimikatz
    selection:
        ParentImage|endswith: '\admin_toolkit.exe'
    condition: not selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    // Match: mimikatz not launched by admin toolkit
    let ev = json!({"CommandLine": "mimikatz.exe", "ParentImage": "C:\\cmd.exe"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);

    // No match: mimikatz launched by admin toolkit (filtered)
    let ev2 = json!({"CommandLine": "mimikatz.exe", "ParentImage": "C:\\admin_toolkit.exe"});
    let event2 = JsonEvent::borrow(&ev2);
    assert!(engine.evaluate(&event2).is_empty());
}

#[test]
fn test_filter_multiple_detections() {
    // Filter with multiple detection items (AND exclusion)
    let yaml = r#"
title: Suspicious Network
id: net-001
logsource:
    product: windows
detection:
    selection:
        DestinationPort: 443
    condition: selection
level: medium
---
title: Exclude Trusted
filter:
    rules:
        - net-001
    trusted_dst:
        DestinationIp|startswith: '10.'
    trusted_user:
        User: 'svc_account'
    condition: not (trusted_dst and trusted_user)
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    // Match: port 443 to external IP
    let ev = json!({"DestinationPort": 443, "DestinationIp": "8.8.8.8", "User": "admin"});
    let event = JsonEvent::borrow(&ev);
    assert_eq!(engine.evaluate(&event).len(), 1);

    // Match: port 443 to internal IP but different user (filter needs both)
    let ev2 = json!({"DestinationPort": 443, "DestinationIp": "10.0.0.1", "User": "admin"});
    let event2 = JsonEvent::borrow(&ev2);
    assert_eq!(engine.evaluate(&event2).len(), 1);

    // No match: port 443 to internal IP by svc_account (both filter conditions met)
    let ev3 = json!({"DestinationPort": 443, "DestinationIp": "10.0.0.1", "User": "svc_account"});
    let event3 = JsonEvent::borrow(&ev3);
    assert!(engine.evaluate(&event3).is_empty());
}

#[test]
fn test_filter_applied_to_multiple_rules() {
    // Filter with empty rules list applies to all rules
    let yaml = r#"
title: Rule One
id: r1
logsource:
    product: windows
detection:
    sel:
        EventID: 1
    condition: sel
---
title: Rule Two
id: r2
logsource:
    product: windows
detection:
    sel:
        EventID: 2
    condition: sel
---
title: Exclude Test
filter:
    rules: []
    selection:
        Environment: 'test'
    condition: not selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    // In prod: both rules should fire
    let ev1 = json!({"EventID": 1, "Environment": "prod"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev1)).len(), 1);
    let ev2 = json!({"EventID": 2, "Environment": "prod"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev2)).len(), 1);

    // In test: both filtered out
    let ev3 = json!({"EventID": 1, "Environment": "test"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev3)).is_empty());
    let ev4 = json!({"EventID": 2, "Environment": "test"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev4)).is_empty());
}

// =========================================================================
// Expand modifier end-to-end
// =========================================================================

#[test]
fn test_expand_modifier_yaml() {
    let yaml = r#"
title: User Profile Access
logsource:
    product: windows
detection:
    selection:
        TargetFilename|expand: 'C:\Users\%username%\AppData\sensitive.dat'
    condition: selection
level: high
"#;
    let engine = make_engine_with_rule(yaml);

    // Match: path matches after expanding %username% from the event
    let ev = json!({
        "TargetFilename": "C:\\Users\\admin\\AppData\\sensitive.dat",
        "username": "admin"
    });
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // No match: different user
    let ev2 = json!({
        "TargetFilename": "C:\\Users\\admin\\AppData\\sensitive.dat",
        "username": "guest"
    });
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

#[test]
fn test_expand_modifier_multiple_placeholders() {
    let yaml = r#"
title: Registry Path
logsource:
    product: windows
detection:
    selection:
        RegistryKey|expand: 'HKLM\SOFTWARE\%vendor%\%product%'
    condition: selection
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    let ev = json!({
        "RegistryKey": "HKLM\\SOFTWARE\\Acme\\Widget",
        "vendor": "Acme",
        "product": "Widget"
    });
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    let ev2 = json!({
        "RegistryKey": "HKLM\\SOFTWARE\\Acme\\Widget",
        "vendor": "Other",
        "product": "Widget"
    });
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

// =========================================================================
// Timestamp modifier end-to-end
// =========================================================================

#[test]
fn test_timestamp_hour_modifier_yaml() {
    let yaml = r#"
title: Off-Hours Login
logsource:
    product: windows
detection:
    selection:
        EventType: 'login'
    time_filter:
        Timestamp|hour: 3
    condition: selection and time_filter
level: high
"#;
    let engine = make_engine_with_rule(yaml);

    // Match: login at 03:xx UTC
    let ev = json!({"EventType": "login", "Timestamp": "2024-07-10T03:45:00Z"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // No match: login at 14:xx UTC
    let ev2 = json!({"EventType": "login", "Timestamp": "2024-07-10T14:45:00Z"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

#[test]
fn test_timestamp_day_modifier_yaml() {
    let yaml = r#"
title: Weekend Activity
logsource:
    product: windows
detection:
    selection:
        EventType: 'access'
    day_check:
        CreatedAt|day: 25
    condition: selection and day_check
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    let ev = json!({"EventType": "access", "CreatedAt": "2024-12-25T10:00:00Z"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    let ev2 = json!({"EventType": "access", "CreatedAt": "2024-12-26T10:00:00Z"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

#[test]
fn test_timestamp_year_modifier_yaml() {
    let yaml = r#"
title: Legacy System
logsource:
    product: windows
detection:
    selection:
        EventType: 'auth'
    old_events:
        EventTime|year: 2020
    condition: selection and old_events
level: low
"#;
    let engine = make_engine_with_rule(yaml);

    let ev = json!({"EventType": "auth", "EventTime": "2020-06-15T10:00:00Z"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    let ev2 = json!({"EventType": "auth", "EventTime": "2024-06-15T10:00:00Z"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

// =========================================================================
// action: repeat through engine
// =========================================================================

#[test]
fn test_action_repeat_evaluates_correctly() {
    // Two rules via repeat: same logsource, different detections
    let yaml = r#"
title: Detect Whoami
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: medium
---
action: repeat
title: Detect Ipconfig
detection:
    selection:
        CommandLine|contains: 'ipconfig'
    condition: selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    assert_eq!(collection.rules.len(), 2);

    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();
    assert_eq!(engine.rule_count(), 2);

    // First rule matches whoami
    let ev1 = json!({"CommandLine": "whoami /all"});
    let matches1 = engine.evaluate(&JsonEvent::borrow(&ev1));
    assert_eq!(matches1.len(), 1);
    assert_eq!(matches1[0].header.rule_title, "Detect Whoami");

    // Second rule matches ipconfig (inherited logsource/level)
    let ev2 = json!({"CommandLine": "ipconfig /all"});
    let matches2 = engine.evaluate(&JsonEvent::borrow(&ev2));
    assert_eq!(matches2.len(), 1);
    assert_eq!(matches2[0].header.rule_title, "Detect Ipconfig");

    // Neither matches dir
    let ev3 = json!({"CommandLine": "dir"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev3)).is_empty());
}

#[test]
fn test_action_repeat_with_global() {
    // Global + repeat: global sets logsource, first doc sets detection,
    // repeat overrides title and detection
    let yaml = r#"
action: global
logsource:
    product: windows
    category: process_creation
level: high
---
title: Detect Net User
detection:
    selection:
        CommandLine|contains: 'net user'
    condition: selection
---
action: repeat
title: Detect Net Group
detection:
    selection:
        CommandLine|contains: 'net group'
    condition: selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    assert_eq!(collection.rules.len(), 2);

    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    let ev1 = json!({"CommandLine": "net user admin"});
    let m1 = engine.evaluate(&JsonEvent::borrow(&ev1));
    assert_eq!(m1.len(), 1);
    assert_eq!(m1[0].header.rule_title, "Detect Net User");

    let ev2 = json!({"CommandLine": "net group admins"});
    let m2 = engine.evaluate(&JsonEvent::borrow(&ev2));
    assert_eq!(m2.len(), 1);
    assert_eq!(m2[0].header.rule_title, "Detect Net Group");
}

// =========================================================================
// |neq modifier
// =========================================================================

#[test]
fn test_neq_modifier_yaml() {
    let yaml = r#"
title: Non-Standard Port
logsource:
    product: windows
detection:
    selection:
        Protocol: TCP
    filter:
        DestinationPort|neq: 443
    condition: selection and filter
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    // Match: TCP on port 80 (neq 443 is true)
    let ev = json!({"Protocol": "TCP", "DestinationPort": "80"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // No match: TCP on port 443 (neq 443 is false)
    let ev2 = json!({"Protocol": "TCP", "DestinationPort": "443"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

#[test]
fn test_neq_modifier_integer() {
    let yaml = r#"
title: Non-Standard Port Numeric
logsource:
    product: windows
detection:
    selection:
        DestinationPort|neq: 443
    condition: selection
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    let ev = json!({"DestinationPort": 80});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    let ev2 = json!({"DestinationPort": 443});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

// =========================================================================
// 1 of them / all of them: underscore exclusion
// =========================================================================

#[test]
fn test_selector_them_excludes_underscore() {
    // Sigma spec: `1 of them` / `all of them` excludes identifiers starting with _
    let yaml = r#"
title: Underscore Test
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'whoami'
    _helper:
        User: 'SYSTEM'
    condition: all of them
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    // With `all of them` excluding `_helper`, only `selection` needs to match
    let ev = json!({"CommandLine": "whoami", "User": "admin"});
    assert_eq!(
        engine.evaluate(&JsonEvent::borrow(&ev)).len(),
        1,
        "all of them should exclude _helper, so only selection is required"
    );
}

#[test]
fn test_selector_them_includes_non_underscore() {
    let yaml = r#"
title: Multiple Selections
logsource:
    product: windows
detection:
    sel_cmd:
        CommandLine|contains: 'cmd'
    sel_ps:
        CommandLine|contains: 'powershell'
    _private:
        User: 'admin'
    condition: 1 of them
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    // `1 of them` excludes `_private`, so only sel_cmd and sel_ps are considered
    let ev = json!({"CommandLine": "cmd.exe", "User": "guest"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // _private alone should not count
    let ev2 = json!({"CommandLine": "notepad", "User": "admin"});
    assert!(
        engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty(),
        "_private should be excluded from 'them'"
    );
}

// =========================================================================
// UTF-16 encoding modifiers
// =========================================================================

#[test]
fn test_utf16le_modifier_yaml() {
    // |wide is an alias for |utf16le
    let yaml = r#"
title: Wide String
logsource:
    product: windows
detection:
    selection:
        Payload|wide|base64: 'Test'
    condition: selection
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    // "Test" in UTF-16LE, then base64 encoded
    // T=0x54,0x00 e=0x65,0x00 s=0x73,0x00 t=0x74,0x00
    // base64 of [0x54,0x00,0x65,0x00,0x73,0x00,0x74,0x00] = "VABlAHMAdAA="
    let ev = json!({"Payload": "VABlAHMAdAA="});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);
}

#[test]
fn test_utf16be_modifier_yaml() {
    let yaml = r#"
title: UTF16BE String
logsource:
    product: windows
detection:
    selection:
        Payload|utf16be|base64: 'AB'
    condition: selection
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    // "AB" in UTF-16BE: A=0x00,0x41 B=0x00,0x42
    // base64 of [0x00,0x41,0x00,0x42] = "AEEAQg=="
    let ev = json!({"Payload": "AEEAQg=="});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);
}

#[test]
fn test_utf16_bom_modifier_yaml() {
    let yaml = r#"
title: UTF16 BOM String
logsource:
    product: windows
detection:
    selection:
        Payload|utf16|base64: 'A'
    condition: selection
level: medium
"#;
    let engine = make_engine_with_rule(yaml);

    // "A" in UTF-16 with BOM: FF FE (BOM) + 41 00 (A in UTF-16LE)
    // base64 of [0xFF,0xFE,0x41,0x00] = "//5BAA=="
    let ev = json!({"Payload": "//5BAA=="});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);
}

// =========================================================================
// Pipeline integration (end-to-end)
// =========================================================================

#[test]
fn test_pipeline_field_mapping_e2e() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Sysmon to ECS
transformations:
  - type: field_name_mapping
    mapping:
      CommandLine: process.command_line
    rule_conditions:
      - type: logsource
        product: windows
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    let rule_yaml = r#"
title: Detect Whoami
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: medium
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // After pipeline: field is renamed to process.command_line
    // So the event must use the original Sigma field name — the pipeline
    // maps rule fields, not event fields. Events still use their native schema.
    // Actually, after pipeline transforms the rule's field names,
    // the rule now looks for "process.command_line" in the event.
    let ev = json!({"process.command_line": "cmd /c whoami"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // Old field name should no longer match
    let ev2 = json!({"CommandLine": "cmd /c whoami"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

#[test]
fn test_pipeline_add_condition_e2e() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Add index condition
transformations:
  - type: add_condition
    conditions:
      source: windows
    rule_conditions:
      - type: logsource
        product: windows
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    let rule_yaml = r#"
title: Detect Cmd
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'cmd'
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // Must have both the original match AND source=windows
    let ev = json!({"CommandLine": "cmd.exe", "source": "windows"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // Missing source field: should not match (pipeline added condition)
    let ev2 = json!({"CommandLine": "cmd.exe"});
    assert!(engine.evaluate(&JsonEvent::borrow(&ev2)).is_empty());
}

#[test]
fn test_pipeline_change_logsource_e2e() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Change logsource
transformations:
  - type: change_logsource
    product: elastic
    category: endpoint
    rule_conditions:
      - type: logsource
        product: windows
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    let rule_yaml = r#"
title: Test Rule
logsource:
    product: windows
    category: process_creation
detection:
    selection:
        action: test
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // Rule still evaluates based on detection logic
    let ev = json!({"action": "test"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // But with logsource routing, the original windows logsource no longer matches
    let ls = LogSource {
        product: Some("windows".to_string()),
        category: Some("process_creation".to_string()),
        ..Default::default()
    };
    assert!(
        engine
            .evaluate_with_logsource(&JsonEvent::borrow(&ev), &ls)
            .is_empty(),
        "logsource was changed; windows/process_creation should not match"
    );

    let ls2 = LogSource {
        product: Some("elastic".to_string()),
        category: Some("endpoint".to_string()),
        ..Default::default()
    };
    assert_eq!(
        engine
            .evaluate_with_logsource(&JsonEvent::borrow(&ev), &ls2)
            .len(),
        1,
        "elastic/endpoint should match the transformed logsource"
    );
}

#[test]
fn test_pipeline_replace_string_e2e() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Replace backslash
transformations:
  - type: replace_string
    regex: "\\\\"
    replacement: "/"
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    let rule_yaml = r#"
title: Path Detection
logsource:
    product: windows
detection:
    selection:
        FilePath|contains: 'C:\Windows'
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // After replace: rule looks for "C:/Windows" instead of "C:\Windows"
    let ev = json!({"FilePath": "C:/Windows/System32/cmd.exe"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);
}

#[test]
fn test_pipeline_skips_non_matching_rules() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Windows Only
transformations:
  - type: field_name_prefix
    prefix: "win."
    rule_conditions:
      - type: logsource
        product: windows
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    // Two rules: one Windows, one Linux
    let rule_yaml = r#"
title: Windows Rule
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: low
---
title: Linux Rule
logsource:
    product: linux
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();
    assert_eq!(collection.rules.len(), 2);

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // Windows rule: field was prefixed to win.CommandLine
    let ev_win = json!({"win.CommandLine": "whoami"});
    let m = engine.evaluate(&JsonEvent::borrow(&ev_win));
    assert_eq!(m.len(), 1);
    assert_eq!(m[0].header.rule_title, "Windows Rule");

    // Linux rule: field was NOT prefixed (still CommandLine)
    let ev_linux = json!({"CommandLine": "whoami"});
    let m2 = engine.evaluate(&JsonEvent::borrow(&ev_linux));
    assert_eq!(m2.len(), 1);
    assert_eq!(m2[0].header.rule_title, "Linux Rule");
}

#[test]
fn test_multiple_pipelines_e2e() {
    use crate::pipeline::parse_pipeline;

    let p1_yaml = r#"
name: First Pipeline
priority: 10
transformations:
  - type: field_name_mapping
    mapping:
      CommandLine: process.args
"#;
    let p2_yaml = r#"
name: Second Pipeline
priority: 20
transformations:
  - type: field_name_suffix
    suffix: ".keyword"
"#;
    let p1 = parse_pipeline(p1_yaml).unwrap();
    let p2 = parse_pipeline(p2_yaml).unwrap();

    let rule_yaml = r#"
title: Test
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'test'
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new();
    engine.add_pipeline(p1);
    engine.add_pipeline(p2);
    engine.add_collection(&collection).unwrap();

    // After p1: CommandLine -> process.args
    // After p2: process.args -> process.args.keyword
    let ev = json!({"process.args.keyword": "testing"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);
}

#[test]
fn test_pipeline_drop_detection_item_e2e() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Drop EventID
transformations:
  - type: drop_detection_item
    field_name_conditions:
      - type: include_fields
        fields:
          - EventID
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    let rule_yaml = r#"
title: Sysmon Process
logsource:
    product: windows
detection:
    selection:
        EventID: 1
        CommandLine|contains: 'whoami'
    condition: selection
level: medium
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // EventID detection item was dropped, so only CommandLine matters
    let ev = json!({"CommandLine": "whoami"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);

    // Without pipeline, EventID=1 would also be required
    let mut engine2 = Engine::new();
    engine2.add_collection(&collection).unwrap();
    // Without EventID, should not match
    assert!(engine2.evaluate(&JsonEvent::borrow(&ev)).is_empty());
}

#[test]
fn test_pipeline_set_state_and_conditional() {
    use crate::pipeline::parse_pipeline;

    let pipeline_yaml = r#"
name: Stateful Pipeline
transformations:
  - id: mark_windows
    type: set_state
    key: is_windows
    value: "true"
    rule_conditions:
      - type: logsource
        product: windows
  - type: field_name_prefix
    prefix: "winlog."
    rule_conditions:
      - type: processing_state
        key: is_windows
        val: "true"
"#;
    let pipeline = parse_pipeline(pipeline_yaml).unwrap();

    let rule_yaml = r#"
title: Windows Detect
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'test'
    condition: selection
level: low
"#;
    let collection = parse_sigma_yaml(rule_yaml).unwrap();

    let mut engine = Engine::new_with_pipeline(pipeline);
    engine.add_collection(&collection).unwrap();

    // State was set → prefix was applied
    let ev = json!({"winlog.CommandLine": "testing"});
    assert_eq!(engine.evaluate(&JsonEvent::borrow(&ev)).len(), 1);
}

#[test]
fn test_add_rules_matches_per_rule_loop() {
    let yaml = r#"
title: Login
logsource:
    product: windows
detection:
    selection:
        EventType: 'login'
    condition: selection
---
title: Process Create
logsource:
    product: windows
detection:
    selection:
        EventType: 'process_create'
    condition: selection
---
title: Keyword
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();

    let mut per_rule = Engine::new();
    for rule in &collection.rules {
        per_rule.add_rule(rule).unwrap();
    }

    let mut batched = Engine::new();
    let errors = batched.add_rules(&collection.rules);
    assert!(errors.is_empty());

    assert_eq!(per_rule.rules().len(), batched.rules().len());

    let evs = [
        json!({"EventType": "login"}),
        json!({"EventType": "process_create", "CommandLine": "whoami"}),
        json!({"CommandLine": "whoami /all"}),
        json!({"EventType": "file_create"}),
    ];
    for v in &evs {
        let event = JsonEvent::borrow(v);
        let a: Vec<_> = per_rule
            .evaluate(&event)
            .into_iter()
            .map(|m| m.header.rule_title)
            .collect();
        let b: Vec<_> = batched
            .evaluate(&event)
            .into_iter()
            .map(|m| m.header.rule_title)
            .collect();
        assert_eq!(a, b, "verdicts diverge for event {v}");
    }
}

#[test]
fn test_add_rules_collects_errors_without_aborting() {
    let good = r#"
title: Login
logsource:
    product: windows
detection:
    selection:
        EventType: 'login'
    condition: selection
"#;
    let bad = r#"
title: Broken Reference
logsource:
    product: windows
detection:
    selection:
        EventType: 'x'
    condition: unknown_identifier
"#;
    let good_rule = parse_sigma_yaml(good).unwrap().rules.remove(0);
    let bad_rule = parse_sigma_yaml(bad).unwrap().rules.remove(0);

    let mut engine = Engine::new();
    let errors = engine.add_rules([&good_rule, &bad_rule, &good_rule]);

    // The bad rule fails; the two good rules still land in the engine.
    assert_eq!(errors.len(), 1);
    assert_eq!(errors[0].0, 1);
    assert_eq!(engine.rules().len(), 2);

    let ev = json!({"EventType": "login"});
    let matches = engine.evaluate(&JsonEvent::borrow(&ev));
    assert_eq!(matches.len(), 2);
}

/// Regression: loading a multi-thousand rule corpus must stay linear in
/// the rule count. The previous `add_rule` per-rule loop rebuilt the
/// inverted index after every push, turning a 3K-rule load into a
/// multi-minute O(N²) stall. Generating 2000 trivial rules and timing the
/// batched load gives us a cheap, deterministic guard: even on a slow
/// debug build this completes in well under a second, and the old
/// per-rule path would blow well past the 30s ceiling.
#[test]
fn test_add_rules_scales_linearly_on_large_corpus() {
    use std::time::Instant;

    let mut yaml = String::new();
    let n = 2000;
    for i in 0..n {
        if i > 0 {
            yaml.push_str("---\n");
        }
        // Mix of exact-match (indexable) and substring (bloom-eligible)
        // rules so both the rule index and the bloom rebuild are exercised.
        yaml.push_str(&format!(
            "title: Rule {i}\nlogsource:\n    product: windows\ndetection:\n    selection:\n        EventID: '{i}'\n        CommandLine|contains: 'needle{i}'\n    condition: selection\n"
        ));
    }
    let collection = parse_sigma_yaml(&yaml).unwrap();
    assert_eq!(collection.rules.len(), n);

    let started = Instant::now();
    let mut engine = Engine::new();
    let errors = engine.add_rules(&collection.rules);
    let elapsed = started.elapsed();

    assert!(errors.is_empty());
    assert_eq!(engine.rules().len(), n);
    // 30s is a coarse ceiling that the linear path clears by ~100x but
    // the old O(N²) rebuild would not get close to. Stay conservative so
    // the test never flakes on overloaded CI runners.
    assert!(
        elapsed.as_secs() < 30,
        "loading {n} rules took {elapsed:?}; suspect quadratic regression"
    );
}

/// Regression: a tight loop of `add_rule` calls must also stay linear in
/// the rule count. Before incremental indexing this path was O(N²)
/// because every call rebuilt the inverted index and bloom filter; the
/// equivalent of [`test_add_rules_scales_linearly_on_large_corpus`] for
/// the single-rule entry point.
#[test]
fn test_add_rule_loop_scales_linearly_on_large_corpus() {
    use std::time::Instant;

    let mut yaml = String::new();
    let n = 2000;
    for i in 0..n {
        if i > 0 {
            yaml.push_str("---\n");
        }
        yaml.push_str(&format!(
            "title: Rule {i}\nlogsource:\n    product: windows\ndetection:\n    selection:\n        EventID: '{i}'\n        CommandLine|contains: 'needle{i}'\n    condition: selection\n"
        ));
    }
    let collection = parse_sigma_yaml(&yaml).unwrap();
    assert_eq!(collection.rules.len(), n);

    let started = Instant::now();
    let mut engine = Engine::new();
    for rule in &collection.rules {
        engine.add_rule(rule).unwrap();
    }
    let elapsed = started.elapsed();

    assert_eq!(engine.rules().len(), n);
    assert!(
        elapsed.as_secs() < 30,
        "loading {n} rules one at a time took {elapsed:?}; suspect quadratic regression"
    );
}

#[test]
fn test_evaluate_batch_matches_sequential() {
    let yaml = r#"
title: Login
logsource:
    product: windows
detection:
    selection:
        EventType: 'login'
    condition: selection
---
title: Process Create
logsource:
    product: windows
detection:
    selection:
        EventType: 'process_create'
    condition: selection
---
title: Keyword
logsource:
    product: windows
detection:
    selection:
        CommandLine|contains: 'whoami'
    condition: selection
"#;
    let collection = parse_sigma_yaml(yaml).unwrap();
    let mut engine = Engine::new();
    engine.add_collection(&collection).unwrap();

    let vals = [
        json!({"EventType": "login", "User": "admin"}),
        json!({"EventType": "process_create", "CommandLine": "whoami"}),
        json!({"EventType": "file_create"}),
        json!({"CommandLine": "whoami /all"}),
    ];
    let events: Vec<JsonEvent> = vals.iter().map(JsonEvent::borrow).collect();

    // Sequential
    let sequential: Vec<Vec<_>> = events.iter().map(|e| engine.evaluate(e)).collect();

    // Batch
    let refs: Vec<&JsonEvent> = events.iter().collect();
    let batch = engine.evaluate_batch(&refs);

    assert_eq!(sequential.len(), batch.len());
    for (seq, bat) in sequential.iter().zip(batch.iter()) {
        assert_eq!(seq.len(), bat.len());
        for (s, b) in seq.iter().zip(bat.iter()) {
            assert_eq!(s.header.rule_title, b.header.rule_title);
        }
    }
}

// =============================================================================
// Array matching (object-scope quantifier blocks + implicit any-member)
// =============================================================================

/// Whether a rule matches an event value.
fn matches(engine: &Engine, ev: &serde_json::Value) -> bool {
    !engine.evaluate(&JsonEvent::borrow(ev)).is_empty()
}

#[test]
fn array_implicit_any_flat_scalar_array() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections: '123.1.1.1'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"connections": ["123.1.2.2", "123.1.1.1", "123.3.3.3"]})
    ));
    assert!(!matches(
        &engine,
        &json!({"connections": ["10.0.0.1", "10.0.0.2"]})
    ));
}

#[test]
fn array_implicit_any_through_object_array_fans_out() {
    // Regression for the first-match-wins traversal bug: the matching element
    // is NOT first, so this only passes with full fan-out.
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections.ip: '123.1.1.1'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"connections": [{"ip": "10.0.0.1"}, {"ip": "123.1.1.1"}]})
    ));
}

#[test]
fn array_brackets_literal_field_below_v3() {
    // Without sigma-version (floor major 2), `args[0]` is a literal field name,
    // not a positional index: it matches an event whose key is literally
    // "args[0]" and does NOT index into an `args` array.
    let engine = make_engine_with_rule(
        r#"
title: T
logsource: { category: test }
detection:
    selection:
        args[0]: 'cmd.exe'
    condition: selection
"#,
    );
    assert!(matches(&engine, &json!({"args[0]": "cmd.exe"})));
    assert!(!matches(&engine, &json!({"args": ["cmd.exe", "-flag"]})));
}

#[test]
fn array_object_scope_any_correlates_same_element() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections[any]:
            protocol: 'TCP'
            ip|cidr: '123.1.0.0/16'
    condition: selection
"#,
    );
    // One element is both TCP and in-CIDR -> match.
    assert!(matches(
        &engine,
        &json!({"connections": [
            {"protocol": "UDP", "ip": "123.1.5.5"},
            {"protocol": "TCP", "ip": "123.1.9.9"}
        ]})
    ));
    // TCP and in-CIDR exist, but on DIFFERENT elements -> no match
    // (this is the property the flattened form cannot express).
    assert!(!matches(
        &engine,
        &json!({"connections": [
            {"protocol": "TCP", "ip": "10.0.0.1"},
            {"protocol": "UDP", "ip": "123.1.9.9"}
        ]})
    ));
}

#[test]
fn array_object_scope_all_requires_every_member_and_nonempty() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections[all]:
            protocol: 'TCP'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"connections": [{"protocol": "TCP"}, {"protocol": "TCP"}]})
    ));
    assert!(!matches(
        &engine,
        &json!({"connections": [{"protocol": "TCP"}, {"protocol": "UDP"}]})
    ));
    // Empty / missing array must not match `all`.
    assert!(!matches(&engine, &json!({"connections": []})));
    assert!(!matches(&engine, &json!({"other": 1})));
}

#[test]
fn array_scalar_member_all_with_modifier() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        ips[all]|startswith: '123.'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"ips": ["123.1.1.1", "123.9.9.9"]})
    ));
    assert!(!matches(
        &engine,
        &json!({"ips": ["123.1.1.1", "10.0.0.1"]})
    ));
}

#[test]
fn array_nested_quantifiers() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        rules[any]:
            type: 'allow'
            ip[all]|startswith: '123.1.1'
    condition: selection
"#,
    );
    // There is an allow rule whose ip array members all start with 123.1.1.
    assert!(matches(
        &engine,
        &json!({"rules": [
            {"type": "block", "ip": ["124.0.0.1"]},
            {"type": "allow", "ip": ["123.1.1.2", "123.1.1.3"]}
        ]})
    ));
    // The allow rule has a non-conforming ip -> no match.
    assert!(!matches(
        &engine,
        &json!({"rules": [
            {"type": "allow", "ip": ["123.1.1.2", "10.0.0.1"]}
        ]})
    ));
}

#[test]
fn array_mixed_map_and_semantics() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        eventName: 'AuthorizeSecurityGroupIngress'
        ipPermissions[any]:
            ipRanges|contains: '0.0.0.0/0'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({
            "eventName": "AuthorizeSecurityGroupIngress",
            "ipPermissions": [{"ipRanges": "0.0.0.0/0"}]
        })
    ));
    // Array matches but the sibling scalar does not -> AND fails.
    assert!(!matches(
        &engine,
        &json!({
            "eventName": "RunInstances",
            "ipPermissions": [{"ipRanges": "0.0.0.0/0"}]
        })
    ));
}

#[test]
fn array_okta_scopes_cloud_shape() {
    let engine = make_engine_with_rule(
        r#"
title: Okta high-priv scope grant
sigma-version: 3
logsource: { product: okta, service: system }
detection:
    selection:
        target[any]:
            type: 'PUBLIC_CLIENT_APP'
            scopes|contains: 'okta.users.manage'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"target": [
            {"type": "USER", "scopes": "okta.users.read"},
            {"type": "PUBLIC_CLIENT_APP", "scopes": "okta.users.manage okta.apps.read"}
        ]})
    ));
}

#[test]
fn array_positional_index_scalar() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        args[0]|endswith: '\powershell.exe'
        args[1]: '-enc'
    condition: selection
"#,
    );
    // Positional disambiguation: image at [0], first parameter at [1].
    assert!(matches(
        &engine,
        &json!({"args": ["C:\\Windows\\System32\\powershell.exe", "-enc", "ZQ=="]})
    ));
    // '-enc' present but NOT at index 1 -> no match (index is exact, not any).
    assert!(!matches(
        &engine,
        &json!({"args": ["C:\\Windows\\System32\\powershell.exe", "-noprofile", "-enc"]})
    ));
}

#[test]
fn array_positional_index_does_not_fan_out() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        ips[0]: '10.0.0.1'
    condition: selection
"#,
    );
    assert!(matches(&engine, &json!({"ips": ["10.0.0.1", "8.8.8.8"]})));
    // 10.0.0.1 present but at index 1, not 0 -> no match.
    assert!(!matches(&engine, &json!({"ips": ["8.8.8.8", "10.0.0.1"]})));
    // Out of range / non-array -> no match.
    assert!(!matches(&engine, &json!({"ips": []})));
    assert!(!matches(&engine, &json!({"ips": "10.0.0.1"})));
}

#[test]
fn array_positional_index_dotted_path() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections[0].ip|cidr: '10.0.0.0/8'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"connections": [{"ip": "10.1.2.3"}, {"ip": "192.168.1.1"}]})
    ));
    // The in-CIDR ip is at index 1, not 0 -> no match.
    assert!(!matches(
        &engine,
        &json!({"connections": [{"ip": "192.168.1.1"}, {"ip": "10.1.2.3"}]})
    ));
}

#[test]
fn array_escaped_brackets_match_literal_field() {
    // `args\[0\]` matches a field literally named "args[0]", not index 0 of an
    // `args` array.
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        args\[0\]: 'cmd.exe'
    condition: selection
"#,
    );
    // Literal field present -> match.
    assert!(matches(&engine, &json!({"args[0]": "cmd.exe"})));
    // An `args` array does NOT satisfy the escaped (literal) field.
    assert!(!matches(&engine, &json!({"args": ["cmd.exe", "x"]})));
}

#[test]
fn array_negative_index_counts_from_end() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        args[-1]: '-enc'
    condition: selection
"#,
    );
    // -1 is the last element.
    assert!(matches(
        &engine,
        &json!({"args": ["powershell.exe", "-noprofile", "-enc"]})
    ));
    // '-enc' present but not last -> no match (index is exact).
    assert!(!matches(
        &engine,
        &json!({"args": ["powershell.exe", "-enc", "ZQ=="]})
    ));
    // Out of range (|index| > len) and non-array -> no match.
    assert!(!matches(&engine, &json!({"args": []})));
    assert!(!matches(&engine, &json!({"args": "-enc"})));
}

#[test]
fn array_negative_index_dotted_path() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        events[-1].action: 'delete'
    condition: selection
"#,
    );
    // The last event's action is what matters.
    assert!(matches(
        &engine,
        &json!({"events": [{"action": "create"}, {"action": "delete"}]})
    ));
    assert!(!matches(
        &engine,
        &json!({"events": [{"action": "delete"}, {"action": "create"}]})
    ));
}

#[test]
fn array_index_inside_quantifier() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        rules[any].ip[0]: '10.0.0.1'
    condition: selection
"#,
    );
    // Some rule whose FIRST ip is 10.0.0.1.
    assert!(matches(
        &engine,
        &json!({"rules": [
            {"ip": ["8.8.8.8"]},
            {"ip": ["10.0.0.1", "1.1.1.1"]}
        ]})
    ));
    // 10.0.0.1 appears, but never at index 0 -> no match.
    assert!(!matches(
        &engine,
        &json!({"rules": [{"ip": ["8.8.8.8", "10.0.0.1"]}]})
    ));
}

#[test]
fn array_object_scope_none_is_dual_of_any() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        containers[none]:
            image|startswith: 'evil/'
    condition: selection
"#,
    );
    // No container runs an evil image -> match.
    assert!(matches(
        &engine,
        &json!({"containers": [{"image": "nginx"}, {"image": "redis"}]})
    ));
    // One container runs an evil image -> no match.
    assert!(!matches(
        &engine,
        &json!({"containers": [{"image": "nginx"}, {"image": "evil/miner"}]})
    ));
    // An empty or missing array matches `none` (no member satisfies the body).
    assert!(matches(&engine, &json!({"containers": []})));
    assert!(matches(&engine, &json!({"other": 1})));
}

#[test]
fn array_object_scope_all_or_empty_matches_empty() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections[all_or_empty]:
            protocol: 'TCP'
    condition: selection
"#,
    );
    // Like `all` when non-empty: every member must satisfy.
    assert!(matches(
        &engine,
        &json!({"connections": [{"protocol": "TCP"}, {"protocol": "TCP"}]})
    ));
    assert!(!matches(
        &engine,
        &json!({"connections": [{"protocol": "TCP"}, {"protocol": "UDP"}]})
    ));
    // Unlike `all`, an empty or missing array matches (vacuously true).
    assert!(matches(&engine, &json!({"connections": []})));
    assert!(matches(&engine, &json!({"other": 1})));
}

#[test]
fn array_extended_block_per_element_negation() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        connections[any]:
            condition: in_cidr and not is_tcp
            in_cidr:
                ip|cidr: '123.1.0.0/16'
            is_tcp:
                protocol: 'TCP'
    condition: selection
"#,
    );
    // One element is in-CIDR and UDP (not TCP) -> match.
    assert!(matches(
        &engine,
        &json!({"connections": [
            {"protocol": "TCP", "ip": "10.0.0.1"},
            {"protocol": "UDP", "ip": "123.1.9.9"}
        ]})
    ));
    // In-CIDR only on the TCP element; the UDP element is out of CIDR. No
    // single element is both in-CIDR and non-TCP -> no match (per-element bind).
    assert!(!matches(
        &engine,
        &json!({"connections": [
            {"protocol": "TCP", "ip": "123.1.9.9"},
            {"protocol": "UDP", "ip": "10.0.0.1"}
        ]})
    ));
}

#[test]
fn array_extended_block_per_element_disjunction() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        events[any]:
            condition: is_delete or is_drop
            is_delete:
                action: 'delete'
            is_drop:
                action: 'drop'
    condition: selection
"#,
    );
    assert!(matches(
        &engine,
        &json!({"events": [{"action": "create"}, {"action": "drop"}]})
    ));
    assert!(!matches(
        &engine,
        &json!({"events": [{"action": "create"}, {"action": "update"}]})
    ));
}

#[test]
fn array_extended_block_all_quantifier() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        mounts[all]:
            condition: readonly and not is_proc
            readonly:
                mode: 'ro'
            is_proc:
                path|startswith: '/proc'
    condition: selection
"#,
    );
    // Every mount is read-only and none under /proc -> match.
    assert!(matches(
        &engine,
        &json!({"mounts": [
            {"mode": "ro", "path": "/data"},
            {"mode": "ro", "path": "/etc"}
        ]})
    ));
    // One mount is read-write -> no match (all required).
    assert!(!matches(
        &engine,
        &json!({"mounts": [
            {"mode": "ro", "path": "/data"},
            {"mode": "rw", "path": "/etc"}
        ]})
    ));
}

#[test]
fn array_extended_block_scalar_element_marker() {
    // `.` references the current scalar member inside an extended block body:
    // "any 5xx response code that is not 504".
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        rcodes[any]:
            condition: server_error and not gateway_timeout
            server_error:
                .|gte: 500
                .|lte: 599
            gateway_timeout:
                .: 504
    condition: selection
"#,
    );
    assert!(matches(&engine, &json!({"rcodes": [502, 504, 200]})));
    // Only a 504 and a non-5xx -> no element is a 5xx that is not 504.
    assert!(!matches(&engine, &json!({"rcodes": [504, 200]})));
    assert!(matches(&engine, &json!({"rcodes": [503]})));
    assert!(!matches(&engine, &json!({"rcodes": [200, 301]})));
}

#[test]
fn array_scalar_element_marker_basic_block() {
    // `.` in a basic block: every member satisfies the predicate.
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        ports[all]:
            .|gte: 1024
    condition: selection
"#,
    );
    assert!(matches(&engine, &json!({"ports": [1080, 8443]})));
    assert!(!matches(&engine, &json!({"ports": [1080, 80]})));
}

#[test]
fn array_scalar_member_none() {
    let engine = make_engine_with_rule(
        r#"
title: T
sigma-version: 3
logsource: { category: test }
detection:
    selection:
        tags[none]: 'admin'
    condition: selection
"#,
    );
    assert!(matches(&engine, &json!({"tags": ["user", "guest"]})));
    assert!(!matches(&engine, &json!({"tags": ["user", "admin"]})));
    assert!(matches(&engine, &json!({"tags": []})));
    assert!(matches(&engine, &json!({"other": 1})));
}