garrison 0.7.2

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
//! Copyright (c) 2026 Kirky.X. All rights reserved.
//! See LICENSE for full license text.

//! PasswordLogic trait — 密码登录契约。
//! 从 v0.5.2 起,从 `GarrisonLogic` 上帝 trait 拆分;本 trait 承接密码登录 1 个方法。
//! super-trait 为 [`SessionLogic`](密码校验通过后调用
//! [`login`](SessionLogic::login) 签发 token)。
//!
//! # v0.5.2 LoginId 迁移:删除 LoginId newtype,全栈使用 String/&str
//!
//! `login_id` 参数从 `i64` 迁移为 `&str`(字符串形式,对象安全)。

use super::GarrisonLogicDefault;
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use super::LoginParams;
#[cfg(all(
    feature = "listener",
    feature = "account-credential",
    feature = "db-sqlite"
))]
use crate::constants::EventReason;
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;

/// 密码逻辑 trait,定义密码登录契约。
///
/// # 默认实现
///
/// [`login_with_password`](Self::login_with_password) 默认返回 `NotImplemented`
/// (未启用 `account-credential` + `db-sqlite` feature)。
/// 由 `GarrisonLogicDefault` 的 impl 覆写为:
/// 1) `UserRepository::find_by_username` 查询用户
/// 2) `PasswordHasher::verify` 校验密码
/// 3) 调用 [`SessionLogic::login`] 签发 token
///
/// # 安全约束
///
/// 用户不存在与密码错误统一返回 `InvalidParam("invalid password")`,
/// 日志和事件 reason 统一为 "invalid_credentials"(v0.4.2 安全审计 A-014),
/// 防止攻击者通过返回值或日志差异进行用户枚举。
#[async_trait]
pub trait PasswordLogic: SessionLogic {
    /// 密码登录:校验密码后签发 token。
    ///
    /// # 参数
    /// - `login_id`: 登录主体标识引用(字符串形式,作为 username 查询 `UserRepository`)。
    /// - `password`: 明文密码(仅校验时临时持有,不存储)。
    ///
    /// # 返回
    /// - `Ok(token)`: 密码校验通过,返回新签发的 token 字符串。
    ///
    /// # 错误
    /// - 未启用 `account-credential` + `db-sqlite` feature:`GarrisonError::NotImplemented`。
    /// - 未注入 `password_hasher`:`GarrisonError::Config("password hasher not configured")`。
    /// - 未注入 `user_repository`:`GarrisonError::Config("user repository not configured")`。
    /// - 用户不存在 / 密码错误:`GarrisonError::InvalidParam("invalid password")`
    ///   (不泄露具体原因,防止用户枚举)。
    /// - 哈希格式不支持:`GarrisonError::InvalidParam("unsupported hash format")`。
    /// - DAO 查询失败:透传 `GarrisonError::Dao`。
    async fn login_with_password(
        &self,
        _login_id: &str,
        _password: &str,
    ) -> GarrisonResult<String> {
        Err(GarrisonError::NotImplemented(
            "login_with_password 未实现:需启用 account-credential + db-sqlite feature".to_string(),
        ))
    }
}

// ============================================================================
// GarrisonLogicDefault impl
// ============================================================================

#[async_trait]
impl PasswordLogic for GarrisonLogicDefault {
    /// 密码登录实现:校验密码后调用 [`login`](Self::login) 签发 token。
    ///
    /// R-002:1) UserRepository 查询 2) PasswordHasher 校验 3) login 签发。
    /// 安全约束:用户不存在与密码错误统一返回 `InvalidParam("invalid password")`,真实原因记录在 tracing 日志。
    #[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
    async fn login_with_password(&self, login_id: &str, password: &str) -> GarrisonResult<String> {
        let hasher = self
            .password_hasher
            .as_ref()
            .ok_or_else(|| GarrisonError::Config("password hasher not configured".to_string()))?;
        let repo = self
            .user_repository
            .as_ref()
            .ok_or_else(|| GarrisonError::Config("user repository not configured".to_string()))?;

        // 1. 查询用户(login_id 转字符串作为 username 查询)
        let username = login_id.to_string();
        let user = repo
            .find_by_username(0, &username)
            .await
            .map_err(|e| GarrisonError::Dao(format!("stp-dao-find-by-id::{}", e)))?;

        let user = match user {
            Some(u) => u,
            None => {
                // v0.4.2 安全审计 A-014: 日志和事件统一为 "invalid_credentials",
                // 不区分 user_not_found/wrong_password,防止日志泄露用户存在性
                tracing::warn!(
                    login_id = login_id,
                    reason = EventReason::InvalidCredentials.as_str(),
                    "login_with_password 失败"
                );
                // 广播 LoginFailure 事件
                #[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;
                }
                return Err(GarrisonError::InvalidParam("invalid password".to_string()));
            },
        };

        // 2. 校验密码(哈希格式不支持返回 "unsupported hash format",可泄露)
        let verified = hasher.verify(password, &user.password_hash).map_err(|e| {
            tracing::warn!(
                login_id = login_id,
                reason = EventReason::HashFormatError.as_str(),
                error = %e,
                "login_with_password 密码哈希格式不支持"
            );
            GarrisonError::InvalidParam("unsupported hash format".to_string())
        })?;

        if !verified {
            // v0.4.2 安全审计 A-014: 日志和事件统一为 "invalid_credentials",
            // 不区分 user_not_found/wrong_password,防止日志泄露用户存在性
            tracing::warn!(
                login_id = login_id,
                reason = EventReason::InvalidCredentials.as_str(),
                "login_with_password 失败"
            );
            // 广播 LoginFailure 事件
            #[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;
            }
            return Err(GarrisonError::InvalidParam("invalid password".to_string()));
        }

        // 3. 调用 login 签发 token(触发 plugin/listener auto-wire)
        self.login(login_id, &LoginParams::default()).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::GarrisonConfig;
    use crate::error::GarrisonResult;
    use crate::stp::core::GarrisonCore;
    use crate::stp::session::SessionLogic;
    use std::sync::Arc;

    /// 最小 mock:实现 `GarrisonCore` + `SessionLogic`(9 必需方法)。
    /// `PasswordLogic` 1 个方法有默认实现,空 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"))]
    mod default_impl_coverage {
        use super::*;
        use crate::account::credential::{Argon2Hasher, PasswordHasher};
        use crate::config::GarrisonConfig;
        use crate::dao::repository::{NewUser, UpdateUser, UserRepository, UserRow};
        use crate::dao::GarrisonDao;
        use crate::listener::{GarrisonEvent, GarrisonListener, GarrisonListenerManager};
        use crate::session::GarrisonSession;
        use crate::stp::mock::{MockDao, MockFirewall, MockUserRepository};
        use crate::strategy::GarrisonPermissionStrategy;
        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(())
            }
        }

        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,
            }
        }

        /// 构造 GarrisonLogicDefault(不注入 hasher/repo,测试 Config 错误路径)。
        fn make_logic_without_creds() -> GarrisonLogicDefault {
            let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
            let session = Arc::new(GarrisonSession::new(dao, 3600, 86400));
            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)
        }

        /// 未注入 password_hasher 时返回 Config("password hasher not configured")。
        ///
        /// 覆盖 password.rs 第 86-89 行 `hasher.as_ref().ok_or_else(...)` 路径。
        #[tokio::test]
        async fn login_with_password_missing_hasher_returns_config_error() {
            let logic = make_logic_without_creds();
            // 注入 repo 但不注入 hasher
            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 == "password hasher not configured"),
                "未注入 hasher 应返回 Config(\"password hasher not configured\"),实际: {:?}",
                result
            );
        }

        /// 未注入 user_repository 时返回 Config("user repository not configured")。
        ///
        /// 覆盖 password.rs 第 90-93 行 `repo.as_ref().ok_or_else(...)` 路径。
        #[tokio::test]
        async fn login_with_password_missing_repo_returns_config_error() {
            let logic = make_logic_without_creds();
            // 注入 hasher 但不注入 repo
            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 == "user repository not configured"),
                "未注入 repo 应返回 Config(\"user repository not configured\"),实际: {:?}",
                result
            );
        }

        /// 用户不存在 + listener_manager 注入 → 广播 LoginFailure 事件。
        ///
        /// 覆盖 password.rs 第 113-121 行 `#[cfg(feature = "listener")] 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 == "invalid password"),
                "用户不存在应返回 InvalidParam(\"invalid password\"),实际: {:?}",
                result
            );

            // 验证广播了 LoginFailure 事件
            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
            );
            // 验证事件 reason 为 "invalid_credentials"(防用户枚举)
            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 事件。
        ///
        /// 覆盖 password.rs 第 145-153 行 `#[cfg(feature = "listener")] 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 == "invalid password"),
                "错误密码应返回 InvalidParam(\"invalid password\"),实际: {:?}",
                result
            );

            // 验证广播了 LoginFailure 事件,reason 为 "invalid_credentials"
            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);
            }
        }

        /// 哈希格式不支持 → 返回 InvalidParam("unsupported hash format")。
        ///
        /// 覆盖 password.rs 第 127-135 行 `hasher.verify(...).map_err(...)` 返回 Err 路径。
        #[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();
            // 插入格式非法的 password_hash(非 Argon2/Bcrypt 格式)
            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 == "unsupported hash format"),
                "哈希格式不支持应返回 InvalidParam(\"unsupported hash format\"),实际: {:?}",
                result
            );
        }

        /// 用户存在 + 密码正确 → 返回 Ok(token)。
        ///
        /// 覆盖 password.rs 第 158-160 行成功登录路径(调用 login 签发 token)。
        #[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 不应为空字符串");
        }

        /// 模拟 UserRepository 查询失败的 mock。
        ///
        /// `find_by_username` 始终返回 Dao 错误,用于测试 password.rs 第 100 行
        /// `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<UserRow>> {
                Err(GarrisonError::Dao("list 模拟失败".to_string()))
            }
        }

        /// login_with_password 在 UserRepository 查询失败时传播 Dao 错误。
        ///
        /// 覆盖 password.rs 第 100 行 `map_err(|e| GarrisonError::Dao(...))` 错误传播路径。
        #[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"),
            }
        }
    }
}