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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! `GarrisonConfig` 与 `TenantIsolationConfig` 实现块(`mod.rs` 只留定义)。

use super::*;
use crate::error::{GarrisonError, GarrisonResult};
use crate::loc;
use confers::config::ConfigBuilder;

impl Default for TenantIsolationConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            resolver: TenantResolverKind::Header,
        }
    }
}

impl Default for PasswordHasherConfig {
    fn default() -> Self {
        Self {
            algorithm: "argon2id".to_string(),
            argon2_m_cost: ARGON2_MIN_M_COST,
            argon2_t_cost: 2,
            argon2_p_cost: 1,
            bcrypt_cost: 12,
            allow_weak_argon2_params: false,
            argon2_pool_size: DEFAULT_ARGON2_POOL_SIZE,
        }
    }
}

impl PasswordHasherConfig {
    /// 按本配置段构造密码哈希器(`account-credential` feature)。
    ///
    /// 校验规则与 `validate_core` 一致(algorithm 白名单 + 参数区间),非法配置返回 `Err(GarrisonError::Config)`(fail-fast);仅影响**新哈希**参数,verify 由 `PasswordVerifier` 按哈希前缀自动识别。
    #[cfg(feature = "account-credential")]
    pub fn build_hasher(
        &self,
    ) -> GarrisonResult<std::sync::Arc<dyn crate::account::credential::PasswordHasher>> {
        match self.algorithm.as_str() {
            "argon2id" => {
                use crate::account::credential::password::Argon2Hasher;

                self.validate_argon2_params()?;
                let (m, t, p) = (self.argon2_m_cost, self.argon2_t_cost, self.argon2_p_cost);
                let hasher =
                    Argon2Hasher::with_params(m, t, p).with_pool(self.argon2_pool_size as usize);
                Ok(std::sync::Arc::new(hasher))
            },
            "bcrypt" => {
                use crate::account::credential::password::BcryptHasher;

                self.validate_bcrypt_cost()?;
                let hasher = BcryptHasher::with_cost(self.bcrypt_cost);
                Ok(std::sync::Arc::new(hasher))
            },
            other => Err(GarrisonError::Config(format!(
                "config-password-hash-algorithm-unsupported::{}",
                other
            ))),
        }
    }

    /// Argon2id 参数校验:t/p 非零 + m_cost 下限(低于下限须显式风险接受,放行时 warn)
    /// + 池大小区间 [1, 256](0 = 零 permit 永久饥饿,fail-fast)。
    fn validate_argon2_params(&self) -> GarrisonResult<()> {
        if self.argon2_t_cost == 0 || self.argon2_p_cost == 0 {
            let which = if self.argon2_t_cost == 0 {
                "t_cost"
            } else {
                "p_cost"
            };
            return Err(GarrisonError::Config(format!(
                "config-password-hash-argon2-param-invalid::{which}"
            )));
        }
        if !(ARGON2_POOL_SIZE_MIN..=ARGON2_POOL_SIZE_MAX).contains(&self.argon2_pool_size) {
            return Err(GarrisonError::Config(format!(
                "config-password-hash-argon2-pool-size-out-of-range::{} (allowed {}-{})",
                self.argon2_pool_size, ARGON2_POOL_SIZE_MIN, ARGON2_POOL_SIZE_MAX
            )));
        }
        if self.argon2_m_cost >= ARGON2_MIN_M_COST {
            return Ok(());
        }
        if !self.allow_weak_argon2_params {
            return Err(GarrisonError::Config(format!(
                "config-password-hash-argon2-m-below-floor::{} (min {})::{}",
                self.argon2_m_cost, ARGON2_MIN_M_COST, self.algorithm
            )));
        }
        let cost = self.argon2_m_cost.to_string();
        let floor = ARGON2_MIN_M_COST.to_string();
        tracing::warn!(
            "{}",
            crate::i18n::translate_detail(
                "logs-config-argon2-weak-params-accepted",
                &[("cost", cost.as_str()), ("floor", floor.as_str())]
            )
        );
        Ok(())
    }

    /// bcrypt cost 区间校验(OWASP ≥10;>15 单次哈希秒级耗多为误配)。
    fn validate_bcrypt_cost(&self) -> GarrisonResult<()> {
        if (BCRYPT_MIN_COST..=BCRYPT_MAX_COST).contains(&self.bcrypt_cost) {
            return Ok(());
        }
        Err(GarrisonError::Config(format!(
            "config-password-hash-bcrypt-cost-out-of-range::{} (allowed {}-{})",
            self.bcrypt_cost, BCRYPT_MIN_COST, BCRYPT_MAX_COST
        )))
    }
}

// 手动 Debug(非 derive):derive 会明文打印 jwt_secret(Zeroizing 的 Debug 透明);借 Serialize 输出完整字段映射(新字段自动纳入)并将密钥字段覆写为 "<redacted>"
impl std::fmt::Debug for GarrisonConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut value = match serde_json::to_value(self) {
            Ok(v) => v,
            Err(_) => serde_json::json!({
                "token_name": self.token_name,
                "token_style": self.token_style,
                "timeout": self.timeout,
            }),
        };
        if let serde_json::Value::Object(ref mut map) = value {
            redact_fields(map, DEBUG_REDACTED_FIELDS.iter().copied());
        }
        f.write_str("GarrisonConfig ")?;
        std::fmt::Debug::fmt(&value, f)
    }
}

/// Debug 输出脱敏字段表(对称/非对称签名密钥)。
const DEBUG_REDACTED_FIELDS: &[&str] = &[
    "jwt_secret",
    "jwt_rsa_private_key_pem",
    "jwt_ec_private_key_pem",
    "jwt_ed_private_key_pem",
];

/// 将 map 中指定字段覆写为 `"<redacted>"`(Debug 输出脱敏公共出口)。
fn redact_fields<I>(map: &mut serde_json::Map<String, serde_json::Value>, keys: I)
where
    I: IntoIterator,
    I::Item: std::ops::Deref<Target = str>,
{
    for key in keys {
        map.insert(
            key.to_string(),
            serde_json::Value::String("<redacted>".to_string()),
        );
    }
}

impl GarrisonConfig {
    /// 创建默认配置实例(token_style="uuid"、timeout=30 天、throw_on_not_login=true)。
    ///
    /// 本方法**不调用 `validate()`**,返回未经校验的原始默认值,便于调用方逐字段改写后再断言 `validate()` 失败。
    /// 生产入口(`GarrisonConfig::load()` / `GarrisonManagerBuilder::build()`)均会调用 `validate()`;直接以 `default_config()` 驱动生产时须在启动前自行调用 `config.validate()`(fail-fast)。
    pub fn default_config() -> Self {
        let config = Self {
            token_name: DEFAULT_TOKEN_NAME.to_string(),
            timeout: DEFAULT_TIMEOUT,
            active_timeout: DEFAULT_ACTIVE_TIMEOUT,
            is_read_cookie: true,
            is_read_header: true,
            is_read_body: DEFAULT_IS_READ_BODY,
            is_write_header: true,
            is_write_cookie: false,
            token_style: "uuid".to_string(),
            throw_on_not_login: true,
            cookie_secure: DEFAULT_COOKIE_SECURE,
            cookie_same_site: DEFAULT_COOKIE_SAME_SITE.to_string(),
            jwt_algorithm: DEFAULT_JWT_ALGORITHM.to_string(),
            jwt_secret: default_jwt_secret(),
            jwt_rsa_private_key_pem: None,
            jwt_ec_private_key_pem: None,
            jwt_ed_private_key_pem: None,
            sign_window_seconds: DEFAULT_SIGN_WINDOW_SECONDS,
            sso_ticket_ttl_seconds: DEFAULT_SSO_TICKET_TTL_SECONDS,
            jwks_retention_secs: DEFAULT_JWKS_RETENTION_SECS,
            remember_me_enabled: false,
            remember_me_timeout: REMEMBER_ME_DEFAULT_TIMEOUT,
            seed_primary_amr: true,
            login_id_max_len: DEFAULT_LOGIN_ID_MAX_LEN,
            session_hover_timeout: DEFAULT_SESSION_HOVER_TIMEOUT,
            frontend_separation: DEFAULT_FRONTEND_SEPARATION,
            auto_renewal_threshold: DEFAULT_AUTO_RENEWAL_THRESHOLD,
            token_map_cleanup_interval_secs: DEFAULT_TOKEN_MAP_CLEANUP_INTERVAL,
            #[cfg(feature = "three-tier-cache")]
            l1_cache_ttl_secs: DEFAULT_L1_CACHE_TTL_SECS,
            #[cfg(feature = "three-tier-cache")]
            l2_cache_ttl_secs: DEFAULT_L2_CACHE_TTL_SECS,
            #[cfg(feature = "three-tier-cache")]
            l1_cache_capacity: DEFAULT_L1_CACHE_CAPACITY,
            #[cfg(feature = "session-extra")]
            login_token_map_persist_interval_secs: DEFAULT_LOGIN_TOKEN_MAP_PERSIST_INTERVAL_SECS,
            #[cfg(feature = "session-extra")]
            anon_session_timeout: DEFAULT_ANON_SESSION_TIMEOUT_SECS,
            is_concurrent: DEFAULT_IS_CONCURRENT,
            is_share: DEFAULT_IS_SHARE,
            max_login_count: DEFAULT_MAX_LOGIN_COUNT,
            device_binding_mode: DEFAULT_DEVICE_BINDING_MODE.to_string(),
            replaced_login_exit_mode: ReplacedLoginExitMode::default(),
            overflow_logout_mode: OverflowLogoutMode::default(),
            #[cfg(feature = "session-hijack-detection")]
            session_hijack_mode: SessionHijackMode::default(),
            enable_jwt_revocation: false,
            allow_stateless_jwt_no_revocation: false,
            require_tenant_bound_jwt: false,
            require_session_tenant_binding: false,
            recent_reuse_behaviour: RecentReuseBehaviour::default(),
            refresh_grace_period_secs: DEFAULT_REFRESH_GRACE_PERIOD_SECS,
            refresh_grace_max_uses: DEFAULT_REFRESH_GRACE_MAX_USES,
            audit_mask_mode: AuditMaskMode::default(),
            tenant_isolation: TenantIsolationConfig::default(),
            password_hasher: PasswordHasherConfig::default(),
            mfa: MfaConfig::default(),
            #[cfg(feature = "web-cors")]
            cors_config: CorsConfig::default(),
            #[cfg(feature = "web-csrf")]
            csrf_config: CsrfConfig::default(),
            #[cfg(feature = "rate-limit-redis")]
            rate_limit_backend: RateLimitBackend::default(),
            #[cfg(feature = "firewall-waf")]
            waf_enabled_hooks: Vec::new(),
            #[cfg(feature = "firewall-waf")]
            waf_white_paths: Vec::new(),
            #[cfg(feature = "firewall-waf")]
            waf_black_paths: Vec::new(),
            #[cfg(feature = "firewall-waf")]
            waf_allowed_hosts: Vec::new(),
            #[cfg(feature = "firewall-waf")]
            waf_allowed_methods: Vec::new(),
            #[cfg(feature = "firewall-waf")]
            waf_banned_headers: Vec::new(),
            #[cfg(feature = "firewall-waf")]
            waf_banned_params: Vec::new(),
            #[cfg(feature = "sms-rate-limit")]
            sms_hourly_limit: 5,
            #[cfg(feature = "sms-rate-limit")]
            sms_daily_limit: 10,
            #[cfg(feature = "sms-rate-limit")]
            sms_verify_max_attempts: 3,
            #[cfg(feature = "sms-rate-limit")]
            sms_unverified_threshold: 3,
            #[cfg(feature = "email-verification")]
            email_hourly_limit: 5,
            #[cfg(feature = "email-verification")]
            email_daily_limit: 10,
            #[cfg(feature = "email-verification")]
            email_verify_max_attempts: 3,
            #[cfg(feature = "email-verification")]
            email_unverified_threshold: 3,
            #[cfg(feature = "email-verification")]
            email_code_ttl: 600,
            #[cfg(feature = "anomalous-detector-dual")]
            anomalous_analyzer_interval_secs: DEFAULT_ANOMALOUS_ANALYZER_INTERVAL_SECS,
            #[cfg(feature = "anomalous-detector-dual")]
            anomalous_analyzer_burst_threshold: DEFAULT_ANOMALOUS_BURST_THRESHOLD,
            #[cfg(feature = "credit-metering")]
            credit: None,
            watcher: None,
        };
        config.with_watcher()
    }

    /// 使用 confers 加载配置(环境变量 > toml 文件 > 代码默认值;`None` 时仅默认值 + 环境变量);文件解析失败、环境变量非法或校验未通过返回 `Config`。
    ///
    /// # Security
    ///
    /// `toml_path` 必须来自可信源(命令行参数 / 硬编码 / 受控环境变量),不可直接传入用户输入;路径加固覆盖空路径拒绝、`..` 遍历检测、fd 复用消除 TOCTOU、特殊文件拒绝、10MB 上限 + `take(MAX+1)` 双保险、错误不泄露完整路径,但不对绝对路径做白名单,调用方需自行确保路径可信。
    pub fn load(toml_path: Option<&str>) -> GarrisonResult<Self> {
        Self::load_with_deprecations(
            toml_path,
            deprecation::deprecations(),
            env!("CARGO_PKG_VERSION"),
        )
    }

    /// [`load`](Self::load) 的可注入变体:注册表与当前版本参数化。
    ///
    /// 生产路径经 `load()`(生产注册表 + 编译期版本号);测试注入 fixture
    /// 注册表与版本字符串以驱动两种 1.0 门分支。
    pub(super) fn load_with_deprecations(
        toml_path: Option<&str>,
        registry: &[deprecation::Deprecation],
        current_version: &'static str,
    ) -> GarrisonResult<Self> {
        // 环境变量注入:separator("__") 仅双下划线折叠为嵌套路径(单下划线保留,兼容扁平 key 模型);
        // excluded_keys 留给 build 后的显式覆盖逻辑(CORS 逗号列表、Redis 枚举无法直接反序列化),优先级最高
        let env_source = {
            let s = confers::config::EnvSource::with_prefix(ENV_PREFIX).separator("__");
            #[cfg(feature = "rate-limit-redis")]
            let s = s.exclude_keys(["rate_limit_backend"]);
            #[cfg(feature = "web-cors")]
            let s = s.exclude_keys(["cors_allowed_origins"]);
            s
        };

        let mut builder = ConfigBuilder::<Self>::new()
            .default("token_name", ConfigValue::string(DEFAULT_TOKEN_NAME))
            .default("timeout", ConfigValue::integer(DEFAULT_TIMEOUT))
            .default(
                "active_timeout",
                ConfigValue::integer(DEFAULT_ACTIVE_TIMEOUT),
            )
            .default("is_read_cookie", ConfigValue::bool(true))
            .default("is_read_header", ConfigValue::bool(true))
            .default("is_read_body", ConfigValue::bool(DEFAULT_IS_READ_BODY))
            .default("is_write_header", ConfigValue::bool(true))
            .default("is_write_cookie", ConfigValue::bool(false))
            .default("token_style", ConfigValue::string("uuid"))
            .default("throw_on_not_login", ConfigValue::bool(true))
            .default("cookie_secure", ConfigValue::bool(DEFAULT_COOKIE_SECURE))
            .default(
                "cookie_same_site",
                ConfigValue::string(DEFAULT_COOKIE_SAME_SITE),
            )
            .default("jwt_algorithm", ConfigValue::string(DEFAULT_JWT_ALGORITHM))
            .default("jwt_secret", ConfigValue::string(""))
            .default(
                "sign_window_seconds",
                ConfigValue::integer(DEFAULT_SIGN_WINDOW_SECONDS),
            )
            .default(
                "sso_ticket_ttl_seconds",
                ConfigValue::uint(DEFAULT_SSO_TICKET_TTL_SECONDS),
            )
            .default(
                "jwks_retention_secs",
                ConfigValue::uint(DEFAULT_JWKS_RETENTION_SECS),
            )
            .default("remember_me_enabled", ConfigValue::bool(false))
            .default(
                "remember_me_timeout",
                ConfigValue::integer(REMEMBER_ME_DEFAULT_TIMEOUT),
            )
            .default("seed_primary_amr", ConfigValue::bool(true))
            .default(
                "login_id_max_len",
                ConfigValue::uint(DEFAULT_LOGIN_ID_MAX_LEN as u64),
            )
            .default(
                "session_hover_timeout",
                ConfigValue::integer(DEFAULT_SESSION_HOVER_TIMEOUT),
            )
            .default(
                "frontend_separation",
                ConfigValue::bool(DEFAULT_FRONTEND_SEPARATION),
            )
            .default(
                "auto_renewal_threshold",
                ConfigValue::integer(DEFAULT_AUTO_RENEWAL_THRESHOLD),
            )
            .default(
                "token_map_cleanup_interval_secs",
                ConfigValue::integer(DEFAULT_TOKEN_MAP_CLEANUP_INTERVAL),
            )
            .default("is_concurrent", ConfigValue::bool(DEFAULT_IS_CONCURRENT))
            .default("is_share", ConfigValue::bool(DEFAULT_IS_SHARE))
            .default(
                "max_login_count",
                ConfigValue::uint(DEFAULT_MAX_LOGIN_COUNT as u64),
            )
            .default(
                "device_binding_mode",
                ConfigValue::string(DEFAULT_DEVICE_BINDING_MODE),
            )
            .default(
                "replaced_login_exit_mode",
                ConfigValue::string(DEFAULT_REPLACED_LOGIN_EXIT_MODE),
            )
            .default(
                "overflow_logout_mode",
                ConfigValue::string(DEFAULT_OVERFLOW_LOGOUT_MODE),
            )
            .default("audit_mask_mode", ConfigValue::string("partial"))
            .default(
                "recent_reuse_behaviour",
                ConfigValue::string(DEFAULT_RECENT_REUSE_BEHAVIOUR),
            )
            .default(
                "refresh_grace_period_secs",
                ConfigValue::integer(DEFAULT_REFRESH_GRACE_PERIOD_SECS),
            )
            .default(
                "refresh_grace_max_uses",
                ConfigValue::uint(DEFAULT_REFRESH_GRACE_MAX_USES as u64),
            )
            .default("require_tenant_bound_jwt", ConfigValue::bool(false))
            .default("require_session_tenant_binding", ConfigValue::bool(false));

        #[cfg(feature = "session-extra")]
        {
            builder = Self::apply_session_extra_defaults(builder);
        }

        #[cfg(feature = "three-tier-cache")]
        {
            builder = Self::apply_three_tier_cache_defaults(builder);
        }

        #[cfg(feature = "sms-rate-limit")]
        {
            builder = Self::apply_sms_rate_limit_defaults(builder);
        }

        #[cfg(feature = "email-verification")]
        {
            builder = Self::apply_email_verification_defaults(builder);
        }

        #[cfg(feature = "anomalous-detector-dual")]
        {
            builder = Self::apply_anomalous_defaults(builder);
        }

        if let Some(path) = toml_path {
            // 文件加载经 confers FileSource(路径/symlink/特殊文件/大小防护见 confers_file_source);空路径前置拒绝,避免下游 canonicalize 的含糊错误
            const MAX_CONFIG_FILE_SIZE: usize = 10 * 1024 * 1024; // 10MB
            if path.is_empty() {
                return Err(GarrisonError::Config(loc!("config-path-empty", "")));
            }
            let file_source = confers_file_source(path, MAX_CONFIG_FILE_SIZE);
            builder = builder.source(Box::new(file_source));
        }

        builder = builder.source(Box::new(env_source));

        // 弃用键迁移挂在合并树反序列化前(env/toml 解析后、validate 前),保证迁移值进入反序列化并通过校验;
        // 闭包无法向上传播错误:硬错误(≥1.0.0 / map_fn 失败 / 版本不可解析)收集到槽位,build 后统一转为 GarrisonError::Config
        let deprecation_failures: std::sync::Arc<std::sync::Mutex<Vec<String>>> =
            std::sync::Arc::default();
        let failure_slot = std::sync::Arc::clone(&deprecation_failures);
        let registry: Vec<deprecation::Deprecation> = registry.to_vec();
        // 新键默认值对照:区分"默认值填充"与"用户显式配置"(序列化一次默认配置)
        let new_key_defaults =
            serde_json::to_value(Self::default_config()).unwrap_or(serde_json::Value::Null);
        builder = builder.map_json(move |tree| {
            if let Err(msgs) =
                deprecation::apply_deprecations(tree, &registry, current_version, &new_key_defaults)
            {
                *failure_slot.lock().unwrap_or_else(|e| {
                    panic!(
                        "{}: {e}",
                        crate::i18n::translate_detail("config-deprecation-slot-lock-poisoned", &[],)
                    )
                }) = msgs;
            }
        });

        let config = builder.build().map_err(map_confers_build_error)?;

        // 弃用键硬错误在 validate() 之前显性拦截(错误含键名与迁移指引)。
        let failures = deprecation_failures
            .lock()
            .unwrap_or_else(|e| {
                panic!(
                    "{}: {e}",
                    crate::i18n::translate_detail("config-deprecation-slot-lock-poisoned", &[],)
                )
            })
            .clone();
        if !failures.is_empty() {
            return Err(GarrisonError::Config(failures.join("; ")));
        }

        // 显式环境变量覆盖必须在 with_watcher() 前完成:watch channel 初值取自 with_watcher() 时的快照,
        // 先建 watcher 再覆盖会让订阅者先收到旧配置、update() 从旧值起步
        #[cfg_attr(
            not(any(
                feature = "web-cors",
                feature = "web-csrf",
                feature = "rate-limit-redis"
            )),
            allow(unused_mut)
        )]
        let mut config = config;

        // confers 通用收集无法处理枚举结构变体,CORS/CSRF/RateLimit 的环境变量由显式逻辑覆盖,优先级最高。
        #[cfg(feature = "web-cors")]
        apply_web_cors_env_override(&mut config);
        #[cfg(feature = "web-csrf")]
        apply_web_csrf_env_override(&mut config)?;
        #[cfg(feature = "rate-limit-redis")]
        apply_rate_limit_env_override(&mut config)?;

        // watcher 在覆盖完成后附加,保证 watch channel 初值即最终生效配置
        let config = config.with_watcher();

        config.validate()?;
        Ok(config)
    }

    /// 为配置实例附加 watcher(创建 watch channel)。
    ///
    /// 反序列化后的 `GarrisonConfig` 没有 watcher,调用此方法启用 `watch()` 与 `update()`。
    pub fn with_watcher(mut self) -> Self {
        if self.watcher.is_none() {
            let (tx, _rx) = watch::channel(self.clone_for_watcher());
            self.watcher = Some(tx);
        }
        self
    }

    /// 克隆实例但不复制 watcher(用于 watcher 初始化时避免递归)。
    fn clone_for_watcher(&self) -> Self {
        let mut c = self.clone();
        c.watcher = None;
        c
    }

    /// 校验配置字段合法性:依次执行 core(token_style/timeout/cookie_same_site/password_hasher)、mfa、jwt_secret、session_config、device_binding、refresh_grace、feature_gated、security_rules 分组校验;失败返回 `GarrisonError::Config`。
    pub fn validate(&self) -> GarrisonResult<()> {
        self.validate_core()?;
        self.validate_mfa()?;
        self.validate_jwt_secret()?;
        self.validate_session_config()?;
        self.validate_device_binding()?;
        self.validate_refresh_grace()?;
        self.validate_feature_gated()?;
        // 两个 cfg 互斥定义(rate-limit-redis 启用/未启用)恰存其一,无条件调用
        self.warn_memory_rate_limit_backend();
        // 安全规则集汇总校验点(feature 关闭时零行为变化)
        #[cfg(feature = "config-security-rules")]
        self.validate_security_rules()?;
        Ok(())
    }

    /// Memory 限流后端部署警示:进程内计数使多实例实际限额 = 配置值 × 实例数,仅 warn 提示切换 Redis(单实例/本地开发合法,不强制失败);未启用 rate-limit-redis 的默认构建同样输出。
    #[cfg(not(feature = "rate-limit-redis"))]
    fn warn_memory_rate_limit_backend(&self) {
        tracing::warn!(
            backend = "memory",
            "{}",
            crate::i18n::translate_detail("logs-config-rate-limit-redis-feature-disabled", &[])
        );
    }

    #[cfg(feature = "rate-limit-redis")]
    fn warn_memory_rate_limit_backend(&self) {
        if self.rate_limit_backend
            == crate::strategy::rate_limiter_backend::RateLimitBackend::Memory
        {
            tracing::warn!(
                backend = "memory",
                "{}",
                crate::i18n::translate_detail("logs-config-rate-limit-memory-backend", &[])
            );
        }
    }

    /// Refresh token 宽限窗口参数校验(fail-closed):`refresh_grace_period_secs < 0` 无语义拒绝误配;`refresh_grace_max_uses < 1` 使窗口形同虚设且与窗口内返回既有 token 语义矛盾,要求 ≥ 1(关闭窗口应置 `period_secs = 0`)。
    fn validate_refresh_grace(&self) -> GarrisonResult<()> {
        if self.refresh_grace_period_secs < 0 {
            return Err(GarrisonError::Config(format!(
                "config-refresh-grace-period-negative::{}",
                self.refresh_grace_period_secs
            )));
        }
        if self.refresh_grace_max_uses < 1 {
            return Err(GarrisonError::Config(format!(
                "config-refresh-grace-max-uses-zero::{}",
                self.refresh_grace_max_uses
            )));
        }
        Ok(())
    }

    /// 核心字段校验:`token_style` / `timeout` / `cookie_same_site` / `jwt_algorithm`。
    fn validate_core(&self) -> GarrisonResult<()> {
        if !TOKEN_STYLES.contains(&self.token_style.as_str()) {
            return Err(GarrisonError::Config(format!(
                "config-unknown-token-style::{}",
                self.token_style
            )));
        }
        if self.timeout <= 0 {
            return Err(GarrisonError::Config(
                "config-timeout-must-positive::".to_string(),
            ));
        }
        if !COOKIE_SAME_SITE_VALUES.contains(&self.cookie_same_site.as_str()) {
            return Err(GarrisonError::Config(format!(
                "config-unknown-cookie-same-site::{}",
                self.cookie_same_site
            )));
        }
        // jwt_algorithm 白名单统一校验(不限 token_style=jwt),防非法算法在非 JWT 模式静默通过
        if !JWT_ALGORITHMS.contains(&self.jwt_algorithm.as_str()) {
            // 复用既有 locale 键 config-jwt-algorithm-unsupported(en/zh 均有翻译),不新造未翻译键
            return Err(GarrisonError::Config(format!(
                "config-jwt-algorithm-unsupported::{}",
                self.jwt_algorithm
            )));
        }
        // 非对称算法-密钥类型匹配(fail-closed):禁止同时配置多类私钥 PEM(防配置歧义);非对称算法必须配套同类型私钥;HS 系禁止配置非对称私钥
        let rsa_set = self.jwt_rsa_private_key_pem.is_some();
        let ec_set = self.jwt_ec_private_key_pem.is_some();
        let ed_set = self.jwt_ed_private_key_pem.is_some();
        let configured_keys = rsa_set as u8 + ec_set as u8 + ed_set as u8;
        if configured_keys > 1 {
            return Err(GarrisonError::Config(
                "config-jwt-key-multiple-types::".to_string(),
            ));
        }
        let is_asymmetric = matches!(self.jwt_algorithm.as_str(), "RS256" | "ES256" | "EdDSA");
        let required_key_present = match self.jwt_algorithm.as_str() {
            "RS256" => rsa_set,
            "ES256" => ec_set,
            "EdDSA" => ed_set,
            _ => true,
        };
        if !required_key_present {
            return Err(GarrisonError::Config(format!(
                "config-jwt-key-missing::{}",
                self.jwt_algorithm
            )));
        }
        if !is_asymmetric && configured_keys > 0 {
            return Err(GarrisonError::Config(format!(
                "config-jwt-key-unexpected-for-hs::{}",
                self.jwt_algorithm
            )));
        }
        // 密码哈希参数校验(fail-closed):默认即 OWASP 建议档,仅防配置弱化(Argon2id m_cost 低于下限须显式风险接受,bcrypt cost ∈ [10, 15])
        self.validate_password_hasher()?;
        // JWKS 保留时长 0 = 轮换瞬间退役旧钥(存量 token 验证立即中断,违背 Passive 保留语义),误配 fail-fast
        if self.jwks_retention_secs == 0 {
            return Err(GarrisonError::Config(
                "config-jwks-retention-must-positive::".to_string(),
            ));
        }
        Ok(())
    }

    /// `mfa` 配置段校验:chain factor 词汇表 fail-closed(启动期拒绝)。
    fn validate_mfa(&self) -> GarrisonResult<()> {
        crate::stp::mfa::validate_mfa_chains(&self.mfa.global_chain, &self.mfa.per_client_chains)
    }

    /// `password_hasher` 配置段校验(见 `PasswordHasherConfig` 文档)。
    fn validate_password_hasher(&self) -> GarrisonResult<()> {
        let ph = &self.password_hasher;
        if !PASSWORD_HASH_ALGORITHMS.contains(&ph.algorithm.as_str()) {
            return Err(GarrisonError::Config(format!(
                "config-password-hash-algorithm-unsupported::{}",
                ph.algorithm
            )));
        }
        if ph.algorithm == "argon2id" {
            ph.validate_argon2_params()
        } else {
            ph.validate_bcrypt_cost()
        }
    }

    /// JWT 密钥强度校验(jwt/simple 两种消费密钥的风格均做弱密钥黑名单校验,见 [`Self::reject_weak_jwt_secret`])。
    ///
    /// `jwt`:非对称算法(RS256/ES256/EdDSA)强度由 PEM 决定(jwt_secret 可留空占位),HS 系按 RFC 7518 最小长度硬校验;`simple`:jwt_secret 即 HMAC-SHA256 密钥可离线爆破,短于 32B 硬错误;`uuid`/`random_64` 等不透明风格不消费 jwt_secret,不要求配置。
    /// `pub(super)`:`config-security-rules` 规则集模块复用同一规则。
    pub(super) fn validate_jwt_secret(&self) -> GarrisonResult<()> {
        if self.token_style == "jwt" {
            // 非对称算法强度由 PEM 决定(JwtHandler 构造期校验),jwt_secret 可留空占位,跳过对称密钥长度校验
            if matches!(self.jwt_algorithm.as_str(), "RS256" | "ES256" | "EdDSA") {
                return Ok(());
            }
            self.validate_hs_secret_min_len()?;
            return self.reject_weak_jwt_secret();
        }
        if self.token_style == "simple" {
            let secret_len = self.jwt_secret.as_str().len();
            if secret_len < 32 {
                return Err(GarrisonError::Config(format!(
                    "config-jwt-secret-too-short::simple (min 32 bytes)::{}",
                    secret_len
                )));
            }
            return self.reject_weak_jwt_secret();
        }
        Ok(())
    }

    /// 常见弱密钥黑名单(吸收 confers `security-rules` WEAK_SECRETS 16 条,落地为自有规则)。
    const WEAK_JWT_SECRETS: &[&str] = &[
        "secret",
        "changeme",
        "change_me",
        "password",
        "test",
        "test123",
        "key",
        "default",
        "admin",
        "letmein",
        "welcome",
        "qwerty",
        "abc123",
        "123456",
        "12345678",
        "1234567890",
    ];

    /// 弱密钥黑名单校验(fail-closed):剥除首尾填充字符(`_`/`-`/`.` 等)后整串比对、忽略大小写("changeme"+填充变体同样命中);不做子串匹配(高熵密钥尾部含弱串不误伤)。
    fn reject_weak_jwt_secret(&self) -> GarrisonResult<()> {
        const PADDING_CHARS: &[char] = &[' ', '\t', '_', '-', '.', '=', '*', '~'];
        let normalized = self
            .jwt_secret
            .as_str()
            .trim_matches(PADDING_CHARS)
            .to_lowercase();
        if Self::WEAK_JWT_SECRETS.contains(&normalized.as_str()) {
            return Err(GarrisonError::Config(
                "config-jwt-secret-weak::blacklist hit (padded/case variants included)".to_string(),
            ));
        }
        Ok(())
    }

    /// HS 系对称密钥长度校验(RFC 7518 §3.2:HS256/HS384/HS512 → 32/48/64 字节)。
    fn validate_hs_secret_min_len(&self) -> GarrisonResult<()> {
        let secret_len = self.jwt_secret.as_str().len();
        if secret_len == 0 {
            return Err(GarrisonError::Config(
                "config-jwt-secret-empty::".to_string(),
            ));
        }
        let min_len = match self.jwt_algorithm.as_str() {
            "HS256" => 32,
            "HS384" => 48,
            "HS512" => 64,
            // 非对称算法强度由 PEM 私钥位长/曲线阶决定(RS256 ≥2048 位在 JwtHandler 构造期精确校验),不做 HMAC 长度校验
            "RS256" | "ES256" | "EdDSA" => 0,
            other => return Err(unsupported_jwt_algorithm(other)),
        };
        if secret_len < min_len {
            return Err(GarrisonError::Config(format!(
                "config-jwt-secret-too-short::{} (min {} bytes)::{}",
                self.jwt_algorithm, min_len, secret_len
            )));
        }
        Ok(())
    }

    /// 会话配置一致性校验:`remember_me` / `auto_renewal` / `is_share` / `frontend_separation`。
    fn validate_session_config(&self) -> GarrisonResult<()> {
        if self.remember_me_enabled && self.remember_me_timeout <= self.timeout {
            return Err(GarrisonError::Config(format!(
                "config-remember-me-timeout-mismatch::{}::{}",
                self.remember_me_timeout, self.timeout
            )));
        }
        if !self.remember_me_enabled && self.remember_me_timeout <= 0 {
            return Err(GarrisonError::Config(format!(
                "config-remember-me-timeout-positive::{}",
                self.remember_me_timeout
            )));
        }
        if self.frontend_separation {
            tracing::info!(
                "frontend separation mode enabled: token read from Authorization header, no cookie set"
            );
        }
        if self.auto_renewal_threshold != -1 && !(0..=100).contains(&self.auto_renewal_threshold) {
            return Err(GarrisonError::Config(format!(
                "config-auto-renewal-threshold-invalid::{}",
                self.auto_renewal_threshold
            )));
        }
        if self.is_share && !self.is_concurrent {
            return Err(GarrisonError::Config(
                "config-is-share-requires-concurrent::".to_string(),
            ));
        }
        // session_hover_timeout 上界 10 年(315_360_000 秒,防配置层超大值误用);合法值 -1(禁用)或 (0, 上界]
        const MAX_SESSION_HOVER_TIMEOUT_SECS: i64 = 315_360_000;
        if self.session_hover_timeout > MAX_SESSION_HOVER_TIMEOUT_SECS {
            return Err(GarrisonError::Config(format!(
                "config-session-hover-timeout-exceeds::{}::{}",
                self.session_hover_timeout, MAX_SESSION_HOVER_TIMEOUT_SECS
            )));
        }
        Ok(())
    }

    /// 设备绑定模式校验。
    fn validate_device_binding(&self) -> GarrisonResult<()> {
        if !DEVICE_BINDING_MODES.contains(&self.device_binding_mode.as_str()) {
            return Err(GarrisonError::Config(format!(
                "config-unknown-device-binding-mode::{}",
                self.device_binding_mode
            )));
        }
        Ok(())
    }

    /// feature-gated 校验:各 feature 的规则拆分为独立小函数(守卫条款风格,规则单点维护)。
    fn validate_feature_gated(&self) -> GarrisonResult<()> {
        #[cfg(feature = "session-extra")]
        self.validate_anon_session()?;
        #[cfg(feature = "three-tier-cache")]
        self.validate_three_tier_cache()?;
        #[cfg(feature = "rate-limit-redis")]
        self.validate_rate_limit_redis()?;
        #[cfg(feature = "firewall-waf")]
        self.validate_firewall_waf()?;
        #[cfg(feature = "sms-rate-limit")]
        self.validate_sms_rate_limit()?;
        #[cfg(feature = "email-verification")]
        self.validate_email_verification()?;
        #[cfg(feature = "anomalous-detector-dual")]
        self.validate_anomalous_detector()?;
        // CORS credentials 与 wildcard origin 冲突校验(生产路径)
        #[cfg(feature = "web-cors")]
        crate::web::cors::CorsConfig::validate(&self.cors_config)?;
        Ok(())
    }

    /// `session-extra` 默认值注入(login token map 持久化间隔 + 匿名会话超时)。
    #[cfg(feature = "session-extra")]
    fn apply_session_extra_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
        builder
            .default(
                "login_token_map_persist_interval_secs",
                ConfigValue::uint(DEFAULT_LOGIN_TOKEN_MAP_PERSIST_INTERVAL_SECS),
            )
            .default(
                "anon_session_timeout",
                ConfigValue::uint(DEFAULT_ANON_SESSION_TIMEOUT_SECS),
            )
    }

    /// `three-tier-cache` 默认值注入(L1/L2 TTL 与 L1 容量)。
    #[cfg(feature = "three-tier-cache")]
    fn apply_three_tier_cache_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
        builder
            .default(
                "l1_cache_ttl_secs",
                ConfigValue::uint(DEFAULT_L1_CACHE_TTL_SECS),
            )
            .default(
                "l2_cache_ttl_secs",
                ConfigValue::uint(DEFAULT_L2_CACHE_TTL_SECS),
            )
            .default(
                "l1_cache_capacity",
                ConfigValue::uint(DEFAULT_L1_CACHE_CAPACITY),
            )
    }

    /// `sms-rate-limit` 默认值注入。
    #[cfg(feature = "sms-rate-limit")]
    fn apply_sms_rate_limit_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
        builder
            .default("sms_hourly_limit", ConfigValue::uint(5))
            .default("sms_daily_limit", ConfigValue::uint(10))
            .default("sms_verify_max_attempts", ConfigValue::uint(3))
            .default("sms_unverified_threshold", ConfigValue::uint(3))
    }

    /// `email-verification` 默认值注入。
    #[cfg(feature = "email-verification")]
    fn apply_email_verification_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
        builder
            .default("email_hourly_limit", ConfigValue::uint(5))
            .default("email_daily_limit", ConfigValue::uint(10))
            .default("email_verify_max_attempts", ConfigValue::uint(3))
            .default("email_unverified_threshold", ConfigValue::uint(3))
            .default("email_code_ttl", ConfigValue::uint(600))
    }

    /// `anomalous-detector-dual` 默认值注入。
    #[cfg(feature = "anomalous-detector-dual")]
    fn apply_anomalous_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
        builder
            .default(
                "anomalous_analyzer_interval_secs",
                ConfigValue::uint(DEFAULT_ANOMALOUS_ANALYZER_INTERVAL_SECS),
            )
            .default(
                "anomalous_analyzer_burst_threshold",
                ConfigValue::uint(DEFAULT_ANOMALOUS_BURST_THRESHOLD.into()),
            )
    }

    /// `session-extra`:匿名会话超时必须非零。
    #[cfg(feature = "session-extra")]
    fn validate_anon_session(&self) -> GarrisonResult<()> {
        if self.anon_session_timeout == 0 {
            return Err(GarrisonError::Config(
                "config-anon-timeout-invalid::".to_string(),
            ));
        }
        Ok(())
    }

    /// `three-tier-cache`:三级缓存 TTL 与容量必须非零。
    #[cfg(feature = "three-tier-cache")]
    fn validate_three_tier_cache(&self) -> GarrisonResult<()> {
        if self.l1_cache_ttl_secs == 0 {
            return Err(GarrisonError::Config("config-l1-ttl-invalid".to_string()));
        }
        if self.l2_cache_ttl_secs == 0 {
            return Err(GarrisonError::Config("config-l2-ttl-invalid".to_string()));
        }
        if self.l1_cache_capacity == 0 {
            return Err(GarrisonError::Config(
                "config-l1-capacity-invalid".to_string(),
            ));
        }
        Ok(())
    }

    /// `rate-limit-redis`:Redis 后端必须配置非空 URL。
    #[cfg(feature = "rate-limit-redis")]
    fn validate_rate_limit_redis(&self) -> GarrisonResult<()> {
        let redis_url = match &self.rate_limit_backend {
            RateLimitBackend::Redis { redis_url } => redis_url,
            _ => return Ok(()),
        };
        if !redis_url.is_empty() {
            return Ok(());
        }
        Err(GarrisonError::Config(
            "config-redis-url-empty::".to_string(),
        ))
    }

    /// `firewall-waf`:允许的 HTTP 方法必须为大写规范形式。
    #[cfg(feature = "firewall-waf")]
    fn validate_firewall_waf(&self) -> GarrisonResult<()> {
        for method in &self.waf_allowed_methods {
            if method == &method.to_uppercase() {
                continue;
            }
            return Err(GarrisonError::Config(format!(
                "config-waf-method-case::{}",
                method
            )));
        }
        Ok(())
    }

    /// `sms-rate-limit`:短信限流阈值一致性(日限额 ≥ 时期限额 > 0,验证尝试/阈值 > 0)。
    #[cfg(feature = "sms-rate-limit")]
    fn validate_sms_rate_limit(&self) -> GarrisonResult<()> {
        if self.sms_hourly_limit == 0 {
            return Err(GarrisonError::Config(
                "config-sms-hourly-invalid::".to_string(),
            ));
        }
        if self.sms_daily_limit < self.sms_hourly_limit {
            return Err(GarrisonError::Config(
                "config-sms-daily-invalid::".to_string(),
            ));
        }
        if self.sms_verify_max_attempts == 0 {
            return Err(GarrisonError::Config(
                "config-sms-max-attempts-invalid::".to_string(),
            ));
        }
        if self.sms_unverified_threshold == 0 {
            return Err(GarrisonError::Config(
                "config-sms-threshold-invalid::".to_string(),
            ));
        }
        Ok(())
    }

    /// `email-verification`:邮件验证阈值一致性(同短信模型 + TTL 非零)。
    #[cfg(feature = "email-verification")]
    fn validate_email_verification(&self) -> GarrisonResult<()> {
        if self.email_hourly_limit == 0 {
            return Err(GarrisonError::Config(
                "config-email-hourly-invalid::".to_string(),
            ));
        }
        if self.email_daily_limit < self.email_hourly_limit {
            return Err(GarrisonError::Config(
                "config-email-daily-invalid::".to_string(),
            ));
        }
        if self.email_verify_max_attempts == 0 {
            return Err(GarrisonError::Config(
                "config-email-max-attempts-invalid::".to_string(),
            ));
        }
        if self.email_unverified_threshold == 0 {
            return Err(GarrisonError::Config(
                "config-email-threshold-invalid::".to_string(),
            ));
        }
        if self.email_code_ttl == 0 {
            return Err(GarrisonError::Config(
                "config-email-ttl-invalid::".to_string(),
            ));
        }
        Ok(())
    }

    /// `anomalous-detector-dual`:分析周期 ≥60s、突发阈值非零。
    #[cfg(feature = "anomalous-detector-dual")]
    fn validate_anomalous_detector(&self) -> GarrisonResult<()> {
        if self.anomalous_analyzer_interval_secs < 60 {
            return Err(GarrisonError::Config(
                "config-anomalous-interval-invalid::".to_string(),
            ));
        }
        if self.anomalous_analyzer_burst_threshold == 0 {
            return Err(GarrisonError::Config(
                "config-anomalous-burst-invalid::".to_string(),
            ));
        }
        Ok(())
    }

    /// 订阅配置变更:返回 `watch::Receiver<GarrisonConfig>`(`borrow_and_update()` 取最新配置);实例未调用 `with_watcher()` 时返回 `None`。
    pub fn watch(&self) -> Option<watch::Receiver<GarrisonConfig>> {
        self.watcher.as_ref().map(|tx| tx.subscribe())
    }

    /// 闭包式更新配置并广播变更;未启用 watcher 时 no-op 返回 `Ok(())`。
    ///
    /// ```ignore
    /// config.update(|c| c.timeout = 3600)?;
    /// ```
    ///
    /// 流程:读取当前配置 → 应用闭包 → `validate()`(失败返回 `Config`)→ 广播给订阅者;watcher 已关闭时返回 `Config("config watcher closed")`。
    pub fn update<F: FnOnce(&mut GarrisonConfig)>(&self, f: F) -> GarrisonResult<()> {
        let Some(sender) = &self.watcher else {
            return Ok(());
        };
        let mut new_config = sender.borrow().clone();
        f(&mut new_config);
        new_config.validate()?;
        sender
            .send(new_config)
            .map_err(|_| GarrisonError::Config("config watcher closed".to_string()))?;
        Ok(())
    }
}

impl Default for GarrisonConfig {
    fn default() -> Self {
        Self::default_config()
    }
}

/// `web-cors` 显式环境变量覆盖:`GARRISON_CORS_ALLOWED_ORIGINS`(逗号分隔列表)。
#[cfg(feature = "web-cors")]
fn apply_web_cors_env_override(config: &mut GarrisonConfig) {
    let Ok(val) = std::env::var("GARRISON_CORS_ALLOWED_ORIGINS") else {
        return;
    };
    config.cors_config.allowed_origins = val
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
}

/// `web-csrf` 显式环境变量覆盖:`GARRISON_CSRF_ENABLED` 仅接受 "true"/"false"(大小写不敏感),其余值返回配置错误(fail-closed:安全控制不允许歧义取值,"1"/"yes"/"on" 等 truthy 习惯值不得静默禁用 CSRF 防护)。
#[cfg(feature = "web-csrf")]
fn apply_web_csrf_env_override(config: &mut GarrisonConfig) -> GarrisonResult<()> {
    let Ok(val) = std::env::var("GARRISON_CSRF_ENABLED") else {
        return Ok(());
    };
    match val.to_lowercase().as_str() {
        "true" => config.csrf_config.enabled = true,
        "false" => config.csrf_config.enabled = false,
        // 错误消息保留用户原始输入,便于定位误配源
        _ => {
            return Err(GarrisonError::Config(format!(
                "config-csrf-enabled-unsupported::{} (allowed: true/false, case-insensitive)",
                val
            )));
        },
    }
    Ok(())
}

/// 解析 `GARRISON_RATE_LIMIT_BACKEND` 环境变量为后端选择(`rate-limit-redis` 面公开):
/// 未设置返回 `None`;`memory` / `redis` 返回对应后端(`redis` 的 URL 取 `GARRISON_REDIS_URL`,
/// 缺省空串由 `validate_rate_limit_redis` 拒绝);未知值返回配置错误(fail-closed)。
/// 库内 `apply_rate_limit_env_override` 与参考部署 bin(auth_server 启动期 fail-closed 校验)
/// 共用本单点解析,避免判定副本漂移。
#[cfg(feature = "rate-limit-redis")]
pub fn parse_rate_limit_backend_env() -> GarrisonResult<Option<RateLimitBackend>> {
    let Ok(val) = std::env::var("GARRISON_RATE_LIMIT_BACKEND") else {
        return Ok(None);
    };
    match val.to_lowercase().as_str() {
        "memory" => Ok(Some(RateLimitBackend::Memory)),
        "redis" => {
            let redis_url = std::env::var("GARRISON_REDIS_URL").unwrap_or_default();
            Ok(Some(RateLimitBackend::Redis { redis_url }))
        },
        _ => Err(GarrisonError::Config(format!(
            "config-rate-limit-backend-unsupported::{}",
            val
        ))),
    }
}

/// `rate-limit-redis` 显式环境变量覆盖:`GARRISON_RATE_LIMIT_BACKEND` + `GARRISON_REDIS_URL`;未知 backend 值返回配置错误(fail-closed)。
#[cfg(feature = "rate-limit-redis")]
fn apply_rate_limit_env_override(config: &mut GarrisonConfig) -> GarrisonResult<()> {
    if let Some(backend) = parse_rate_limit_backend_env()? {
        config.rate_limit_backend = backend;
    }
    Ok(())
}

/// 构造 confers FileSource(TOML 文件安全加载配置单点维护):路径遍历/symlink 防护、特殊文件拒绝、10MB 上限 + take 双保险、错误路径脱敏。
///
/// 显式钉 `Format::Toml`:confers 0.6.0-rc.6 起扩展名白名单门先于路径校验执行,显式 format 是其文档化豁免通道——钉死后安全校验次序恢复(校验先于解析),代价是其他扩展名一律按 TOML 解析(fail-closed,文件配置承诺格式即 TOML)。
/// 钉定内嵌在 `LoaderConfig` 链上而非 `FileSource::with_format`(后者与 `with_loader_config` 存在整体替换的顺序耦合,先设会被抹掉)。
fn confers_file_source(path: &str, max_size: usize) -> confers::config::FileSource {
    confers::config::FileSource::new(path)
        .with_priority(10)
        .with_loader_config(
            confers::loader::LoaderConfig::new()
                .allow_absolute()
                .max_size(max_size)
                .redact_error_paths()
                .with_format(confers::loader::Format::Toml),
        )
}

/// 将 confers `ConfigError` 映射为 i18n 化的 `GarrisonError::Config`:`FileNotFound` → `config-open-failed`,`SizeLimitExceeded` → `config-too-large`,其余(解析失败、路径遍历拒绝等)→ 泛化 `config-confers-build-failed`(confers 已启用 `redact_error_paths`,错误不含服务端文件系统结构)。
fn map_confers_build_error(e: confers::ConfigError) -> GarrisonError {
    use confers::ConfigError as CE;
    match e {
        CE::FileNotFound { filename, .. } => {
            let name = filename.display().to_string();
            GarrisonError::Config(loc!("config-open-failed", "", ("arg0", name.as_str())))
        },
        CE::SizeLimitExceeded { actual, limit } => {
            let actual_str = actual.to_string();
            let limit_str = limit.to_string();
            GarrisonError::Config(loc!(
                "config-too-large",
                "",
                ("arg0", "config"),
                ("arg1", actual_str.as_str()),
                ("arg2", limit_str.as_str())
            ))
        },
        other => GarrisonError::Config(format!("config-confers-build-failed::{}", other)),
    }
}

/// 非对称白名单外算法的统一配置错误。
fn unsupported_jwt_algorithm(alg: &str) -> GarrisonError {
    GarrisonError::Config(format!("config-jwt-algorithm-unsupported::{alg}"))
}