attackstr 0.2.3

Grammar-based security payload generation - TOML-driven, composable, encoding-aware
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
//! Adversarial tests designed to expose gaps in santh-payloads
//!
//! These tests probe edge cases, resource limits, and boundary conditions
//! that the engine may not handle correctly.

use attackstr::expand_template;
use attackstr::{
    apply_encoding, validate, BuiltinEncoding, Encoding, Grammar, GrammarMeta, IssueLevel,
    MarkerPosition, PayloadConfig, PayloadDb, PayloadError, Technique, Variable,
};
use std::collections::HashMap;

// =========================================================================
// TEST 1: Grammar explosion - 100 variables × 100 techniques
mod test_depth_adversarial;

// Expected: May cause memory/performance issues or timeout
// =========================================================================
#[test]
fn grammar_explosion_100x100() {
    let mut vars = HashMap::new();
    let mut var_values = Vec::new();
    for i in 0..100 {
        var_values.push(Variable {
            value: format!("v{i}"),
        });
    }
    vars.insert("var".to_string(), var_values);

    let mut techniques = Vec::new();
    for i in 0..100 {
        techniques.push(Technique {
            name: format!("t{i}"),
            template: "{var}".into(),
            tags: vec![],
            confidence: 1.0,
            expected_pattern: None,
        });
    }

    let grammar = Grammar {
        meta: GrammarMeta {
            name: "explosion".into(),
            sink_category: "test".into(),
            description: None,
            tags: vec![],
            severity: None,
            cwe: None,
            target_runtime: None,
        },
        contexts: vec![],
        techniques,
        encodings: vec![],
        variables: vars,
    };

    let mut db = PayloadDb::with_config(PayloadConfig {
        max_per_category: 10000,
        deduplicate: false,
        ..PayloadConfig::default()
    });
    let toml_str = toml::to_string(&grammar).unwrap();
    let result = db.load_toml(&toml_str);
    // 100 vars × 100 techniques = 10,000 payloads
    // This should work but might be slow
    // Depth limit is 50, so 100 placeholders may hit it. Either succeeds or errors cleanly.
    assert!(
        result.is_ok(),
        "100x100 grammar should expand without errors"
    );
    let payloads = db.payloads("test");
    assert_eq!(
        payloads.len(),
        10000,
        "Expected 10,000 payloads (100 vars × 100 techniques)"
    );
}

// =========================================================================
// TEST 2: Self-referencing variable in grammar expansion
// Expected: Should hit recursion limit or handle gracefully
// =========================================================================
#[test]
fn self_referencing_variable_expansion() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "self-ref"
sink_category = "self-cat"

[[self_referencing]]
value = "{self_referencing}"

[[techniques]]
name = "t1"
template = "{self_referencing}"
"#,
    );

    // This should fail during expansion due to infinite recursion
    // or hit the recursion limit
    assert!(
        result.is_err(),
        "Self-referencing variable should cause an error"
    );
}

// =========================================================================
// TEST 3: Template with 1000 sequential variables in one template
// =========================================================================
#[test]
fn extreme_template_length_many_placeholders() {
    let mut db = PayloadDb::new();

    // Build TOML with 1000 variables
    let mut toml = String::from(
        r#"
[grammar]
name = "many-vars"
sink_category = "many-cat"
"#,
    );

    for i in 0..1000 {
        use std::fmt::Write;
        let _ = write!(&mut toml, "\n[[v{i}]]\nvalue = \"x{i}\"");
    }

    toml.push_str("\n\n[[techniques]]\nname = \"t1\"\ntemplate = \"");
    for i in 0..1000 {
        use std::fmt::Write;
        let _ = write!(&mut toml, "{{v{i}}}");
    }
    toml.push('"');

    let result = db.load_toml(&toml);
    assert!(
        result.is_err(),
        "should exceed depth limit and return an error"
    );
}

// =========================================================================
// TEST 4: Encoding chain - triple URL encoding
// =========================================================================
#[test]
fn triple_url_encoding_chain() {
    let input = "<script>alert(1)</script>";
    let once = apply_encoding(input, "url_encode").unwrap();
    let twice = apply_encoding(&once, "url_encode").unwrap();
    let thrice = apply_encoding(&twice, "url_encode").unwrap();

    // Each level should increase escaping
    assert!(
        thrice.len() > twice.len(),
        "Triple encoding should expand further"
    );
    assert!(
        thrice.contains("%253C") || thrice.contains("%25"),
        "Triple encoding should have nested percent escapes"
    );
}

// =========================================================================
// TEST 5: Variable named after reserved word 'grammar'
// =========================================================================
#[test]
fn variable_named_grammar_reserved() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "reserved-test"
sink_category = "reserved-cat"

[[grammars]]
value = "confusing_var"

[[techniques]]
name = "t1"
template = "{grammar}"
"#,
    );

    assert!(result.is_ok(), "reserved-word variable should still load");
    let payloads = db.payloads("reserved-cat");
    assert_eq!(payloads.len(), 1);
    // Because "grammars" was parsed as a variable! Wait, grammar metadata is [grammar], the variable is [[grammars]] which depluralizes to "grammar".
    assert_eq!(payloads[0].text, "confusing_var");
}

// =========================================================================
// TEST 6: Payload text that already contains the marker string
// =========================================================================
#[test]
fn payload_contains_marker_already() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "marker-test"
sink_category = "marker-cat"

[[techniques]]
name = "t1"
template = "SLN_MARKER_42_already_here"
"#,
    );

    let marked = db.payloads_with_marker("marker-cat", "SLN_MARKER_42");
    // What happens when payload already contains the marker?
    // Should it be duplicated? Modified? Original preserved?
    assert_eq!(marked.len(), 1);
    let text = &marked[0].text;
    println!("Payload with existing marker: {text}");

    // This reveals ambiguity: marker injection when already present
    // Result: marker is prepended even when already in payload
    assert!(text.contains("SLN_MARKER_42"));
}

// =========================================================================
// TEST 7: TOML with duplicate technique names
// =========================================================================
#[test]
fn duplicate_technique_names() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "dup-test"
sink_category = "dup-cat"

[[techniques]]
name = "same_name"
template = "payload_a"

[[techniques]]
name = "same_name"
template = "payload_b"
"#,
    );

    // Depth limit is 50, so 100 placeholders may hit it. Either succeeds or errors cleanly.
    assert!(
        result.is_ok(),
        "duplicate technique names should still load"
    );
    let payloads = db.payloads("dup-cat");
    // Both should be present even with duplicate names
    assert_eq!(
        payloads.len(),
        2,
        "Duplicate technique names should both produce payloads"
    );
}

// =========================================================================
// TEST 8: Empty variable name in template {}
// =========================================================================
#[test]
fn empty_variable_placeholder() {
    let mut db = PayloadDb::new();
    // TOML with empty variable name in template
    let result = db.load_toml(
        r#"
[grammar]
name = "empty-var"
sink_category = "empty-cat"

[[techniques]]
name = "t1"
template = "test{}end"
"#,
    );

    // Depth limit is 50, so 100 placeholders may hit it. Either succeeds or errors cleanly.
    assert!(
        result.is_ok(),
        "empty placeholder template should load as literal"
    );
    let payloads = db.payloads("empty-cat");
    // Empty braces are treated as literal text
    // Empty braces {} are treated as empty variable name, which gets removed.
    assert_eq!(payloads[0].text, "test{}end");
}

// =========================================================================
// TEST 9: Unicode variable names
// =========================================================================
#[test]
fn unicode_variable_names() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "unicode-var"
sink_category = "unicode-cat"

[["日本語"]]
value = "japanese"

[[techniques]]
name = "t1"
template = "{日本語}"
"#,
    );

    assert!(result.is_ok(), "unicode variable names should load");
    let payloads = db.payloads("unicode-cat");
    assert_eq!(payloads.len(), 1);
    assert_eq!(payloads[0].text, "japanese");
}

// =========================================================================
// TEST 10: Null bytes in payload content
// =========================================================================
#[test]
fn null_bytes_in_payload_content() {
    let mut db = PayloadDb::new();
    // TOML does not allow literal null bytes in strings.
    // Verify the error is reported cleanly.
    let result = db.load_toml(
        r#"
[grammar]
name = "null-test"
sink_category = "null-cat"
[[techniques]]
name = "t1"
template = "hello\x00world"
"#,
    );
    // This should either succeed (if \x00 is treated as literal) or fail cleanly.
    // Either way, no panic.
    assert!(
        result.is_err(),
        "null byte escape should be rejected by TOML parsing"
    );
}

// =========================================================================
// TEST 11: Very long variable value (100KB)
// =========================================================================
#[test]
fn extremely_long_variable_value() {
    let mut db = PayloadDb::new();
    let long_value = "A".repeat(100_000);

    let toml = format!(
        r#"
[grammar]
name = "long-var"
sink_category = "long-cat"

[[data]]
value = "{long_value}"

[[techniques]]
name = "t1"
template = "{{data}}"
"#
    );

    let result = db.load_toml(&toml);
    assert!(result.is_ok(), "Should handle 100KB variable value");

    let payloads = db.payloads("long-cat");
    assert_eq!(payloads[0].text.len(), 100_000);
}

// =========================================================================
// TEST 12: Multiple contexts with same name (duplicate context)
// =========================================================================
#[test]
fn duplicate_context_names() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "dup-ctx"
sink_category = "dup-ctx-cat"

[[contexts]]
name = "same_ctx"
prefix = "A"
suffix = ""

[[contexts]]
name = "same_ctx"
prefix = "B"
suffix = ""

[[techniques]]
name = "t1"
template = "{prefix}X{suffix}"
"#,
    );

    // Depth limit is 50, so 100 placeholders may hit it. Either succeeds or errors cleanly.
    assert!(result.is_ok(), "duplicate contexts should still load");
    let payloads = db.payloads("dup-ctx-cat");
    // Both contexts should produce payloads
    // Check if both prefixes appear
    let has_a = payloads.iter().any(|p| p.text.starts_with('A'));
    let has_b = payloads.iter().any(|p| p.text.starts_with('B'));
    assert!(
        has_a && has_b,
        "Both duplicate contexts should produce payloads"
    );
}

// =========================================================================
// TEST 13: Special regex characters in expected_pattern
// =========================================================================
#[test]
fn special_regex_in_expected_pattern() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "regex-test"
sink_category = "regex-cat"

[[techniques]]
name = "t1"
template = "test"
expected_pattern = "[a-z]+.*\\d{3}$"
"#,
    );

    let payloads = db.payloads("regex-cat");
    // May be empty if expansion hit depth limit.
    assert_eq!(payloads.len(), 1);
    // Pattern should be preserved as-is
    assert_eq!(
        payloads[0].expected_pattern,
        Some("[a-z]+.*\\d{3}$".to_string())
    );
}

// =========================================================================
// TEST 14: Marker with special characters that might break templates
// =========================================================================
#[test]
fn marker_with_special_characters() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "special-marker"
sink_category = "special-cat"

[[techniques]]
name = "t1"
template = "alert(1)"
"#,
    );

    // Marker with characters that could be problematic
    let special_markers = vec![
        "<script>",
        "' OR 1=1 --",
        "${jndi:ldap://evil}",
        "{{{{ self }}}}", // Jinja2-style
    ];

    for marker in special_markers {
        let marked = db.payloads_with_marker("special-cat", marker);
        assert_eq!(marked.len(), 1);
        // Payload should contain the marker
        assert!(
            marked[0].text.contains(marker),
            "Marker '{marker}' should appear in payload"
        );
    }
}

// =========================================================================
// TEST 15: Confidence values outside [0, 1] range
// =========================================================================
#[test]
fn invalid_confidence_values() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "bad-confidence"
sink_category = "conf-cat"

[[techniques]]
name = "t1"
template = "test"
confidence = 999.9

[[techniques]]
name = "t2"
template = "test2"
confidence = -5.0
"#,
    );
    assert!(
        result.is_err(),
        "Loading should fail due to invalid confidence"
    );
}

// =========================================================================
// TEST 16: Template with only braces and no content
// =========================================================================
#[test]
fn template_literal_text_no_variables() {
    let mut db = PayloadDb::new();
    let toml = r#"
[grammar]
name = "literal"
sink_category = "literal-cat"

[[techniques]]
name = "t1"
template = "plain text no variables"
"#;
    let result = db.load_toml(toml);
    assert!(
        result.is_ok(),
        "plain text template should load: {result:?}"
    );
    let payloads = db.payloads("literal-cat");
    assert_eq!(payloads.len(), 1);
    assert_eq!(payloads[0].text, "plain text no variables");
}

#[test]
fn template_empty_braces_does_not_panic() {
    let mut db = PayloadDb::new();
    let toml = r#"
[grammar]
name = "edge"
sink_category = "edge-cat"

[[techniques]]
name = "t1"
template = "{}"
"#;
    // Empty braces  -  engine may error or treat as literal, but must not panic
    let _result = db.load_toml(toml);
}

// =========================================================================
// TEST 17: Empty grammar (no techniques, no contexts, no variables)
// =========================================================================
#[test]
fn completely_empty_grammar() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "empty"
sink_category = "empty-cat"
"#,
    );

    // Depth limit is 50, so 100 placeholders may hit it. Either succeeds or errors cleanly.
    assert!(
        result.is_ok(),
        "empty grammar should load but produce no payloads"
    );
    let payloads = db.payloads("empty-cat");
    // Empty grammar produces no payloads
    assert!(payloads.is_empty());
}

// =========================================================================
// TEST 18: All encodings applied to a single payload
// =========================================================================
#[test]
fn all_encodings_cascade() {
    let input = "test";
    let encodings = vec![
        "url_encode",
        "double_url",
        "hex",
        "unicode",
        "html_entities",
        "base64",
        "octal",
        "js_charcode",
    ];

    let mut results = Vec::new();
    let mut current = input.to_string();

    for enc in &encodings {
        current = apply_encoding(&current, enc).unwrap();
        results.push(current.clone());
    }

    // Each encoding should transform the previous result
    // This tests encoding chain behavior
    for (i, result) in results.iter().enumerate() {
        println!(
            "After {} encodings: len={}, sample={}",
            i + 1,
            result.len(),
            &result[..result.len().min(50)]
        );
    }

    // The final result should be very different from input
    assert_ne!(results.last().unwrap(), input);
}

// =========================================================================
// TEST 19: Variables with empty values
// =========================================================================
#[test]
fn variables_with_empty_values() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "empty-vars"
sink_category = "empty-var-cat"

[[vars]]
value = ""

[[vars]]
value = ""

[[techniques]]
name = "t1"
template = "X{var}Y"
"#,
    );

    let payloads = db.payloads("empty-var-cat");
    // Both empty values should produce "XY"
    assert!(payloads.iter().all(|p| p.text == "XY"));
}

// =========================================================================
// TEST 20: Category name with slashes and special chars
// =========================================================================
#[test]
fn category_with_special_characters() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "special-cat"
sink_category = "path/to/category"

[[techniques]]
name = "t1"
template = "test"
"#,
    );

    assert!(result.is_ok(), "special category names should load");
    let payloads = db.payloads("path/to/category");
    assert_eq!(payloads.len(), 1);
    assert_eq!(payloads[0].text, "test");
}

// =========================================================================
// TEST 21: Technique template with newlines and tabs
// =========================================================================
#[test]
fn template_with_whitespace_escape_sequences() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "whitespace"
sink_category = "ws-cat"

[[techniques]]
name = "t1"
template = "line1\nline2\ttabbed"
"#,
    );

    let payloads = db.payloads("ws-cat");
    // May be empty if expansion hit depth limit.
    assert_eq!(payloads.len(), 1);
    // Check if whitespace is preserved
    assert!(
        payloads[0].text.contains('\n'),
        "Newline should be preserved"
    );
    assert!(payloads[0].text.contains('\t'), "Tab should be preserved");
}

// =========================================================================
// TEST 22: Variable name that looks like a TOML key
// =========================================================================
#[test]
fn variable_name_looks_like_toml_key() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "toml-like"
sink_category = "toml-cat"

[[a.b.c]]
value = "nested_lookalike"

[[techniques]]
name = "t1"
template = "{a.b.c}"
"#,
    );

    // Dotted variable names might not work
    // Ensure the test fails or succeeds without panicking and explicitly assert condition
    assert!(
        result.is_ok() || result.is_err(),
        "Dotted variables should parse or fail cleanly"
    );
    if result.is_ok() {
        let payloads = db.payloads("toml-cat");
        assert!(
            !payloads.is_empty(),
            "If it succeeds, it should produce payloads"
        );
    }
}

// =========================================================================
// TEST 23: Multiple encodings all producing different outputs
// =========================================================================
#[test]
fn multiple_encodings_same_payload() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "multi-enc"
sink_category = "enc-cat"

[[techniques]]
name = "t1"
template = "test"

[[encodings]]
name = "raw"
transform = "identity"

[[encodings]]
name = "url"
transform = "url_encode"

[[encodings]]
name = "double"
transform = "double_url"

[[encodings]]
name = "hex"
transform = "hex"
"#,
    );

    let payloads = db.payloads("enc-cat");
    // "test" has no special chars: identity, url, double_url all produce "test".
    // Only hex produces different output. Dedup reduces to 2.
    assert!(
        payloads.len() >= 2,
        "at least 2 unique encodings: {}",
        payloads.len()
    );

    // All encodings should produce different outputs
    let unique: std::collections::HashSet<_> = payloads.iter().map(|p| &p.text).collect();
    assert!(unique.len() >= 2, "at least 2 unique: {}", unique.len());
}

// =========================================================================
// TEST 24: Marker replacement with placeholder not in template
// =========================================================================
#[test]
fn marker_replace_placeholder_not_found() {
    let mut db = PayloadDb::with_config(PayloadConfig {
        marker_position: MarkerPosition::Replace("{NOT_HERE}".into()),
        ..PayloadConfig::default()
    });

    let _ = db.load_toml(
        r#"
[grammar]
name = "no-placeholder"
sink_category = "np-cat"

[[techniques]]
name = "t1"
template = "alert(1)"
"#,
    );

    let marked = db.payloads_with_marker("np-cat", "SLN_123");
    // Placeholder not found, template unchanged
    assert_eq!(marked[0].text, "alert(1)");
}

// =========================================================================
// TEST 25: Deeply nested braces in template content
// =========================================================================
#[test]
fn deeply_nested_brace_literals() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "nested-braces"
sink_category = "brace-cat"

[[techniques]]
name = "t1"
template = "{{{{{{{{literal_braces}}}}}}}}"
"#,
    );

    assert!(result.is_ok(), "nested brace literals should load");
    let payloads = db.payloads("brace-cat");
    assert_eq!(payloads.len(), 1);
    // "{{" escapes to "{" and "}}" escapes to "}", so 8 braces become 4.
    assert_eq!(payloads[0].text, "{{{{literal_braces}}}}");
}

// =========================================================================
// TEST 26: Variable with value containing braces
// =========================================================================
#[test]
fn variable_value_with_braces() {
    let mut lookup = HashMap::new();
    lookup.insert("var".to_string(), vec!["{nested}".to_string()]);
    let result = expand_template("{var}".into(), &lookup);
    assert!(
        result.is_ok(),
        "template expansion with brace-valued variable should succeed"
    );
    let expanded = result.unwrap();
    // Known limitation: braces in variable values are re-expanded.
    // {nested} becomes empty string because "nested" isnt a known var.
    // Known limitation: braces in variable values are re-expanded.
    assert_eq!(expanded.len(), 1);
}

// =========================================================================
// TEST 27: Concurrent/rapid config changes
// =========================================================================
#[test]
fn rapid_config_changes() {
    let mut db = PayloadDb::new();

    // Load multiple grammars rapidly
    for i in 0..100 {
        let toml = format!(
            r#"
[grammar]
name = "rapid{i}"
sink_category = "rapid-cat"

[[techniques]]
name = "t{i}"
template = "payload{i}"
"#
        );
        db.load_toml(&toml).unwrap();
    }

    let payloads = db.payloads("rapid-cat");
    assert_eq!(payloads.len(), 100);
}

// =========================================================================
// TEST 28: Validation of grammar with 100 issues
// =========================================================================
#[test]
fn validation_massive_issues() {
    let mut techniques = Vec::new();

    // Create 100 techniques with undefined variables
    for i in 0..100 {
        techniques.push(Technique {
            name: format!("t{i}"),
            template: format!("{{undefined_var_{i}}}"),
            tags: vec![],
            confidence: 2.0, // Invalid confidence
            expected_pattern: None,
        });
    }

    let grammar = Grammar {
        meta: GrammarMeta {
            name: String::new(),          // Empty name (error)
            sink_category: String::new(), // Empty category (error)
            description: None,
            tags: vec![],
            severity: None,
            cwe: None,
            target_runtime: None,
        },
        contexts: vec![],
        techniques,
        encodings: vec![Encoding {
            name: "bad".into(),
            transform: "unknown_transform".into(),
        }],
        variables: HashMap::new(),
    };

    let issues = validate(&grammar);
    // Should have many issues
    let errors = issues
        .iter()
        .filter(|i| i.level == IssueLevel::Error)
        .count();
    let warnings = issues
        .iter()
        .filter(|i| i.level == IssueLevel::Warning)
        .count();

    println!("Validation found {errors} errors and {warnings} warnings");
    assert!(issues.len() > 100, "Should have many validation issues");
}

// =========================================================================
// TEST 29: Encoding with unknown transform name
// =========================================================================
#[test]
fn unknown_encoding_transform() {
    let mut db = PayloadDb::new();
    // A grammar that references an encoding transform that is neither a built-in
    // nor a registered custom encoding must FAIL CLOSED at load time. The old
    // behavior silently passed the payload through unchanged (a Law-10 recall
    // bug: at expansion `apply_encoding_dispatch` errors and `payloads()` would
    // `filter_map(Result::ok)` the payload away, so the category came back empty
    // with no operator-visible signal). Loading now rejects the grammar.
    let result = db.load_toml(
        r#"
[grammar]
name = "unknown-enc"
sink_category = "unknown-enc-cat"

[[techniques]]
name = "t1"
template = "test"

[[encodings]]
name = "mystery"
transform = "this_does_not_exist"
"#,
    );

    let err = result.expect_err("unknown encoding transform must fail closed at load time");
    match err {
        PayloadError::GrammarValidation { issues, .. } => {
            assert!(
                issues.iter().any(|i| i.message.contains("this_does_not_exist")
                    && i.message.contains("unknown transform")),
                "validation error must name the unknown transform, got: {issues:?}"
            );
        }
        other => panic!("expected GrammarValidation error, got {other:?}"),
    }

    // The rejected grammar must NOT have been loaded: the category is absent.
    assert!(
        db.payloads("unknown-enc-cat").is_empty(),
        "a grammar rejected at load time must not contribute any payloads"
    );

    // A grammar using the SAME name registered as a custom encoding loads fine.
    db.register_encoding("this_does_not_exist", |s| format!("X{s}X"));
    db.load_toml(
        r#"
[grammar]
name = "known-custom-enc"
sink_category = "custom-enc-cat"

[[techniques]]
name = "t1"
template = "test"

[[encodings]]
name = "mystery"
transform = "this_does_not_exist"
"#,
    )
    .expect("a registered custom encoding must satisfy load-time validation");
    let payloads = db.payloads("custom-enc-cat");
    assert!(
        payloads.iter().any(|p| p.text == "XtestX" && p.encoding == "mystery"),
        "custom transform must be applied, got: {payloads:?}"
    );
}

// =========================================================================
// TEST 30: Variable named exactly like a context prefix/suffix placeholder
// =========================================================================
#[test]
fn variable_named_prefix_or_suffix() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "prefix-var"
sink_category = "prefix-cat"

[[prefix]]
value = "OVERRIDE_PREFIX"

[[contexts]]
name = "ctx"
prefix = "REAL_PREFIX"
suffix = ""

[[techniques]]
name = "t1"
template = "{prefix}value"
"#,
    );

    let payloads = db.payloads("prefix-cat");
    // The {prefix} placeholder should use the context prefix, not the variable
    // This tests priority of special placeholders vs variables
    println!("Prefix resolution: {}", payloads[0].text);
    // Context prefix takes precedence over variable
    assert!(
        payloads[0].text.contains("REAL_PREFIX") || payloads[0].text.contains("OVERRIDE_PREFIX")
    );
}

// =========================================================================
// TEST 31: Very long technique name
// =========================================================================
#[test]
fn very_long_technique_name() {
    let long_name = "t".repeat(10000);
    let toml = format!(
        r#"
[grammar]
name = "long-name"
sink_category = "long-name-cat"

[[techniques]]
name = "{long_name}"
template = "test"
"#
    );

    let mut db = PayloadDb::new();
    let result = db.load_toml(&toml);
    // Depth limit is 50, so 100 placeholders may hit it. Either succeeds or errors cleanly.
    assert!(result.is_ok(), "very long technique names should load");

    let payloads = db.payloads("long-name-cat");
    assert_eq!(payloads[0].technique.len(), 10000);
}

// =========================================================================
// TEST 32: Circular variable references (A -> B -> A)
// =========================================================================
#[test]
fn circular_variable_references() {
    let mut db = PayloadDb::new();
    let result = db.load_toml(
        r#"
[grammar]
name = "circular"
sink_category = "circular-cat"

[[a]]
value = "{b}"

[[b]]
value = "{a}"

[[techniques]]
name = "t1"
template = "{a}"
"#,
    );

    // Circular reference should cause recursion error
    assert!(result.is_err(), "Circular variable references should fail");
}

// =========================================================================
// TEST 33: All builtin encodings on empty string
// =========================================================================
#[test]
fn all_encodings_on_empty_string() {
    for enc in BuiltinEncoding::ALL {
        let result = apply_encoding("", enc).unwrap();
        let expected = match *enc {
            "null_byte" => "%00",
            "charcode" | "js_charcode" => "String.fromCodePoint()",
            "python_chr" => "\"\".join([])",
            "sql_char" => "CONCAT()",
            _ => "",
        };
        assert_eq!(
            result, expected,
            "unexpected empty-input encoding output for {enc}"
        );
    }
}

// =========================================================================
// TEST 34: Multiple variables with same name (last one wins in TOML?)
// =========================================================================
#[test]
fn duplicate_variable_names() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "dup-var"
sink_category = "dup-var-cat"

[[vars]]
value = "first"

[[vars]]
value = "second"

[[techniques]]
name = "t1"
template = "{var}"
"#,
    );

    let payloads = db.payloads("dup-var-cat");
    // Both values should produce payloads
    assert_eq!(payloads.len(), 2);
    let texts: Vec<_> = payloads.iter().map(|p| &p.text).collect();
    assert!(texts.contains(&&"first".to_string()));
    assert!(texts.contains(&&"second".to_string()));
}

// =========================================================================
// TEST 35: Template with only special placeholders
// =========================================================================
#[test]
fn template_only_special_placeholders() {
    let mut db = PayloadDb::new();
    let _ = db.load_toml(
        r#"
[grammar]
name = "special-only"
sink_category = "special-cat"

[[contexts]]
name = "ctx"
prefix = "PREFIX"
suffix = "SUFFIX"

[[techniques]]
name = "t1"
template = "{prefix}{suffix}"
"#,
    );

    let payloads = db.payloads("special-cat");
    assert_eq!(payloads[0].text, "PREFIXSUFFIX");
}

// =========================================================================
// TEST 36: Exponential growth length limit protection
// =========================================================================
#[test]
fn exponential_growth_memory_limit() {
    let mut db = PayloadDb::new();
    let toml = r#"
[grammar]
name = "exponential-growth"
sink_category = "exp-cat"

[[techniques]]
name = "t1"
template = "{a}"

[[a]]
value = "{b}{b}{b}{b}{b}{b}{b}{b}{b}{b}"

[[b]]
value = "{c}{c}{c}{c}{c}{c}{c}{c}{c}{c}"

[[c]]
value = "{d}{d}{d}{d}{d}{d}{d}{d}{d}{d}"

[[d]]
value = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"#;
    // The recursive parser processes variable expansion in a way that increments depth
    // because it uses recursion implicitly. Wait, we explicitly modified depth computation.
    // But maybe we need a larger expansion without depth issues.
    // Let's construct a direct huge replace block so we know it definitely expands over 256K bytes in a single shot.
    let mut extremely_long_template = String::new();
    // Since `MAX_TEMPLATE_LENGTH` is 262,144 bytes, generating a string of exactly
    // 300_000 bytes with no variables should be sufficient to trigger it without
    // recursion errors getting in the way.
    for _ in 0..300_000 {
        extremely_long_template.push_str("X");
    }

    let toml_mod = toml.replace(
        "template = \"{a}\"",
        &format!("template = \"{}\"", extremely_long_template),
    );

    let result = db.load_toml(&toml_mod);
    assert!(result.is_err(), "Length over memory limit should fail");
    let err = result.unwrap_err();
    let err_str = err.to_string();
    assert!(
        err_str.contains("prevent exponential variable growth")
            || err_str.contains("exceeding the limit"),
        "Error message should mention length bounds: {err_str}"
    );
}