garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! WAF Hook 实现(9 个内置 Hook),每个 Hook 实现 `WafHook` trait,经 `WafHookChain` 按注册顺序执行。
//!
//! 9 个 Hook(name):`WhitePathHook`(white_path,路径前缀白名单,匹配返回 AllowAndSkip)、`BlackPathHook`(black_path,路径前缀黑名单)、
//! `DangerCharacterHook`(danger_char,危险字符 `//` / `\` / `%2e` / `%00` 等,校验 path/param/header 值)、
//! `BannedCharacterHook`(banned_char,不可打印 ASCII)、`DirectoryTraversalHook`(dir_traversal,`./` / `../` / `//`)、
//! `HostHook`(host,Host 头白名单)、`HttpMethodHook`(http_method)、`HeaderHook`(header)、`ParameterHook`(parameter)。

use super::waf::{WafContext, WafHook, WafVerdict};
use crate::i18n::translate_detail;
use async_trait::async_trait;

// 1. WhitePathHook — 路径前缀白名单

/// 路径前缀白名单 Hook:匹配时返回 `AllowAndSkip`(放行并跳过后续 Hook),不匹配返回 `Allow`(继续后续 Hook)。
///
/// # 注册顺序约束
///
/// **警告**:本 Hook 必须注册在所有安全关键 Hook(如 `DirectoryTraversalHook` / `DangerCharacterHook`)**之后**——
/// 若注册在安全 Hook 之前,白名单匹配会短路跳过安全校验,导致 `/api/../admin` 等路径遍历攻击绕过。为兜底,本 Hook 在匹配白名单前
/// 先检查 path 是否含可疑模式(`..` 或 `//`),含可疑模式则不短路、返回 `Allow` 交给后续安全 Hook;但这只是兜底,正确的注册顺序仍是强约束。
pub struct WhitePathHook {
    paths: Vec<String>,
}

impl WhitePathHook {
    /// 创建白名单 Hook,传入允许的路径前缀列表(匹配任一前缀时返回 `AllowAndSkip`,短路后续 Hook;注册顺序约束见类型文档)。
    pub fn new(paths: Vec<String>) -> Self {
        Self { paths }
    }
}

/// 精确路径段匹配:`path == prefix` 或 `path` 以 `prefix/` 开头,避免 `starts_with` 的前缀混淆(如 `/api` 误匹配 `/api-v2/secret`)。
fn path_matches(prefix: &str, path: &str) -> bool {
    path == prefix || path.starts_with(&format!("{}/", prefix))
}

#[async_trait]
impl WafHook for WhitePathHook {
    fn name(&self) -> &'static str {
        "white_path"
    }

    /// 校验请求上下文:匹配白名单前先检查 path 是否含可疑模式(字面量 `..` / `//`、URL 编码 `%2e` / `%2f` / `%5c` 及双重编码标志 `%25`),
    /// 含可疑模式则返回 `Allow`(不短路)交给后续安全 Hook;注册顺序约束见类型文档。
    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        // 安全兜底:含可疑模式(字面量或 URL 编码,含双重编码标志 %25)时不短路,返回 Allow 交给后续安全 Hook 处理,
        // 防止 `/api/../admin` 或 `/api/%2e%2e/admin` 通过 `starts_with("/api")` 绕过安全 Hook。
        let lower = ctx.path.to_lowercase();
        if lower.contains("..")
            || lower.contains("//")
            || lower.contains("%2e")
            || lower.contains("%2f")
            || lower.contains("%5c")
            || lower.contains("%25")
        {
            return WafVerdict::Allow;
        }
        if self.paths.iter().any(|p| path_matches(p, ctx.path)) {
            return WafVerdict::AllowAndSkip;
        }
        WafVerdict::Allow
    }
}

// 2. BlackPathHook — 路径前缀黑名单

/// 路径前缀黑名单 Hook:匹配任一黑名单前缀时返回 Deny,否则 Allow;空列表始终 Allow。
pub struct BlackPathHook {
    paths: Vec<String>,
}

impl BlackPathHook {
    /// 创建黑名单 Hook,传入禁止的路径前缀列表。
    pub fn new(paths: Vec<String>) -> Self {
        Self { paths }
    }
}

#[async_trait]
impl WafHook for BlackPathHook {
    fn name(&self) -> &'static str {
        "black_path"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        if self.paths.is_empty() {
            return WafVerdict::Allow;
        }
        if self.paths.iter().any(|p| ctx.path.starts_with(p)) {
            return WafVerdict::Deny {
                reason: format!("waf-blacklist-path::{}", ctx.path),
                hook: "black_path",
            };
        }
        WafVerdict::Allow
    }
}

// 3. DangerCharacterHook — 危险字符检测

/// 危险字符检测 Hook:检测 path、参数值、请求头值中的危险字符 `//` / `\` / `;` / `\0` / `\n` / `\r`,
/// 以及百分号编码 `%2e` / `%2f` / `%00` / `%5c` / `%3b` / `%0a` / `%0d`(大小写不敏感)。
pub struct DangerCharacterHook;

impl DangerCharacterHook {
    /// 创建危险字符检测 Hook。
    pub fn new() -> Self {
        Self
    }
}

impl Default for DangerCharacterHook {
    fn default() -> Self {
        Self::new()
    }
}

/// 检测字符串中的危险字符,返回对应的 i18n pattern ID;所有模式均大小写不敏感,统一在 `lower`(小写形式)中检测
/// (非编码模式为符号和控制字符无大小写之分,百分号编码模式经小写形式统一匹配)。
fn check_danger_chars(lower: &str) -> Option<&'static str> {
    // (pattern, i18n_pattern_id) — 所有模式均大小写不敏感,统一用 lower.contains(pattern) 检测
    const PATTERNS: &[(&str, &str)] = &[
        ("//", "double-slash"),
        ("\\", "backslash"),
        (";", "semicolon"),
        ("\0", "null-byte"),
        ("\n", "newline"),
        ("\r", "carriage-return"),
        ("%2e", "pct-2e"),
        ("%2f", "pct-2f"),
        ("%00", "pct-00"),
        ("%5c", "pct-5c"),
        ("%3b", "pct-3b"),
        ("%0a", "pct-0a"),
        ("%0d", "pct-0d"),
    ];
    for &(pattern, id) in PATTERNS {
        if lower.contains(pattern) {
            return Some(id);
        }
    }
    // 双重/多重编码检测:迭代将 %25 解码为 % 后重新校验(单次 replace 对三重及以上编码失效:%25252e → %252e 仍无 %2e 子串),
    // 循环解码直到不再含 %25(上限 5 轮,防恶意超长编码链拖垮检测),覆盖 %252e(双重)、%25252e(三重)、%2525252e(四重)等绕过。
    if lower.contains("%25") {
        let mut decoded = lower.to_string();
        const MAX_DECODE_ROUNDS: usize = 5;
        let mut rounds = 0;
        while decoded.contains("%25") && rounds < MAX_DECODE_ROUNDS {
            decoded = decoded.replace("%25", "%");
            rounds += 1;
        }
        for &(pattern, id) in PATTERNS {
            if decoded.contains(pattern) {
                return Some(id);
            }
        }
    }
    None
}

/// 将危险字符 pattern ID 翻译为当前 locale 的描述字符串。
fn danger_char_i18n(pattern_id: &str) -> String {
    let key = match pattern_id {
        "double-slash" => "waf-danger-desc-double-slash",
        "backslash" => "waf-danger-desc-backslash",
        "semicolon" => "waf-danger-desc-semicolon",
        "null-byte" => "waf-danger-desc-null-byte",
        "newline" => "waf-danger-desc-newline",
        "carriage-return" => "waf-danger-desc-carriage-return",
        "pct-2e" => "waf-danger-desc-pct-2e",
        "pct-2f" => "waf-danger-desc-pct-2f",
        "pct-00" => "waf-danger-desc-pct-00",
        "pct-5c" => "waf-danger-desc-pct-5c",
        "pct-3b" => "waf-danger-desc-pct-3b",
        "pct-0a" => "waf-danger-desc-pct-0a",
        "pct-0d" => "waf-danger-desc-pct-0d",
        _ => pattern_id,
    };
    translate_detail(key, &[])
}

#[async_trait]
impl WafHook for DangerCharacterHook {
    fn name(&self) -> &'static str {
        "danger_char"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        let path = ctx.path;
        let lower = path.to_lowercase();
        if let Some(desc_id) = check_danger_chars(&lower) {
            let desc = danger_char_i18n(desc_id);
            let combined = format!("{}: {}", ctx.path, desc);
            return WafVerdict::Deny {
                reason: format!("waf-danger-char-path::{}", combined),
                hook: "danger_char",
            };
        }
        for (_, value) in ctx.params {
            let lower = value.to_lowercase();
            if let Some(desc_id) = check_danger_chars(&lower) {
                let desc = danger_char_i18n(desc_id);
                let combined = format!("{}: {}", value, desc);
                return WafVerdict::Deny {
                    reason: format!("waf-danger-char-param::{}", combined),
                    hook: "danger_char",
                };
            }
        }
        for (_, value) in ctx.headers {
            let lower = value.to_lowercase();
            if let Some(desc_id) = check_danger_chars(&lower) {
                let desc = danger_char_i18n(desc_id);
                let combined = format!("{}: {}", value, desc);
                return WafVerdict::Deny {
                    reason: format!("waf-danger-char-header::{}", combined),
                    hook: "danger_char",
                };
            }
        }
        WafVerdict::Allow
    }
}

// 4. BannedCharacterHook — 不可打印 ASCII 字符检测

/// 不可打印 ASCII 字符检测 Hook:检测 path 中的不可打印字符(ASCII < 0x20 或 > 0x7E)。
pub struct BannedCharacterHook;

impl BannedCharacterHook {
    /// 创建不可打印字符检测 Hook。
    pub fn new() -> Self {
        Self
    }
}

impl Default for BannedCharacterHook {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl WafHook for BannedCharacterHook {
    fn name(&self) -> &'static str {
        "banned_char"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        for &b in ctx.path.as_bytes() {
            if !(0x20..=0x7E).contains(&b) {
                return WafVerdict::Deny {
                    reason: format!("waf-banned-char::(0x{:02X})", b),
                    hook: "banned_char",
                };
            }
        }
        WafVerdict::Allow
    }
}

// 5. DirectoryTraversalHook — 目录遍历检测

/// 目录遍历检测 Hook:检测 path 中的目录遍历模式 `./` / `../` / `//`。
pub struct DirectoryTraversalHook;

impl DirectoryTraversalHook {
    /// 创建目录遍历检测 Hook。
    pub fn new() -> Self {
        Self
    }
}

impl Default for DirectoryTraversalHook {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl WafHook for DirectoryTraversalHook {
    fn name(&self) -> &'static str {
        "dir_traversal"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        const PATTERNS: &[&str] = &["../", "./", "//"];
        for &pattern in PATTERNS {
            if ctx.path.contains(pattern) {
                return WafVerdict::Deny {
                    reason: format!("waf-dir-traversal::{}", pattern),
                    hook: "dir_traversal",
                };
            }
        }
        WafVerdict::Allow
    }
}

// 6. HostHook — Host 头白名单

/// Host 头白名单 Hook:空列表始终 Allow;非空时 Host 头必须在白名单中,无 Host 头时 **Deny**(fail-closed)——
/// 白名单非空却缺失 Host 头的请求若放行将完全绕过 Host 白名单校验(虚拟主机隔离场景下可被利用)。
pub struct HostHook {
    hosts: Vec<String>,
}

impl HostHook {
    /// 创建 Host 白名单 Hook,传入允许的 Host 列表。
    pub fn new(hosts: Vec<String>) -> Self {
        Self { hosts }
    }
}

#[async_trait]
impl WafHook for HostHook {
    fn name(&self) -> &'static str {
        "host"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        if self.hosts.is_empty() {
            return WafVerdict::Allow;
        }
        match ctx.host {
            // fail-closed:白名单非空时缺失 Host 头视为不匹配(防止绕过白名单)
            None => WafVerdict::Deny {
                reason: "waf-host-missing::".to_string(),
                hook: "host",
            },
            Some(host) => {
                if self.hosts.iter().any(|h| h == host) {
                    WafVerdict::Allow
                } else {
                    WafVerdict::Deny {
                        reason: format!("waf-host-not-allowed::{}", host),
                        hook: "host",
                    }
                }
            },
        }
    }
}

// 7. HttpMethodHook — HTTP 方法白名单

/// HTTP 方法白名单 Hook:空列表始终 Allow;非空时方法必须在列表中(大小写敏感,RFC 7230)。
pub struct HttpMethodHook {
    methods: Vec<String>,
}

impl HttpMethodHook {
    /// 创建 HTTP 方法白名单 Hook,传入允许的方法列表。
    pub fn new(methods: Vec<String>) -> Self {
        Self { methods }
    }
}

#[async_trait]
impl WafHook for HttpMethodHook {
    fn name(&self) -> &'static str {
        "http_method"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        if self.methods.is_empty() {
            return WafVerdict::Allow;
        }
        if self.methods.iter().any(|m| m == ctx.method) {
            WafVerdict::Allow
        } else {
            WafVerdict::Deny {
                reason: format!("waf-method-not-allowed::{}", ctx.method),
                hook: "http_method",
            }
        }
    }
}

// 8. HeaderHook — 禁止请求头黑名单

/// 禁止请求头黑名单 Hook:空列表始终 Allow;非空时请求头中含黑名单 header 则 Deny(header 名称比较大小写不敏感)。
pub struct HeaderHook {
    headers: Vec<String>,
}

impl HeaderHook {
    /// 创建禁止 Header 黑名单 Hook,传入禁止的 header 名称列表。
    pub fn new(headers: Vec<String>) -> Self {
        Self { headers }
    }
}

#[async_trait]
impl WafHook for HeaderHook {
    fn name(&self) -> &'static str {
        "header"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        if self.headers.is_empty() {
            return WafVerdict::Allow;
        }
        for banned in &self.headers {
            let banned_lower = banned.to_lowercase();
            for (name, _) in ctx.headers {
                if name.to_lowercase() == banned_lower {
                    return WafVerdict::Deny {
                        reason: format!("waf-header-banned::{}", name),
                        hook: "header",
                    };
                }
            }
        }
        WafVerdict::Allow
    }
}

// 9. ParameterHook — 禁止参数黑名单

/// 禁止参数黑名单 Hook:空列表始终 Allow;非空时请求参数中含黑名单参数则 Deny。
pub struct ParameterHook {
    params: Vec<String>,
}

impl ParameterHook {
    /// 创建禁止参数黑名单 Hook,传入禁止的参数名称列表。
    pub fn new(params: Vec<String>) -> Self {
        Self { params }
    }
}

#[async_trait]
impl WafHook for ParameterHook {
    fn name(&self) -> &'static str {
        "parameter"
    }

    async fn check(&self, ctx: &WafContext<'_>) -> WafVerdict {
        if self.params.is_empty() {
            return WafVerdict::Allow;
        }
        for banned in &self.params {
            for (name, _) in ctx.params {
                if name == banned {
                    return WafVerdict::Deny {
                        reason: format!("waf-param-banned::{}", name),
                        hook: "parameter",
                    };
                }
            }
        }
        WafVerdict::Allow
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::strategy::firewall::WafHookChain;
    use std::sync::{Arc, Mutex};

    /// 记录执行顺序的 Mock Hook(用于验证链短路行为)。
    struct RecordingHook {
        hook_name: &'static str,
        log: Arc<Mutex<Vec<&'static str>>>,
    }

    #[async_trait]
    impl WafHook for RecordingHook {
        fn name(&self) -> &'static str {
            self.hook_name
        }
        async fn check(&self, _ctx: &WafContext<'_>) -> WafVerdict {
            self.log.lock().unwrap().push(self.hook_name);
            WafVerdict::Allow
        }
    }

    /// 构造测试用 WafContext。
    fn make_ctx<'a>(
        path: &'a str,
        method: &'a str,
        host: Option<&'a str>,
        headers: &'a [(String, String)],
        params: &'a [(String, String)],
    ) -> WafContext<'a> {
        WafContext {
            path,
            method,
            host,
            headers,
            params,
        }
    }

    /// 默认上下文(/api/test, GET, example.com, 无 headers/params)。
    fn default_ctx<'a>() -> WafContext<'a> {
        make_ctx("/api/test", "GET", Some("example.com"), &[], &[])
    }

    // 1. WhitePathHook 测试

    /// 验证匹配白名单路径返回 AllowAndSkip。
    #[tokio::test]
    async fn white_path_match_returns_allow_and_skip() {
        let hook = WhitePathHook::new(vec!["/api".to_string()]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::AllowAndSkip));
    }

    /// 验证不匹配白名单路径也返回 Allow。
    #[tokio::test]
    async fn white_path_no_match_returns_allow() {
        let hook = WhitePathHook::new(vec!["/admin".to_string()]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证空白名单返回 Allow。
    #[tokio::test]
    async fn white_path_empty_returns_allow() {
        let hook = WhitePathHook::new(vec![]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 2. BlackPathHook 测试

    /// 验证匹配黑名单路径返回 Deny。
    #[tokio::test]
    async fn black_path_match_returns_deny() {
        let hook = BlackPathHook::new(vec!["/admin".to_string()]);
        let ctx = make_ctx("/admin/secret", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证不匹配黑名单路径返回 Allow。
    #[tokio::test]
    async fn black_path_no_match_returns_allow() {
        let hook = BlackPathHook::new(vec!["/admin".to_string()]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证空黑名单返回 Allow。
    #[tokio::test]
    async fn black_path_empty_returns_allow() {
        let hook = BlackPathHook::new(vec![]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 3. DangerCharacterHook 测试

    /// 验证含 `//` 返回 Deny。
    #[tokio::test]
    async fn danger_char_double_slash_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api//test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证含 `\` 返回 Deny。
    #[tokio::test]
    async fn danger_char_backslash_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api\\test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证正常路径返回 Allow。
    #[tokio::test]
    async fn danger_char_normal_path_returns_allow() {
        let hook = DangerCharacterHook::new();
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 4. BannedCharacterHook 测试

    /// 验证含不可打印字符返回 Deny。
    #[tokio::test]
    async fn banned_char_non_printable_returns_deny() {
        let hook = BannedCharacterHook::new();
        // 0x01 (SOH) 是不可打印字符
        let ctx = make_ctx("/api\x01test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证正常路径返回 Allow。
    #[tokio::test]
    async fn banned_char_normal_path_returns_allow() {
        let hook = BannedCharacterHook::new();
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 5. DirectoryTraversalHook 测试

    /// 验证含 `../` 返回 Deny。
    #[tokio::test]
    async fn dir_traversal_dot_dot_slash_returns_deny() {
        let hook = DirectoryTraversalHook::new();
        let ctx = make_ctx("/api/../etc/passwd", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证含 `./` 返回 Deny。
    #[tokio::test]
    async fn dir_traversal_dot_slash_returns_deny() {
        let hook = DirectoryTraversalHook::new();
        let ctx = make_ctx("/api/./test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证正常路径返回 Allow。
    #[tokio::test]
    async fn dir_traversal_normal_path_returns_allow() {
        let hook = DirectoryTraversalHook::new();
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 6. HostHook 测试

    /// 验证 Host 不在白名单返回 Deny。
    #[tokio::test]
    async fn host_not_in_whitelist_returns_deny() {
        let hook = HostHook::new(vec!["allowed.com".to_string()]);
        let ctx = make_ctx("/api/test", "GET", Some("evil.com"), &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证 Host 在白名单返回 Allow。
    #[tokio::test]
    async fn host_in_whitelist_returns_allow() {
        let hook = HostHook::new(vec!["example.com".to_string()]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证白名单非空但无 Host 头时 Deny(fail-closed,防止绕过白名单)。
    #[tokio::test]
    async fn host_none_returns_deny_fail_closed() {
        let hook = HostHook::new(vec!["example.com".to_string()]);
        let ctx = make_ctx("/api/test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "白名单非空且无 Host 头应 Deny(fail-closed)"
        );
    }

    // 7. HttpMethodHook 测试

    /// 验证 Method 不在允许列表返回 Deny。
    #[tokio::test]
    async fn http_method_not_allowed_returns_deny() {
        let hook = HttpMethodHook::new(vec!["GET".to_string()]);
        let ctx = make_ctx("/api/test", "POST", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证 Method 在允许列表返回 Allow。
    #[tokio::test]
    async fn http_method_allowed_returns_allow() {
        let hook = HttpMethodHook::new(vec!["GET".to_string(), "POST".to_string()]);
        let ctx = default_ctx();
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 8. HeaderHook 测试

    /// 验证含黑名单 Header 返回 Deny。
    #[tokio::test]
    async fn header_banned_returns_deny() {
        let hook = HeaderHook::new(vec!["X-Forbidden".to_string()]);
        let headers = vec![("X-Forbidden".to_string(), "value".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证不含黑名单 Header 返回 Allow。
    #[tokio::test]
    async fn header_not_banned_returns_allow() {
        let hook = HeaderHook::new(vec!["X-Forbidden".to_string()]);
        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 9. ParameterHook 测试

    /// 验证含黑名单参数返回 Deny。
    #[tokio::test]
    async fn parameter_banned_returns_deny() {
        let hook = ParameterHook::new(vec!["password".to_string()]);
        let params = vec![("password".to_string(), "secret".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &[], &params);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Deny { .. }));
    }

    /// 验证不含黑名单参数返回 Allow。
    #[tokio::test]
    async fn parameter_not_banned_returns_allow() {
        let hook = ParameterHook::new(vec!["password".to_string()]);
        let params = vec![("username".to_string(), "admin".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &[], &params);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    // 10. WAF 绕过场景测试

    /// 验证 path 含 `%00` 编码返回 Deny。
    #[tokio::test]
    async fn danger_char_percent_00_encoded_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%00test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "path 含 %00 应被拦截"
        );
    }

    /// 验证 path 含 `%5c` 编码返回 Deny。
    #[tokio::test]
    async fn danger_char_percent_5c_encoded_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%5ctest", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "path 含 %5c 应被拦截"
        );
    }

    /// 验证 path 含 `%3b` 编码返回 Deny。
    #[tokio::test]
    async fn danger_char_percent_3b_encoded_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%3btest", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "path 含 %3b 应被拦截"
        );
    }

    /// 验证 path 含 `%0a` 编码返回 Deny。
    #[tokio::test]
    async fn danger_char_percent_0a_encoded_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%0atest", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "path 含 %0a 应被拦截"
        );
    }

    /// 验证 path 含 `%0d` 编码返回 Deny。
    #[tokio::test]
    async fn danger_char_percent_0d_encoded_returns_deny() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%0dtest", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "path 含 %0d 应被拦截"
        );
    }

    /// 验证大写百分号编码返回 Deny(大小写不敏感)。
    #[tokio::test]
    async fn danger_char_uppercase_percent_encoded_returns_deny() {
        let hook = DangerCharacterHook::new();
        // %2E(大写 %2e)
        let ctx = make_ctx("/api/%2Etest", "GET", None, &[], &[]);
        assert!(
            matches!(hook.check(&ctx).await, WafVerdict::Deny { .. }),
            "path 含 %2E 应被拦截"
        );
        // %2F(大写 %2f)
        let ctx = make_ctx("/api/%2Ftest", "GET", None, &[], &[]);
        assert!(
            matches!(hook.check(&ctx).await, WafVerdict::Deny { .. }),
            "path 含 %2F 应被拦截"
        );
        // %00(大写 %00)
        let ctx = make_ctx("/api/%00test", "GET", None, &[], &[]);
        assert!(
            matches!(hook.check(&ctx).await, WafVerdict::Deny { .. }),
            "path 含 %00 应被拦截"
        );
    }

    /// 验证 query 参数值含 `//` 返回 Deny。
    #[tokio::test]
    async fn danger_char_query_param_value_returns_deny() {
        let hook = DangerCharacterHook::new();
        let params = vec![("q".to_string(), "a//b".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &[], &params);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "参数值含 // 应被拦截"
        );
    }

    /// 验证 header 值含 `\` 返回 Deny。
    #[tokio::test]
    async fn danger_char_header_value_returns_deny() {
        let hook = DangerCharacterHook::new();
        let headers = vec![("X-Custom".to_string(), "a\\b".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "header 值含 \\ 应被拦截"
        );
    }

    /// 验证 WhitePathHook 匹配时短路,后续 Hook 不执行。
    #[tokio::test]
    async fn white_path_match_short_circuits_chain() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = default_ctx(); // path = /api/test 匹配 /api
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "WhitePathHook 匹配时应放行");
        let executed = log.lock().unwrap();
        assert!(
            executed.is_empty(),
            "WhitePathHook 匹配时应短路,后续 Hook 不应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证 WhitePathHook 不匹配时后续 Hook 继续执行。
    #[tokio::test]
    async fn white_path_no_match_continues_chain() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/admin".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = default_ctx(); // path = /api/test 不匹配 /admin
        let result = chain.check(&ctx).await;
        assert!(result.is_ok());
        let executed = log.lock().unwrap();
        assert_eq!(
            executed.len(),
            1,
            "WhitePathHook 不匹配时后续 Hook 应执行,实际执行: {:?}",
            executed
        );
    }

    // 11. 回归测试

    /// 验证 path 含 `..` 时 WhitePathHook 不短路:`/api/../admin` 以 `/api` 开头但含可疑模式,返回 Allow 交给后续安全 Hook。
    #[tokio::test]
    async fn white_path_traversal_not_short_circuited() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = make_ctx("/api/../admin", "GET", None, &[], &[]);
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "含 .. 的路径应放行(不短路)");
        let executed = log.lock().unwrap();
        assert!(
            !executed.is_empty(),
            "含 .. 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证 path 含 `//` 时 WhitePathHook 不短路。
    #[tokio::test]
    async fn white_path_double_slash_not_short_circuited() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = make_ctx("/api//test", "GET", None, &[], &[]);
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "含 // 的路径应放行(不短路)");
        let executed = log.lock().unwrap();
        assert!(
            !executed.is_empty(),
            "含 // 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证 path 含 URL 编码 `..`(`%2e%2e`)时 WhitePathHook 不短路。
    #[tokio::test]
    async fn white_path_url_encoded_traversal_not_short_circuited() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = make_ctx("/api/%2e%2e/admin", "GET", None, &[], &[]);
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "含 %2e%2e 的路径应放行(不短路)");
        let executed = log.lock().unwrap();
        assert!(
            !executed.is_empty(),
            "含 %2e%2e 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证 path 含 URL 编码 `/`(`%2f`)时 WhitePathHook 不短路。
    #[tokio::test]
    async fn white_path_url_encoded_slash_not_short_circuited() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = make_ctx("/api%2ftest", "GET", None, &[], &[]);
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "含 %2f 的路径应放行(不短路)");
        let executed = log.lock().unwrap();
        assert!(
            !executed.is_empty(),
            "含 %2f 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证精确匹配白名单路径返回 AllowAndSkip。
    #[tokio::test]
    async fn white_path_exact_match_returns_allow_and_skip() {
        let hook = WhitePathHook::new(vec!["/api".to_string()]);
        let ctx = make_ctx("/api", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::AllowAndSkip),
            "精确匹配 /api 应返回 AllowAndSkip"
        );
    }

    /// 验证段前缀匹配白名单路径返回 AllowAndSkip。
    #[tokio::test]
    async fn white_path_segment_match_returns_allow_and_skip() {
        let hook = WhitePathHook::new(vec!["/api".to_string()]);
        let ctx = make_ctx("/api/test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::AllowAndSkip),
            "段前缀匹配 /api/test 应返回 AllowAndSkip"
        );
    }

    /// 验证前缀混淆路径不匹配白名单:`/api-v2/secret` 以 `/api` 开头但既非精确匹配也非段前缀匹配,返回 Allow。
    #[tokio::test]
    async fn white_path_prefix_confusion_not_matched() {
        let hook = WhitePathHook::new(vec!["/api".to_string()]);
        let ctx = make_ctx("/api-v2/secret", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Allow),
            "前缀混淆 /api-v2/secret 不应命中 /api 白名单"
        );
    }

    // 12. 双重编码边界测试(%252e)

    /// 验证 `%252e` 双重编码被检测到(经 `%25` 双重编码检测路径拦截)。
    #[tokio::test]
    async fn double_encoding_percent_252e_detected() {
        let mut chain = WafHookChain::new();
        chain.register(Box::new(DangerCharacterHook::new()));

        let ctx = crate::strategy::firewall::WafContext {
            path: "/api/%252e%252e/admin",
            method: "GET",
            host: Some("example.com"),
            headers: &[],
            params: &[],
        };

        let result = chain.check(&ctx).await;
        assert!(result.is_err(), "%252e 双重编码应被拦截");
    }

    // 13. 覆盖率补充:边界分支与空列表路径

    /// 验证 path 含 `%5c` 时 WhitePathHook 不短路(覆盖 `%5c` 可疑模式分支)。
    #[tokio::test]
    async fn white_path_percent_5c_not_short_circuited() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = make_ctx("/api%5ctest", "GET", None, &[], &[]);
        let result = chain.check(&ctx).await;
        assert!(result.is_ok(), "含 %5c 的路径应放行(不短路)");
        let executed = log.lock().unwrap();
        assert!(
            !executed.is_empty(),
            "含 %5c 的路径不应短路,后续 Hook 应执行,实际执行: {:?}",
            executed
        );
    }

    /// 验证 path 含高于 0x7E 的字符返回 Deny(覆盖 `> 0x7E` 分支)。
    #[tokio::test]
    async fn banned_char_high_ascii_returns_deny() {
        let hook = BannedCharacterHook::new();
        // 0x80 是不可打印字符(高于 0x7E)
        let ctx = make_ctx("/api\u{80}test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "高于 0x7E 的字符应被拦截"
        );
    }

    /// 验证 path 含 `//` 返回 Deny(覆盖 DirectoryTraversalHook 的 `//` 模式分支)。
    #[tokio::test]
    async fn dir_traversal_double_slash_returns_deny() {
        let hook = DirectoryTraversalHook::new();
        let ctx = make_ctx("/api//test", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "含 // 的路径应被拦截"
        );
    }

    /// 验证空 Host 白名单返回 Allow(覆盖 `self.hosts.is_empty()` 分支)。
    #[tokio::test]
    async fn host_empty_list_returns_allow() {
        let hook = HostHook::new(vec![]);
        let ctx = make_ctx("/api/test", "GET", Some("evil.com"), &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证空 HTTP 方法白名单返回 Allow(覆盖 `self.methods.is_empty()` 分支)。
    #[tokio::test]
    async fn http_method_empty_list_returns_allow() {
        let hook = HttpMethodHook::new(vec![]);
        let ctx = make_ctx("/api/test", "DELETE", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证空 Header 黑名单返回 Allow(覆盖 `self.headers.is_empty()` 分支)。
    #[tokio::test]
    async fn header_empty_list_returns_allow() {
        let hook = HeaderHook::new(vec![]);
        let headers = vec![("X-Any".to_string(), "v".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证空 Parameter 黑名单返回 Allow(覆盖 `self.params.is_empty()` 分支)。
    #[tokio::test]
    async fn parameter_empty_list_returns_allow() {
        let hook = ParameterHook::new(vec![]);
        let params = vec![("any".to_string(), "v".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &[], &params);
        let verdict = hook.check(&ctx).await;
        assert!(matches!(verdict, WafVerdict::Allow));
    }

    /// 验证 HeaderHook 大小写不敏感匹配(覆盖 `name.to_lowercase() == banned_lower` 分支)。
    #[tokio::test]
    async fn header_case_insensitive_match_returns_deny() {
        let hook = HeaderHook::new(vec!["X-Forbidden".to_string()]);
        // header 名用小写,黑名单用大写,应仍命中
        let headers = vec![("x-forbidden".to_string(), "value".to_string())];
        let ctx = make_ctx("/api/test", "GET", None, &headers, &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "大小写不敏感匹配应命中黑名单"
        );
    }

    /// 验证双重编码 `%252f` 被检测到(覆盖 check_danger_chars 的 `%25` 双重编码检测路径)。
    #[tokio::test]
    async fn danger_char_double_encoding_percent_25_2f_detected() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%252ftest", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "%252f 双重编码应被拦截"
        );
    }

    /// 验证三重编码 `%25252e` 被检测到:迭代解码至不含 `%25`(上限 5 轮)后命中 `%2e` 模式。
    #[tokio::test]
    async fn danger_char_triple_encoding_percent_25252e_detected() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%25252e%25252e/admin", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "%25252e 三重编码应被拦截"
        );
    }

    /// 验证四重编码 `%2525252e` 被检测到(迭代解码)。
    #[tokio::test]
    async fn danger_char_quadruple_encoding_detected() {
        let hook = DangerCharacterHook::new();
        let ctx = make_ctx("/api/%2525252ftest", "GET", None, &[], &[]);
        let verdict = hook.check(&ctx).await;
        assert!(
            matches!(verdict, WafVerdict::Deny { .. }),
            "%2525252f 四重编码应被拦截"
        );
    }

    /// 验证 path 含 `%252e` 双重编码时 WhitePathHook 不短路:`/api/%252e/admin` 不含明文 `%2e` 但含 `%25` 双重编码标志,
    /// 守卫返回 Allow 交给后续安全 Hook,应被 DangerCharacterHook 拦截而非被白名单短路放行。
    #[tokio::test]
    async fn white_path_double_encoded_traversal_not_short_circuited() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut chain = WafHookChain::new();
        chain.register(Box::new(WhitePathHook::new(vec!["/api".to_string()])));
        chain.register(Box::new(DangerCharacterHook::new()));
        chain.register(Box::new(RecordingHook {
            hook_name: "recorder",
            log: log.clone(),
        }));
        let ctx = make_ctx("/api/%252e%252e/admin", "GET", None, &[], &[]);
        // DangerCharacterHook 应拦截(%252e 双重编码),而非被白名单短路放行
        let result = chain.check(&ctx).await;
        assert!(
            result.is_err(),
            "含 %252e 的白名单路径不应被短路放行,应被 danger_char 拦截"
        );
    }
}