Skip to main content

gitflow_core/
auth.rs

1//! 认证领域类型与平台抽象。
2//!
3//! 定义了认证状态数据,以及跨平台实现所需的 [`AuthProvider`] trait。
4//! GitHub、GitLab、GitCode 等平台实现都需实现该 trait,使上层
5//! 命令层可统一处理登录、登出、状态查询及 Token 管理。
6
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use crate::Result;
11
12/// 单个 host 的认证状态(GitLab 场景下可能同时配置多个 host)。
13#[derive(Debug, Clone, Serialize, Deserialize)]
14#[serde(rename_all = "camelCase")]
15pub struct HostAuthStatus {
16    /// host 名称或地址(如 `gitlab.com`、`192.168.230.23`)。
17    pub host: String,
18    /// 该 host 是否已登录。
19    pub logged_in: bool,
20    /// 该 host 下的登录用户名(未登录时为 None)。
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub user: Option<String>,
23}
24
25/// 当前认证状态。
26///
27/// 由 [`AuthProvider::status`] 返回,用于判断用户是否已登录、
28/// 当前用户身份以及持有的权限范围。
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase")]
31pub struct AuthStatus {
32    /// 用户是否已登录(任一已知 host 已登录即为 true)。
33    pub logged_in: bool,
34    /// 当前登录用户名(未登录时为 None)。
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub user: Option<String>,
37    /// 已授权的权限范围列表。
38    #[serde(default)]
39    pub scopes: Vec<String>,
40    /// 按 host 拆分的认证状态明细(单 host 平台如 GitHub/GitCode 始终为空数组)。
41    #[serde(default, skip_serializing_if = "Vec::is_empty")]
42    pub hosts: Vec<HostAuthStatus>,
43}
44
45/// 认证操作的平台抽象。
46///
47/// 所有平台实现(GitHub/GitLab/GitCode)都必须实现此 trait,
48/// 以提供统一的登录、登出、状态查询及 Token 获取能力。
49///
50/// # Errors
51///
52/// 所有方法在平台调用失败、反序列化失败或鉴权失败时返回
53/// [`CoreError`](crate::CoreError)。
54///
55/// [`CoreError`]: crate::CoreError
56#[async_trait]
57pub trait AuthProvider: std::fmt::Debug + Send + Sync {
58    /// 执行登录流程(交互式或非交互式)。
59    ///
60    /// 如果提供了 `token`,则使用 token 进行非交互式登录;
61    /// 否则启动交互式登录流程。
62    ///
63    /// 登录成功后凭据会被持久化到本地存储。
64    ///
65    /// # Errors
66    ///
67    /// 当认证失败或凭据存储失败时返回错误。
68    async fn login(&self, token: Option<&str>) -> Result<()>;
69
70    /// 执行登出流程,清除本地凭据。
71    ///
72    /// # Errors
73    ///
74    /// 当凭据清除失败时返回错误。
75    async fn logout(&self) -> Result<()>;
76
77    /// 查询当前认证状态。
78    ///
79    /// # Errors
80    ///
81    /// 当无法读取本地凭据或平台 API 调用失败时返回错误。
82    async fn status(&self) -> Result<AuthStatus>;
83
84    /// 获取当前有效的访问 Token。
85    ///
86    /// 返回的字符串可用于后续的平台 API 调用。
87    ///
88    /// # Errors
89    ///
90    /// 当用户未登录或 Token 获取失败时返回错误。
91    async fn token(&self) -> Result<String>;
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn test_should_omit_empty_hosts_field_when_serializing() {
100        let status = AuthStatus {
101            logged_in: true,
102            user: Some("alice".to_string()),
103            scopes: vec![],
104            hosts: vec![],
105        };
106        let json = serde_json::to_string(&status).expect("serialize");
107        assert!(!json.contains("hosts"));
108    }
109
110    #[test]
111    fn test_should_include_hosts_field_when_non_empty() {
112        let status = AuthStatus {
113            logged_in: true,
114            user: Some("alice".to_string()),
115            scopes: vec![],
116            hosts: vec![HostAuthStatus {
117                host: "gitlab.com".to_string(),
118                logged_in: true,
119                user: Some("alice".to_string()),
120            }],
121        };
122        let json = serde_json::to_string(&status).expect("serialize");
123        assert!(json.contains("\"hosts\""));
124        assert!(json.contains("\"gitlab.com\""));
125    }
126
127    #[test]
128    fn test_should_deserialize_auth_status_logged_in() {
129        let json = r#"{
130            "loggedIn": true,
131            "user": "octocat",
132            "scopes": ["repo", "read:org"]
133        }"#;
134        let status: AuthStatus = serde_json::from_str(json).expect("valid AuthStatus JSON");
135
136        assert!(status.logged_in);
137        assert_eq!(status.user.as_deref(), Some("octocat"));
138        assert_eq!(
139            status.scopes,
140            vec!["repo".to_string(), "read:org".to_string()]
141        );
142    }
143
144    #[test]
145    fn test_should_deserialize_auth_status_not_logged_in() {
146        let json = r#"{
147            "loggedIn": false
148        }"#;
149        let status: AuthStatus = serde_json::from_str(json).expect("valid AuthStatus JSON");
150
151        assert!(!status.logged_in);
152        assert!(status.user.is_none());
153        assert!(status.scopes.is_empty());
154    }
155
156    #[test]
157    fn test_should_roundtrip_auth_status_via_serde() {
158        let json = r#"{
159            "loggedIn": true,
160            "user": "alice",
161            "scopes": ["repo"]
162        }"#;
163        let status: AuthStatus = serde_json::from_str(json).expect("deserialize");
164        let re_serialized = serde_json::to_string(&status).expect("serialize");
165        let round_tripped: AuthStatus =
166            serde_json::from_str(&re_serialized).expect("re-deserialize");
167
168        assert_eq!(round_tripped.logged_in, status.logged_in);
169        assert_eq!(round_tripped.user, status.user);
170        assert_eq!(round_tripped.scopes, status.scopes);
171    }
172
173    #[test]
174    fn test_should_serialize_auth_status_camel_case() {
175        let status = AuthStatus {
176            logged_in: true,
177            user: Some("bob".into()),
178            scopes: vec!["gist".into()],
179            hosts: vec![],
180        };
181        let json = serde_json::to_string(&status).expect("serialize");
182        assert!(json.contains("\"loggedIn\":true"));
183        assert!(json.contains("\"user\":\"bob\""));
184        assert!(json.contains("\"scopes\""));
185        assert!(!json.contains("\"logged_in\""));
186    }
187
188    #[test]
189    fn test_should_omit_none_user_on_serialize() {
190        let status = AuthStatus {
191            logged_in: false,
192            user: None,
193            scopes: vec![],
194            hosts: vec![],
195        };
196        let json = serde_json::to_string(&status).expect("serialize");
197        assert!(!json.contains("null"));
198        assert!(!json.contains("\"user\":"));
199        assert!(json.contains("\"loggedIn\":false"));
200    }
201
202    #[test]
203    fn test_should_default_empty_scopes() {
204        let json = r#"{"loggedIn":true,"user":"u"}"#;
205        let status: AuthStatus = serde_json::from_str(json).expect("deserialize");
206        assert!(status.scopes.is_empty());
207    }
208
209    #[test]
210    fn test_should_format_debug_for_auth_status() {
211        let status = AuthStatus {
212            logged_in: true,
213            user: Some("test".into()),
214            scopes: vec!["repo".into()],
215            hosts: vec![],
216        };
217        let debug = format!("{status:?}");
218        assert!(debug.contains("AuthStatus"));
219        assert!(debug.contains("test"));
220    }
221
222    #[test]
223    fn test_should_clone_auth_status() {
224        let original = AuthStatus {
225            logged_in: true,
226            user: Some("alice".into()),
227            scopes: vec!["repo".into(), "gist".into()],
228            hosts: vec![],
229        };
230        let cloned = original.clone();
231
232        assert_eq!(cloned.logged_in, original.logged_in);
233        assert_eq!(cloned.user, original.user);
234        assert_eq!(cloned.scopes, original.scopes);
235
236        // Verify it's a deep clone, not the same object
237        assert!(!std::ptr::eq(
238            std::ptr::from_ref(&cloned.scopes),
239            std::ptr::from_ref(&original.scopes)
240        ));
241    }
242}