garrison 0.7.3

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

//! TokenLogic trait — Token 类型校验与刷新契约。
//! 从 v0.5.2 起,从 `GarrisonLogic` 上帝 trait 拆分;本 trait 承接 token 类型校验、
//! 显式 token 验证、token 刷新 5 个方法。super-trait 为 [`SessionLogic`]
//! (token 校验依赖会话状态,默认实现委托 [`check_login`](SessionLogic::check_login))。
//!
//! # 返回类型迁移
//!
//! `verify_token()` 返回类型从 `GarrisonResult<i64>` 迁移为 `GarrisonResult<String>`
//! (v0.5.2 LoginId 迁移:删除 LoginId newtype,全栈使用 String/&str)。

use super::GarrisonLogicDefault;
use crate::core::token::TokenStyleFactory;
use crate::error::{GarrisonError, GarrisonResult};
// GarrisonEvent 仅在 refresh_token(protocol-jwt feature)中使用,故 import 同时门控两个 feature
// 避免 listener 启用但 protocol-jwt 关闭时出现 unused import 警告
#[cfg(all(feature = "listener", feature = "protocol-jwt"))]
use crate::listener::GarrisonEvent;
use crate::stp::session::SessionLogic;
use async_trait::async_trait;

/// Token 逻辑 trait,定义 token 类型校验、显式验证与刷新契约。
///
/// 对应 `StpLogic` 的 token 类型区分与 `getTokenValue` 校验部分。
///
/// # 默认实现
///
/// - [`check_access_token`](Self::check_access_token) /
///   [`check_client_token`](Self::check_client_token) /
///   [`check_temp_token`](Self::check_temp_token):委托
///   [`SessionLogic::check_login`],已登录返回 `Ok(())`,未登录返回 `Err(NotLogin)`。
///   业务方可在子类 override 实现类型区分(如校验 token 是否为 access_token 类型)。
/// - [`verify_token`](Self::verify_token) /
///   [`refresh_token`](Self::refresh_token):默认返回 `NotImplemented`,
///   由 `GarrisonLogicDefault` 的 impl 覆写为委托 `core-token::Token::verify` /
///   `JwtHandler::refresh`。
#[async_trait]
pub trait TokenLogic: SessionLogic {
    /// 校验 access_token 类型会话。
    ///
    /// 语义别名:默认实现委托 [`check_login`](SessionLogic::check_login),
    /// 已登录返回 `Ok(())`,未登录返回 `Err(NotLogin)`。
    ///
    /// # 返回
    /// - `Ok(())`: 当前会话 token 有效(已登录)。
    ///
    /// # 错误
    /// - 未登录:`GarrisonError::NotLogin`。
    async fn check_access_token(&self) -> GarrisonResult<()> {
        let valid = self.check_login().await?;
        if valid {
            Ok(())
        } else {
            Err(GarrisonError::NotLogin(
                "stp-token-invalid-or-not-login::".to_string(),
            ))
        }
    }

    /// 校验 client_token 类型会话。
    ///
    /// 语义别名:默认实现委托 [`check_login`](SessionLogic::check_login)。
    ///
    /// # 返回
    /// - `Ok(())`: 当前会话 token 有效(已登录)。
    ///
    /// # 错误
    /// - 未登录:`GarrisonError::NotLogin`。
    async fn check_client_token(&self) -> GarrisonResult<()> {
        let valid = self.check_login().await?;
        if valid {
            Ok(())
        } else {
            Err(GarrisonError::NotLogin(
                "stp-token-invalid-or-not-login::".to_string(),
            ))
        }
    }

    /// 校验 temp_token 类型会话。
    ///
    /// 语义别名:默认实现委托 [`check_login`](SessionLogic::check_login)。
    ///
    /// # 返回
    /// - `Ok(())`: 当前会话 token 有效(已登录)。
    ///
    /// # 错误
    /// - 未登录:`GarrisonError::NotLogin`。
    async fn check_temp_token(&self) -> GarrisonResult<()> {
        let valid = self.check_login().await?;
        if valid {
            Ok(())
        } else {
            Err(GarrisonError::NotLogin(
                "stp-token-invalid-or-not-login::".to_string(),
            ))
        }
    }

    /// 验证显式传入的 token 并返回关联的 `String`。
    ///
    /// 委托 `core-token::Token::verify` 实现。与
    /// [`check_login`](SessionLogic::check_login) 区别:
    /// `check_login` 从 task_local 读取 token;`verify_token` 接收显式 token 参数。
    ///
    /// # 参数
    /// - `token`: 待验证的 token 字符串。
    ///
    /// # 返回
    /// - `Ok(login_id)`: token 有效,返回关联的 `String`。
    ///
    /// # 错误
    /// - `GarrisonError::InvalidToken`: token 无效或不包含 login_id。
    /// - `GarrisonError::NotImplemented`: 默认实现未委托 Token trait。
    async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
        Err(GarrisonError::NotImplemented(
            "verify_token 需子类 override 委托 core-token::Token::verify".to_string(),
        ))
    }

    /// 刷新 token。
    ///
    /// 仅在启用 `protocol-jwt` feature 时由 `JwtHandler` 提供有效实现。
    ///
    /// # 参数
    /// - `token`: 待刷新的旧 token 字符串。
    ///
    /// # 返回
    /// - `Ok(new_token)`: 刷新后的新 token 字符串。
    ///
    /// # 错误
    /// - `GarrisonError::NotImplemented`: 未启用 protocol-jwt feature。
    /// - `GarrisonError::InvalidToken`: token 已过期或无效。
    async fn refresh_token(&self, _token: &str) -> GarrisonResult<String> {
        Err(GarrisonError::NotImplemented(
            "refresh_token 需启用 protocol-jwt feature".to_string(),
        ))
    }
}

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

#[async_trait]
impl TokenLogic for GarrisonLogicDefault {
    async fn verify_token(&self, token: &str) -> GarrisonResult<String> {
        // 委托 core-token::Token::verify
        // spec: "不泄露 token 具体失效原因(统一 InvalidToken)"
        let token_handler =
            TokenStyleFactory::new(&self.config.token_style, self.config.jwt_secret.as_str())?;
        match token_handler.verify(token) {
            Ok(Some(login_id)) => Ok(login_id),
            Ok(None) => Err(GarrisonError::InvalidToken(
                "stp-token-invalid-or-no-login-id::".to_string(),
            )),
            Err(_) => Err(GarrisonError::InvalidToken(
                "stp-token-invalid::".to_string(),
            )),
        }
    }

    #[cfg(feature = "protocol-jwt")]
    async fn refresh_token(&self, token: &str) -> GarrisonResult<String> {
        // 启用 protocol-jwt 时委托 JwtHandler::refresh
        if self.config.token_style != "jwt" {
            return Err(GarrisonError::NotImplemented(
                "refresh_token 仅在 token_style=jwt 时可用".to_string(),
            ));
        }
        // 获取 login_id(用于 plugin/listener 回调)
        let login_id = self.verify_token(token).await?;
        let handler = crate::protocol::jwt::JwtHandler::new(self.config.jwt_secret.as_str());
        let new_token = handler.refresh(token, self.config.timeout)?;
        // auto-wire: 触发 plugin on_login(新 token)
        if let Some(pm) = &self.plugin_manager {
            pm.on_login(&login_id, &new_token);
        }
        // 广播 TokenRefresh 事件(替换原 Login 事件)
        #[cfg(feature = "listener")]
        if let Some(lm) = &self.listener_manager {
            lm.broadcast(&GarrisonEvent::TokenRefresh {
                login_id,
                old_token: token.to_string(),
                new_token: new_token.clone(),
                request_context: None,
            })
            .await;
        }
        Ok(new_token)
    }
}

#[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 必需方法)。
    /// `TokenLogic` 5 个方法均有默认实现,空 impl 即可获得全部默认行为。
    struct MockToken {
        config: Arc<GarrisonConfig>,
        logged_in: bool,
    }

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

    #[async_trait]
    impl SessionLogic for MockToken {
        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(self.logged_in)
        }
        async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
            if self.logged_in {
                Ok(Some("42".to_string()))
            } else {
                Ok(None)
            }
        }
    }

    #[async_trait]
    impl TokenLogic for MockToken {}

    #[tokio::test]
    async fn check_access_token_ok_when_logged_in() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        mock.check_access_token().await.unwrap();
    }

    #[tokio::test]
    async fn check_access_token_denies_when_not_logged_in() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: false,
        };
        let result = mock.check_access_token().await;
        assert!(matches!(result, Err(GarrisonError::NotLogin(_))));
    }

    /// 验证 `check_client_token` 在已登录时返回 Ok(())。
    ///
    /// 覆盖 trait 默认实现 `check_client_token` 的 Ok 分支(token.rs 第 69-78 行)。
    #[tokio::test]
    async fn check_client_token_ok_when_logged_in() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        mock.check_client_token().await.unwrap();
    }

    /// 验证 `check_client_token` 在未登录时返回 Err(NotLogin)。
    ///
    /// 覆盖 trait 默认实现 `check_client_token` 的 Err 分支。
    #[tokio::test]
    async fn check_client_token_denies_when_not_logged_in() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: false,
        };
        let result = mock.check_client_token().await;
        assert!(
            matches!(result, Err(GarrisonError::NotLogin(ref msg)) if msg.contains("stp-token-invalid-or-not-login")),
            "未登录时应返回 NotLogin 包含 'client_token',实际: {:?}",
            result
        );
    }

    /// 验证 `check_temp_token` 在已登录时返回 Ok(())。
    ///
    /// 覆盖 trait 默认实现 `check_temp_token` 的 Ok 分支(token.rs 第 89-98 行)。
    #[tokio::test]
    async fn check_temp_token_ok_when_logged_in() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        mock.check_temp_token().await.unwrap();
    }

    /// 验证 `check_temp_token` 在未登录时返回 Err(NotLogin)。
    ///
    /// 覆盖 trait 默认实现 `check_temp_token` 的 Err 分支。
    #[tokio::test]
    async fn check_temp_token_denies_when_not_logged_in() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: false,
        };
        let result = mock.check_temp_token().await;
        assert!(
            matches!(result, Err(GarrisonError::NotLogin(ref msg)) if msg.contains("stp-token-invalid-or-not-login")),
            "未登录时应返回 NotLogin 包含 'temp_token',实际: {:?}",
            result
        );
    }

    #[tokio::test]
    async fn verify_token_default_returns_not_implemented() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        let result = mock.verify_token("some-token").await;
        assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
    }

    #[tokio::test]
    async fn refresh_token_default_returns_not_implemented() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        let result = mock.refresh_token("old").await;
        assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
    }

    // ========================================================================
    // MockToken SessionLogic 方法覆盖测试
    // ========================================================================

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

    /// MockToken::login_with_token / logout / logout_by_login_id / kickout /
    /// kickout_by_token / revoke_token 均返回 Ok(())。
    #[tokio::test]
    async fn mock_token_session_methods_return_ok() {
        let mock = MockToken {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        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();
    }

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

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

    // ========================================================================
    // GarrisonLogicDefault impl 覆盖测试(verify_token / refresh_token)
    // ========================================================================

    mod default_impl_coverage {
        use super::*;
        use crate::dao::GarrisonDao;
        use crate::session::GarrisonSession;
        use crate::stp::mock::{MockDao, MockFirewall};
        use crate::strategy::GarrisonPermissionStrategy;
        use std::sync::Arc;

        /// A11: simple 模式测试用的 HMAC 密钥(与 make_logic 中设置的 jwt_secret 一致)。
        const STP_TOKEN_SIMPLE_TEST_SECRET: &str = "stp-token-simple-test-secret";

        /// A11: 构造测试用 JwtSecret(兼容 protocol-zeroize 启用/禁用两种配置)。
        fn test_jwt_secret(secret: &str) -> crate::config::JwtSecret {
            #[cfg(feature = "protocol-zeroize")]
            {
                secret.to_string().into()
            }
            #[cfg(not(feature = "protocol-zeroize"))]
            {
                secret.to_string()
            }
        }

        /// 构造 GarrisonLogicDefault,token_style 可配置。
        fn make_logic(token_style: &str) -> 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 = token_style.to_string();
            // A11: simple 模式下 verify_token 委托 core-token SimpleTokenStyle(需 HMAC),
            // 设置非空 jwt_secret 避免 fail-closed。
            if token_style == "simple" {
                config.jwt_secret = test_jwt_secret(STP_TOKEN_SIMPLE_TEST_SECRET);
            }
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
                has_permission: true,
                has_role: true,
            });
            GarrisonLogicDefault::new(session, Arc::new(config), firewall)
        }

        /// verify_token + simple token_style → 返回 login_id。
        ///
        /// 覆盖 token.rs 第 147-159 行 GarrisonLogicDefault::verify_token 的
        /// `Ok(Some(login_id))` 分支。
        ///
        /// A11: SimpleTokenStyle 改为 HMAC-SHA256 签名格式 `<login_id>-<uuid>.<hmac>`,
        /// 需用 SimpleTokenStyle::new(secret).generate 生成合法 token。
        /// 注意:login_id 不能含 `-`(verify 在首个 `-` 处分割 login_id 与 uuid 部分)。
        #[cfg(feature = "secure-simple-token")]
        #[tokio::test]
        async fn verify_token_simple_style_returns_login_id() {
            let logic = make_logic("simple");
            // A11: 用 SimpleTokenStyle 生成合法 HMAC token
            let style =
                crate::core::token::SimpleTokenStyle::new(STP_TOKEN_SIMPLE_TEST_SECRET.to_string());
            let token = crate::core::token::Token::generate(&style, "verifyuser", 3600).unwrap();
            let result = logic.verify_token(&token).await;
            assert!(
                result.is_ok(),
                "simple token verify_token 应返回 Ok,实际: {:?}",
                result
            );
            assert_eq!(
                result.unwrap(),
                "verifyuser",
                "verify_token 应提取 login_id 'verifyuser'"
            );
        }

        /// verify_token + uuid token_style → 返回 InvalidToken(UUID 无法编码 login_id)。
        ///
        /// 覆盖 token.rs 第 154-156 行 `Ok(None)` → `Err(InvalidToken)` 分支。
        #[tokio::test]
        async fn verify_token_uuid_style_returns_invalid_token() {
            let logic = make_logic("uuid");
            let result = logic.verify_token("some-uuid-token").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidToken(ref msg)) if msg.contains("stp-token-invalid-or-no-login-id")),
                "uuid token verify_token 应返回 InvalidToken 包含 '不包含 login_id',实际: {:?}",
                result
            );
        }

        /// verify_token + 无效 simple token(无连字符)→ 返回 InvalidToken。
        ///
        /// 覆盖 token.rs 第 157 行 `Err(_) => Err(InvalidToken)` 分支。
        ///
        /// 注意:SimpleTokenStyle::parse 在无 `-` 时返回 Err,
        /// 但 verify 使用 split_once 返回 Ok(None) → InvalidToken。
        #[tokio::test]
        async fn verify_token_invalid_simple_token_returns_invalid_token() {
            let logic = make_logic("simple");
            // 无连字符的 simple token:split_once('-') 返回 None → Ok(None) → InvalidToken
            let result = logic.verify_token("nodashtoken").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidToken(_))),
                "无效 simple token 应返回 InvalidToken,实际: {:?}",
                result
            );
        }

        /// verify_token + JWT token → 返回 login_id。
        ///
        /// 覆盖 token.rs 第 153 行 `Ok(Some(login_id))` 分支(JWT 路径)。
        #[cfg(feature = "protocol-jwt")]
        #[tokio::test]
        async fn verify_token_jwt_style_returns_login_id() {
            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 = "jwt".to_string();
            config.jwt_secret = "verify-jwt-secret".to_string().into();
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
                has_permission: true,
                has_role: true,
            });
            let logic = GarrisonLogicDefault::new(session, Arc::new(config), firewall);

            // 签发 JWT token
            let handler = crate::protocol::jwt::JwtHandler::new("verify-jwt-secret");
            let jwt_token = handler.sign("jwt-verify-user", 3600).unwrap();

            let result = logic.verify_token(&jwt_token).await;
            assert!(
                result.is_ok(),
                "JWT token verify_token 应返回 Ok,实际: {:?}",
                result
            );
            assert_eq!(
                result.unwrap(),
                "jwt-verify-user",
                "verify_token 应提取 login_id 'jwt-verify-user'"
            );
        }

        /// verify_token + 无效 JWT → 返回 InvalidToken。
        ///
        /// 覆盖 token.rs 第 157 行 `Err(_) => Err(InvalidToken("token 无效"))` 分支。
        #[cfg(feature = "protocol-jwt")]
        #[tokio::test]
        async fn verify_token_invalid_jwt_returns_invalid_token() {
            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 = "jwt".to_string();
            config.jwt_secret = "verify-jwt-secret".to_string().into();
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
                has_permission: true,
                has_role: true,
            });
            let logic = GarrisonLogicDefault::new(session, Arc::new(config), firewall);

            let result = logic.verify_token("invalid.jwt.token").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidToken(_))),
                "无效 JWT 应返回 InvalidToken,实际: {:?}",
                result
            );
        }

        /// refresh_token + 非 JWT token_style → 返回 NotImplemented。
        ///
        /// 覆盖 token.rs 第 164-168 行 `token_style != "jwt"` → NotImplemented 分支。
        #[cfg(feature = "protocol-jwt")]
        #[tokio::test]
        async fn refresh_token_non_jwt_style_returns_not_implemented() {
            let logic = make_logic("uuid");
            let result = logic.refresh_token("any-token").await;
            assert!(
                matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("jwt")),
                "非 JWT token_style refresh_token 应返回 NotImplemented 包含 'jwt',实际: {:?}",
                result
            );
        }

        /// refresh_token + JWT token_style + 有效 token → 返回新 token。
        ///
        /// 覆盖 token.rs 第 162-189 行 refresh_token 成功路径。
        #[cfg(feature = "protocol-jwt")]
        #[tokio::test]
        async fn refresh_token_jwt_valid_returns_new_token() {
            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 = "jwt".to_string();
            config.jwt_secret = "refresh-jwt-secret".to_string().into();
            config.timeout = 3600;
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
                has_permission: true,
                has_role: true,
            });
            let logic = GarrisonLogicDefault::new(session, Arc::new(config), firewall);

            // 签发 JWT token
            let handler = crate::protocol::jwt::JwtHandler::new("refresh-jwt-secret");
            let old_token = handler.sign("refresh-user", 3600).unwrap();

            let result = logic.refresh_token(&old_token).await;
            assert!(
                result.is_ok(),
                "JWT refresh_token 应返回 Ok,实际: {:?}",
                result
            );
            let new_token = result.unwrap();
            assert_ne!(
                new_token, old_token,
                "refresh_token 应返回新 token,与旧 token 不同"
            );
        }

        /// refresh_token + 无效 JWT → 返回错误(verify_token 失败)。
        ///
        /// 覆盖 token.rs 第 170 行 `let login_id = self.verify_token(token).await?` 错误传播。
        #[cfg(feature = "protocol-jwt")]
        #[tokio::test]
        async fn refresh_token_invalid_jwt_returns_error() {
            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 = "jwt".to_string();
            config.jwt_secret = "refresh-jwt-secret".to_string().into();
            config.timeout = 3600;
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall {
                has_permission: true,
                has_role: true,
            });
            let logic = GarrisonLogicDefault::new(session, Arc::new(config), firewall);

            let result = logic.refresh_token("invalid.jwt.token").await;
            assert!(
                result.is_err(),
                "无效 JWT refresh_token 应返回 Err,实际: {:?}",
                result
            );
        }
    }
}