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
//! OAuth2 客户端管理模块:`OAuth2Client` + `OAuth2ClientStore` trait + `DaoOAuth2ClientStore` 实现。
//!
//! `client_secret` 以 Argon2id 哈希存储不明文,`pkce_required` 恒为 `true`;客户端配置序列化为 JSON
//! 存于 `DaoKeyPrefix::OAuth2Client`(`oauth2:client:`)前缀下。

use crate::constants::DaoKeyPrefix;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use argon2::{
    password_hash::{phc::PasswordHash, PasswordHasher, PasswordVerifier},
    Algorithm, Argon2, Version,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// OAuth2 授权类型(RFC 6749 定义的四种 grant_type)。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
    /// 授权码流程(authorization_code)。
    AuthorizationCode,
    /// 刷新令牌流程(refresh_token)。
    RefreshToken,
    /// 客户端凭证流程(client_credentials)。
    ClientCredentials,
    /// 密码流程(password,RFC 6749 §4.3)。
    Password,
}

impl GrantType {
    /// 返回 OAuth2 规范的 grant_type 字符串。
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::AuthorizationCode => "authorization_code",
            Self::RefreshToken => "refresh_token",
            Self::ClientCredentials => "client_credentials",
            Self::Password => "password",
        }
    }
}

impl std::str::FromStr for GrantType {
    type Err = GarrisonError;

    /// 从字符串解析 grant_type(RFC 6749 §4):与 `Annotation` / `DigestAlgorithm` 一致采用 `std::str::FromStr`
    /// trait,调用方用 `"authorization_code".parse::<GrantType>()`,避免遮蔽 std trait。
    fn from_str(s: &str) -> GarrisonResult<Self> {
        match s {
            "authorization_code" => Ok(Self::AuthorizationCode),
            "refresh_token" => Ok(Self::RefreshToken),
            "client_credentials" => Ok(Self::ClientCredentials),
            "password" => Ok(Self::Password),
            other => Err(GarrisonError::OAuth2(format!(
                "unsupported_grant_type: {other}"
            ))),
        }
    }
}

/// OAuth2 客户端配置(RFC 6749 §2):管理客户端元数据与凭证;`client_secret` 以 Argon2id 哈希存储,`pkce_required` 始终为 `true`(强制 PKCE)。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2Client {
    /// 客户端 ID(唯一标识)。
    pub client_id: String,
    /// 客户端密钥的 Argon2id 哈希字符串。
    pub client_secret_hash: String,
    /// 允许的 redirect_uri 白名单。
    pub redirect_uris: Vec<String>,
    /// 允许的 grant_type 列表。
    pub grant_types: Vec<GrantType>,
    /// 允许的 scope 列表。
    pub scopes: Vec<String>,
    /// 是否强制 PKCE(始终为 `true`)。
    pub pkce_required: bool,
}

impl OAuth2Client {
    /// 创建新的 OAuth2 客户端:对 `client_secret` 执行 Argon2id 哈希后存储,`pkce_required` 恒为 `true`。
    pub fn new(
        client_id: &str,
        client_secret: &str,
        redirect_uris: Vec<String>,
        grant_types: Vec<GrantType>,
        scopes: Vec<String>,
    ) -> GarrisonResult<Self> {
        if client_id.is_empty() {
            return Err(GarrisonError::InvalidParam("oauth2-client-id-empty".into()));
        }
        if client_secret.is_empty() {
            return Err(GarrisonError::InvalidParam(
                "oauth2-client-secret-empty".into(),
            ));
        }
        // redirect_uri 白名单后续按精确匹配被信任,入库前做基本合法性校验:
        // 拒绝空串、超长(> 2048)与含空白/控制字符的条目(绝对 URI 必含 scheme 分隔 `:`),
        // 防止畸形 URI 静默进入白名单(纵深防御)。
        const REDIRECT_URI_MAX_LEN: usize = 2048;
        for uri in &redirect_uris {
            if uri.is_empty()
                || uri.len() > REDIRECT_URI_MAX_LEN
                || !uri.contains(':')
                || uri.chars().any(|c| c.is_whitespace() || c.is_control())
            {
                return Err(GarrisonError::InvalidParam(
                    "oauth2-client-redirect-uri-invalid".to_string(),
                ));
            }
        }
        let client_secret_hash = hash_secret(client_secret)?;
        Ok(Self {
            client_id: client_id.to_string(),
            client_secret_hash,
            redirect_uris,
            grant_types,
            scopes,
            pkce_required: true,
        })
    }

    /// 验证客户端密钥:将明文与存储的 Argon2id 哈希比对;哈希格式无效返回 `Err`。
    pub fn verify_secret(&self, client_secret: &str) -> GarrisonResult<bool> {
        verify_secret(client_secret, &self.client_secret_hash)
    }

    /// 校验 redirect_uri 是否在白名单中(精确匹配,不支持通配符),防 open redirect 攻击。
    pub fn is_redirect_uri_allowed(&self, redirect_uri: &str) -> bool {
        self.redirect_uris.iter().any(|uri| uri == redirect_uri)
    }

    /// 校验是否允许指定 grant_type。
    pub fn allows_grant_type(&self, grant_type: &GrantType) -> bool {
        self.grant_types.iter().any(|gt| gt == grant_type)
    }

    /// 校验是否允许指定 scope:fail-closed(空 `scopes` 不允许任何 scope,需显式配置);
    /// `"*"` 通配元素表示允许任意 scope。
    pub fn allows_scope(&self, scope: &str) -> bool {
        self.scopes.iter().any(|s| s == "*" || s == scope)
    }

    /// 批量校验 scope 列表是否全部被允许:任一不在 `scopes` 内即返回 `Err`(含 `invalid_scope`)。
    pub fn validate_scopes(&self, scopes: &[String]) -> GarrisonResult<()> {
        if scopes.is_empty() {
            return Ok(());
        }
        if self.scopes.iter().any(|s| s == "*") {
            return Ok(());
        }
        for s in scopes {
            if !self.allows_scope(s) {
                return Err(GarrisonError::OAuth2(format!(
                    "oauth2-server-client-invalid-scope::{}",
                    s
                )));
            }
        }
        Ok(())
    }
}

/// OAuth2 客户端存储 trait:CRUD 操作抽象(`DaoOAuth2ClientStore` 基于 `GarrisonDao` 实现)。
#[async_trait]
pub trait OAuth2ClientStore: Send + Sync {
    /// 创建客户端(若 client_id 已存在则返回错误)。
    async fn create(&self, client: OAuth2Client) -> GarrisonResult<()>;

    /// 获取客户端配置。
    async fn get(&self, client_id: &str) -> GarrisonResult<Option<OAuth2Client>>;

    /// 更新客户端配置(必须已存在)。
    async fn update(&self, client: OAuth2Client) -> GarrisonResult<()>;

    /// 删除客户端。
    async fn delete(&self, client_id: &str) -> GarrisonResult<()>;

    /// 列出所有客户端(按 client_id 排序)。
    async fn list(&self) -> GarrisonResult<Vec<OAuth2Client>>;
}

/// 基于 `GarrisonDao` 的 `OAuth2ClientStore` 实现:客户端配置序列化为 JSON,key 为 `oauth2:client:{client_id}`;
/// `list()` 经 `keys()` 扫描实现。
pub struct DaoOAuth2ClientStore {
    dao: Arc<dyn GarrisonDao>,
}

impl DaoOAuth2ClientStore {
    /// 创建 store 实例。
    pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
        Self { dao }
    }

    /// 构造 DAO key。
    fn build_key(client_id: &str) -> String {
        DaoKeyPrefix::OAuth2Client.build_key(client_id)
    }
}

#[async_trait]
impl OAuth2ClientStore for DaoOAuth2ClientStore {
    async fn create(&self, client: OAuth2Client) -> GarrisonResult<()> {
        let key = Self::build_key(&client.client_id);
        let json = serde_json::to_string(&client).map_err(|e| {
            GarrisonError::Internal(format!("oauth2-server-client-serialize::{}", e))
        })?;
        // 原子 create-if-absent(SETNX 语义):消除 get→set_permanent 的 check-then-act TOCTOU 竞态
        if !self.dao.set_if_absent(&key, &json, 0).await? {
            return Err(GarrisonError::OAuth2(format!(
                "oauth2-server-client-exists::{}",
                client.client_id
            )));
        }
        Ok(())
    }

    async fn get(&self, client_id: &str) -> GarrisonResult<Option<OAuth2Client>> {
        let key = Self::build_key(client_id);
        match self.dao.get(&key).await? {
            Some(json) => {
                let client: OAuth2Client = serde_json::from_str(&json).map_err(|e| {
                    GarrisonError::Internal(format!("oauth2-server-client-deserialize::{}", e))
                })?;
                Ok(Some(client))
            },
            None => Ok(None),
        }
    }

    async fn update(&self, client: OAuth2Client) -> GarrisonResult<()> {
        let key = Self::build_key(&client.client_id);
        let current = self.dao.get(&key).await?.ok_or_else(|| {
            GarrisonError::OAuth2(format!(
                "oauth2-server-client-not-found::{}",
                client.client_id
            ))
        })?;
        let json = serde_json::to_string(&client).map_err(|e| {
            GarrisonError::Internal(format!("oauth2-server-client-serialize::{}", e))
        })?;
        // 原子 compare-and-swap:仅当值仍为读取时的内容才写入,消除 get→update 的 TOCTOU(并发丢失更新 / 覆盖)
        if !self
            .dao
            .compare_and_swap(&key, Some(current.as_str()), &json, 0)
            .await?
        {
            return Err(GarrisonError::OAuth2(format!(
                "oauth2-server-client-update-conflict::{}",
                client.client_id
            )));
        }
        Ok(())
    }

    async fn delete(&self, client_id: &str) -> GarrisonResult<()> {
        let key = Self::build_key(client_id);
        self.dao.delete(&key).await
    }

    async fn list(&self) -> GarrisonResult<Vec<OAuth2Client>> {
        let pattern = format!("{}*", DaoKeyPrefix::OAuth2Client.as_str());
        let keys = self.dao.keys(&pattern).await?;
        let mut clients = Vec::with_capacity(keys.len());
        for key in keys {
            match self.dao.get(&key).await? {
                Some(json) => {
                    let client: OAuth2Client = serde_json::from_str(&json).map_err(|e| {
                        GarrisonError::Internal(format!("oauth2-server-client-deserialize::{}", e))
                    })?;
                    clients.push(client);
                },
                None => continue,
            }
        }
        clients.sort_by(|a, b| a.client_id.cmp(&b.client_id));
        Ok(clients)
    }
}

// 内部 Argon2 哈希工具

/// 共享 Argon2 构造:`hash_secret` 与 `verify_secret` 必须使用完全相同的算法 / 版本 / 参数,
/// 否则 crate 默认参数一旦调整,存量哈希校验会静默失败。参数:Argon2id, V0x13, `Params::default()`(m=19456, t=2, p=1)。
fn argon2_instance() -> Argon2<'static> {
    Argon2::new(
        Algorithm::Argon2id,
        Version::V0x13,
        argon2::Params::default(),
    )
}

/// 使用 Argon2id 哈希密钥(与 `account::credential::Argon2Hasher` 独立,不引入 account-credential 依赖);
/// 实例构造统一由 [`argon2_instance`] 提供。
fn hash_secret(secret: &str) -> GarrisonResult<String> {
    let hash = argon2_instance()
        .hash_password(secret.as_bytes())
        .map_err(|e| GarrisonError::Internal(format!("oauth2-server-client-hash::{}", e)))?;
    Ok(hash.to_string())
}

/// 验证明文密钥与 Argon2id 哈希是否匹配(与 `hash_secret` 共享 [`argon2_instance`],保证参数永远一致)。
fn verify_secret(secret: &str, hash_str: &str) -> GarrisonResult<bool> {
    let parsed = PasswordHash::new(hash_str).map_err(|e| {
        GarrisonError::InvalidParam(format!("oauth2-server-client-hash-format::{}", e))
    })?;
    Ok(argon2_instance()
        .verify_password(secret.as_bytes(), &parsed)
        .is_ok())
}

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

    // GrantType 测试

    #[test]
    fn grant_type_as_str() {
        assert_eq!(GrantType::AuthorizationCode.as_str(), "authorization_code");
        assert_eq!(GrantType::RefreshToken.as_str(), "refresh_token");
        assert_eq!(GrantType::ClientCredentials.as_str(), "client_credentials");
        assert_eq!(GrantType::Password.as_str(), "password");
    }

    #[test]
    fn grant_type_serde_roundtrip() {
        let gt = GrantType::AuthorizationCode;
        let json = serde_json::to_string(&gt).unwrap();
        assert_eq!(json, "\"authorization_code\"");
        let de: GrantType = serde_json::from_str(&json).unwrap();
        assert_eq!(de, gt);
    }

    // FromStr trait 测试(与项目内 Annotation/DigestAlgorithm 惯例对齐)

    #[test]
    fn grant_type_from_str_parses_all_known_types() {
        assert_eq!(
            "authorization_code".parse::<GrantType>().unwrap(),
            GrantType::AuthorizationCode
        );
        assert_eq!(
            "refresh_token".parse::<GrantType>().unwrap(),
            GrantType::RefreshToken
        );
        assert_eq!(
            "client_credentials".parse::<GrantType>().unwrap(),
            GrantType::ClientCredentials
        );
        assert_eq!(
            "password".parse::<GrantType>().unwrap(),
            GrantType::Password
        );
    }

    #[test]
    fn grant_type_from_str_rejects_unknown() {
        let err = "unknown_grant".parse::<GrantType>().unwrap_err();
        assert!(
            matches!(err, GarrisonError::OAuth2(_)),
            "未知 grant_type 应返回 OAuth2 错误"
        );
        assert!(
            err.to_string().contains("unsupported_grant_type"),
            "错误信息应包含 unsupported_grant_type"
        );
    }

    #[test]
    fn grant_type_from_str_roundtrips_with_as_str() {
        for original in [
            GrantType::AuthorizationCode,
            GrantType::RefreshToken,
            GrantType::ClientCredentials,
            GrantType::Password,
        ] {
            let s = original.as_str();
            let parsed: GrantType = s.parse().unwrap();
            assert_eq!(parsed, original, "as_str -> FromStr 往返失败");
        }
    }

    // OAuth2Client 测试

    #[test]
    fn new_client_hashes_secret_and_enforces_pkce() {
        let client = OAuth2Client::new(
            "client-001",
            "super-secret",
            vec!["https://app.example.com/callback".into()],
            vec![GrantType::AuthorizationCode],
            vec!["read".into()],
        )
        .expect("创建客户端");
        assert_eq!(client.client_id, "client-001");
        assert_ne!(client.client_secret_hash, "super-secret");
        assert!(client.client_secret_hash.starts_with("$argon2id$"));
        assert!(client.pkce_required, "pkce_required 必须始终为 true");
        assert_eq!(client.redirect_uris.len(), 1);
        assert_eq!(client.grant_types.len(), 1);
    }

    #[test]
    fn new_client_rejects_empty_id() {
        let err = OAuth2Client::new("", "secret", vec![], vec![], vec![]).unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
    }

    #[test]
    fn new_client_rejects_empty_secret() {
        let err = OAuth2Client::new("cid", "", vec![], vec![], vec![]).unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
    }

    /// redirect_uri 白名单条目入库前须通过基本合法性校验(纵深防御)。
    #[test]
    fn new_client_rejects_invalid_redirect_uris() {
        let err = OAuth2Client::new("cid", "s", vec!["".into()], vec![], vec![]).unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
        // 缺 scheme(无 `:`)
        let err = OAuth2Client::new(
            "cid",
            "s",
            vec!["app.example.com/cb".into()],
            vec![],
            vec![],
        )
        .unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
        // 含空白字符
        let err = OAuth2Client::new(
            "cid",
            "s",
            vec!["https://app.example.com/ cb".into()],
            vec![],
            vec![],
        )
        .unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
        // 超长(> 2048)
        let long_uri = format!("https://app.example.com/{}", "a".repeat(2048));
        let err = OAuth2Client::new("cid", "s", vec![long_uri], vec![], vec![]).unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
        // 合法 URI(含自定义 scheme)不受影响
        assert!(
            OAuth2Client::new("cid", "s", vec!["myapp://callback".into()], vec![], vec![]).is_ok()
        );
    }

    #[test]
    fn verify_secret_matches_correct() {
        let client = OAuth2Client::new("client-001", "super-secret", vec![], vec![], vec![])
            .expect("创建客户端");
        assert!(client.verify_secret("super-secret").expect("验证"));
    }

    #[test]
    fn verify_secret_rejects_wrong() {
        let client = OAuth2Client::new("client-001", "super-secret", vec![], vec![], vec![])
            .expect("创建客户端");
        assert!(!client.verify_secret("wrong-secret").expect("验证"));
    }

    #[test]
    fn verify_secret_rejects_invalid_hash() {
        let err = verify_secret("secret", "not-a-valid-hash").unwrap_err();
        assert!(matches!(err, GarrisonError::InvalidParam(_)));
    }

    // redirect_uri 白名单测试

    #[test]
    fn is_redirect_uri_allowed_exact_match() {
        let client = OAuth2Client::new(
            "c1",
            "s",
            vec![
                "https://app1.example.com/callback".into(),
                "https://app2.example.com/callback".into(),
            ],
            vec![],
            vec![],
        )
        .unwrap();
        assert!(client.is_redirect_uri_allowed("https://app1.example.com/callback"));
        assert!(client.is_redirect_uri_allowed("https://app2.example.com/callback"));
    }

    #[test]
    fn is_redirect_uri_allowed_rejects_not_in_whitelist() {
        let client = OAuth2Client::new(
            "c1",
            "s",
            vec!["https://app.example.com/callback".into()],
            vec![],
            vec![],
        )
        .unwrap();
        assert!(!client.is_redirect_uri_allowed("https://evil.example.com/callback"));
    }

    #[test]
    fn is_redirect_uri_allowed_rejects_partial_match() {
        let client = OAuth2Client::new(
            "c1",
            "s",
            vec!["https://app.example.com/callback".into()],
            vec![],
            vec![],
        )
        .unwrap();
        assert!(!client.is_redirect_uri_allowed("https://app.example.com/callback/extra"));
        assert!(!client.is_redirect_uri_allowed("http://app.example.com/callback"));
    }

    // grant_type / scope 校验测试

    #[test]
    fn allows_grant_type() {
        let client = OAuth2Client::new(
            "c1",
            "s",
            vec![],
            vec![GrantType::AuthorizationCode, GrantType::RefreshToken],
            vec![],
        )
        .unwrap();
        assert!(client.allows_grant_type(&GrantType::AuthorizationCode));
        assert!(client.allows_grant_type(&GrantType::RefreshToken));
        assert!(!client.allows_grant_type(&GrantType::ClientCredentials));
    }

    #[test]
    fn allows_scope_empty_means_none_fail_closed() {
        let client = OAuth2Client::new("c1", "s", vec![], vec![], vec![]).unwrap();
        assert!(
            !client.allows_scope("anything"),
            "空 allowed_scopes 必须拒绝一切 scope(fail-closed)"
        );
    }

    #[test]
    fn validate_scopes_empty_request_ok_in_all_client_states() {
        // R-oauth2-001:请求 scope 为空时,无论 client allowed_scopes 为空/通配/显式列表均 Ok
        for scopes in [Vec::new(), vec!["*".to_string()], vec!["read".to_string()]] {
            let client = OAuth2Client::new("c1", "s", vec![], vec![], scopes).unwrap();
            let empty: Vec<String> = Vec::new();
            assert!(
                client.validate_scopes(&empty).is_ok(),
                "空 scope 请求应对任意 client 配置放行"
            );
        }
    }

    #[test]
    fn allows_scope_wildcard_means_any() {
        let client = OAuth2Client::new("c1", "s", vec![], vec![], vec!["*".into()]).unwrap();
        assert!(
            client.allows_scope("anything"),
            "\"*\" 通配应允许任意 scope"
        );
    }

    #[test]
    fn allows_scope_explicit_list() {
        let client = OAuth2Client::new(
            "c1",
            "s",
            vec![],
            vec![],
            vec!["read".into(), "write".into()],
        )
        .unwrap();
        assert!(client.allows_scope("read"));
        assert!(client.allows_scope("write"));
        assert!(!client.allows_scope("admin"));
    }

    // DaoOAuth2ClientStore 测试

    use crate::dao::InMemoryDao;

    fn make_test_client(id: &str) -> OAuth2Client {
        OAuth2Client::new(
            id,
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![GrantType::AuthorizationCode, GrantType::RefreshToken],
            vec!["read".into(), "write".into()],
        )
        .unwrap()
    }

    #[tokio::test]
    async fn store_create_and_get() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        let client = make_test_client("store-001");
        store.create(client.clone()).await.expect("创建");
        let got = store.get("store-001").await.expect("查询").expect("应存在");
        assert_eq!(got.client_id, "store-001");
        assert_eq!(got.redirect_uris, client.redirect_uris);
        assert_eq!(got.grant_types, client.grant_types);
        assert!(got.pkce_required);
    }

    #[tokio::test]
    async fn store_create_duplicate_fails() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        let client = make_test_client("dup-001");
        store.create(client.clone()).await.expect("首次创建");
        let err = store.create(client).await.unwrap_err();
        assert!(matches!(err, GarrisonError::OAuth2(_)));
    }

    /// 并发 create 同一 client_id:set_if_absent(SETNX)保证仅一个成功,其余返回 client-exists 错误。
    #[tokio::test(flavor = "multi_thread")]
    async fn store_create_concurrent_only_one_wins() {
        let store = Arc::new(DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new())));
        let mut handles = Vec::new();
        for _ in 0..16 {
            let s = store.clone();
            let client = make_test_client("conc-001");
            handles.push(tokio::spawn(async move { s.create(client).await }));
        }
        let mut wins = 0usize;
        for h in handles {
            if h.await.unwrap().is_ok() {
                wins += 1;
            }
        }
        assert_eq!(
            wins, 1,
            "并发创建同一 client_id 仅一个应成功,实际 {}",
            wins
        );
        // 最终仅存在一个客户端记录
        assert_eq!(store.list().await.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn store_get_nonexistent_returns_none() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        let got = store.get("no-such").await.expect("查询");
        assert!(got.is_none());
    }

    #[tokio::test]
    async fn store_update_existing() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        let mut client = make_test_client("upd-001");
        store.create(client.clone()).await.expect("创建");
        client.scopes = vec!["admin".into()];
        store.update(client).await.expect("更新");
        let got = store.get("upd-001").await.unwrap().unwrap();
        assert_eq!(got.scopes, vec!["admin"]);
    }

    #[tokio::test]
    async fn store_update_nonexistent_fails() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        let client = make_test_client("no-exist");
        let err = store.update(client).await.unwrap_err();
        assert!(matches!(err, GarrisonError::OAuth2(_)));
    }

    #[tokio::test]
    async fn store_delete() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        store
            .create(make_test_client("del-001"))
            .await
            .expect("创建");
        store.delete("del-001").await.expect("删除");
        assert!(store.get("del-001").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn store_list_sorted_by_client_id() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        store.create(make_test_client("charlie")).await.unwrap();
        store.create(make_test_client("alpha")).await.unwrap();
        store.create(make_test_client("bravo")).await.unwrap();
        let list = store.list().await.expect("列表");
        assert_eq!(list.len(), 3);
        assert_eq!(list[0].client_id, "alpha");
        assert_eq!(list[1].client_id, "bravo");
        assert_eq!(list[2].client_id, "charlie");
    }

    #[tokio::test]
    async fn store_list_empty() {
        let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
        let list = store.list().await.expect("列表");
        assert!(list.is_empty());
    }

    #[test]
    fn build_key_format() {
        let key = DaoOAuth2ClientStore::build_key("my-client");
        assert_eq!(key, "oauth2:client:my-client");
    }
}