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

//! Token 风格实现块(mod.rs 接口隔离约定):承载各风格与 `TokenStyleFactory` 的 impl。

use super::*;
use uuid::Uuid;

// UuidTokenStyle

impl Token for UuidTokenStyle {
    fn generate(&self, _login_id: &str, _timeout: i64) -> GarrisonResult<String> {
        Ok(Uuid::new_v4().to_string())
    }

    fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
        // UUID 无 payload,无法提取 login_id
        Ok(None)
    }

    fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
        Err(GarrisonError::Internal(
            "core-token-parse-not-supported::UUID".to_string(),
        ))
    }
}

// Random64TokenStyle

impl Token for Random64TokenStyle {
    fn generate(&self, _login_id: &str, _timeout: i64) -> GarrisonResult<String> {
        // 拼接两个 UUID v4 的 simple 表示(各 32 hex 字符 = 64 字符)
        let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
        Ok(token)
    }

    fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
        // 随机 hex 无 payload,无法提取 login_id
        Ok(None)
    }

    fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
        Err(GarrisonError::Internal(
            "core-token-parse-not-supported::random_64".to_string(),
        ))
    }
}

// SimpleTokenStyle

#[cfg(feature = "secure-simple-token")]
impl SimpleTokenStyle {
    /// 计算 HMAC-SHA256 并返回 URL-safe Base64(43 字符无 padding);输入 `login_id|uuid|exp`,
    /// exp 绑定进签名防篡改。
    fn compute_hmac(&self, login_id: &str, uuid_part: &str, exp: i64) -> GarrisonResult<String> {
        use hmac::{Hmac, KeyInit, Mac};
        use sha2::Sha256;

        type HmacSha256 = Hmac<Sha256>;
        let message = format!("{}|{}|{}", login_id, uuid_part, exp);
        let mut mac = HmacSha256::new_from_slice(self.secret.as_bytes())
            .map_err(|e| GarrisonError::Config(format!("core-hmac-key-invalid::{}", e)))?;
        mac.update(message.as_bytes());
        Ok(Self::base64_url_no_pad(&mac.finalize().into_bytes()))
    }

    /// 将字节切片编码为 URL-safe Base64(无 padding)。
    ///
    /// 手写实现的原因:`base64` crate 未被 `secure-simple-token` feature 启用,切换需变更
    /// feature 图谱且输出必须与存量 token 逐字节兼容;补偿:纯函数 + `#[cfg(test)]` 中 RFC 4648
    /// test vectors 锁定、输入恒为 32 字节定长。切换 `URL_SAFE_NO_PAD` 已列入 protocol-zeroize
    /// 同一批次(见 `SimpleTokenStyle` 文档)。
    fn base64_url_no_pad(bytes: &[u8]) -> String {
        const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
        let mut result = String::with_capacity((bytes.len() * 4).div_ceil(3));
        for chunk in bytes.chunks(3) {
            let b0 = chunk[0] as u32;
            let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
            let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
            let n = (b0 << 16) | (b1 << 8) | b2;
            result.push(CHARS[((n >> 18) & 0x3F) as usize] as char);
            result.push(CHARS[((n >> 12) & 0x3F) as usize] as char);
            if chunk.len() > 1 {
                result.push(CHARS[((n >> 6) & 0x3F) as usize] as char);
            }
            if chunk.len() > 2 {
                result.push(CHARS[(n & 0x3F) as usize] as char);
            }
        }
        result
    }
}

/// 拆分 Simple token 为四个部分:`<login_id>\x1f<uuid>.<exp>.<hmac>` →
/// (login_id, uuid, exp, hmac)。任一段缺失或 exp 非法时返回 None。
#[cfg(feature = "secure-simple-token")]
fn split_simple_token_parts(token: &str) -> Option<(&str, &str, i64, &str)> {
    // 先 rsplit '.' 取 HMAC 与 exp 段,再按 \x1f 分离 login_id / uuid。
    let (body, hmac_part) = token.rsplit_once('.')?;
    let (left, exp_str) = body.rsplit_once('.')?;
    let exp: i64 = exp_str.parse().ok()?;
    let (login_id, uuid_part) = left.split_once('\x1f')?;
    Some((login_id, uuid_part, exp, hmac_part))
}

#[cfg(feature = "secure-simple-token")]
impl Token for SimpleTokenStyle {
    fn generate(&self, login_id: &str, timeout: i64) -> GarrisonResult<String> {
        // 对齐 JWT 双向强校验:secret 短于 32 字节拒绝生成 token
        if self.secret.len() < 32 {
            return Err(GarrisonError::Config(
                "core-simple-secret-too-short::".to_string(),
            ));
        }
        // 必须携带过期时间:timeout <= 0 无法构造有意义的 exp,拒绝生成(fail-closed),
        // 杜绝事实永久的泄露 token;空 login_id 会产生可还原出空身份的 token(身份旁路),
        // 含 `\x1f` 的 login_id 会造成 verify 字段切分歧义——两者均拒绝生成。
        if login_id.is_empty() {
            return Err(GarrisonError::InvalidParam(
                "core-simple-login-id-empty::".to_string(),
            ));
        }
        if login_id.contains('\x1f') {
            return Err(GarrisonError::InvalidParam(
                "core-simple-login-id-sep::".to_string(),
            ));
        }
        if timeout <= 0 {
            return Err(GarrisonError::InvalidParam(format!(
                "core-simple-timeout-invalid::{}",
                timeout
            )));
        }
        let uuid = Uuid::new_v4();
        let uuid_str = uuid.to_string();
        // exp 绑定进 HMAC 消息,防篡改。
        let exp = chrono::Utc::now().timestamp() + timeout;
        let exp_str = exp.to_string();
        let hmac = self.compute_hmac(login_id, &uuid_str, exp)?;
        Ok(format!("{}\x1f{}.{}.{}", login_id, uuid_str, exp_str, hmac))
    }

    fn verify(&self, token: &str) -> GarrisonResult<Option<String>> {
        // 对齐 JWT:secret 短于 32 字节视为无效(所有 token 拒绝)
        if self.secret.len() < 32 {
            return Ok(None);
        }
        // 旧格式(无 exp 段 / 无 HMAC)一律 None。
        let (login_id, uuid_part, exp, hmac_part) = match split_simple_token_parts(token) {
            Some(parts) => parts,
            None => return Ok(None),
        };
        // 防御手工构造的空 login_id(generate 已禁止)。
        if login_id.is_empty() {
            return Ok(None);
        }
        if Uuid::parse_str(uuid_part).is_err() {
            return Ok(None);
        }
        // 过期视为无效(对齐 JWT verify 语义)。
        if exp != 0 && chrono::Utc::now().timestamp() >= exp {
            return Ok(None);
        }
        let expected_hmac = match self.compute_hmac(login_id, uuid_part, exp) {
            Ok(h) => h,
            Err(_) => return Ok(None),
        };
        // 常量时间比较统一走公共原语(ADR-0003 决策 2),防 timing side-channel。
        if crate::secure::ct_eq::constant_time_eq(expected_hmac.as_bytes(), hmac_part.as_bytes()) {
            Ok(Some(login_id.to_string()))
        } else {
            Ok(None)
        }
    }

    fn parse(&self, token: &str) -> GarrisonResult<TokenClaims> {
        // 对齐 JWT:secret 短于 32 字节拒绝解析
        if self.secret.len() < 32 {
            return Err(GarrisonError::Config(
                "core-simple-secret-too-short::".to_string(),
            ));
        }
        // 缺段 → Internal(格式错误)。
        let (login_id, uuid_part, exp, hmac_part) = split_simple_token_parts(token)
            .ok_or_else(|| GarrisonError::Internal("core-simple-token-no-sep::".to_string()))?;
        // 防御空 login_id 段。
        if login_id.is_empty() {
            return Err(GarrisonError::InvalidToken(
                "core-simple-token-login-id-empty::".to_string(),
            ));
        }
        if Uuid::parse_str(uuid_part).is_err() {
            return Err(GarrisonError::Internal(
                "core-simple-token-uuid-invalid::".to_string(),
            ));
        }
        // 过期解析失败(对齐 JWT parse 语义)。
        if exp != 0 && chrono::Utc::now().timestamp() >= exp {
            return Err(GarrisonError::ExpiredToken(
                "core-simple-token-expired::".to_string(),
            ));
        }
        // 校验 HMAC(常数时间比较,ADR-0003 决策 2)。
        let expected_hmac = self.compute_hmac(login_id, uuid_part, exp)?;
        if !crate::secure::ct_eq::constant_time_eq(expected_hmac.as_bytes(), hmac_part.as_bytes()) {
            return Err(GarrisonError::InvalidToken(
                "core-simple-token-hmac-failed::".to_string(),
            ));
        }
        // exp 段即过期时间。
        Ok(TokenClaims {
            login_id: login_id.to_string(),
            expire_at: exp,
            device: None,
        })
    }
}

#[cfg(not(feature = "secure-simple-token"))]
impl Token for SimpleTokenStyle {
    fn generate(&self, _login_id: &str, _timeout: i64) -> GarrisonResult<String> {
        // fail-closed:未启用 secure-simple-token feature 拒绝生成。
        Err(GarrisonError::Config(
            "core-simple-requires-feature::".to_string(),
        ))
    }

    fn verify(&self, _token: &str) -> GarrisonResult<Option<String>> {
        // fail-closed:未启用 feature 一律视为无效。
        Ok(None)
    }

    fn parse(&self, _token: &str) -> GarrisonResult<TokenClaims> {
        Err(GarrisonError::Config(
            "core-simple-requires-feature::".to_string(),
        ))
    }
}

// JwtTokenStyle

#[cfg(feature = "protocol-jwt")]
impl JwtTokenStyle {
    /// 创建 JWT Token 风格(`secret` 为签名密钥)。
    pub fn new(secret: &str) -> Self {
        Self {
            handler: crate::protocol::jwt::JwtHandler::new(secret),
        }
    }

    /// 按算法名与私钥 PEM 构建 JWT 风格(config 非对称透传路径):HS 系用 `secret`,
    /// 非对称路径用对应 PEM(未配置传 None)。
    pub fn from_algorithm_parts(
        algorithm: &str,
        secret: &str,
        rsa_pem: Option<&str>,
        ec_pem: Option<&str>,
        ed_pem: Option<&str>,
    ) -> GarrisonResult<Self> {
        Ok(Self {
            handler: crate::protocol::jwt::JwtHandler::from_algorithm_parts(
                algorithm, secret, rsa_pem, ec_pem, ed_pem,
            )?,
        })
    }
}

#[cfg(feature = "protocol-jwt")]
impl Token for JwtTokenStyle {
    fn generate(&self, login_id: &str, timeout: i64) -> GarrisonResult<String> {
        self.handler.sign(login_id, timeout)
    }

    fn generate_with_amr(
        &self,
        login_id: &str,
        timeout: i64,
        amr: &[String],
        auth_time: Option<i64>,
    ) -> GarrisonResult<String> {
        self.handler
            .sign_with_amr(login_id, timeout, amr, auth_time)
    }

    fn verify(&self, token: &str) -> GarrisonResult<Option<String>> {
        match self.handler.verify(token) {
            Ok(claims) => Ok(Some(claims.login_id)),
            Err(_) => Ok(None),
        }
    }

    fn parse(&self, token: &str) -> GarrisonResult<TokenClaims> {
        let claims = self.handler.verify(token)?;
        Ok(TokenClaims {
            login_id: claims.login_id,
            expire_at: claims.exp,
            device: claims.device.clone(),
        })
    }
}

// TokenStyleFactory

impl TokenStyleFactory {
    /// 依据风格字符串创建 Token 实现(`"uuid"` / `"random_64"` / `"simple"` / `"jwt"`;`secret`
    /// 仅 `jwt` 使用);未知风格返回 `Err(GarrisonError::Config)`(消息含 "unknown token_style")。
    #[allow(clippy::new_ret_no_self)]
    pub fn new(style: &str, secret: &str) -> GarrisonResult<Box<dyn Token>> {
        Self::new_with_jwt_keys(style, secret, None, None, None, None)
    }

    /// 非对称 JWT 扩展工厂:透传算法名与私钥 PEM(HS 路径传 None 时行为与 [`new`](Self::new)
    /// 一致;RS256/ES256/EdDSA 需配套对应 PEM)。
    #[allow(clippy::new_ret_no_self)]
    pub fn new_with_jwt_keys(
        style: &str,
        secret: &str,
        jwt_algorithm: Option<&str>,
        rsa_pem: Option<&str>,
        ec_pem: Option<&str>,
        ed_pem: Option<&str>,
    ) -> GarrisonResult<Box<dyn Token>> {
        #[cfg(feature = "protocol-jwt")]
        let jwt_algorithm = jwt_algorithm.unwrap_or("HS256");
        #[cfg(not(feature = "protocol-jwt"))]
        // 非 jwt 构建下四个 JWT 专用参数不进入任何分支(见下方 not(protocol-jwt) 臂)
        let _ = (jwt_algorithm, rsa_pem, ec_pem, ed_pem);
        match style {
            "uuid" => Ok(Box::new(UuidTokenStyle)),
            "random_64" => Ok(Box::new(Random64TokenStyle)),
            "simple" => Ok(Box::new(SimpleTokenStyle::new(secret.to_string()))),
            #[cfg(feature = "protocol-jwt")]
            "jwt" => Ok(Box::new(JwtTokenStyle::from_algorithm_parts(
                jwt_algorithm,
                secret,
                rsa_pem,
                ec_pem,
                ed_pem,
            )?)),
            #[cfg(not(feature = "protocol-jwt"))]
            "jwt" => {
                let _ = secret; // 避免 unused 警告(jwt 风格需 protocol-jwt feature)
                Err(GarrisonError::Config(
                    "config-unknown-token-style-jwt::".to_string(),
                ))
            },
            other => Err(GarrisonError::Config(format!(
                "config-unknown-token-style::{}",
                other
            ))),
        }
    }
}

// base64_url_no_pad 与 exp 过期语义的行为锁定测试(补偿控制):手写 Base64 属
// crypto-adjacent 原语,切换 `base64` crate 前用 RFC 4648 vectors + 定长契约防漂移;
// exp 语义需私有 compute_hmac,故在本模块锁定。
#[cfg(all(test, feature = "secure-simple-token"))]
mod simple_token_impl_tests {
    use super::*;

    /// 构造测试用 style(secret 满足 >= 32 字节强校验)。
    fn make_style() -> SimpleTokenStyle {
        SimpleTokenStyle::new("test-hmac-secret-key-for-unit-tests-01".to_string())
    }

    /// RFC 4648 test vectors(URL-safe 字母表与标准字母表在这些向量上输出一致)。
    #[test]
    fn base64_url_no_pad_rfc4648_vectors() {
        let cases: &[(&[u8], &str)] = &[
            (b"", ""),
            (b"f", "Zg"),
            (b"fo", "Zm8"),
            (b"foo", "Zm9v"),
            (b"foob", "Zm9vYg"),
            (b"fooba", "Zm9vYmE"),
            (b"foobar", "Zm9vYmFy"),
        ];
        for (input, expected) in cases {
            assert_eq!(
                &SimpleTokenStyle::base64_url_no_pad(input),
                expected,
                "input: {:?}",
                input
            );
        }
    }

    /// URL-safe 字母表契约:6 个 0xFF 字节应产生 `-`/`_`(而非 `+`/`/`)且无 padding `=`。
    #[test]
    fn base64_url_no_pad_uses_url_safe_alphabet_no_padding() {
        let encoded = SimpleTokenStyle::base64_url_no_pad(&[0xff; 6]);
        assert_eq!(encoded, "________"); // 6 字节 → 8 字符,无 padding
        assert!(
            !encoded.contains('+') && !encoded.contains('/') && !encoded.contains('='),
            "URL-safe 输出不得含 '+', '/', '='"
        );
    }

    /// HMAC 输出契约:32 字节(HMAC-SHA256 定长)输入应产出 43 字符无 padding 编码。
    #[test]
    fn base64_url_no_pad_hmac_output_length() {
        let encoded = SimpleTokenStyle::base64_url_no_pad(&[0x42; 32]);
        assert_eq!(encoded.len(), 43, "32 字节输入应编码为 43 字符");
    }

    /// 过期 token verify 返回 None、parse 返回 ExpiredToken;未过期正常通过;篡改 exp 段因
    /// HMAC 绑定而失效。
    #[test]
    fn simple_token_expiry_enforced() {
        let style = make_style();
        let uuid_str = Uuid::new_v4().to_string();

        // 过去的 exp(合法签名)→ verify None,parse ExpiredToken
        let past_exp = chrono::Utc::now().timestamp() - 100;
        let hmac = style.compute_hmac("u1", &uuid_str, past_exp).unwrap();
        let expired = format!("u1\x1f{}.{}.{}", uuid_str, past_exp, hmac);
        assert_eq!(style.verify(&expired).unwrap(), None, "过期 token 应无效");
        assert!(
            matches!(style.parse(&expired), Err(GarrisonError::ExpiredToken(_))),
            "过期 token parse 应返回 ExpiredToken,实际: {:?}",
            style.parse(&expired)
        );

        // 未来的 exp(合法签名)→ 正常通过
        let future_exp = chrono::Utc::now().timestamp() + 3600;
        let hmac_future = style.compute_hmac("u1", &uuid_str, future_exp).unwrap();
        let valid = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, hmac_future);
        assert_eq!(style.verify(&valid).unwrap(), Some("u1".to_string()));
        let claims = style.parse(&valid).unwrap();
        assert_eq!(claims.expire_at, future_exp);

        // 篡改 exp(延长有效期)→ HMAC 绑定校验失败 → None
        let tampered = format!("u1\x1f{}.{}.{}", uuid_str, future_exp + 86_400, hmac_future);
        assert_eq!(
            style.verify(&tampered).unwrap(),
            None,
            "篡改 exp 后 HMAC 应失败"
        );
    }

    /// 篡改 HMAC 段(单字节 + 末字节):verify None、parse InvalidToken(HMAC 校验统一走
    /// 公共原语,ADR-0003 决策 2/3)。
    #[test]
    fn simple_token_tampered_hmac_rejected() {
        let style = make_style();
        let uuid_str = Uuid::new_v4().to_string();
        let future_exp = chrono::Utc::now().timestamp() + 3600;
        let hmac = style.compute_hmac("u1", &uuid_str, future_exp).unwrap();

        // 单字节差异(首字符翻转)→ verify None + parse InvalidToken
        let mut tampered_hmac = hmac.clone();
        tampered_hmac.replace_range(0..1, if &hmac[0..1] == "A" { "B" } else { "A" });
        let bad = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, tampered_hmac);
        assert_eq!(
            style.verify(&bad).unwrap(),
            None,
            "篡改 HMAC 首字符后 token 应无效"
        );
        assert!(
            matches!(style.parse(&bad), Err(GarrisonError::InvalidToken(_))),
            "篡改 HMAC 后 parse 应返回 InvalidToken,实际: {:?}",
            style.parse(&bad)
        );

        // 篡改最后字节 → 同样拒绝
        let mut last_flipped = hmac.clone();
        let last = last_flipped.pop().unwrap();
        last_flipped.push(if last == 'A' { 'B' } else { 'A' });
        let bad_last = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, last_flipped);
        assert_eq!(style.verify(&bad_last).unwrap(), None);

        // HMAC 段长度不符(截断)→ 长度不等常量时间判 false → None
        let truncated = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, &hmac[..42]);
        assert_eq!(
            style.verify(&truncated).unwrap(),
            None,
            "HMAC 段长度不符应无效"
        );

        // 正确 HMAC 仍通过(防测试本身写错方向)
        let good = format!("u1\x1f{}.{}.{}", uuid_str, future_exp, hmac);
        assert_eq!(style.verify(&good).unwrap(), Some("u1".to_string()));
    }
}