Skip to main content

acosmi/auth/
types.rs

1//! 鉴权 / 身份域类型。端口自 `auth/types.ts`。
2//!
3//! P1 前置 `TokenSet` 及其形状校验(`core::store` / `core::client` 依赖);
4//! P2 补 `token_set_is_expired`(ISO 8601 日期解析 + 30s 偏移)。
5
6use serde::{Deserialize, Serialize};
7
8/// OAuth Authorization Server 元数据(RFC 8414)。
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct ServerMetadata {
11    pub issuer: String,
12    pub authorization_endpoint: String,
13    pub token_endpoint: String,
14    pub revocation_endpoint: String,
15    pub registration_endpoint: String,
16    pub scopes_supported: Vec<String>,
17}
18
19/// OAuth token 响应。
20#[derive(Clone, Serialize, Deserialize)]
21pub struct TokenResponse {
22    pub access_token: String,
23    pub token_type: String,
24    pub expires_in: i64,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub refresh_token: Option<String>,
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub scope: Option<String>,
29}
30
31/// 持久化 token 对。
32#[derive(Clone, Serialize, Deserialize)]
33pub struct TokenSet {
34    pub access_token: String,
35    pub refresh_token: String,
36    /// ISO 8601 格式。
37    pub expires_at: String,
38    pub scope: String,
39    pub client_id: String,
40    pub server_url: String,
41}
42
43/// 动态注册响应。
44#[derive(Clone, Serialize, Deserialize)]
45pub struct ClientRegistration {
46    pub client_id: String,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub client_secret: Option<String>,
49}
50
51/// token 是否已过期(提前 30 秒视为过期)。对应 TS `tokenSetIsExpired`。
52///
53/// bug-for-bug:非法 / 空 `expires_at`(空串 / `"not-a-date"` 等无法解析为 ISO 8601)
54/// 视为**已过期**(返 `true`),触发 refresh / 重登 —— 而非把坏 token 当作"未过期"长期复用。
55///
56/// `newTokenSet` 始终产出 `toISOString()`(UTC `Z` 后缀),故解析按 RFC3339 / ISO 8601。
57pub fn token_set_is_expired(t: &TokenSet) -> bool {
58    use chrono::{DateTime, Utc};
59    match DateTime::parse_from_rfc3339(&t.expires_at) {
60        Ok(expires_at) => {
61            // 提前 30 秒视为过期(与 TS `Date.now() > expiresAt - 30_000` 一致)。
62            Utc::now() > expires_at.with_timezone(&Utc) - chrono::Duration::seconds(30)
63        }
64        // 非法 / 空 expires_at → 视为已过期。
65        Err(_) => true,
66    }
67}
68
69/// 运行时校验任意 JSON 值是否为合法 `TokenSet` 形状(所有 6 字段都是 string)。
70///
71/// 对应 TS `isValidTokenSet`。serde 反序列化到非可选 `String` 字段天然等价该校验:
72/// 缺字段 / 类型错 → `Err` → 视为无 token。
73pub fn is_valid_token_set(x: &serde_json::Value) -> bool {
74    serde_json::from_value::<TokenSet>(x.clone()).is_ok()
75}
76
77impl std::fmt::Debug for TokenSet {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("TokenSet").finish_non_exhaustive()
80    }
81}
82
83impl std::fmt::Debug for TokenResponse {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.debug_struct("TokenResponse").finish_non_exhaustive()
86    }
87}
88
89impl std::fmt::Debug for ClientRegistration {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("ClientRegistration").finish_non_exhaustive()
92    }
93}
94
95impl zeroize::Zeroize for TokenSet {
96    fn zeroize(&mut self) {
97        self.access_token.zeroize();
98        self.refresh_token.zeroize();
99    }
100}
101impl zeroize::Zeroize for TokenResponse {
102    fn zeroize(&mut self) {
103        self.access_token.zeroize();
104        self.refresh_token.zeroize();
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use chrono::{Duration, Utc};
112
113    fn token_with_expiry(expires_at: &str) -> TokenSet {
114        TokenSet {
115            access_token: "at".into(),
116            refresh_token: "rt".into(),
117            expires_at: expires_at.into(),
118            scope: "ai".into(),
119            client_id: "cid".into(),
120            server_url: "https://acosmi.com".into(),
121        }
122    }
123
124    #[test]
125    fn expired_when_in_the_past() {
126        let past = (Utc::now() - Duration::hours(1)).to_rfc3339();
127        assert!(token_set_is_expired(&token_with_expiry(&past)));
128    }
129
130    #[test]
131    fn not_expired_when_well_in_the_future() {
132        let future = (Utc::now() + Duration::hours(1)).to_rfc3339();
133        assert!(!token_set_is_expired(&token_with_expiry(&future)));
134    }
135
136    #[test]
137    fn expired_within_30s_skew_window() {
138        // 距过期仅 10s(<30s 提前量)→ 视为已过期。
139        let soon = (Utc::now() + Duration::seconds(10)).to_rfc3339();
140        assert!(token_set_is_expired(&token_with_expiry(&soon)));
141    }
142
143    #[test]
144    fn not_expired_just_outside_30s_skew_window() {
145        // 距过期 60s(>30s 提前量)→ 未过期。
146        let later = (Utc::now() + Duration::seconds(60)).to_rfc3339();
147        assert!(!token_set_is_expired(&token_with_expiry(&later)));
148    }
149
150    #[test]
151    fn illegal_expires_at_treated_as_expired() {
152        assert!(token_set_is_expired(&token_with_expiry("")));
153        assert!(token_set_is_expired(&token_with_expiry("not-a-date")));
154        // 'Z' 后缀 UTC(newTokenSet 的实际产出格式)能解析。
155        let z = "2099-01-01T00:00:00Z";
156        assert!(!token_set_is_expired(&token_with_expiry(z)));
157    }
158}