wafrift-strategy 0.3.1

Evasion strategy pipeline — orchestrates all WAF Rift modules into a coherent evasion flow.
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
#[cfg(test)]
#[allow(clippy::module_inception)]
mod tests {
    use crate::strategy::{
        CalibrationResult, EscalationLevel, EvasionConfig, EvasionPlan, HostState,
        analyze_calibration, evade, evade_adaptive,
    };
    use wafrift_types::{Request, Technique};

    // ============================================
    // Basic Evasion Tests (1-10)
    // ============================================

    #[test]
    fn no_evasion_on_clean_state() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let state = HostState::default();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        // Fingerprint rotation still happens by default
        assert!(
            result
                .techniques
                .iter()
                .all(|t| matches!(t, Technique::UserAgentRotation)),
            "only fingerprint rotation on clean state"
        );
    }

    #[test]
    fn light_evasion_after_blocks() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        state.record_block();
        state.record_block();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::PayloadEncoding(_)))
        );
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::HeaderObfuscation(_)))
        );
    }

    #[test]
    fn medium_evasion_content_type_switch() {
        let req = Request::post("https://example.com", b"q=test&a=value".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..4 {
            state.record_block();
        }
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::ContentTypeSwitch(_)))
        );
    }

    #[test]
    fn medium_evasion_applies_grammar() {
        let req = Request::post("https://example.com", b"q=' OR 1=1--".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..4 {
            state.record_block();
        }
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::GrammarMutation(_)))
        );
    }

    #[test]
    fn heavy_evasion_after_many_blocks() {
        let _req = Request::post("https://example.com", b"q=test".to_vec());
        let mut state = HostState::default();
        for _ in 0..10 {
            state.record_block();
        }
        assert_eq!(state.escalation_level(), EscalationLevel::Heavy);
    }

    #[test]
    fn fingerprint_rotation_adds_ua() {
        let req = Request::get("https://example.com");
        let state = HostState::default();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(result.request.get_header("User-Agent").is_some());
    }

    #[test]
    fn no_fingerprint_when_disabled() {
        let req = Request::get("https://example.com");
        let state = HostState::default();
        let config = EvasionConfig {
            fingerprint_rotation: false,
            ..EvasionConfig::default()
        };
        let result = evade(&req, &state, &config);
        assert!(
            !result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::UserAgentRotation))
        );
    }

    #[test]
    fn calibration_403_is_waf() {
        assert_eq!(
            analyze_calibration(403, b"Forbidden"),
            CalibrationResult::WafPresent
        );
    }

    #[test]
    fn calibration_redirect_is_uncertain() {
        assert_eq!(
            analyze_calibration(301, b"Moved"),
            CalibrationResult::Uncertain
        );
    }

    #[test]
    fn calibration_200_clean_is_no_waf() {
        assert_eq!(analyze_calibration(200, b"OK"), CalibrationResult::NoWaf);
    }

    // ============================================
    // Configuration Tests (11-20)
    // ============================================

    #[test]
    fn strategy_record_success_same_technique() {
        let mut state = HostState::default();
        state.record_success(Technique::PayloadEncoding("DoubleUrlEncode".into()));
        state.record_success(Technique::PayloadEncoding("DoubleUrlEncode".into()));
        assert_eq!(state.successes, 2);
    }

    #[test]
    fn header_obfuscation_disabled() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        state.record_block();
        let config = EvasionConfig {
            header_obfuscation: false,
            ..EvasionConfig::default()
        };
        let result = evade(&req, &state, &config);
        assert!(
            !result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::HeaderObfuscation(_)))
        );
    }

    #[test]
    fn grammar_disabled() {
        let req = Request::post("https://example.com", b"q=' OR 1=1--".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..4 {
            state.record_block();
        }
        let config = EvasionConfig {
            grammar_mutations: false,
            ..EvasionConfig::default()
        };
        let result = evade(&req, &state, &config);
        assert!(
            !result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::GrammarMutation(_)))
        );
    }

    #[test]
    fn encoding_disabled() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        state.record_block();
        let config = EvasionConfig {
            encoding_enabled: false,
            ..EvasionConfig::default()
        };
        let result = evade(&req, &state, &config);
        assert!(
            !result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::PayloadEncoding(_)))
        );
    }

    #[test]
    fn content_type_switching_disabled() {
        let req = Request::post("https://example.com", b"q=test&a=value".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..4 {
            state.record_block();
        }
        let config = EvasionConfig {
            content_type_switching: false,
            ..EvasionConfig::default()
        };
        let result = evade(&req, &state, &config);
        assert!(
            !result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::ContentTypeSwitch(_)))
        );
    }

    // ============================================
    // Adaptive Evasion Tests (21-30)
    // ============================================

    #[test]
    fn evade_adaptive_basic() {
        let req = Request::post("https://example.com", b"q=test".to_vec());
        let config = EvasionConfig::default();
        let plan = EvasionPlan::default();
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        // Should still apply fingerprint rotation
        assert!(result.request.get_header("User-Agent").is_some());
    }

    #[test]
    fn evade_adaptive_no_fingerprint() {
        let req = Request::post("https://example.com", b"q=test".to_vec());
        let config = EvasionConfig {
            fingerprint_rotation: false,
            ..EvasionConfig::default()
        };
        let plan = EvasionPlan::default();
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        assert!(
            !result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::UserAgentRotation))
        );
    }

    #[test]
    fn evade_adaptive_with_grammar() {
        let req = Request::post("https://example.com", b"q=' OR 1=1".to_vec());
        let config = EvasionConfig::default();
        let plan = EvasionPlan {
            use_grammar: true,
            ..EvasionPlan::default()
        };
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::GrammarMutation(_)))
        );
    }

    #[test]
    fn evade_adaptive_with_header_obfuscation() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let config = EvasionConfig::default();
        let plan = EvasionPlan {
            use_header_obfuscation: true,
            ..EvasionPlan::default()
        };
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::HeaderObfuscation(_)))
        );
    }

    #[test]
    fn evade_adaptive_with_smuggling() {
        let req = Request::post("https://example.com", b"q=test".to_vec());
        let config = EvasionConfig::default();
        let plan = EvasionPlan {
            use_smuggling: true,
            ..EvasionPlan::default()
        };
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::RequestSmuggling(_)))
        );
    }

    #[test]
    fn evade_adaptive_with_h2() {
        let req = Request::post("https://example.com", b"q=test".to_vec());
        let config = EvasionConfig::default();
        let plan = EvasionPlan {
            use_h2: true,
            ..EvasionPlan::default()
        };
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::H2Evasion(_)))
        );
    }

    /// B-3 wiring regression: when `plan.context = None` (the default),
    /// `evade_adaptive` uses the plain encoder, NOT the contextual one
    /// — preserves pre-wiring behaviour (LAW 2 backwards compat).
    #[test]
    fn evade_adaptive_no_context_uses_plain_encoder() {
        use wafrift_encoding::encoding::Strategy;
        let req = Request::post("https://example.com", br#"q="abc""#.to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let config = EvasionConfig::default();
        let plan = EvasionPlan {
            encoding_strategies: vec![Strategy::CaseAlternation],
            context: None,
            ..EvasionPlan::default()
        };
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        // Pre-fix and post-fix this call path is identical when context=None.
        // We assert the result is non-empty and contains the encoding technique.
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::PayloadEncoding(_)))
        );
        // No JSON-string escaping applied — the raw `"` is still present.
        let body = result.request.body.as_deref().unwrap_or(&[]);
        assert!(
            body.contains(&b'"'),
            "context=None: plain encoder must NOT JSON-escape the quote"
        );
    }

    /// B-3 wiring: when `plan.context = Some(JsonString)`,
    /// `evade_adaptive` uses the contextual encoder which JSON-escapes
    /// the encoded output so the resulting bytes are legal inside a
    /// JSON string. The literal `"` becomes `\"`.
    #[test]
    fn evade_adaptive_json_string_context_applies_escaping() {
        use wafrift_encoding::encoding::Strategy;
        use wafrift_types::injection_context::InjectionContext;
        let req = Request::post("https://example.com", br#"q="abc""#.to_vec())
            .header("Content-Type", "application/json");
        let config = EvasionConfig::default();
        let plan = EvasionPlan {
            encoding_strategies: vec![Strategy::CaseAlternation],
            context: Some(InjectionContext::JsonString),
            ..EvasionPlan::default()
        };
        let result = evade_adaptive(&req, &config, &plan, &HostState::default());
        let body = result.request.body.as_deref().unwrap_or(&[]);
        // The contextual encoder must have escaped the literal quote.
        let body_str = std::str::from_utf8(body).expect("body is utf8");
        assert!(
            body_str.contains("\\\""),
            "context=JsonString: contextual encoder must JSON-escape `\"` to `\\\"`, got: {body_str:?}"
        );
    }

    // ============================================
    // Heavy Escalation Tests (31-40)
    // ============================================

    #[test]
    fn heavy_evasion_applies_smuggling_metadata() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..10 {
            state.record_block();
        }
        assert_eq!(state.escalation_level(), EscalationLevel::Heavy);
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::RequestSmuggling(_)))
        );
    }

    #[test]
    fn heavy_evasion_applies_h2_metadata() {
        let req = Request::post("https://example.com", b"q=test".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..10 {
            state.record_block();
        }
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::H2Evasion(_)))
        );
    }

    #[test]
    fn heavy_evasion_applies_grammar() {
        let req = Request::post("https://example.com", b"q=' OR 1=1--".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..10 {
            state.record_block();
        }
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(
            result
                .techniques
                .iter()
                .any(|t| matches!(t, Technique::GrammarMutation(_)))
        );
    }

    #[test]
    fn heavy_evasion_multiple_techniques() {
        let req = Request::post("https://example.com", b"q=test&foo=bar".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        let mut state = HostState::default();
        for _ in 0..10 {
            state.record_block();
        }
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        // Heavy evasion should apply multiple techniques
        assert!(
            result.techniques.len() >= 3,
            "Heavy evasion should apply at least 3 techniques, got {:?}",
            result.techniques
        );
    }

    #[test]
    fn evasion_result_has_description() {
        let req = Request::post("https://example.com", b"q=test".to_vec());
        let state = HostState::default();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(!result.description.is_empty());
    }

    // ============================================
    // Edge Case Tests (41-50)
    // ============================================

    #[test]
    fn get_request_no_body() {
        let req = Request::get("https://example.com/api");
        let state = HostState::default();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert_eq!(result.request.body, None);
    }

    #[test]
    fn put_request_with_body() {
        let req = Request::put("https://example.com/api", b"data=value".to_vec());
        let mut state = HostState::default();
        state.record_block();
        state.record_block();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert!(result.request.body.is_some());
    }

    #[test]
    fn delete_request_no_body() {
        let req = Request::delete("https://example.com/api/1");
        let mut state = HostState::default();
        state.record_block();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert_eq!(result.request.method.as_str(), "DELETE");
    }

    #[test]
    fn empty_body_request() {
        let req = Request::post("https://example.com", vec![]);
        let mut state = HostState::default();
        state.record_block();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        // Request should be processed correctly even with empty body
        assert_eq!(result.request.body, Some(vec![]));
        // Should have applied some light evasion
        assert!(!result.techniques.is_empty());
    }

    #[test]
    fn evasion_plan_default() {
        let plan = EvasionPlan::default();
        assert!(!plan.use_grammar);
        assert!(!plan.use_header_obfuscation);
        assert!(!plan.use_content_type_switch);
        assert!(!plan.use_smuggling);
        assert!(!plan.use_h2);
        assert!(plan.encoding_strategies.is_empty());
    }

    #[test]
    fn evasion_plan_with_strategies() {
        use wafrift_encoding::encoding::Strategy;
        let plan = EvasionPlan {
            encoding_strategies: vec![Strategy::DoubleUrlEncode, Strategy::UnicodeEncode],
            use_grammar: true,
            use_header_obfuscation: true,
            use_content_type_switch: true,
            use_smuggling: true,
            use_h2: true,
            rationale: vec!["test plan".into()],
            context: None,
        };
        assert_eq!(plan.encoding_strategies.len(), 2);
        assert!(plan.use_grammar);
        assert!(plan.use_header_obfuscation);
    }

    #[test]
    fn calibration_503_service_unavailable() {
        assert_eq!(
            analyze_calibration(503, b"Service Unavailable"),
            CalibrationResult::WafPresent
        );
    }

    #[test]
    fn calibration_429_rate_limit() {
        assert_eq!(
            analyze_calibration(429, b"Too Many Requests"),
            CalibrationResult::WafPresent
        );
    }

    #[test]
    fn evasion_preserves_url() {
        let url = "https://example.com/path?query=value";
        let req = Request::get(url);
        let state = HostState::default();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert_eq!(result.request.url, url);
    }

    #[test]
    fn evasion_preserves_method() {
        let req = Request::put("https://example.com/api", b"data".to_vec());
        let state = HostState::default();
        let config = EvasionConfig::default();
        let result = evade(&req, &state, &config);
        assert_eq!(result.request.method.as_str(), "PUT");
    }

    #[test]
    fn winner_pick_varies_with_request_url() {
        // F146 regression: pre-fix `current_winner` used
        // `state.rotation_index % state.proven_winners.len()` but `evade`
        // gets a CLONED &HostState that is dropped after each call —
        // `rotation_index` is never advanced from the transport path, so
        // every request picked `proven_winners[0]` and the round-robin
        // claim was a lie. Post-fix the pick hashes (URL + method), so
        // distinct requests rotate across the winner pool naturally
        // even when state is immutable.
        //
        // Use POST with bodies so the encoding techniques actually fire
        // (apply_encoding skips bodyless requests, which would mask the
        // bug).
        let mut state = HostState {
            proven_winners: vec![
                "encoding:UrlEncode".to_string(),
                "encoding:DoubleUrlEncode".to_string(),
                "encoding:Base64Encode".to_string(),
                "encoding:HexEncode".to_string(),
            ],
            ..Default::default()
        };
        state.discovery_complete = true;
        let config = EvasionConfig::default();

        let mut seen_techniques = std::collections::HashSet::new();
        for url in [
            "https://target/api/users",
            "https://target/api/posts",
            "https://target/api/login",
            "https://target/api/admin",
            "https://target/health",
            "https://target/search",
            "https://target/v1/data",
            "https://target/v2/data",
        ] {
            let req = Request::post(url, b"q=admin' OR 1=1--".to_vec());
            let result = evade(&req, &state, &config);
            // Extract just the PayloadEncoding entries (fingerprint
            // techniques aren't gated on URL so they'd add noise).
            let encoding_techs: Vec<String> = result
                .techniques
                .iter()
                .filter_map(|t| match t {
                    Technique::PayloadEncoding(name) => Some(name.clone()),
                    _ => None,
                })
                .collect();
            seen_techniques.insert(format!("{encoding_techs:?}"));
        }
        assert!(
            seen_techniques.len() >= 2,
            "winner pick must vary across distinct URLs (pre-fix every URL got encoding:UrlEncode); saw only {} distinct encoding choices: {seen_techniques:?}",
            seen_techniques.len()
        );
    }

    #[test]
    fn winner_pick_is_deterministic_per_url() {
        // Same URL -> same winner -> same evasion. Replay safety.
        let mut state = HostState {
            proven_winners: vec![
                "encoding:UrlEncode".to_string(),
                "encoding:DoubleUrlEncode".to_string(),
                "encoding:HexEncode".to_string(),
            ],
            ..Default::default()
        };
        state.discovery_complete = true;
        let config = EvasionConfig::default();
        let req = Request::post("https://target/api/x", b"q=admin' OR 1=1--".to_vec());
        let a = evade(&req, &state, &config);
        let b = evade(&req, &state, &config);
        let a_enc: Vec<&Technique> = a
            .techniques
            .iter()
            .filter(|t| matches!(t, Technique::PayloadEncoding(_)))
            .collect();
        let b_enc: Vec<&Technique> = b
            .techniques
            .iter()
            .filter(|t| matches!(t, Technique::PayloadEncoding(_)))
            .collect();
        assert_eq!(
            format!("{a_enc:?}"),
            format!("{b_enc:?}"),
            "same URL must pick the same winner deterministically"
        );
    }

    // ============================================
    // GraphQL routing tests (61-67)
    // ============================================

    #[test]
    fn is_graphql_request_detects_application_graphql_content_type() {
        use crate::strategy::is_graphql_request;
        let req = Request::post(
            "https://example.com/graphql",
            b"{ user { id name } }".to_vec(),
        )
        .header("Content-Type", "application/graphql");
        assert!(
            is_graphql_request(&req),
            "application/graphql Content-Type must be detected as GraphQL"
        );
    }

    #[test]
    fn is_graphql_request_detects_json_body_with_query_key() {
        use crate::strategy::is_graphql_request;
        let body = br#"{"query":"{ user { id name } }","variables":{}}"#;
        let req = Request::post("https://example.com/graphql", body.to_vec())
            .header("Content-Type", "application/json");
        assert!(
            is_graphql_request(&req),
            "JSON body containing \"query\": key must be detected as GraphQL"
        );
    }

    #[test]
    fn is_graphql_request_rejects_plain_form_body() {
        use crate::strategy::is_graphql_request;
        let req = Request::post("https://example.com/api", b"q=SELECT+1+FROM+users".to_vec())
            .header("Content-Type", "application/x-www-form-urlencoded");
        assert!(
            !is_graphql_request(&req),
            "form-urlencoded body must NOT be detected as GraphQL"
        );
    }

    #[test]
    fn is_graphql_request_rejects_get_without_body() {
        use crate::strategy::is_graphql_request;
        let req = Request::get("https://example.com/graphql?query={__typename}");
        assert!(
            !is_graphql_request(&req),
            "GET without body must not be detected as GraphQL"
        );
    }

    #[test]
    fn graphql_payloads_for_request_returns_battery_for_graphql_request() {
        use crate::strategy::{graphql_payloads_for_request, is_graphql_request};
        let body = br#"{"query":"{ __typename }"}"#;
        let req = Request::post("https://example.com/graphql", body.to_vec())
            .header("Content-Type", "application/json");
        assert!(is_graphql_request(&req));
        let payloads = graphql_payloads_for_request(&req);
        assert!(
            !payloads.is_empty(),
            "graphql_payloads_for_request must return the full battery for a GraphQL request"
        );
        // Verify all three core classes are present.
        let has_alias = payloads.iter().any(|p| p.contains("AliasFlood"));
        let has_intro = payloads.iter().any(|p| p.contains("__schema"));
        let has_mismatch = payloads.iter().any(|p| p.contains("operationName"));
        assert!(has_alias, "alias-flood payloads missing from battery");
        assert!(has_intro, "introspection payloads missing from battery");
        assert!(
            has_mismatch,
            "op-name-mismatch payloads missing from battery"
        );
    }

    #[test]
    fn graphql_payloads_for_request_empty_for_non_graphql() {
        use crate::strategy::graphql_payloads_for_request;
        let req = Request::get("https://example.com/api?q=test");
        let payloads = graphql_payloads_for_request(&req);
        assert!(
            payloads.is_empty(),
            "graphql_payloads_for_request must return empty Vec for non-GraphQL requests"
        );
    }

    #[test]
    fn content_type_routing_application_graphql_returns_battery() {
        use crate::strategy::graphql_payloads_for_request;
        let req = Request::post(
            "https://api.example.com/graphql",
            b"query { viewer { login } }".to_vec(),
        )
        .header("Content-Type", "application/graphql");
        let payloads = graphql_payloads_for_request(&req);
        assert!(
            !payloads.is_empty(),
            "application/graphql Content-Type must route to GraphQL battery"
        );
        assert!(
            payloads.len() >= 10,
            "GraphQL battery must have at least 10 payloads, got {}",
            payloads.len()
        );
    }

    // ── is_text_payload panic-safety tests ───────────────────────────────────
    // Pins the fix that replaced `.expect("body exists")` with `let Some(body)`.
    // LAW 1: the function must never panic; it must return false for any input
    // that lacks a body.

    #[test]
    fn is_text_payload_returns_false_for_bodyless_get() {
        use crate::strategy::is_text_payload;
        // GET with no body — is_text_payload must return false, not panic.
        let req = Request::get("https://example.com/api?q=test");
        assert!(req.body.is_none(), "precondition: GET has no body");
        assert!(
            !is_text_payload(&req),
            "bodyless request must not be text payload"
        );
    }

    #[test]
    fn is_text_payload_returns_false_for_delete_no_body() {
        use crate::strategy::is_text_payload;
        let req = Request::delete("https://example.com/resource/1");
        assert!(!is_text_payload(&req), "bodyless DELETE must return false");
    }

    #[test]
    fn is_text_payload_returns_true_for_valid_utf8_body_no_content_type() {
        use crate::strategy::is_text_payload;
        // POST with no Content-Type — falls through to UTF-8 check.
        let req = Request::post("https://example.com/api", b"hello world".to_vec());
        assert!(
            req.headers
                .iter()
                .all(|(k, _)| !k.eq_ignore_ascii_case("content-type")),
            "precondition: no content-type header"
        );
        assert!(
            is_text_payload(&req),
            "valid UTF-8 body with no CT header must be text payload"
        );
    }

    #[test]
    fn is_text_payload_returns_false_for_binary_body_no_content_type() {
        use crate::strategy::is_text_payload;
        // POST with no Content-Type and a non-UTF-8 body.
        let req = Request::post("https://example.com/api", vec![0xFE, 0xFF, 0x00, 0x01]);
        assert!(
            !is_text_payload(&req),
            "non-UTF-8 body with no CT header must NOT be text payload"
        );
    }
}