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

//! PasswordLogic trait — 密码登录契约。
//! super-trait 为 [`SessionLogic`](校验通过后调用 [`login`](SessionLogic::login) 签发 token);`login_id` 参数为 `&str`(对象安全)。

use super::GarrisonLogicDefault;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use super::LoginParams;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::account::credential::password::{verify_and_rehash_pooled, verify_pooled};
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::constants::EventReason;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::dao::repository::UpdateUser;
#[cfg(feature = "firewall-bruteforce")]
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
#[cfg(all(
    feature = "listener",
    feature = "account-credential",
    feature = "db-sqlite"
))]
use crate::listener::GarrisonEvent;
use crate::stp::session::SessionLogic;
use async_trait::async_trait;
#[cfg(feature = "firewall-bruteforce")]
use std::sync::Arc;

/// 密码逻辑 trait,定义密码登录契约。
/// 默认返回 `NotImplemented`,`GarrisonLogicDefault` 覆写为:查用户 → 校验密码(verify 通过且档位低于配置时惰性重哈希落库并广播 `GarrisonEvent::PasswordRehashed`,需 `listener` feature)→ [`SessionLogic::login`] 签发 token。
/// 安全约束:用户不存在与密码错误统一返回 `InvalidParam("stp-invalid-password")`,日志和事件 reason 统一 "invalid_credentials",防止用户枚举。
#[async_trait]
pub trait PasswordLogic: SessionLogic {
    /// 密码登录:校验密码后签发 token。
    /// 未启用 `account-credential` + `db-sqlite` 返回 `NotImplemented`;未注入 hasher/repo 返回 `Config`;用户不存在 / 密码错误 / 哈希格式不支持统一 `InvalidParam("stp-invalid-password")`(不泄露原因);DAO 失败透传 `Dao`。
    async fn login_with_password(
        &self,
        _login_id: &str,
        _password: &str,
    ) -> GarrisonResult<String> {
        Err(GarrisonError::NotImplemented(format!(
            "stp-not-implemented::{}",
            "login_with_password"
        )))
    }
}

// GarrisonLogicDefault impl

/// dummy Argon2id 哈希,模块级惰性生成一次,参数与 [`Argon2Hasher`](crate::account::credential::password::Argon2Hasher) 默认一致(Argon2id, m=19456, t=2, p=1)。
/// 「用户不存在」分支对它执行一次等价开销的 verify(结果丢弃),使耗时与「密码错误」分支同量级,消除响应时间双峰——否则可借时序差枚举有效用户名(统一错误消息只防住消息差)。
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
static DUMMY_ARGON2_HASH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
    use crate::account::credential::password::{Argon2Hasher, PasswordHasher as _};
    Argon2Hasher::default()
        .hash("garrison-h1-timing-equalizer")
        .expect("固定输入的 Argon2 hash 生成恒成功(H-1 时序对齐 dummy)")
});

// 账号维度密码爆破锁定(firewall-bruteforce)

/// 账号维度失败计数键:`bf:acct:<login_id>:*` 与 brute_force.rs 的 IP 维度(`bf:<ip>:*`)同属 `DaoKeyPrefix::BruteForce` 但以 `acct:` 段隔离(防登录方可控的 login_id 污染 IP 计数键);与 hooks 的 `fw:acct:*` 无关,解锁仅靠 TTL 过期或手动删除 `bf:acct:<login_id>:lock`。
// 唯一生产调用方 login_with_password 门控在 account-credential + db-sqlite 之下:仅 firewall-bruteforce 的组合中函数编译但调用方不在,按仓库 cfg_attr 先例定向豁免 dead_code。
#[cfg_attr(
    not(all(feature = "account-credential", feature = "db-sqlite")),
    allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
fn acct_count_key(login_id: &str) -> String {
    format!(
        "{}acct:{}:count",
        crate::constants::DaoKeyPrefix::BruteForce,
        login_id
    )
}

/// 账号维度锁定标记键(前缀语义见 [`acct_count_key`])。
#[cfg_attr(
    not(all(feature = "account-credential", feature = "db-sqlite")),
    allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
fn acct_lock_key(login_id: &str) -> String {
    format!(
        "{}acct:{}:lock",
        crate::constants::DaoKeyPrefix::BruteForce,
        login_id
    )
}

/// 前置检查:账号处于锁定期内则拒绝(不消耗校验资源)。
#[cfg_attr(
    not(all(feature = "account-credential", feature = "db-sqlite")),
    allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
async fn is_password_locked(dao: &Arc<dyn GarrisonDao>, login_id: &str) -> GarrisonResult<bool> {
    dao.get(&acct_lock_key(login_id))
        .await
        .map(|v| v.is_some())
        .map_err(|e| GarrisonError::Dao(format!("stp-password-lock-check::{}", e)))
}

/// 记录一次密码认证失败:窗口内原子递增,超阈值置锁定标记。
#[cfg_attr(
    not(all(feature = "account-credential", feature = "db-sqlite")),
    allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
async fn record_password_failure(dao: &Arc<dyn GarrisonDao>, login_id: &str) -> GarrisonResult<()> {
    use crate::strategy::firewall::brute_force::BruteForceConfig;
    let cfg = BruteForceConfig::default();
    let count = dao
        .incr(&acct_count_key(login_id), cfg.window_seconds)
        .await
        .map_err(|e| GarrisonError::Dao(format!("stp-password-lock-incr::{}", e)))?;
    // 达到阈值即锁(第 max_attempts 次失败后,下一次尝试无论凭证对错都被拒)
    if count >= cfg.max_attempts as u64 {
        dao.set(&acct_lock_key(login_id), "1", cfg.lock_seconds)
            .await
            .map_err(|e| GarrisonError::Dao(format!("stp-password-lock-set::{}", e)))?;
    }
    Ok(())
}

/// 登录成功后清零失败计数。
#[cfg_attr(
    not(all(feature = "account-credential", feature = "db-sqlite")),
    allow(dead_code)
)]
#[cfg(feature = "firewall-bruteforce")]
async fn reset_password_failures(dao: &Arc<dyn GarrisonDao>, login_id: &str) {
    if let Err(e) = dao.delete(&acct_count_key(login_id)).await {
        tracing::warn!(
            login_id = login_id,
            error = %e,
            "{}", crate::i18n::translate_detail("logs-stp-password-lockout-reset-failed", &[])
        );
    }
}

#[async_trait]
impl PasswordLogic for GarrisonLogicDefault {
    /// 密码登录实现:UserRepository 查询 → PasswordHasher 校验 → login 签发;用户不存在与密码错误统一 `InvalidParam("stp-invalid-password")`,真实原因只进 tracing 日志。
    #[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
    async fn login_with_password(&self, login_id: &str, password: &str) -> GarrisonResult<String> {
        // 账号维度锁定前置短路(仅 firewall-bruteforce):锁定检查失败降级放行——锁定是加速器,最终防线是密码校验,fail-closed 会把 DAO 抖动放大为登录全拒。
        #[cfg(feature = "firewall-bruteforce")]
        match is_password_locked(self.session.dao(), login_id).await {
            Ok(true) => {
                tracing::warn!(
                    login_id = login_id,
                    "{}",
                    crate::i18n::translate_detail("logs-stp-password-account-locked", &[])
                );
                return Err(GarrisonError::FirewallBlocked(format!(
                    "stp-password-account-locked::{}",
                    login_id
                )));
            },
            Err(e) => {
                tracing::warn!(login_id = login_id, error = %e,
                    "{}", crate::i18n::translate_detail("logs-stp-password-lockout-check-failed", &[]));
            },
            Ok(false) => {},
        }

        let hasher = self.password_hasher.as_ref().ok_or_else(|| {
            GarrisonError::Config("stp-password-hasher-not-configured::".to_string())
        })?;
        let repo = self
            .user_repository
            .as_ref()
            .ok_or_else(|| GarrisonError::Config("stp-user-repo-not-configured::".to_string()))?;

        let username = login_id.to_string();
        // 从租户上下文读真实租户(多租户按调用方租户查询),无上下文回退默认租户 0
        let tenant_id = crate::context::tenant::TENANT
            .try_get()
            .map(|ctx| ctx.tenant_id)
            .unwrap_or(0);
        let user = repo
            .find_by_username(tenant_id, &username)
            .await
            .map_err(|e| GarrisonError::Dao(format!("stp-dao-find-by-id::{}", e)))?;

        let user = match user {
            Some(u) => u,
            None => {
                // 与真实校验等价开销的 dummy Argon2 verify(结果丢弃),对齐「用户不存在」与「密码错误」分支耗时(见 DUMMY_ARGON2_HASH);verify_pooled 把慢哈希下沉 spawn_blocking 并受并发 permit 池约束。
                let _verified_dummy = verify_pooled(hasher, password, &DUMMY_ARGON2_HASH).await?;

                // 日志和事件统一为 "invalid_credentials",不区分 user_not_found/wrong_password,防止日志泄露用户存在性
                tracing::warn!(
                    login_id = login_id,
                    reason = EventReason::InvalidCredentials.as_str(),
                    "login_with_password failed"
                );
                #[cfg(feature = "listener")]
                if let Some(lm) = &self.listener_manager {
                    lm.broadcast(&GarrisonEvent::LoginFailure {
                        login_id: login_id.to_string(),
                        reason: EventReason::InvalidCredentials.to_string(),
                        request_context: None,
                    })
                    .await;
                }
                // 失败计数:用户不存在同样计入(防用户名枚举爆破)
                #[cfg(feature = "firewall-bruteforce")]
                if let Err(e) = record_password_failure(self.session.dao(), login_id).await {
                    tracing::warn!(login_id = login_id, error = %e,
                        "{}", crate::i18n::translate_detail("logs-stp-password-lockout-record-failed", &[]));
                }
                return Err(GarrisonError::InvalidParam(
                    "stp-invalid-password::".to_string(),
                ));
            },
        };

        // 校验密码:哈希数据类错误与密码错误统一返回,防账号存在预言机;verify_and_rehash_pooled 把 50-300ms 级纯 CPU 慢哈希下沉 spawn_blocking 避免阻塞 tokio worker,
        // 有池时受并发 permit 约束(内存驻留上界 = permits × m_cost),verify 与惰性重哈希共用 permit;基础设施错误(join/池关闭)显性传播,数据类错误并入统一防枚举分支。
        let (verified, rehash) = match verify_and_rehash_pooled(
            hasher,
            password,
            &user.password_hash,
        )
        .await
        {
            Ok(v) => v,
            Err(GarrisonError::InvalidParam(hash_err)) => {
                // 存量哈希畸形在解析处毫秒级失败,补一次等价开销 dummy verify 对齐「密码错误」分支耗时;统一返回 invalid-password,不以专用错误码泄露账号存在性。
                let _verified_dummy = verify_pooled(hasher, password, &DUMMY_ARGON2_HASH).await?;
                tracing::warn!(
                    login_id = login_id,
                    reason = EventReason::HashFormatError.as_str(),
                    error = %hash_err,
                    "login_with_password: unsupported password hash format"
                );
                // 哈希数据类错误同样计入失败计数
                #[cfg(feature = "firewall-bruteforce")]
                if let Err(record_err) = record_password_failure(self.session.dao(), login_id).await
                {
                    tracing::warn!(login_id = login_id, error = %record_err,
                        "{}", crate::i18n::translate_detail("logs-stp-password-lockout-record-failed", &[]));
                }
                return Err(GarrisonError::InvalidParam(
                    "stp-invalid-password::".to_string(),
                ));
            },
            Err(e) => return Err(e),
        };

        if !verified {
            tracing::warn!(
                login_id = login_id,
                reason = EventReason::InvalidCredentials.as_str(),
                "login_with_password failed"
            );
            #[cfg(feature = "listener")]
            if let Some(lm) = &self.listener_manager {
                lm.broadcast(&GarrisonEvent::LoginFailure {
                    login_id: login_id.to_string(),
                    reason: EventReason::InvalidCredentials.to_string(),
                    request_context: None,
                })
                .await;
            }
            #[cfg(feature = "firewall-bruteforce")]
            if let Err(e) = record_password_failure(self.session.dao(), login_id).await {
                tracing::warn!(login_id = login_id, error = %e,
                    "{}", crate::i18n::translate_detail("logs-stp-password-lockout-record-failed", &[]));
            }
            return Err(GarrisonError::InvalidParam(
                "stp-invalid-password::".to_string(),
            ));
        }

        #[cfg(feature = "firewall-bruteforce")]
        reset_password_failures(self.session.dao(), login_id).await;

        // 惰性升级(尽力而为):无事务上下文,退 Immediately 档(listener_manager.broadcast),先落库成功后广播保证审计不虚报;
        // 落库失败仅日志不影响登录——升级是安全加固,不能反过来成为准入条件(存量弱档位账户在存储故障期仍须可登录)。
        if let Some(new_hash) = rehash {
            match repo
                .update(
                    tenant_id,
                    &user.id,
                    UpdateUser {
                        password_hash: Some(new_hash),
                        ..UpdateUser::default()
                    },
                )
                .await
            {
                Ok(()) =>
                {
                    #[cfg(feature = "listener")]
                    if let Some(lm) = &self.listener_manager {
                        lm.broadcast(&GarrisonEvent::PasswordRehashed {
                            login_id: login_id.to_string(),
                            request_context: None,
                        })
                        .await;
                    }
                },
                Err(e) => {
                    tracing::warn!(
                        login_id = login_id,
                        error = %e,
                        "{}", crate::i18n::translate_detail("logs-stp-password-rehash-persist-failed", &[])
                    );
                },
            }
        }

        self.login(login_id, &LoginParams::default()).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::GarrisonConfig;
    // 显式导入:父模块的 GarrisonDao 门控在 firewall-bruteforce 下,
    // production 等不含该 feature 的组合中 `use super::*` 不可见
    use crate::dao::repository::UserRow;
    use crate::dao::GarrisonDao;
    use crate::error::GarrisonResult;
    use crate::session::GarrisonSession;
    use crate::stp::core::GarrisonCore;
    use crate::stp::mock::{MockDao, MockFirewall};
    use crate::stp::session::SessionLogic;
    use crate::strategy::GarrisonPermissionStrategy;
    use std::sync::Arc;

    /// 构造 GarrisonLogicDefault(不注入 hasher/repo,测试 Config 错误路径),供 default_impl_coverage 与顶层锁定回归测试共用(锁定测试不能依赖 listener 门)。
    // 使用方测试门控在 account-credential + db-sqlite 再加 firewall-bruteforce(顶层锁定回归)或 listener(default_impl_coverage)之下:任一缺失的组合(如 cli-ops lib 测试面)中助手编译但无调用方,按仓库 cfg_attr 先例定向豁免 dead_code。
    #[cfg_attr(
        not(all(
            feature = "account-credential",
            feature = "db-sqlite",
            any(feature = "firewall-bruteforce", feature = "listener")
        )),
        allow(dead_code)
    )]
    fn make_logic_without_creds() -> GarrisonLogicDefault {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
        let mut config = GarrisonConfig::default_config();
        config.throw_on_not_login = false;
        config.token_style = "uuid".to_string();
        let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
            has_permission: true,
            has_role: true,
        });
        GarrisonLogicDefault::new(
            session,
            Arc::new(config),
            firewall,
            Arc::new(crate::account::disable::DefaultDisableRepository::new(
                dao.clone(),
            )),
        )
    }

    // 同 make_logic_without_creds:调用方门控含 firewall-bruteforce/listener,缺者的组合定向豁免 dead_code。
    #[cfg_attr(
        not(all(
            feature = "account-credential",
            feature = "db-sqlite",
            any(feature = "firewall-bruteforce", feature = "listener")
        )),
        allow(dead_code)
    )]
    fn make_user_row(login_id: &str, password_hash: &str) -> UserRow {
        UserRow {
            id: format!("u-{}", login_id),
            username: login_id.to_string(),
            password_hash: password_hash.to_string(),
            status: "active".to_string(),
            tenant_id: 0,
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
            last_login_at: None,
        }
    }

    /// 账号维度爆破锁定:连续失败达阈值(BruteForceConfig::default 5 次)后,正确密码也被拒(FirewallBlocked);锁定期内不再消耗校验资源。
    // 放 mod tests 顶层而非 default_impl_coverage(后者 cfg 含 listener):最小 feature 组合下锁定回归也必须编译执行。
    #[cfg(all(
        feature = "firewall-bruteforce",
        feature = "account-credential",
        feature = "db-sqlite"
    ))]
    #[tokio::test]
    async fn login_with_password_locks_account_after_max_failures() {
        use crate::account::credential::{Argon2Hasher, PasswordHasher};
        use crate::strategy::firewall::brute_force::BruteForceConfig;

        let logic = make_logic_without_creds();
        let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
        let correct = "correct-horse-battery";
        let hash = hasher.hash(correct).expect("argon2 hash 生成应成功");
        let repo = crate::stp::mock::MockUserRepository::new();
        repo.insert(make_user_row("alice", &hash));
        let logic = logic
            .with_password_hasher(Arc::clone(&hasher) as Arc<dyn PasswordHasher>)
            .with_user_repository(Arc::new(repo));

        let cfg = BruteForceConfig::default();
        for i in 0..cfg.max_attempts {
            let result = logic.login_with_password("alice", "wrong-password").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "前 {} 次失败应为统一 invalid-password,实际: {:?}",
                i + 1,
                result
            );
        }

        let result = logic.login_with_password("alice", correct).await;
        assert!(
            matches!(result, Err(GarrisonError::FirewallBlocked(ref msg)) if msg.contains("stp-password-account-locked")),
            "超过阈值后正确密码也应被锁定拒绝,实际: {:?}",
            result
        );
    }

    /// 存量哈希 verify 期数据类错误(`$scrypt$`:可解析但 Argon2 校验期拒绝)→ 与密码错误统一返回 `stp-invalid-password`(响应不可区分)且失败计数递增;基础设施错误(join/池关闭)仍显性传播。
    #[cfg(all(
        feature = "firewall-bruteforce",
        feature = "account-credential",
        feature = "db-sqlite"
    ))]
    #[tokio::test]
    async fn login_with_password_verify_time_data_error_unified_and_counted() {
        use crate::account::credential::{Argon2Hasher, PasswordHasher};
        use crate::stp::mock::MockUserRepository;

        let logic = make_logic_without_creds();
        let dao = logic.session.dao().clone();
        let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
        let repo = MockUserRepository::new();
        let real_hash = hasher.hash("correct-password").expect("argon2 hash 应成功");
        repo.insert(make_user_row("alice", &real_hash));
        repo.insert(make_user_row(
            "bob",
            "$scrypt$ln=16,r=8,p=1$c2FsdDEyMzQ1Njc4$MDEyMzQ1Njc4OWFiY2RlZg",
        ));
        let logic = logic
            .with_password_hasher(hasher)
            .with_user_repository(Arc::new(repo));

        let unified = |e: &GarrisonError| matches!(e, GarrisonError::InvalidParam(m) if m == "stp-invalid-password::");

        // 对照组:密码错误
        let wrong_pw = logic
            .login_with_password("alice", "wrong-password")
            .await
            .unwrap_err();
        // 实验组:存量 $scrypt$ 哈希(verify 期数据类错误)
        let legacy = logic
            .login_with_password("bob", "any-password")
            .await
            .unwrap_err();

        assert!(
            unified(&wrong_pw) && unified(&legacy),
            "verify 期数据类错误应与密码错误统一返回 stp-invalid-password,实际: {:?} vs {:?}",
            wrong_pw,
            legacy
        );
        assert_eq!(
            dao.get(&acct_count_key("bob")).await.unwrap().as_deref(),
            Some("1"),
            "verify 期数据类错误应计入账号维度失败计数"
        );
        assert_eq!(
            dao.get(&acct_count_key("alice")).await.unwrap().as_deref(),
            Some("1"),
            "密码错误对照组应计入账号维度失败计数"
        );
    }

    /// 最小 mock:实现 `GarrisonCore` + `SessionLogic`;`PasswordLogic` 有默认实现,空 impl 即可。
    struct MockPassword {
        config: Arc<GarrisonConfig>,
    }

    impl GarrisonCore for MockPassword {
        fn config(&self) -> Arc<GarrisonConfig> {
            Arc::clone(&self.config)
        }
    }

    #[async_trait]
    impl SessionLogic for MockPassword {
        async fn login(
            &self,
            _login_id: &str,
            _params: &crate::stp::LoginParams,
        ) -> GarrisonResult<String> {
            Ok("mock-token".to_string())
        }
        async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout(&self) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_login(&self) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
            Ok(Some("42".to_string()))
        }
    }

    #[async_trait]
    impl PasswordLogic for MockPassword {}

    #[tokio::test]
    async fn login_with_password_default_returns_not_implemented() {
        let mock = MockPassword {
            config: Arc::new(GarrisonConfig::default()),
        };
        let id = "alice";
        let result = mock.login_with_password(id, "secret").await;
        assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
    }

    // MockPassword SessionLogic 方法覆盖测试

    /// MockPassword::login 返回 "mock-token"。
    #[tokio::test]
    async fn mock_password_login_returns_token() {
        let mock = MockPassword {
            config: Arc::new(GarrisonConfig::default()),
        };
        let token = mock
            .login("alice", &crate::stp::LoginParams::default())
            .await
            .unwrap();
        assert_eq!(token, "mock-token");
    }

    /// MockPassword::login_with_token / logout / logout_by_login_id /
    /// kickout / kickout_by_token / revoke_token 均返回 Ok(())。
    #[tokio::test]
    async fn mock_password_session_methods_return_ok() {
        let mock = MockPassword {
            config: Arc::new(GarrisonConfig::default()),
        };
        mock.login_with_token("alice", "tok").await.unwrap();
        mock.logout().await.unwrap();
        mock.logout_by_login_id("alice").await.unwrap();
        mock.kickout("alice").await.unwrap();
        mock.kickout_by_token("tok").await.unwrap();
        mock.revoke_token("tok").await.unwrap();
    }

    /// MockPassword::check_login 返回 true, get_login_id 返回 Some("42")。
    #[tokio::test]
    async fn mock_password_check_login_and_get_login_id() {
        let mock = MockPassword {
            config: Arc::new(GarrisonConfig::default()),
        };
        assert!(mock.check_login().await.unwrap());
        let id = mock.get_login_id().await.unwrap();
        assert_eq!(id.as_deref(), Some("42"));
    }

    /// MockPassword::config 返回内部 config 的 Arc clone。
    #[tokio::test]
    async fn mock_password_config_returns_arc_clone() {
        let mock = MockPassword {
            config: Arc::new(GarrisonConfig::default()),
        };
        let c1 = mock.config();
        let c2 = mock.config();
        assert!(Arc::ptr_eq(&c1, &c2), "两次 config() 应返回同一 Arc");
    }

    // GarrisonLogicDefault impl 覆盖测试(cfg-gated: account-credential + db-sqlite)
    // 覆盖 hasher/repo 未注入 + listener_manager 广播 LoginFailure 路径

    #[cfg(all(
        feature = "account-credential",
        feature = "db-sqlite",
        feature = "listener"
    ))]
    mod default_impl_coverage {
        use super::*;
        use crate::account::credential::{Argon2Hasher, PasswordHasher};
        use crate::dao::repository::{NewUser, UpdateUser, UserListRow, UserRepository};
        use crate::listener::{GarrisonEvent, GarrisonListener, GarrisonListenerManager};
        use crate::stp::mock::MockUserRepository;
        use async_trait::async_trait;
        use parking_lot::Mutex;
        use std::sync::Arc;

        /// 记录事件监听器,捕获广播的 GarrisonEvent 用于断言。
        struct RecordingListener {
            events: Mutex<Vec<GarrisonEvent>>,
        }

        impl RecordingListener {
            fn new() -> Self {
                Self {
                    events: Mutex::new(Vec::new()),
                }
            }

            fn captured(&self) -> Vec<GarrisonEvent> {
                self.events.lock().clone()
            }
        }

        #[async_trait]
        impl GarrisonListener for RecordingListener {
            async fn on_event(&self, event: &GarrisonEvent) -> crate::error::GarrisonResult<()> {
                self.events.lock().push(event.clone());
                Ok(())
            }
        }

        /// 未注入 password_hasher 时返回 Config("stp-password-hasher-not-configured")(覆盖 `hasher.as_ref().ok_or_else(...)` 路径)。
        #[tokio::test]
        async fn login_with_password_missing_hasher_returns_config_error() {
            let logic = make_logic_without_creds();
            let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new());
            let logic = logic.with_user_repository(repo);

            let result = logic.login_with_password("alice", "any").await;
            assert!(
                matches!(result, Err(GarrisonError::Config(ref msg)) if msg == "stp-password-hasher-not-configured::"),
                "未注入 hasher 应返回 Config(\"stp-password-hasher-not-configured\"),实际: {:?}",
                result
            );
        }

        /// 未注入 user_repository 时返回 Config("stp-user-repo-not-configured")(覆盖 `repo.as_ref().ok_or_else(...)` 路径)。
        #[tokio::test]
        async fn login_with_password_missing_repo_returns_config_error() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let logic = logic.with_password_hasher(hasher);

            let result = logic.login_with_password("alice", "any").await;
            assert!(
                matches!(result, Err(GarrisonError::Config(ref msg)) if msg == "stp-user-repo-not-configured::"),
                "未注入 repo 应返回 Config(\"stp-user-repo-not-configured\"),实际: {:?}",
                result
            );
        }

        /// 用户不存在 + listener_manager 注入 → 广播 LoginFailure 事件(覆盖 `lm.broadcast(LoginFailure)` 路径)。
        #[cfg(feature = "listener")]
        #[tokio::test]
        async fn login_with_password_user_not_found_broadcasts_login_failure() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new()); // 空仓库
            let recorder = Arc::new(RecordingListener::new());
            let lm = Arc::new(GarrisonListenerManager::new());
            lm.register(recorder.clone() as Arc<dyn GarrisonListener>);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo)
                .with_listener_manager(lm);

            let result = logic.login_with_password("missing-user", "any").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "用户不存在应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
                result
            );

            let events = recorder.captured();
            let failure_count = events
                .iter()
                .filter(|e| matches!(e, GarrisonEvent::LoginFailure { .. }))
                .count();
            assert_eq!(
                failure_count, 1,
                "应广播 1 次 LoginFailure 事件,实际广播: {} 次",
                failure_count
            );
            if let Some(GarrisonEvent::LoginFailure {
                login_id, reason, ..
            }) = events.first()
            {
                assert_eq!(login_id, "missing-user");
                assert_eq!(
                    reason, "invalid_credentials",
                    "reason 应为 'invalid_credentials'(防用户枚举),实际: {}",
                    reason
                );
            }
        }

        /// 密码错误 + listener_manager 注入 → 广播 LoginFailure 事件(覆盖 `lm.broadcast(LoginFailure)` 路径)。
        #[cfg(feature = "listener")]
        #[tokio::test]
        async fn login_with_password_wrong_password_broadcasts_login_failure() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let hash = hasher.hash("correct-password").unwrap();
            let mock_repo = MockUserRepository::new();
            mock_repo.insert(make_user_row("1001", &hash));
            let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);
            let recorder = Arc::new(RecordingListener::new());
            let lm = Arc::new(GarrisonListenerManager::new());
            lm.register(recorder.clone() as Arc<dyn GarrisonListener>);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo)
                .with_listener_manager(lm);

            let result = logic.login_with_password("1001", "wrong-password").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "错误密码应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
                result
            );

            let events = recorder.captured();
            if let Some(GarrisonEvent::LoginFailure {
                login_id, reason, ..
            }) = events.first()
            {
                assert_eq!(login_id, "1001");
                assert_eq!(
                    reason, "invalid_credentials",
                    "reason 应为 'invalid_credentials',实际: {}",
                    reason
                );
            } else {
                panic!("应广播 LoginFailure 事件,实际捕获: {:?}", events);
            }
        }

        /// 用户不存在分支执行一次 dummy verify(时序对齐),错误与事件语义不变。
        #[tokio::test]
        async fn login_with_password_user_not_found_performs_dummy_verify() {
            use std::sync::atomic::{AtomicUsize, Ordering};

            /// 计数哈希器:记录 verify 调用次数(恒返回不匹配)。
            struct CountingHasher {
                verify_calls: AtomicUsize,
            }

            impl PasswordHasher for CountingHasher {
                fn hash(&self, _password: &str) -> GarrisonResult<String> {
                    Ok("$argon2id$v=19$m=19456,t=2,p=1$dummy$dummy".to_string())
                }
                fn verify(&self, _password: &str, _hash: &str) -> GarrisonResult<bool> {
                    self.verify_calls.fetch_add(1, Ordering::Relaxed);
                    Ok(false)
                }
            }

            let logic = make_logic_without_creds();
            let counter = Arc::new(CountingHasher {
                verify_calls: AtomicUsize::new(0),
            });
            let hasher: Arc<dyn PasswordHasher> = counter.clone();
            let repo: Arc<dyn UserRepository> = Arc::new(MockUserRepository::new()); // 空仓库
            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo);

            let result = logic.login_with_password("missing-user", "any").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "用户不存在应返回 InvalidParam(\"stp-invalid-password\"),实际: {:?}",
                result
            );
            assert_eq!(
                counter.verify_calls.load(Ordering::Relaxed),
                1,
                "用户不存在分支应恰好执行一次 dummy verify(H-1 时序对齐),实际 0 次"
            );
        }

        /// 哈希格式不支持(存量数据异常)→ 与密码错误统一返回 InvalidParam("stp-invalid-password"),消除账号存在预言机。
        #[tokio::test]
        async fn login_with_password_unsupported_hash_format_returns_error() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let mock_repo = MockUserRepository::new();
            mock_repo.insert(make_user_row("1002", "not-a-valid-hash-format"));
            let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo);

            let result = logic.login_with_password("1002", "any-password").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "哈希格式不支持应与密码错误统一返回 stp-invalid-password,实际: {:?}",
                result
            );
        }

        /// 哈希格式非法分支也执行一次 dummy verify:畸形哈希在解析处毫秒级失败,与「密码错误」分支的完整 Argon2 开销形成耗时双峰,必须补齐等价开销(锁定不因重构静默丢失)。
        #[tokio::test]
        async fn login_with_password_bad_hash_format_performs_dummy_verify() {
            use std::sync::atomic::{AtomicUsize, Ordering};

            /// 计数哈希器:对畸形存量哈希返回数据类错误(对齐 Argon2Hasher 的 PHC 解析失败语义),其余输入记一次 verify 并返回不匹配。
            struct FormatErrorCountingHasher {
                verify_calls: AtomicUsize,
            }

            impl PasswordHasher for FormatErrorCountingHasher {
                fn hash(&self, _password: &str) -> GarrisonResult<String> {
                    Ok("$argon2id$v=19$m=19456,t=2,p=1$dummy$dummy".to_string())
                }
                fn verify(&self, _password: &str, hash: &str) -> GarrisonResult<bool> {
                    self.verify_calls.fetch_add(1, Ordering::Relaxed);
                    if hash.starts_with("$argon2") {
                        Ok(false)
                    } else {
                        Err(GarrisonError::InvalidParam(
                            "unsupported hash format".to_string(),
                        ))
                    }
                }
            }

            let logic = make_logic_without_creds();
            let counter = Arc::new(FormatErrorCountingHasher {
                verify_calls: AtomicUsize::new(0),
            });
            let hasher: Arc<dyn PasswordHasher> = counter.clone();
            let mock_repo = MockUserRepository::new();
            mock_repo.insert(make_user_row("1002", "not-a-valid-hash-format"));
            let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo);

            let result = logic.login_with_password("1002", "any-password").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "哈希格式非法应统一返回 stp-invalid-password,实际: {:?}",
                result
            );
            assert_eq!(
                counter.verify_calls.load(Ordering::Relaxed),
                2,
                "哈希格式非法分支应恰好执行 1 次真实校验 + 1 次 dummy verify(共 2 次),实际: {}",
                counter.verify_calls.load(Ordering::Relaxed)
            );
        }

        /// 用户存在 + 密码正确 → 返回 Ok(token)(成功登录路径,调用 login 签发)。
        #[tokio::test]
        async fn login_with_password_correct_credentials_returns_token() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let hash = hasher.hash("correct-password").unwrap();
            let mock_repo = MockUserRepository::new();
            mock_repo.insert(make_user_row("1003", &hash));
            let repo: Arc<dyn UserRepository> = Arc::new(mock_repo);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo);

            let result = logic.login_with_password("1003", "correct-password").await;
            assert!(
                result.is_ok(),
                "用户存在 + 密码正确应返回 Ok(token),实际: {:?}",
                result
            );
            let token = result.unwrap();
            assert!(!token.is_empty(), "返回的 token 不应为空字符串");
        }

        // 登录期惰性升级(verify_and_rehash 接线)

        /// 低档位存量哈希(m=8MiB < 配置 19MiB)登录成功:库内 hash 已升级为
        /// 当前配置档位(可用原密码 verify),并广播 PasswordRehashed 事件。
        #[tokio::test]
        async fn login_with_password_rehashes_legacy_hash_and_broadcasts_event() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let legacy = Argon2Hasher::with_params(8192, 2, 1);
            let stored = legacy.hash("correct-password").expect("hash 应成功");
            let mock_repo = Arc::new(MockUserRepository::new());
            mock_repo.insert(make_user_row("2001", &stored));
            let recorder = Arc::new(RecordingListener::new());
            let lm = Arc::new(GarrisonListenerManager::new());
            lm.register(recorder.clone() as Arc<dyn GarrisonListener>);

            let logic = logic
                .with_password_hasher(hasher.clone())
                .with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
                .with_listener_manager(lm);

            let result = logic.login_with_password("2001", "correct-password").await;
            assert!(
                result.is_ok(),
                "低档位账户正确密码应登录成功,实际: {:?}",
                result
            );

            let upgraded = mock_repo
                .find_by_username(0, "2001")
                .await
                .expect("查询应成功")
                .expect("用户应存在");
            assert_ne!(
                upgraded.password_hash, stored,
                "登录成功后库内 hash 应已被升级重写"
            );
            assert!(
                upgraded.password_hash.contains("m=19456"),
                "升级后 hash 应为当前配置档位 m=19456,实际: {}",
                upgraded.password_hash
            );
            assert!(
                hasher
                    .verify("correct-password", &upgraded.password_hash)
                    .expect("verify 应成功"),
                "升级后 hash 应可用原密码 verify 通过"
            );

            let events = recorder.captured();
            assert!(
                events.iter().any(|e| matches!(
                    e,
                    GarrisonEvent::PasswordRehashed { login_id, .. } if login_id.as_str() == "2001"
                )),
                "登录升级后应广播 PasswordRehashed 事件,实际: {:?}",
                events
            );
        }

        /// 登录失败(密码错误):不升级、不广播——重哈希只发生在 verify 通过后。
        #[tokio::test]
        async fn login_with_password_failure_does_not_rehash() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let legacy = Argon2Hasher::with_params(8192, 2, 1);
            let stored = legacy.hash("correct-password").expect("hash 应成功");
            let mock_repo = Arc::new(MockUserRepository::new());
            mock_repo.insert(make_user_row("2002", &stored));
            let recorder = Arc::new(RecordingListener::new());
            let lm = Arc::new(GarrisonListenerManager::new());
            lm.register(recorder.clone() as Arc<dyn GarrisonListener>);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
                .with_listener_manager(lm);

            let result = logic.login_with_password("2002", "wrong-password").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg == "stp-invalid-password::"),
                "错误密码应返回统一 invalid-password,实际: {:?}",
                result
            );
            let row = mock_repo
                .find_by_username(0, "2002")
                .await
                .expect("查询应成功")
                .expect("用户应存在");
            assert_eq!(row.password_hash, stored, "登录失败不得升级存量哈希");
            assert!(
                recorder
                    .captured()
                    .iter()
                    .all(|e| !matches!(e, GarrisonEvent::PasswordRehashed { .. })),
                "登录失败不得广播 PasswordRehashed 事件"
            );
        }

        /// 存量档位与配置持平:登录成功但 hash 原样保留、不广播升级事件。
        #[tokio::test]
        async fn login_with_password_current_tier_keeps_hash_and_skips_event() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let stored = hasher.hash("correct-password").expect("hash 应成功");
            let mock_repo = Arc::new(MockUserRepository::new());
            mock_repo.insert(make_user_row("2003", &stored));
            let recorder = Arc::new(RecordingListener::new());
            let lm = Arc::new(GarrisonListenerManager::new());
            lm.register(recorder.clone() as Arc<dyn GarrisonListener>);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
                .with_listener_manager(lm);

            let result = logic.login_with_password("2003", "correct-password").await;
            assert!(
                result.is_ok(),
                "当前档位正确密码应登录成功,实际: {:?}",
                result
            );
            let row = mock_repo
                .find_by_username(0, "2003")
                .await
                .expect("查询应成功")
                .expect("用户应存在");
            assert_eq!(row.password_hash, stored, "档位持平时登录不得重写 hash");
            assert!(
                recorder
                    .captured()
                    .iter()
                    .all(|e| !matches!(e, GarrisonEvent::PasswordRehashed { .. })),
                "档位持平时不得广播 PasswordRehashed 事件"
            );
        }

        /// 升级落库失败:登录仍成功(升级尽力而为,失败仅记日志),且不广播
        /// PasswordRehashed 事件(未落库成功不得虚报审计)。
        #[tokio::test]
        async fn login_with_password_rehash_persist_failure_does_not_fail_login() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let legacy = Argon2Hasher::with_params(8192, 2, 1);
            let stored = legacy.hash("correct-password").expect("hash 应成功");
            let mock_repo = Arc::new(MockUserRepository::new());
            mock_repo.insert(make_user_row("2004", &stored));
            mock_repo.set_update_error("dao-update 模拟故障");
            let recorder = Arc::new(RecordingListener::new());
            let lm = Arc::new(GarrisonListenerManager::new());
            lm.register(recorder.clone() as Arc<dyn GarrisonListener>);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(Arc::clone(&mock_repo) as Arc<dyn UserRepository>)
                .with_listener_manager(lm);

            let result = logic.login_with_password("2004", "correct-password").await;
            assert!(
                result.is_ok(),
                "升级落库失败不得导致登录失败(尽力而为),实际: {:?}",
                result
            );
            let row = mock_repo
                .find_by_username(0, "2004")
                .await
                .expect("查询应成功")
                .expect("用户应存在");
            assert_eq!(row.password_hash, stored, "落库失败时库内 hash 应保持原样");
            assert!(
                recorder
                    .captured()
                    .iter()
                    .all(|e| !matches!(e, GarrisonEvent::PasswordRehashed { .. })),
                "落库失败不得广播 PasswordRehashed 事件(不虚报升级)"
            );
        }

        /// 模拟 UserRepository 查询失败的 mock:所有方法返回 Dao 错误,用于测试 `map_err(|e| GarrisonError::Dao(...))` 错误传播路径。
        struct ErrorUserRepository;

        #[async_trait]
        impl UserRepository for ErrorUserRepository {
            async fn find_by_id(
                &self,
                _tenant_id: i64,
                _id: &str,
            ) -> GarrisonResult<Option<UserRow>> {
                Err(GarrisonError::Dao("find_by_id 模拟失败".to_string()))
            }

            async fn find_by_username(
                &self,
                _tenant_id: i64,
                _username: &str,
            ) -> GarrisonResult<Option<UserRow>> {
                Err(GarrisonError::Dao(
                    "find_by_username 模拟连接断开".to_string(),
                ))
            }

            async fn create(&self, _tenant_id: i64, _user: NewUser) -> GarrisonResult<String> {
                Err(GarrisonError::Dao("create 模拟失败".to_string()))
            }

            async fn update(
                &self,
                _tenant_id: i64,
                _id: &str,
                _user: UpdateUser,
            ) -> GarrisonResult<()> {
                Err(GarrisonError::Dao("update 模拟失败".to_string()))
            }

            async fn delete(&self, _tenant_id: i64, _id: &str) -> GarrisonResult<()> {
                Err(GarrisonError::Dao("delete 模拟失败".to_string()))
            }

            async fn list(
                &self,
                _tenant_id: i64,
                _offset: i64,
                _limit: i64,
            ) -> GarrisonResult<Vec<UserListRow>> {
                Err(GarrisonError::Dao("list 模拟失败".to_string()))
            }
        }

        /// login_with_password 在 UserRepository 查询失败时传播 Dao 错误(覆盖 `map_err(...)` 路径)。
        #[tokio::test]
        async fn login_with_password_repo_query_error_propagates_dao_error() {
            let logic = make_logic_without_creds();
            let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2Hasher::default());
            let repo: Arc<dyn UserRepository> = Arc::new(ErrorUserRepository);

            let logic = logic
                .with_password_hasher(hasher)
                .with_user_repository(repo);

            let result = logic.login_with_password("alice", "any").await;
            assert!(
                result.is_err(),
                "UserRepository 查询失败应传播错误,实际: {:?}",
                result
            );
            match result {
                Err(GarrisonError::Dao(msg)) => {
                    assert!(
                        msg.contains("stp-dao-find-by-id"),
                        "错误消息应包含 'login_with_password 查询用户失败',实际: {}",
                        msg
                    );
                    assert!(
                        msg.contains("find_by_username 模拟连接断开"),
                        "错误消息应包含原始错误描述,实际: {}",
                        msg
                    );
                },
                Err(other) => panic!("期望 Dao 错误,实际: {:?}", other),
                Ok(_) => panic!("期望错误传播,实际返回 Ok"),
            }
        }

        // 锁定回归测试位于 mod tests 顶层:本嵌套模块 cfg 含 listener,最小 feature 组合下测试不能随之消失。
    }
}