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

//! Stp 层测试 mock 实现,仅在 `cfg(test)` 下编译(`mod.rs` 中 `#[cfg(test)] mod mock;` 声明)。
//! 提供 MockDao / MockFirewall / MockInterface 等 mock,供 `stp::tests` 集成测试复用。

use super::GarrisonInterface;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::strategy::GarrisonPermissionStrategy;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::time::{Duration, Instant};

#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
use crate::dao::repository::{NewUser, UpdateUser, UserListRow, UserRepository, UserRow};

// MockDao:复用 dao/session 测试的 HashMap + Instant 模拟 TTL

pub struct MockDao {
    store: Mutex<HashMap<String, (String, Option<Instant>)>>,
}

impl MockDao {
    pub fn new() -> Self {
        Self {
            store: Mutex::new(HashMap::new()),
        }
    }
}

#[async_trait]
impl GarrisonDao for MockDao {
    async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
        let mut store = self.store.lock();
        match store.get(key) {
            Some((value, expire_at)) => {
                if let Some(deadline) = expire_at {
                    if Instant::now() >= *deadline {
                        store.remove(key);
                        return Ok(None);
                    }
                }
                Ok(Some(value.clone()))
            },
            None => Ok(None),
        }
    }

    async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
        let expire_at = if ttl_seconds == 0 {
            None
        } else {
            Some(Instant::now() + Duration::from_secs(ttl_seconds))
        };
        self.store
            .lock()
            .insert(key.to_string(), (value.to_string(), expire_at));
        Ok(())
    }

    async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
        let mut store = self.store.lock();
        match store.get_mut(key) {
            Some((existing, _)) => {
                *existing = value.to_string();
                Ok(())
            },
            None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
        }
    }

    async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
        let mut store = self.store.lock();
        match store.get_mut(key) {
            Some((_, expire_at)) => {
                *expire_at = if seconds == 0 {
                    None
                } else {
                    Some(Instant::now() + Duration::from_secs(seconds))
                };
                Ok(())
            },
            None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
        }
    }

    async fn delete(&self, key: &str) -> GarrisonResult<()> {
        self.store.lock().remove(key);
        Ok(())
    }

    async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
        let store = self.store.lock();
        match store.get(key) {
            Some((_, Some(deadline))) => {
                let now = Instant::now();
                if *deadline <= now {
                    Ok(None)
                } else {
                    Ok(Some(*deadline - now))
                }
            },
            _ => Ok(None),
        }
    }
    crate::atomic_test_fallback!();
}

// MockFirewall:模拟 GarrisonPermissionStrategy,控制权限/角色校验返回值

/// 测试用 GarrisonPermissionStrategy mock,可控制 check_permission/check_role 返回值。
pub struct MockFirewall {
    pub has_permission: bool,
    pub has_role: bool,
}

#[async_trait]
impl GarrisonPermissionStrategy for MockFirewall {
    async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(vec![])
    }
    async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(vec![])
    }
    async fn check_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<bool> {
        Ok(self.has_permission)
    }
    async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
        Ok(self.has_role)
    }
    async fn check_role_any(&self, _login_id: &str, _roles: &[&str]) -> GarrisonResult<bool> {
        Ok(self.has_role)
    }
    async fn check_role_all(&self, _login_id: &str, _roles: &[&str]) -> GarrisonResult<bool> {
        Ok(self.has_role)
    }
    async fn check_permission_in_tenant(
        &self,
        _tenant_id: i64,
        _login_id: &str,
        _permission: &str,
    ) -> GarrisonResult<bool> {
        // 测试桩与租户无关:任意租户返回相同结果
        Ok(self.has_permission)
    }
    async fn check_role_in_tenant(
        &self,
        _tenant_id: i64,
        _login_id: &str,
        _role: &str,
    ) -> GarrisonResult<bool> {
        // 测试桩与租户无关:任意租户返回相同结果
        Ok(self.has_role)
    }
    #[cfg(any(
        feature = "sms-rate-limit",
        feature = "firewall-ratelimit",
        feature = "firewall-bruteforce",
        feature = "firewall-ddos",
        feature = "firewall",
        feature = "oauth2-server"
    ))]
    async fn check_login_hooks(
        &self,
        _login_id: &str,
        _ctx: &crate::strategy::hooks::LoginContext,
    ) -> GarrisonResult<()> {
        // 测试桩不注入防火墙 hook,显式 no-op
        Ok(())
    }
}

// MockInterface:用于 GarrisonUtil 全局管理器测试

pub struct MockInterface;

#[async_trait]
impl GarrisonInterface for MockInterface {
    async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(vec![])
    }
    async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(vec![])
    }
}

/// 带预设权限/角色列表的 MockInterface(用于 has_permission/has_role 返回 true 的测试)。
pub struct MockInterfaceWithPerms {
    pub permissions: Vec<String>,
    pub roles: Vec<String>,
}

#[async_trait]
impl GarrisonInterface for MockInterfaceWithPerms {
    async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.permissions.clone())
    }
    async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.roles.clone())
    }
}

// MockUserRepository:测试用 UserRepository mock(cfg-gated)

/// 测试用 UserRepository mock,用 HashMap 存储 UserRow,按 username 索引。
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
pub struct MockUserRepository {
    users: Mutex<HashMap<String, UserRow>>,
    /// 非空时 `update` 返回该错误(注入持久化失败,测试写路径尽力而为语义)。
    update_error: Mutex<Option<String>>,
}

#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
impl MockUserRepository {
    pub fn new() -> Self {
        Self {
            users: Mutex::new(HashMap::new()),
            update_error: Mutex::new(None),
        }
    }
    pub fn insert(&self, user: UserRow) {
        self.users.lock().insert(user.username.clone(), user);
    }
    /// 注入 update 持久化失败(此后 `update` 返回 `Internal`,直至再次置空)。
    // 唯一调用方在 password.rs default_impl_coverage 测试(门控 account-credential + db-sqlite + listener):
    // 无 listener 的组合(如 cli-ops lib 测试面)中编译但无调用方,定向豁免 dead_code。
    #[cfg_attr(not(feature = "listener"), allow(dead_code))]
    pub fn set_update_error(&self, msg: &str) {
        *self.update_error.lock() = Some(msg.to_string());
    }
}

#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
#[async_trait]
impl UserRepository for MockUserRepository {
    async fn find_by_id(&self, _tenant_id: i64, id: &str) -> GarrisonResult<Option<UserRow>> {
        Ok(self.users.lock().values().find(|u| u.id == id).cloned())
    }
    async fn find_by_username(
        &self,
        _tenant_id: i64,
        username: &str,
    ) -> GarrisonResult<Option<UserRow>> {
        Ok(self.users.lock().get(username).cloned())
    }
    async fn create(&self, _tenant_id: i64, _user: NewUser) -> GarrisonResult<String> {
        Err(GarrisonError::Internal(
            "stp-mock-not-implemented::".to_string(),
        ))
    }
    async fn update(&self, _tenant_id: i64, id: &str, user: UpdateUser) -> GarrisonResult<()> {
        if let Some(msg) = self.update_error.lock().clone() {
            return Err(GarrisonError::Internal(msg));
        }
        let mut users = self.users.lock();
        let key = users
            .values()
            .find(|u| u.id == id)
            .map(|u| u.username.clone());
        if let Some(row) = key.as_deref().and_then(|k| users.get_mut(k)) {
            if let Some(username) = user.username {
                row.username = username;
            }
            if let Some(password_hash) = user.password_hash {
                row.password_hash = password_hash;
            }
            if let Some(status) = user.status {
                row.status = status;
            }
            if let Some(last_login_at) = user.last_login_at {
                row.last_login_at = Some(last_login_at);
            }
        }
        Ok(())
    }
    async fn delete(&self, _tenant_id: i64, _id: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn list(
        &self,
        _tenant_id: i64,
        _offset: i64,
        _limit: i64,
    ) -> GarrisonResult<Vec<UserListRow>> {
        Ok(vec![])
    }
}

// MockInterfaceWithLoginType:支持 login_type 隔离的 GarrisonInterface mock

/// 测试用 GarrisonInterface mock,支持 login_type 隔离(override 新方法)。
pub struct MockInterfaceWithLoginType {
    pub perms: HashMap<String, Vec<String>>,
    pub roles: HashMap<String, Vec<String>>,
}

#[async_trait]
impl GarrisonInterface for MockInterfaceWithLoginType {
    async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.perms.get("default").cloned().unwrap_or_default())
    }
    async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.roles.get("default").cloned().unwrap_or_default())
    }
    // override 新方法以支持多账号隔离
    async fn get_permission_list_with_type(
        &self,
        _login_id: &str,
        login_type: &str,
    ) -> GarrisonResult<Vec<String>> {
        Ok(self.perms.get(login_type).cloned().unwrap_or_default())
    }
    async fn get_role_list_with_type(
        &self,
        _login_id: &str,
        login_type: &str,
    ) -> GarrisonResult<Vec<String>> {
        Ok(self.roles.get(login_type).cloned().unwrap_or_default())
    }
}

// mock 实现自身的单元测试

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    // MockDao 测试

    /// 调用 MockDao 的所有 trait 默认方法 + atomic_test_fallback! 方法以覆盖 async_trait wrapper。
    #[tokio::test]
    async fn mock_dao_default_trait_methods_coverage() {
        use crate::dao::GarrisonDao;
        let dao = MockDao::new();
        dao.set("k1", "v1", 60).await.unwrap();
        let _ = dao.set_if_absent("a1", "v1", 60).await;
        let _ = dao.get_and_delete("a1").await;
        let _ = dao.incr("ctr", 60).await;
        let _ = dao.decr("ctr").await;
        let _ = dao.rename("k1", "k2").await;
        let _ = dao.compare_and_swap("k2", Some("v1"), "v2", 60).await;
        let _ = dao.set_permanent("perm", "val").await;
        let _ = dao.get_with_ttl("k1").await;
        let _ = dao.keys("*").await;
        let _ = dao.find_social_binding(0, "wechat", "openid").await;
        let _ = dao
            .insert_social_binding(0, "1001", "wechat", "openid", None, 0)
            .await;
        let _ = dao.compare_and_update_if_greater("k1", 10, 60).await;
        let _ = dao.eval_lua("return 1", vec![], vec![]).await;
        #[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
        {
            let _ = dao
                .insert_credit_consumption(0, "meter", 1, 100, 100, 0)
                .await;
            let _ = dao.query_credit_consumption(0, 0, 0).await;
            let _ = dao.query_role_hierarchy_edges(0).await;
            let _ = dao.insert_role_hierarchy_edge(0, "child", "parent").await;
            let _ = dao.delete_role_hierarchy_edge(0, "child", "parent").await;
        }
    }

    /// set 后 get 返回相同值。
    #[tokio::test]
    async fn mock_dao_set_then_get_returns_value() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 0).await.unwrap();
        let v = dao.get("k1").await.unwrap();
        assert_eq!(v.as_deref(), Some("v1"));
    }

    /// get 不存在的 key 返回 None。
    #[tokio::test]
    async fn mock_dao_get_missing_returns_none() {
        let dao = MockDao::new();
        let v = dao.get("no-such-key").await.unwrap();
        assert!(v.is_none(), "不存在的 key 应返回 None");
    }

    /// update 已存在的 key 后 get 返回新值。
    #[tokio::test]
    async fn mock_dao_update_existing_key() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 0).await.unwrap();
        dao.update("k1", "v2").await.unwrap();
        assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("v2"));
    }

    /// update 不存在的 key 返回 Dao 错误。
    #[tokio::test]
    async fn mock_dao_update_missing_key_returns_error() {
        let dao = MockDao::new();
        let result = dao.update("missing", "v").await;
        assert!(
            matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("missing")),
            "update 不存在的 key 应返回 Dao 错误包含 key 名,实际: {:?}",
            result
        );
    }

    /// expire 不存在的 key 返回 Dao 错误。
    #[tokio::test]
    async fn mock_dao_expire_missing_key_returns_error() {
        let dao = MockDao::new();
        let result = dao.expire("missing", 60).await;
        assert!(
            matches!(result, Err(GarrisonError::Dao(_))),
            "expire 不存在的 key 应返回 Dao 错误,实际: {:?}",
            result
        );
    }

    /// expire 设置 0 秒后 TTL 变为 None(永久)。
    #[tokio::test]
    async fn mock_dao_expire_zero_seconds_clears_ttl() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 60).await.unwrap();
        dao.expire("k1", 0).await.unwrap();
        assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("v1"));
        let t = dao.get_timeout("k1").await.unwrap();
        assert!(
            t.is_none(),
            "expire 0 后应无 deadline,get_timeout 返回 None"
        );
    }

    /// delete 后 key 不再可读。
    #[tokio::test]
    async fn mock_dao_delete_removes_key() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 0).await.unwrap();
        dao.delete("k1").await.unwrap();
        assert!(dao.get("k1").await.unwrap().is_none());
    }

    /// delete 不存在的 key 仍返回 Ok(幂等)。
    #[tokio::test]
    async fn mock_dao_delete_missing_key_is_idempotent() {
        let dao = MockDao::new();
        assert!(dao.delete("missing").await.is_ok());
    }

    /// get_timeout 不存在的 key 返回 None。
    #[tokio::test]
    async fn mock_dao_get_timeout_missing_returns_none() {
        let dao = MockDao::new();
        let t = dao.get_timeout("missing").await.unwrap();
        assert!(t.is_none());
    }

    /// get_timeout 永久 key(无 TTL)返回 None。
    #[tokio::test]
    async fn mock_dao_get_timeout_permanent_key_returns_none() {
        let dao = MockDao::new();
        dao.set("perm", "v", 0).await.unwrap();
        assert!(dao.get_timeout("perm").await.unwrap().is_none());
    }

    /// set 带 TTL 后 get_timeout 返回 Some(Duration)。
    #[tokio::test]
    async fn mock_dao_get_timeout_returns_some_for_ttl_key() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 3600).await.unwrap();
        let t = dao.get_timeout("k1").await.unwrap();
        assert!(t.is_some(), "带 TTL 的 key get_timeout 应返回 Some");
        let d = t.unwrap();
        assert!(d.as_secs() <= 3600, "剩余时间应 <= 3600s,实际: {:?}", d);
    }

    /// set 带 1 秒 TTL 后等待过期,get 返回 None(覆盖过期清理路径)。
    #[tokio::test]
    async fn mock_dao_get_expired_key_returns_none() {
        let dao = MockDao::new();
        dao.set("expiring", "v", 1).await.unwrap();
        assert_eq!(dao.get("expiring").await.unwrap().as_deref(), Some("v"));
        tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
        assert!(
            dao.get("expiring").await.unwrap().is_none(),
            "过期 key 应返回 None"
        );
    }

    /// deadline 已过期时 get_timeout 返回 None。
    #[tokio::test]
    async fn mock_dao_get_timeout_expired_returns_none() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 1).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
        let t = dao.get_timeout("k1").await.unwrap();
        assert!(
            t.is_none(),
            "deadline <= now 时 get_timeout 应返回 None,实际: {:?}",
            t
        );
    }

    /// set 带 TTL 后 expire 重新设置更长 TTL,key 仍可读。
    #[tokio::test]
    async fn mock_dao_expire_extends_ttl() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 1).await.unwrap();
        dao.expire("k1", 3600).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
        assert_eq!(
            dao.get("k1").await.unwrap().as_deref(),
            Some("v1"),
            "expire 续期后 key 应仍可读"
        );
    }

    // MockFirewall 测试

    /// MockFirewall 的 check_permission/check_role 返回构造时设置的 bool 值。
    #[tokio::test]
    async fn mock_firewall_returns_configured_booleans() {
        let fw = MockFirewall {
            has_permission: true,
            has_role: false,
        };
        assert!(fw.check_permission("u1", "p1").await.unwrap());
        assert!(!fw.check_role("u1", "r1").await.unwrap());
    }

    /// MockFirewall 的 check_role_any 返回 has_role(与 role 列表无关)。
    #[tokio::test]
    async fn mock_firewall_check_role_any_returns_has_role() {
        let fw = MockFirewall {
            has_permission: false,
            has_role: true,
        };
        assert!(fw.check_role_any("u1", &["a", "b"]).await.unwrap());
    }

    /// MockFirewall 的 check_role_all 返回 has_role(与 role 列表无关)。
    #[tokio::test]
    async fn mock_firewall_check_role_all_returns_has_role() {
        let fw = MockFirewall {
            has_permission: false,
            has_role: false,
        };
        assert!(!fw.check_role_all("u1", &["a", "b"]).await.unwrap());
    }

    /// MockFirewall 的 get_permission_list / get_role_list 返回空 Vec。
    #[tokio::test]
    async fn mock_firewall_get_lists_return_empty() {
        let fw = MockFirewall {
            has_permission: true,
            has_role: true,
        };
        assert_eq!(
            fw.get_permission_list("u1").await.unwrap(),
            Vec::<String>::new()
        );
        assert_eq!(fw.get_role_list("u1").await.unwrap(), Vec::<String>::new());
    }

    // MockInterface / MockInterfaceWithPerms 测试

    /// MockInterface 默认返回空权限/角色列表。
    #[tokio::test]
    async fn mock_interface_returns_empty_lists() {
        let iface = MockInterface;
        assert_eq!(
            iface.get_permission_list("u1").await.unwrap(),
            Vec::<String>::new()
        );
        assert_eq!(
            iface.get_role_list("u1").await.unwrap(),
            Vec::<String>::new()
        );
        let _ = iface
            .get_permission_list_with_type("u1", "default")
            .await
            .unwrap();
        let _ = iface
            .get_role_list_with_type("u1", "default")
            .await
            .unwrap();
    }

    /// MockInterfaceWithPerms 返回构造时设置的权限/角色列表。
    #[tokio::test]
    async fn mock_interface_with_perms_returns_configured_lists() {
        let iface = MockInterfaceWithPerms {
            permissions: vec!["user:read".to_string(), "user:write".to_string()],
            roles: vec!["admin".to_string()],
        };
        assert_eq!(
            iface.get_permission_list("u1").await.unwrap(),
            vec!["user:read".to_string(), "user:write".to_string()]
        );
        assert_eq!(
            iface.get_role_list("u1").await.unwrap(),
            vec!["admin".to_string()]
        );
        let _ = iface
            .get_permission_list_with_type("u1", "default")
            .await
            .unwrap();
        let _ = iface
            .get_role_list_with_type("u1", "default")
            .await
            .unwrap();
    }

    // MockInterfaceWithLoginType 测试

    /// get_permission_list_with_type 按 login_type 隔离返回权限列表。
    #[tokio::test]
    async fn mock_interface_with_login_type_returns_perms_by_type() {
        let mut perms = HashMap::new();
        perms.insert(
            "admin".to_string(),
            vec!["admin:read".to_string(), "admin:write".to_string()],
        );
        perms.insert("user".to_string(), vec!["user:read".to_string()]);
        let iface = MockInterfaceWithLoginType {
            perms,
            roles: HashMap::new(),
        };
        assert_eq!(
            iface
                .get_permission_list_with_type("u1", "admin")
                .await
                .unwrap(),
            vec!["admin:read".to_string(), "admin:write".to_string()]
        );
        assert_eq!(
            iface
                .get_permission_list_with_type("u1", "user")
                .await
                .unwrap(),
            vec!["user:read".to_string()]
        );
        assert_eq!(
            iface
                .get_permission_list_with_type("u1", "unknown")
                .await
                .unwrap(),
            Vec::<String>::new()
        );
    }

    /// get_role_list_with_type 按 login_type 隔离返回角色列表。
    #[tokio::test]
    async fn mock_interface_with_login_type_returns_roles_by_type() {
        let mut roles = HashMap::new();
        roles.insert("admin".to_string(), vec!["super-admin".to_string()]);
        let iface = MockInterfaceWithLoginType {
            perms: HashMap::new(),
            roles,
        };
        assert_eq!(
            iface.get_role_list_with_type("u1", "admin").await.unwrap(),
            vec!["super-admin".to_string()]
        );
        assert_eq!(
            iface.get_role_list_with_type("u1", "user").await.unwrap(),
            Vec::<String>::new()
        );
    }

    /// get_permission_list(不带 type)默认查询 "default" login_type。
    #[tokio::test]
    async fn mock_interface_with_login_type_default_uses_default_key() {
        let mut perms = HashMap::new();
        perms.insert("default".to_string(), vec!["default:perm".to_string()]);
        let iface = MockInterfaceWithLoginType {
            perms,
            roles: HashMap::new(),
        };
        assert_eq!(
            iface.get_permission_list("u1").await.unwrap(),
            vec!["default:perm".to_string()]
        );
    }

    // MockUserRepository 测试(cfg-gated: account-credential + db-sqlite)

    #[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
    mod user_repo_tests {
        use super::*;

        fn make_row(id: &str, username: &str) -> UserRow {
            UserRow {
                id: id.to_string(),
                username: username.to_string(),
                password_hash: "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,
            }
        }

        /// insert 后 find_by_username 返回 Some。
        #[tokio::test]
        async fn mock_user_repo_find_by_username_returns_some() {
            let repo = MockUserRepository::new();
            repo.insert(make_row("u-1", "alice"));
            let r = repo.find_by_username(0, "alice").await.unwrap();
            assert!(r.is_some(), "插入后 find_by_username 应返回 Some");
            assert_eq!(r.unwrap().id, "u-1");
        }

        /// find_by_username 不存在的用户返回 None。
        #[tokio::test]
        async fn mock_user_repo_find_by_username_missing_returns_none() {
            let repo = MockUserRepository::new();
            let r = repo.find_by_username(0, "nobody").await.unwrap();
            assert!(r.is_none(), "未插入用户 find_by_username 应返回 None");
        }

        /// find_by_id 按 id 字段查找(与 username 无关)。
        #[tokio::test]
        async fn mock_user_repo_find_by_id_returns_some() {
            let repo = MockUserRepository::new();
            repo.insert(make_row("u-42", "alice"));
            let r = repo.find_by_id(0, "u-42").await.unwrap();
            assert!(r.is_some(), "插入后 find_by_id 应返回 Some");
            assert_eq!(r.unwrap().username, "alice");
        }

        /// find_by_id 不存在返回 None。
        #[tokio::test]
        async fn mock_user_repo_find_by_id_missing_returns_none() {
            let repo = MockUserRepository::new();
            let r = repo.find_by_id(0, "missing").await.unwrap();
            assert!(r.is_none());
        }

        /// create 始终返回 Err(Internal)(mock 未实现 create)。
        #[tokio::test]
        async fn mock_user_repo_create_returns_internal_error() {
            let repo = MockUserRepository::new();
            let new_user = NewUser {
                username: "new".to_string(),
                password_hash: "hash".to_string(),
                status: "active".to_string(),
            };
            let result = repo.create(0, new_user).await;
            assert!(
                matches!(result, Err(GarrisonError::Internal(ref msg)) if msg.contains("stp-mock-not-implemented")),
                "create 应返回 Internal 错误包含 'stp-mock-not-implemented',实际: {:?}",
                result
            );
        }

        /// update 始终返回 Ok(no-op)。
        #[tokio::test]
        async fn mock_user_repo_update_returns_ok() {
            let repo = MockUserRepository::new();
            let update = UpdateUser {
                username: None,
                password_hash: Some("new-hash".to_string()),
                status: Some("inactive".to_string()),
                last_login_at: None,
            };
            repo.update(0, "any-id", update).await.unwrap();
        }

        /// delete 始终返回 Ok(no-op)。
        #[tokio::test]
        async fn mock_user_repo_delete_returns_ok() {
            let repo = MockUserRepository::new();
            repo.delete(0, "any-id").await.unwrap();
        }

        /// list 始终返回空 Vec。
        #[tokio::test]
        async fn mock_user_repo_list_returns_empty() {
            let repo = MockUserRepository::new();
            let v = repo.list(0, 0, 10).await.unwrap();
            assert!(v.is_empty(), "list 应返回空 Vec,实际长度: {}", v.len());
        }
    }
}