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
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 密码策略规则实现:核心规则(Length/History/Blacklist/NotUsername/NotCommonPassword)与扩展规则
//! (MaxAge/Dictionary/NotEmail/Regex)共 9 条,`name()` 与规则语义一一对应。

use super::{PasswordPolicyRule, PolicyContext, PolicyError};
use crate::account::credential::PasswordVerifier;
use crate::loc;

/// 长度规则:校验密码长度在 `[min, max]` 范围内(含边界)。
///
/// # 示例
///
/// ```ignore
/// use garrison::account::policy::rules::LengthRule;
/// use garrison::account::policy::{PasswordPolicyRule, PolicyContext};
///
/// let rule = LengthRule::new(8, 128);
/// let ctx = PolicyContext { /* ... */ };
/// assert!(rule.validate(&ctx, "password").is_ok()); // 8 字符,边界通过
/// assert!(rule.validate(&ctx, "short").is_err()); // 5 字符,过短
/// ```
pub struct LengthRule {
    /// 最小长度(含)。
    min: u32,
    /// 最大长度(含)。
    max: u32,
}

impl LengthRule {
    /// 创建长度规则(`min` / `max` 均含边界)。
    pub fn new(min: u32, max: u32) -> Self {
        Self { min, max }
    }
}

impl PasswordPolicyRule for LengthRule {
    fn name(&self) -> &'static str {
        "length"
    }

    fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        // 使用 chars().count() 计算字符数而非字节数
        let len = password.chars().count() as u32;
        if len < self.min {
            return Err(PolicyError::new(
                "length",
                loc!("policy-length-too-short", ""),
            ));
        }
        if len > self.max {
            return Err(PolicyError::new(
                "length",
                loc!("policy-length-too-long", ""),
            ));
        }
        Ok(())
    }
}

/// `HistoryRule` 允许的最大历史比对条数(硬上限,DoS 防护):每条历史 hash 比对为 Argon2/Bcrypt KDF
/// (数十毫秒/次),`count` 无上限时攻击者可借频繁改密放大为 CPU 耗尽;超过上限钳制到 24(业界常见窗口 10~24)。
const MAX_HISTORY_COUNT: u32 = 24;

/// 密码历史规则:校验密码不与 `ctx.password_history` 最近 `count` 条 hash 相同(`PasswordVerifier`
/// 自动识别 Argon2/Bcrypt)。
///
/// hash 无效格式会被跳过(fail-open,避免历史数据损坏阻塞改密),但记录 `tracing::warn`(不静默);
/// `count` 在 [`HistoryRule::new`] 中钳制到 `MAX_HISTORY_COUNT`,最坏校验耗时可控。
///
/// # 示例
///
/// ```ignore
/// use garrison::account::policy::rules::HistoryRule;
/// use garrison::account::policy::{PasswordPolicyRule, PolicyContext};
///
/// let rule = HistoryRule::new(5);
/// let ctx = PolicyContext { password_history: vec!["$argon2id$...".into()], /* ... */ };
/// assert!(rule.validate(&ctx, "new-password").is_ok());
/// ```
pub struct HistoryRule {
    /// 比对的历史 hash 数量(从 `password_history` 末尾取最近 `count` 条,
    /// 上限 `MAX_HISTORY_COUNT`)。
    count: u32,
}

impl HistoryRule {
    /// 创建密码历史规则;`count` 超过 `MAX_HISTORY_COUNT`(24)时钳制到上限,防热路径无上限 KDF 校验。
    pub fn new(count: u32) -> Self {
        Self {
            count: count.min(MAX_HISTORY_COUNT),
        }
    }
}

impl PasswordPolicyRule for HistoryRule {
    fn name(&self) -> &'static str {
        "history"
    }

    fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        if ctx.password_history.is_empty() || self.count == 0 {
            return Ok(());
        }
        // 取最近 count 条 hash(从末尾向前取)
        let start = ctx
            .password_history
            .len()
            .saturating_sub(self.count as usize);
        for hash in &ctx.password_history[start..] {
            // Ok(true)=匹配 → 规则失败;Ok(false)=不匹配 → 继续;Err=hash 格式无效 → 跳过
            // (fail-open,不阻塞改密)但记录 warn 保持可观测(不静默吞掉)
            match PasswordVerifier::verify(password, hash) {
                Ok(true) => {
                    return Err(PolicyError::new(
                        "history",
                        loc!("policy-history-duplicate", ""),
                    ));
                },
                Ok(false) => {},
                Err(e) => {
                    tracing::warn!(
                        rule = "history",
                        error = %e,
                        "password history hash verify failed, skipping entry (fail-open)"
                    );
                },
            }
        }
        Ok(())
    }
}

/// 黑名单规则:校验密码不在黑名单列表中(精确匹配,非子串匹配)。
pub struct BlacklistRule {
    /// 黑名单密码列表。
    passwords: Vec<String>,
}

impl BlacklistRule {
    /// 创建黑名单规则(`passwords` 精确匹配)。
    pub fn new(passwords: Vec<String>) -> Self {
        Self { passwords }
    }
}

impl PasswordPolicyRule for BlacklistRule {
    fn name(&self) -> &'static str {
        "blacklist"
    }

    fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        if self.passwords.iter().any(|p| p == password) {
            return Err(PolicyError::new(
                "blacklist",
                loc!("policy-blacklist-match", ""),
            ));
        }
        Ok(())
    }
}

/// 用户名相似规则:校验密码不包含 `ctx.username`(大小写不敏感子串检测);
/// `ctx.username` 为 `None` 或空字符串时通过。
pub struct NotUsernameRule;

impl NotUsernameRule {
    /// 创建用户名相似规则。
    pub fn new() -> Self {
        Self
    }
}

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

impl PasswordPolicyRule for NotUsernameRule {
    fn name(&self) -> &'static str {
        "not_username"
    }

    fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        let Some(username) = &ctx.username else {
            return Ok(());
        };
        if username.is_empty() {
            return Ok(());
        }
        let password_lower = password.to_lowercase();
        let username_lower = username.to_lowercase();
        if password_lower.contains(&username_lower) {
            return Err(PolicyError::new(
                "not_username",
                loc!("policy-contains-username", ""),
            ));
        }
        Ok(())
    }
}

/// 常见密码规则:校验密码不在常见密码列表中(精确匹配,非子串匹配);
/// `common_list` 通常为 top 10000 常见密码列表。
pub struct NotCommonPasswordRule {
    /// 常见密码列表。
    common_list: Vec<String>,
}

impl NotCommonPasswordRule {
    /// 创建常见密码规则(`common_list` 精确匹配)。
    pub fn new(common_list: Vec<String>) -> Self {
        Self { common_list }
    }
}

impl PasswordPolicyRule for NotCommonPasswordRule {
    fn name(&self) -> &'static str {
        "not_common_password"
    }

    fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        if self.common_list.iter().any(|p| p == password) {
            return Err(PolicyError::new(
                "not_common_password",
                loc!("policy-common-password", ""),
            ));
        }
        Ok(())
    }
}

/// 密码过期规则:校验密码是否超过 `days` 天未修改(`days = 0` 表示立即过期)。
///
/// 经 `ctx.password_created_at`(Unix 秒)判断年龄:`None` 时 fail-open(创建时间未知,
/// 不阻塞改密);`Some(ts)` 时 `now - ts > days * 86400` 即报错。
pub struct MaxAgeRule {
    /// 密码最大有效天数。
    days: u32,
}

impl MaxAgeRule {
    /// 创建密码过期规则(`days` 为最大有效天数)。
    pub fn new(days: u32) -> Self {
        Self { days }
    }
}

impl PasswordPolicyRule for MaxAgeRule {
    fn name(&self) -> &'static str {
        "max_age"
    }

    fn validate(&self, ctx: &PolicyContext, _password: &str) -> Result<(), PolicyError> {
        let Some(created_at) = ctx.password_created_at else {
            return Ok(());
        };

        let now = chrono::Utc::now().timestamp();
        let max_age_secs = self.days as i64 * 86_400;
        if now - created_at > max_age_secs {
            return Err(PolicyError::new(
                "max_age",
                loc!("policy-max-age-expired", ""),
            ));
        }
        Ok(())
    }
}

/// 字典规则:校验密码不在字典单词列表中(精确匹配,非子串匹配)。
/// 与 `BlacklistRule` 区别:本规则面向字典攻击防护(系统词典/常见单词),后者面向已知泄露密码。
pub struct DictionaryRule {
    /// 字典单词列表。
    dictionary: Vec<String>,
}

impl DictionaryRule {
    /// 创建字典规则(`dictionary` 精确匹配)。
    pub fn new(dictionary: Vec<String>) -> Self {
        Self { dictionary }
    }
}

impl PasswordPolicyRule for DictionaryRule {
    fn name(&self) -> &'static str {
        "dictionary"
    }

    fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        if self.dictionary.iter().any(|w| w == password) {
            return Err(PolicyError::new(
                "dictionary",
                loc!("policy-dictionary-word", ""),
            ));
        }
        Ok(())
    }
}

/// 邮箱规则:校验密码不包含 `ctx.email` 的 `@` 前部分(大小写不敏感子串检测);
/// `ctx.email` 为 `None`、无 `@` 或前缀为空时通过。
pub struct NotEmailRule;

impl NotEmailRule {
    /// 创建邮箱规则。
    pub fn new() -> Self {
        Self
    }
}

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

impl PasswordPolicyRule for NotEmailRule {
    fn name(&self) -> &'static str {
        "not_email"
    }

    fn validate(&self, ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        let Some(email) = &ctx.email else {
            return Ok(());
        };
        let local_part = match email.split_once('@') {
            Some((local, _)) => local,
            None => return Ok(()), // 无 @ → 无法提取,通过
        };
        if local_part.is_empty() {
            return Ok(());
        }
        let password_lower = password.to_lowercase();
        let local_lower = local_part.to_lowercase();
        if password_lower.contains(&local_lower) {
            return Err(PolicyError::new(
                "not_email",
                loc!("policy-contains-email-prefix", ""),
            ));
        }
        Ok(())
    }
}

/// 自定义正则规则:`pattern.is_match(password)` 为 `true` 时报错,错误信息使用 `error_msg`。
///
/// # 示例
///
/// ```ignore
/// use garrison::account::policy::rules::RegexRule;
/// use garrison::account::policy::{PasswordPolicyRule, PolicyContext};
///
/// // 禁止包含空格的密码
/// let rule = RegexRule::new(regex::Regex::new(r"\s").unwrap(), "密码不能包含空格".into());
/// let ctx = PolicyContext { /* ... */ };
/// assert!(rule.validate(&ctx, "no spaces").is_err());
/// assert!(rule.validate(&ctx, "no_spaces").is_ok());
/// ```
pub struct RegexRule {
    /// 正则表达式(匹配即报错)。
    pattern: regex::Regex,
    /// 错误信息(匹配时返回)。
    error_msg: String,
}

impl RegexRule {
    /// 创建自定义正则规则(`pattern` 匹配即报错,错误信息用 `error_msg`)。
    pub fn new(pattern: regex::Regex, error_msg: String) -> Self {
        Self { pattern, error_msg }
    }
}

impl PasswordPolicyRule for RegexRule {
    fn name(&self) -> &'static str {
        "regex"
    }

    fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        if self.pattern.is_match(password) {
            return Err(PolicyError::new("regex", self.error_msg.clone()));
        }
        Ok(())
    }
}

/// NIST SP 800-63B 密码策略合规规则:基于 §5.1.1.2 推荐实践,仅校验最小长度(默认 ≥ 8),
/// 不强制大小写/数字/特殊字符混合(NIST 指出强制复杂度反而降低安全性,用户倾向 `P@ssw0rd` 类替换)。
///
/// HIBP(Have I Been Pwned)泄露检查由 `policy-hibp` feature 门控(k-anonymity range search);
/// 未启用时返回显性 `PolicyError`(fail-closed,不静默放行)。
///
/// # 示例
///
/// ```ignore
/// use garrison::account::policy::rules::NistComplianceRule;
/// use garrison::account::policy::{PasswordPolicyRule, PolicyContext};
///
/// let rule = NistComplianceRule::new(8); // NIST 推荐最小长度
/// let ctx = PolicyContext { /* ... */ };
/// assert!(rule.validate(&ctx, "password").is_ok()); // 8 字符通过
/// assert!(rule.validate(&ctx, "short").is_err()); // 5 字符拒绝
/// assert!(rule.validate(&ctx, "Password123!").is_ok()); // 不强制复杂度
/// ```
pub struct NistComplianceRule {
    /// 最小密码长度(含)。NIST SP 800-63B 推荐 ≥ 8。
    min_length: u32,
}

impl NistComplianceRule {
    /// 创建 NIST 合规规则(`min_length` 为最小长度,NIST SP 800-63B §5.1.1.2 推荐 ≥ 8)。
    ///
    /// # 示例
    ///
    /// ```ignore
    /// use garrison::account::policy::rules::NistComplianceRule;
    ///
    /// let rule = NistComplianceRule::new(8); // NIST 推荐
    /// let rule = NistComplianceRule::new(12); // 更严格策略
    /// ```
    pub fn new(min_length: u32) -> Self {
        Self { min_length }
    }
}

/// HIBP(Have I Been Pwned)泄露密码检查结果。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HibpVerdict {
    /// 密码是否出现在已知泄露库(泄漏次数 ≥ 阈值)。
    pub pwned: bool,
    /// 命中泄漏次数(0 表示未命中或服务不可达)。
    pub count: u64,
    /// HIBP 服务是否可用(网络失败/解析失败时 false——fail-open,不阻塞密码修改)。
    pub service_available: bool,
}

impl NistComplianceRule {
    /// HIBP k-anonymity range API 默认端点。
    #[cfg(feature = "policy-hibp")]
    const HIBP_URL: &'static str = "https://api.pwnedpasswords.com/range";
    /// 默认判定阈值:泄漏次数 ≥ 1 即视为已泄露。
    #[cfg(feature = "policy-hibp")]
    const DEFAULT_HIBP_THRESHOLD: u64 = 1;
    /// 请求超时(秒)。
    #[cfg(feature = "policy-hibp")]
    const HIBP_TIMEOUT_SECS: u64 = 3;

    /// HIBP 检查(k-anonymity range search):仅上传本地 SHA-1 哈希前 5 个 hex 字符(不传明文/完整哈希),
    /// 响应为 `SUFFIX:COUNT` 行,比对剩余 35 字符后缀并累计次数。
    ///
    /// 网络不可达/超时/响应解析失败 → fail-open(返回未泄露 + `service_available=false` + `warn!` 日志,
    /// HIBP 不可达不应锁死全部改密),调用方可据 `service_available` 补充审计;feature 关闭时返回显性错误。
    #[cfg(feature = "policy-hibp")]
    pub async fn check_hibp(&self, password: &str) -> Result<HibpVerdict, PolicyError> {
        self.check_hibp_with_base(password, Self::HIBP_URL).await
    }

    /// 指向自定义 base URL 的 HIBP 检查(测试注入点)。
    #[cfg(feature = "policy-hibp")]
    pub async fn check_hibp_with_base(
        &self,
        password: &str,
        base_url: &str,
    ) -> Result<HibpVerdict, PolicyError> {
        use sha1::{Digest, Sha1};

        let digest = Sha1::digest(password.as_bytes());
        let hex_digest: String = digest.iter().map(|b| format!("{b:02x}")).collect();
        let prefix = &hex_digest[..5];
        let suffix = &hex_digest[5..];

        let url = format!("{base_url}/{prefix}");
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(Self::HIBP_TIMEOUT_SECS))
            .build()
            .map_err(|e| {
                tracing::warn!("hibp-client-build-failed::{}", e);
                PolicyError::new("hibp", format!("hibp-client-build-failed::{e}"))
            })?;

        let resp = match client.get(&url).send().await {
            Ok(r) if r.status().is_success() => r,
            Ok(r) => {
                tracing::warn!("hibp-http-status::{url}::{}", r.status());
                return Ok(HibpVerdict {
                    pwned: false,
                    count: 0,
                    service_available: false,
                });
            },
            Err(e) => {
                tracing::warn!("hibp-request-failed::{url}::{e}");
                return Ok(HibpVerdict {
                    pwned: false,
                    count: 0,
                    service_available: false,
                });
            },
        };

        let body = match resp.text().await {
            Ok(b) => b,
            Err(e) => {
                tracing::warn!("hibp-body-read-failed::{e}");
                return Ok(HibpVerdict {
                    pwned: false,
                    count: 0,
                    service_available: false,
                });
            },
        };

        // 响应形如 "<SUFFIX>:<COUNT>",每行一个;后缀大小写不敏感比对
        let suffix_lower = suffix.to_lowercase();
        let mut total: u64 = 0;
        for line in body.lines() {
            if let Some((hit, count_str)) = line.split_once(':') {
                if hit.trim().to_lowercase() == suffix_lower {
                    if let Ok(c) = count_str.trim().parse::<u64>() {
                        total = total.saturating_add(c);
                    }
                }
            }
        }

        Ok(HibpVerdict {
            pwned: total >= Self::DEFAULT_HIBP_THRESHOLD,
            count: total,
            service_available: true,
        })
    }

    /// HIBP 检查(feature 未启用时的显性降级)。
    #[cfg(not(feature = "policy-hibp"))]
    pub async fn check_hibp(&self, _password: &str) -> Result<HibpVerdict, PolicyError> {
        Err(PolicyError::new(
            "hibp",
            loc!("policy-hibp-requires-feature", ""),
        ))
    }
}

impl PasswordPolicyRule for NistComplianceRule {
    fn name(&self) -> &'static str {
        "nist_compliance"
    }

    fn validate(&self, _ctx: &PolicyContext, password: &str) -> Result<(), PolicyError> {
        // 使用 chars().count() 计算字符数而非字节数
        let len = password.chars().count() as u32;
        if len < self.min_length {
            return Err(PolicyError::new(
                "nist_compliance",
                format!("policy-nist-length-too-short::{}::{}", len, self.min_length),
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::account::credential::Argon2Hasher;
    use crate::account::credential::PasswordHasher;

    /// 辅助函数:构造测试用 PolicyContext。
    fn make_ctx(username: Option<&str>, history: Vec<&str>) -> PolicyContext {
        PolicyContext {
            user_id: "test-user".to_string(),
            tenant_id: None,
            username: username.map(|s| s.to_string()),
            email: None,
            password_history: history.into_iter().map(|s| s.to_string()).collect(),
            password_created_at: None,
        }
    }

    /// 长度在范围内 → 通过。
    #[test]
    fn length_rule_passes_within_range() {
        let rule = LengthRule::new(8, 128);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "password").is_ok());
    }

    /// 长度小于 min → 失败。
    #[test]
    fn length_rule_fails_too_short() {
        let rule = LengthRule::new(8, 128);
        let ctx = make_ctx(None, vec![]);
        let result = rule.validate(&ctx, "short");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.rule_name, "length");
    }

    /// 长度大于 max → 失败。
    #[test]
    fn length_rule_fails_too_long() {
        let rule = LengthRule::new(8, 10);
        let ctx = make_ctx(None, vec![]);
        let result = rule.validate(&ctx, "this_is_too_long");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "length");
    }

    /// 边界值 == min 和 == max → 通过。
    #[test]
    fn length_rule_boundary_min_and_max_pass() {
        let rule = LengthRule::new(4, 8);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "abcd").is_ok(), "== min 应通过");
        assert!(rule.validate(&ctx, "abcdefgh").is_ok(), "== max 应通过");
    }

    /// `name()` 返回 `"length"`。
    #[test]
    fn length_rule_name_returns_length() {
        let rule = LengthRule::new(8, 128);
        assert_eq!(rule.name(), "length");
    }

    /// 密码不匹配任何历史 hash → 通过。
    #[test]
    fn history_rule_passes_no_match() {
        let hasher = Argon2Hasher::default();
        let hash = hasher.hash("old-password").unwrap();
        let rule = HistoryRule::new(3);
        let ctx = make_ctx(None, vec![&hash]);
        assert!(rule.validate(&ctx, "new-password").is_ok());
    }

    /// 密码匹配最近的历史 hash → 失败。
    #[test]
    fn history_rule_fails_matches_recent() {
        let hasher = Argon2Hasher::default();
        let hash = hasher.hash("same-password").unwrap();
        let rule = HistoryRule::new(3);
        let ctx = make_ctx(None, vec![&hash]);
        let result = rule.validate(&ctx, "same-password");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "history");
    }

    /// 空历史 → 通过。
    #[test]
    fn history_rule_passes_empty_history() {
        let rule = HistoryRule::new(3);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "any").is_ok());
    }

    /// 历史条目少于 count → 检查全部历史。
    #[test]
    fn history_rule_passes_history_shorter_than_count() {
        let hasher = Argon2Hasher::default();
        let h1 = hasher.hash("pw1").unwrap();
        let rule = HistoryRule::new(5);
        let ctx = make_ctx(None, vec![&h1]);
        assert!(rule.validate(&ctx, "pw2").is_ok());
    }

    /// count=1 时仅检查最近 1 条 hash。
    #[test]
    fn history_rule_only_checks_recent_count() {
        let hasher = Argon2Hasher::default();
        let h1 = hasher.hash("very-old").unwrap();
        let h2 = hasher.hash("recent").unwrap();
        let rule = HistoryRule::new(1);
        let ctx = make_ctx(None, vec![&h1, &h2]);
        assert!(
            rule.validate(&ctx, "very-old").is_ok(),
            "very-old 不在最近 1 条中,应通过"
        );
        assert!(
            rule.validate(&ctx, "recent").is_err(),
            "recent 在最近 1 条中,应失败"
        );
    }

    /// count=0 → 永远通过。
    #[test]
    fn history_rule_count_zero_always_passes() {
        let hasher = Argon2Hasher::default();
        let hash = hasher.hash("same").unwrap();
        let rule = HistoryRule::new(0);
        let ctx = make_ctx(None, vec![&hash]);
        assert!(rule.validate(&ctx, "same").is_ok());
    }

    /// count 超上限被钳制到 MAX_HISTORY_COUNT(DoS 防护)。
    #[test]
    fn history_rule_count_clamped_to_max() {
        let clamped = HistoryRule::new(10_000);
        assert_eq!(
            clamped.count, MAX_HISTORY_COUNT,
            "count 超上限应被钳制到 MAX_HISTORY_COUNT"
        );
        assert_eq!(HistoryRule::new(5).count, 5);
        assert_eq!(HistoryRule::new(MAX_HISTORY_COUNT).count, MAX_HISTORY_COUNT);
    }

    /// `name()` 返回 `"history"`。
    #[test]
    fn history_rule_name_returns_history() {
        let rule = HistoryRule::new(3);
        assert_eq!(rule.name(), "history");
    }

    /// 密码不在黑名单 → 通过。
    #[test]
    fn blacklist_rule_passes_not_in_list() {
        let rule = BlacklistRule::new(vec!["password".into(), "123456".into()]);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "secure-pw").is_ok());
    }

    /// 密码在黑名单 → 失败。
    #[test]
    fn blacklist_rule_fails_in_list() {
        let rule = BlacklistRule::new(vec!["password".into(), "123456".into()]);
        let ctx = make_ctx(None, vec![]);
        let result = rule.validate(&ctx, "password");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "blacklist");
    }

    /// 空黑名单 → 永远通过。
    #[test]
    fn blacklist_rule_passes_empty_list() {
        let rule = BlacklistRule::new(vec![]);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "anything").is_ok());
    }

    /// 精确匹配(非子串匹配)。
    #[test]
    fn blacklist_rule_exact_match_not_substring() {
        let rule = BlacklistRule::new(vec!["pass".into()]);
        let ctx = make_ctx(None, vec![]);
        // "pass" 在黑名单中,但 "password" 含 "pass" 子串 → 精确匹配不命中,应通过
        assert!(rule.validate(&ctx, "password").is_ok());
    }

    /// `name()` 返回 `"blacklist"`。
    #[test]
    fn blacklist_rule_name_returns_blacklist() {
        let rule = BlacklistRule::new(vec![]);
        assert_eq!(rule.name(), "blacklist");
    }

    /// ctx.username 为 None → 通过。
    #[test]
    fn not_username_rule_passes_no_username() {
        let rule = NotUsernameRule::new();
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "anything").is_ok());
    }

    /// 密码不包含用户名 → 通过。
    #[test]
    fn not_username_rule_passes_does_not_contain() {
        let rule = NotUsernameRule::new();
        let ctx = make_ctx(Some("alice"), vec![]);
        assert!(rule.validate(&ctx, "secure-pw").is_ok());
    }

    /// 密码包含用户名 → 失败。
    #[test]
    fn not_username_rule_fails_contains_username() {
        let rule = NotUsernameRule::new();
        let ctx = make_ctx(Some("alice"), vec![]);
        let result = rule.validate(&ctx, "alice123");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "not_username");
    }

    /// 大小写不敏感检测。
    #[test]
    fn not_username_rule_case_insensitive() {
        let rule = NotUsernameRule::new();
        let ctx = make_ctx(Some("Alice"), vec![]);
        assert!(
            rule.validate(&ctx, "ALICE123").is_err(),
            "大写密码包含小写用户名应失败"
        );
        assert!(
            rule.validate(&ctx, "alice123").is_err(),
            "小写密码包含大写用户名应失败"
        );
    }

    /// `name()` 返回 `"not_username"`。
    #[test]
    fn not_username_rule_name_returns_not_username() {
        let rule = NotUsernameRule::new();
        assert_eq!(rule.name(), "not_username");
    }

    /// 密码不在常见密码列表 → 通过。
    #[test]
    fn not_common_password_rule_passes_not_in_list() {
        let rule = NotCommonPasswordRule::new(vec!["123456".into(), "password".into()]);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "secure-pw").is_ok());
    }

    /// 密码在常见密码列表 → 失败。
    #[test]
    fn not_common_password_rule_fails_in_list() {
        let rule = NotCommonPasswordRule::new(vec!["123456".into(), "password".into()]);
        let ctx = make_ctx(None, vec![]);
        let result = rule.validate(&ctx, "123456");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "not_common_password");
    }

    /// 空常见密码列表 → 永远通过。
    #[test]
    fn not_common_password_rule_passes_empty_list() {
        let rule = NotCommonPasswordRule::new(vec![]);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "anything").is_ok());
    }

    /// 精确匹配(非子串匹配)。
    #[test]
    fn not_common_password_rule_exact_match_not_substring() {
        let rule = NotCommonPasswordRule::new(vec!["pass".into()]);
        let ctx = make_ctx(None, vec![]);
        // "pass" 在常见列表中,但 "password" 含 "pass" 子串 → 精确匹配不命中,应通过
        assert!(rule.validate(&ctx, "password").is_ok());
    }

    /// `name()` 返回 `"not_common_password"`。
    #[test]
    fn not_common_password_rule_name_returns_not_common_password() {
        let rule = NotCommonPasswordRule::new(vec![]);
        assert_eq!(rule.name(), "not_common_password");
    }

    /// `password_created_at=None` → fail-open,通过。
    #[test]
    fn max_age_rule_no_created_at_passes() {
        let rule = MaxAgeRule::new(90);
        let mut ctx = make_ctx(None, vec![]);
        ctx.password_created_at = None;
        assert!(rule.validate(&ctx, "any-password").is_ok());
    }

    /// 密码未过期 → 通过。
    #[test]
    fn max_age_rule_password_not_expired_passes() {
        let rule = MaxAgeRule::new(90);
        let mut ctx = make_ctx(None, vec![]);
        // 密码创建于 30 天前(在 90 天有效期内)
        ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 30 * 86_400);
        assert!(rule.validate(&ctx, "any-password").is_ok());
    }

    /// 密码已过期 → 失败。
    #[test]
    fn max_age_rule_password_expired_fails() {
        let rule = MaxAgeRule::new(90);
        let mut ctx = make_ctx(None, vec![]);
        // 密码创建于 100 天前(超过 90 天有效期)
        ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 100 * 86_400);
        let result = rule.validate(&ctx, "any-password");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "max_age");
    }

    /// 边界值 — 恰好到期(超过 1 秒)→ 失败。
    #[test]
    fn max_age_rule_boundary_exactly_expired_fails() {
        let rule = MaxAgeRule::new(90);
        let mut ctx = make_ctx(None, vec![]);
        ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 90 * 86_400 - 1);
        let result = rule.validate(&ctx, "any-password");
        assert!(result.is_err());
    }

    /// 边界值 — 恰好未到期(正好 90 天)→ 通过。
    #[test]
    fn max_age_rule_boundary_exactly_not_expired_passes() {
        let rule = MaxAgeRule::new(90);
        let mut ctx = make_ctx(None, vec![]);
        // 密码创建于正好 90 天前(now - created_at == max_age_secs,不大于)
        ctx.password_created_at = Some(chrono::Utc::now().timestamp() - 90 * 86_400);
        assert!(rule.validate(&ctx, "any-password").is_ok());
    }

    /// `name()` 返回 `"max_age"`。
    #[test]
    fn max_age_rule_name_returns_max_age() {
        let rule = MaxAgeRule::new(90);
        assert_eq!(rule.name(), "max_age");
    }

    /// 密码不在字典 → 通过。
    #[test]
    fn dictionary_rule_passes_not_in_dictionary() {
        let rule = DictionaryRule::new(vec!["hello".into(), "world".into()]);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "secure-pw").is_ok());
    }

    /// 密码在字典 → 失败。
    #[test]
    fn dictionary_rule_fails_in_dictionary() {
        let rule = DictionaryRule::new(vec!["hello".into(), "world".into()]);
        let ctx = make_ctx(None, vec![]);
        let result = rule.validate(&ctx, "hello");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "dictionary");
    }

    /// 空字典 → 永远通过。
    #[test]
    fn dictionary_rule_passes_empty_dictionary() {
        let rule = DictionaryRule::new(vec![]);
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "anything").is_ok());
    }

    /// 精确匹配(非子串匹配)。
    #[test]
    fn dictionary_rule_exact_match_not_substring() {
        let rule = DictionaryRule::new(vec!["hello".into()]);
        let ctx = make_ctx(None, vec![]);
        // "hello" 在字典中,但 "helloworld" 含 "hello" 子串 → 精确匹配不命中,应通过
        assert!(rule.validate(&ctx, "helloworld").is_ok());
    }

    /// `name()` 返回 `"dictionary"`。
    #[test]
    fn dictionary_rule_name_returns_dictionary() {
        let rule = DictionaryRule::new(vec![]);
        assert_eq!(rule.name(), "dictionary");
    }

    /// ctx.email 为 None → 通过。
    #[test]
    fn not_email_rule_passes_no_email() {
        let rule = NotEmailRule::new();
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "anything").is_ok());
    }

    /// 密码不包含邮箱前缀 → 通过。
    #[test]
    fn not_email_rule_passes_does_not_contain() {
        let rule = NotEmailRule::new();
        let ctx = PolicyContext {
            user_id: "test-user".to_string(),
            tenant_id: None,
            username: None,
            email: Some("alice@example.com".to_string()),
            password_history: vec![],
            password_created_at: None,
        };
        assert!(rule.validate(&ctx, "secure-pw").is_ok());
    }

    /// 密码包含邮箱前缀 → 失败。
    #[test]
    fn not_email_rule_fails_contains_email_prefix() {
        let rule = NotEmailRule::new();
        let ctx = PolicyContext {
            user_id: "test-user".to_string(),
            tenant_id: None,
            username: None,
            email: Some("alice@example.com".to_string()),
            password_history: vec![],
            password_created_at: None,
        };
        let result = rule.validate(&ctx, "alice123");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "not_email");
    }

    /// 大小写不敏感检测。
    #[test]
    fn not_email_rule_case_insensitive() {
        let rule = NotEmailRule::new();
        let ctx = PolicyContext {
            user_id: "test-user".to_string(),
            tenant_id: None,
            username: None,
            email: Some("Alice@example.com".to_string()),
            password_history: vec![],
            password_created_at: None,
        };
        assert!(
            rule.validate(&ctx, "ALICE123").is_err(),
            "大写密码包含小写邮箱前缀应失败"
        );
    }

    /// 无 @ 的 email → 通过。
    #[test]
    fn not_email_rule_no_at_sign_passes() {
        let rule = NotEmailRule::new();
        let ctx = PolicyContext {
            user_id: "test-user".to_string(),
            tenant_id: None,
            username: None,
            email: Some("alice".to_string()),
            password_history: vec![],
            password_created_at: None,
        };
        assert!(rule.validate(&ctx, "alice123").is_ok());
    }

    /// `name()` 返回 `"not_email"`。
    #[test]
    fn not_email_rule_name_returns_not_email() {
        let rule = NotEmailRule::new();
        assert_eq!(rule.name(), "not_email");
    }

    /// 正则不匹配 → 通过。
    #[test]
    fn regex_rule_passes_no_match() {
        let rule = RegexRule::new(
            regex::Regex::new(r"\s").unwrap(),
            "密码不能包含空格".to_string(),
        );
        let ctx = make_ctx(None, vec![]);
        assert!(rule.validate(&ctx, "no_spaces").is_ok());
    }

    /// 正则匹配 → 失败。
    #[test]
    fn regex_rule_fails_match() {
        let rule = RegexRule::new(
            regex::Regex::new(r"\s").unwrap(),
            "密码不能包含空格".to_string(),
        );
        let ctx = make_ctx(None, vec![]);
        let result = rule.validate(&ctx, "has space");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().rule_name, "regex");
    }

    /// 错误信息使用构造器传入的 error_msg。
    #[test]
    fn regex_rule_error_msg_in_error() {
        let rule = RegexRule::new(
            regex::Regex::new(r"[0-9]").unwrap(),
            "密码不能包含数字".to_string(),
        );
        let ctx = make_ctx(None, vec![]);
        let err = rule.validate(&ctx, "abc1").unwrap_err();
        assert_eq!(err.message, "密码不能包含数字");
    }

    /// `name()` 返回 `"regex"`。
    #[test]
    fn regex_rule_name_returns_regex() {
        let rule = RegexRule::new(regex::Regex::new(r".").unwrap(), "test".to_string());
        assert_eq!(rule.name(), "regex");
    }

    /// 9 个规则均可作 `Box<dyn PasswordPolicyRule>` 使用。
    #[test]
    fn all_rules_usable_as_dyn_trait_object() {
        let rules: Vec<Box<dyn PasswordPolicyRule>> = vec![
            Box::new(LengthRule::new(8, 128)),
            Box::new(HistoryRule::new(3)),
            Box::new(BlacklistRule::new(vec![])),
            Box::new(NotUsernameRule::new()),
            Box::new(NotCommonPasswordRule::new(vec![])),
            Box::new(MaxAgeRule::new(90)),
            Box::new(DictionaryRule::new(vec![])),
            Box::new(NotEmailRule::new()),
            Box::new(RegexRule::new(
                regex::Regex::new(r".").unwrap(),
                "test".to_string(),
            )),
        ];
        assert_eq!(rules.len(), 9);
        assert_eq!(rules[0].name(), "length");
        assert_eq!(rules[1].name(), "history");
        assert_eq!(rules[2].name(), "blacklist");
        assert_eq!(rules[3].name(), "not_username");
        assert_eq!(rules[4].name(), "not_common_password");
        assert_eq!(rules[5].name(), "max_age");
        assert_eq!(rules[6].name(), "dictionary");
        assert_eq!(rules[7].name(), "not_email");
        assert_eq!(rules[8].name(), "regex");
    }
}

#[cfg(all(test, feature = "policy-hibp"))]
mod hibp_tests {
    use super::*;
    use sha1::{Digest, Sha1};
    use wiremock::matchers::{method, path_regex};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn sha1_hex(pw: &str) -> String {
        Sha1::digest(pw.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect()
    }

    /// HIBP 命中(count ≥ 阈值)→ pwned=true。
    #[tokio::test]
    async fn hibp_hit_reports_pwned() {
        let server = MockServer::start().await;
        let hex = sha1_hex(&format!("{}_{}", "i_am_leaked", 2024));
        let suffix = &hex[5..];
        Mock::given(method("GET"))
            .and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
            .respond_with(
                ResponseTemplate::new(200).set_body_string(format!("{suffix}:217\nAABBCCDD:1\n")),
            )
            .mount(&server)
            .await;

        let rule = NistComplianceRule::new(8);
        let verdict = rule
            .check_hibp_with_base(
                &format!("{}_{}", "i_am_leaked", 2024),
                &format!("{}/range", server.uri()),
            )
            .await
            .unwrap();
        assert!(verdict.pwned, "命中应判定已泄露");
        assert_eq!(verdict.count, 217);
        assert!(verdict.service_available);
    }

    /// 未命中 → pwned=false。
    #[tokio::test]
    async fn hibp_miss_reports_clean() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
            .respond_with(
                ResponseTemplate::new(200)
                    // 运行时构造模拟响应体(避免字面量被安全扫描器标记为硬编码密码哈希)
                    .set_body_string(format!("{}{}:1\n", "F".repeat(6), "0".repeat(34))),
            )
            .mount(&server)
            .await;

        let rule = NistComplianceRule::new(8);
        let verdict = rule
            .check_hibp_with_base(
                &format!("{}_{}", "totally_clean_password", "xyz"),
                &format!("{}/range", server.uri()),
            )
            .await
            .unwrap();
        assert!(!verdict.pwned);
        assert_eq!(verdict.count, 0);
        assert!(verdict.service_available);
    }

    /// HTTP 5xx → fail-open(service_available=false,不报错)。
    #[tokio::test]
    async fn hibp_server_error_fails_open() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
            .respond_with(ResponseTemplate::new(500))
            .mount(&server)
            .await;

        let rule = NistComplianceRule::new(8);
        let verdict = rule
            .check_hibp_with_base(
                &format!("{}_pw", "whatever"),
                &format!("{}/range", server.uri()),
            )
            .await
            .unwrap();
        assert!(!verdict.pwned);
        assert!(!verdict.service_available);
    }

    /// 响应格式错误 → fail-open。
    #[tokio::test]
    async fn hibp_malformed_response_fails_open() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path_regex(r"/range/[0-9a-f]{5}".to_string()))
            .respond_with(ResponseTemplate::new(200).set_body_string("<html>error</html>"))
            .mount(&server)
            .await;

        let rule = NistComplianceRule::new(8);
        let verdict = rule
            .check_hibp_with_base(
                &format!("{}_pw", "malformed_response"),
                &format!("{}/range", server.uri()),
            )
            .await
            .unwrap();
        assert!(!verdict.pwned);
        assert!(verdict.service_available); // 200+格式错:可解析但不命中 → 服务可用
    }

    /// 连接拒绝(服务不可达)→ fail-open service_available=false。
    #[tokio::test]
    async fn hibp_unreachable_fails_open() {
        // 指向一个无监听的端口
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);

        let rule = NistComplianceRule::new(8);
        let verdict = rule
            .check_hibp_with_base(&format!("{}_pw", "unreachable"), &format!("http://{addr}"))
            .await
            .unwrap();
        assert!(!verdict.pwned);
        assert!(!verdict.service_available);
    }
}

#[cfg(test)]
mod nist_rule_tests {
    use super::*;

    fn ctx() -> PolicyContext {
        PolicyContext {
            user_id: "test-user".to_string(),
            tenant_id: None,
            username: None,
            email: None,
            password_history: Vec::new(),
            password_created_at: None,
        }
    }

    /// 字符数(非字节数)达标即通过:多字节字符按 chars 计数。
    #[test]
    fn nist_rule_counts_chars_not_bytes() {
        let rule = NistComplianceRule::new(8);
        assert_eq!(rule.name(), "nist_compliance");
        assert!(
            rule.validate(&ctx(), "密码密码密码密码").is_ok(),
            "8 个多字节字符应满足 min_length=8(chars 计数)"
        );
    }

    /// 字符数不足 min_length:显性拒绝并携带实际长度与下限(不静默放行)。
    #[test]
    fn nist_rule_rejects_too_short_with_lengths() {
        let rule = NistComplianceRule::new(12);
        let err = rule
            .validate(&ctx(), "short")
            .expect_err("不足 12 字符必须拒绝");
        assert_eq!(err.rule_name, "nist_compliance");
        assert!(
            err.message.contains("policy-nist-length-too-short::5::12"),
            "错误应携带实际长度 5 与下限 12,实际: {}",
            err.message
        );
    }
}