Skip to main content

gitflow_gitcode/
auth.rs

1//! GitCode 认证提供者实现。
2//!
3//! 通过 `gc auth` CLI 命令实现 [`AuthProvider`] trait,支持登录、
4//! 登出、状态查询及 Token 管理。
5//! 所有方法通过 `tokio::process::Command` 调用 `gc`。
6
7use async_trait::async_trait;
8use gitflow_core::{
9    CoreError, Result,
10    auth::{AuthProvider, AuthStatus},
11};
12use tracing::debug;
13
14use crate::{
15    error::parse_gitcode_error,
16    runner::{CommandRunner, RealCommandRunner},
17};
18
19/// GitCode 认证提供者,通过 `gitcode` CLI 操作认证。
20///
21/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
22/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
23///
24/// # Examples
25///
26/// ```no_run
27/// use gitflow_gitcode::GitCodeAuthProvider;
28///
29/// let provider = GitCodeAuthProvider::new();
30/// ```
31#[derive(Debug, Clone)]
32pub struct GitCodeAuthProvider<R: CommandRunner = RealCommandRunner> {
33    /// 用于执行 `gitcode` CLI 命令的 runner。
34    runner: R,
35}
36
37impl GitCodeAuthProvider<RealCommandRunner> {
38    /// 创建新的 GitCode 认证提供者。
39    #[must_use]
40    pub fn new() -> Self {
41        Self {
42            runner: RealCommandRunner,
43        }
44    }
45}
46
47impl<R: CommandRunner> GitCodeAuthProvider<R> {
48    /// 使用自定义 [`CommandRunner`] 创建提供者。
49    ///
50    /// 主要用于测试,可注入模拟 runner 以控制 `gitcode` CLI 的输出。
51    #[must_use]
52    pub fn with_runner(runner: R) -> Self {
53        Self { runner }
54    }
55}
56
57impl Default for GitCodeAuthProvider<RealCommandRunner> {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63#[async_trait]
64impl<R: CommandRunner + 'static> AuthProvider for GitCodeAuthProvider<R> {
65    /// 执行登录。
66    ///
67    /// 调用 `gc auth login`。如果提供了 token,则通过 `--with-token` 参数并将
68    /// token 写入子进程 stdin 进行非交互式登录,避免 token 出现在进程参数中。
69    ///
70    /// # Errors
71    ///
72    /// 当认证失败或 `gc` 调用失败时返回错误。
73    async fn login(&self, token: Option<&str>) -> Result<()> {
74        debug!("spawning `gc auth login`");
75
76        let binary = crate::gitcode_binary();
77        let output = if let Some(token) = token {
78            self.runner
79                .run_with_stdin(
80                    &binary,
81                    &["auth", "login", "--with-token"],
82                    token.as_bytes(),
83                )
84                .await
85                .map_err(|e| {
86                    CoreError::Platform(format!("Failed to spawn gitcode auth login: {e}"))
87                })?
88        } else {
89            self.runner
90                .run(&binary, &["auth", "login"])
91                .await
92                .map_err(|e| {
93                    CoreError::Platform(format!("Failed to spawn gitcode auth login: {e}"))
94                })?
95        };
96
97        if !output.status.success() {
98            return Err(parse_gitcode_error(&output.stderr).into());
99        }
100
101        Ok(())
102    }
103
104    /// 执行登出,清除本地凭据。
105    ///
106    /// # Errors
107    ///
108    /// 当 `gc` 调用失败时返回错误。
109    async fn logout(&self) -> Result<()> {
110        debug!("spawning `gc auth logout`");
111
112        let binary = crate::gitcode_binary();
113        let output = self
114            .runner
115            .run(&binary, &["auth", "logout"])
116            .await
117            .map_err(|e| {
118                CoreError::Platform(format!("Failed to spawn gitcode auth logout: {e}"))
119            })?;
120
121        if !output.status.success() {
122            return Err(parse_gitcode_error(&output.stderr).into());
123        }
124
125        Ok(())
126    }
127
128    /// 查询当前认证状态。
129    ///
130    /// 调用 `gc auth status` 并解析输出来构造 [`AuthStatus`]。
131    ///
132    /// # Errors
133    ///
134    /// 当 `gc` 调用失败或无法解析状态输出时返回错误。
135    async fn status(&self) -> Result<AuthStatus> {
136        debug!("spawning `gc auth status`");
137
138        let binary = crate::gitcode_binary();
139        let output = self
140            .runner
141            .run(&binary, &["auth", "status"])
142            .await
143            .map_err(|e| {
144                CoreError::Platform(format!("Failed to spawn gitcode auth status: {e}"))
145            })?;
146
147        let stdout = String::from_utf8_lossy(&output.stdout);
148        let stderr = String::from_utf8_lossy(&output.stderr);
149
150        // gitcode auth status 在未登录时会返回非零退出码
151        if !output.status.success() {
152            // 检查是否为未登录状态
153            let text = format!("{stdout}{stderr}").to_lowercase();
154            if text.contains("not logged in")
155                || text.contains("no active account")
156                || text.contains("not authenticated")
157            {
158                return Ok(AuthStatus {
159                    logged_in: false,
160                    user: None,
161                    scopes: vec![],
162                });
163            }
164
165            return Err(parse_gitcode_error(&output.stderr).into());
166        }
167
168        // 解析登录用户:查找 "Logged in to gitcode.com as <username>" 行
169        let user = parse_user_from_status(&stdout);
170
171        Ok(AuthStatus {
172            logged_in: user.is_some(),
173            user,
174            scopes: vec![], // gitcode auth status 不直接返回 scopes 列表
175        })
176    }
177
178    /// 获取当前有效的访问 Token。
179    ///
180    /// # Errors
181    ///
182    /// 当用户未登录或 Token 获取失败时返回错误。
183    async fn token(&self) -> Result<String> {
184        debug!("spawning `gc auth token`");
185
186        let binary = crate::gitcode_binary();
187        let output = self
188            .runner
189            .run(&binary, &["auth", "token"])
190            .await
191            .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode auth token: {e}")))?;
192
193        if !output.status.success() {
194            return Err(parse_gitcode_error(&output.stderr).into());
195        }
196
197        let token = String::from_utf8_lossy(&output.stdout);
198        Ok(token.trim().to_string())
199    }
200}
201
202// AuthChecker 是同步 trait,必须使用 std::process::Command
203#[allow(clippy::disallowed_types, reason = "AuthChecker is synchronous")]
204impl<R: CommandRunner> gitflow_core::AuthChecker for GitCodeAuthProvider<R> {
205    fn is_authenticated(&self) -> bool {
206        // 1. 优先检查环境变量
207        if std::env::var("GITCODE_TOKEN").is_ok() {
208            return true;
209        }
210
211        // 2. 检查 gitcode CLI 是否可用
212        let binary = crate::gitcode_binary();
213        debug!(binary = %binary, "checking gitcode authentication");
214
215        let output = std::process::Command::new(&binary)
216            .args(["auth", "status"])
217            .output();
218
219        match output {
220            Ok(out) => {
221                debug!(
222                    exit_code = %out.status,
223                    stdout = %String::from_utf8_lossy(&out.stdout),
224                    stderr = %String::from_utf8_lossy(&out.stderr),
225                    "gitcode auth status result"
226                );
227                out.status.success()
228            }
229            Err(e) => {
230                debug!(error = %e, "failed to execute gitcode auth status");
231                false
232            }
233        }
234    }
235
236    fn check_status(&self) -> gitflow_core::AuthCheckResult {
237        // 1. 检查环境变量
238        if std::env::var("GITCODE_TOKEN").is_ok() {
239            return gitflow_core::AuthCheckResult {
240                authenticated: true,
241                user: None,
242                reason: None,
243                hint: None,
244            };
245        }
246
247        // 2. 执行 gitcode auth status
248        let binary = crate::gitcode_binary();
249        let output = match std::process::Command::new(&binary)
250            .args(["auth", "status"])
251            .output()
252        {
253            Ok(out) => out,
254            Err(e) => {
255                return gitflow_core::AuthCheckResult {
256                    authenticated: false,
257                    user: None,
258                    reason: Some(format!("Failed to execute gitcode: {e}")),
259                    hint: Some("Ensure gitcode CLI is installed: pip install gitcode-cli".into()),
260                };
261            }
262        };
263
264        // 3. 解析结果
265        if output.status.success() {
266            let stdout = String::from_utf8_lossy(&output.stdout);
267            let user = parse_user_from_status(&stdout);
268
269            gitflow_core::AuthCheckResult {
270                authenticated: true,
271                user,
272                reason: None,
273                hint: None,
274            }
275        } else {
276            let stderr = String::from_utf8_lossy(&output.stderr);
277
278            gitflow_core::AuthCheckResult {
279                authenticated: false,
280                user: None,
281                reason: Some(stderr.to_string()),
282                hint: Some("Run `gc auth login` to authenticate".into()),
283            }
284        }
285    }
286}
287
288/// 从 `gc auth status` 的输出中解析用户名。
289///
290/// 支持两种格式:
291/// - 旧格式: `"Logged in to gitcode.com as <username>"`
292/// - 新格式: `"Logged in as <username>"`
293fn parse_user_from_status(output: &str) -> Option<String> {
294    // 匹配模式:查找 " as " 后跟用户名(两种格式都适用)
295    for line in output.lines() {
296        if let Some(pos) = line.find(" as ") {
297            let after_as = &line[pos + 4..];
298            // 用户名后面可能跟 " (" 或空格或其他
299            if let Some(end) = after_as.find(' ') {
300                let user = &after_as[..end];
301                if !user.is_empty() {
302                    return Some(user.to_string());
303                }
304            } else if !after_as.is_empty() {
305                return Some(after_as.trim().to_string());
306            }
307        }
308    }
309    None
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use crate::runner::MockCommandRunner;
316
317    #[test]
318    fn test_should_construct_gitcode_auth_provider() {
319        let provider = GitCodeAuthProvider::new();
320        let _ = format!("{provider:?}");
321    }
322
323    #[test]
324    fn test_should_default_gitcode_auth_provider() {
325        let provider = GitCodeAuthProvider::default();
326        let _ = format!("{provider:?}");
327    }
328
329    #[test]
330    fn test_should_clone_gitcode_auth_provider() {
331        let original = GitCodeAuthProvider::new();
332        let cloned = original.clone();
333        let _ = format!("{cloned:?}");
334    }
335
336    #[test]
337    fn test_should_parse_user_from_status_output() {
338        let status = r"gitcode.com
339  ✓ Logged in to gitcode.com as octocat (keyring)
340  ✓ Git operations for gitcode.com configured to use ssh protocol.
341  ✓ API calls for gitcode.com should use https protocol
342";
343        assert_eq!(parse_user_from_status(status), Some("octocat".to_string()));
344    }
345
346    #[test]
347    fn test_should_parse_user_from_status_with_different_host() {
348        let status = r"gitcode.com
349  ✓ Logged in to gitcode.com as alice (oauth_token)
350  ✓ Token: gco_****
351";
352        assert_eq!(parse_user_from_status(status), Some("alice".to_string()));
353    }
354
355    #[test]
356    fn test_should_return_none_when_no_user_in_status() {
357        let status = "No active account found";
358        assert!(parse_user_from_status(status).is_none());
359    }
360
361    #[test]
362    fn test_should_return_none_for_empty_status() {
363        assert!(parse_user_from_status("").is_none());
364    }
365
366    #[test]
367    fn test_should_parse_user_without_suffix() {
368        let status = "Logged in to gitcode.com as bob";
369        assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
370    }
371
372    #[test]
373    fn test_should_parse_user_from_status_new_format() {
374        let status = "Logged in as alice";
375        assert_eq!(parse_user_from_status(status), Some("alice".to_string()));
376    }
377
378    #[test]
379    fn test_should_parse_user_from_status_new_format_with_suffix() {
380        let status = "Logged in as bob (oauth_token)";
381        assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
382    }
383
384    #[test]
385    fn test_auth_checker_is_authenticated_with_env_var() {
386        use gitflow_core::AuthChecker;
387        temp_env::with_var("GITCODE_TOKEN", Some("test_token"), || {
388            let provider = GitCodeAuthProvider::new();
389            assert!(provider.is_authenticated());
390        });
391    }
392
393    #[test]
394    fn test_auth_checker_check_status_with_env_var() {
395        use gitflow_core::AuthChecker;
396        temp_env::with_var("GITCODE_TOKEN", Some("test_token"), || {
397            let provider = GitCodeAuthProvider::new();
398            let result = provider.check_status();
399            assert!(result.authenticated);
400            assert!(result.reason.is_none());
401        });
402    }
403
404    // --- Failure-path tests using an injected MockCommandRunner ---
405
406    #[tokio::test]
407    async fn test_should_return_platform_error_when_gc_fails_for_login() {
408        let runner = MockCommandRunner::failure("authentication failed", 256);
409        let provider = GitCodeAuthProvider::with_runner(runner);
410
411        let result = provider.login(Some("gco_token")).await;
412
413        assert!(matches!(
414            result.unwrap_err(),
415            gitflow_core::CoreError::Cli(_)
416        ));
417    }
418
419    #[tokio::test]
420    async fn test_should_return_platform_error_when_gc_fails_for_logout() {
421        let runner = MockCommandRunner::failure("not logged in", 256);
422        let provider = GitCodeAuthProvider::with_runner(runner);
423
424        let result = provider.logout().await;
425
426        assert!(matches!(
427            result.unwrap_err(),
428            gitflow_core::CoreError::Cli(_)
429        ));
430    }
431
432    #[tokio::test]
433    async fn test_should_return_logged_out_status_when_gc_reports_not_logged_in() {
434        let runner = MockCommandRunner::failure("not logged in to any GitCode hosts", 256);
435        let provider = GitCodeAuthProvider::with_runner(runner);
436
437        let status = provider.status().await.expect("graceful logged-out status");
438
439        assert!(!status.logged_in);
440        assert!(status.user.is_none());
441    }
442
443    #[tokio::test]
444    async fn test_should_return_platform_error_when_status_fails_unexpectedly() {
445        let runner = MockCommandRunner::failure("internal server error", 256);
446        let provider = GitCodeAuthProvider::with_runner(runner);
447
448        let result = provider.status().await;
449
450        assert!(matches!(
451            result.unwrap_err(),
452            gitflow_core::CoreError::Cli(_)
453        ));
454    }
455
456    #[tokio::test]
457    async fn test_should_return_platform_error_when_gc_fails_for_token() {
458        let runner = MockCommandRunner::failure("no token found", 256);
459        let provider = GitCodeAuthProvider::with_runner(runner);
460
461        let result = provider.token().await;
462
463        assert!(matches!(
464            result.unwrap_err(),
465            gitflow_core::CoreError::Cli(_)
466        ));
467    }
468
469    #[tokio::test]
470    async fn test_should_return_empty_token_when_stdout_is_empty() {
471        let runner = MockCommandRunner::success("");
472        let provider = GitCodeAuthProvider::with_runner(runner);
473
474        let token = provider
475            .token()
476            .await
477            .expect("empty stdout yields empty token");
478
479        assert!(token.is_empty());
480    }
481
482    // --- Success-path tests using an injected MockCommandRunner ---
483
484    #[test]
485    fn test_should_create_gitcode_auth_provider() {
486        let provider = GitCodeAuthProvider::new();
487        assert!(format!("{provider:?}").contains("GitCodeAuthProvider"));
488    }
489
490    #[tokio::test]
491    async fn test_should_handle_gitcode_login() {
492        let runner = MockCommandRunner::success("");
493        let provider = GitCodeAuthProvider::with_runner(runner);
494
495        let result = provider.login(None).await;
496
497        assert!(result.is_ok());
498    }
499
500    #[tokio::test]
501    async fn test_should_login_successfully_with_token() {
502        let runner = MockCommandRunner::success("");
503        let provider = GitCodeAuthProvider::with_runner(runner);
504
505        let result = provider.login(Some("gco_test_token")).await;
506
507        assert!(result.is_ok());
508    }
509
510    #[tokio::test]
511    async fn test_should_logout_successfully() {
512        let runner = MockCommandRunner::success("");
513        let provider = GitCodeAuthProvider::with_runner(runner);
514
515        let result = provider.logout().await;
516
517        assert!(result.is_ok());
518    }
519
520    #[tokio::test]
521    async fn test_should_return_status_when_authenticated() {
522        let status_output = r"gitcode.com
523  ✓ Logged in to gitcode.com as octocat (keyring)
524  ✓ Git operations for gitcode.com configured to use ssh protocol.
525";
526        let runner = MockCommandRunner::success(status_output);
527        let provider = GitCodeAuthProvider::with_runner(runner);
528
529        let status = provider.status().await.expect("successful status check");
530
531        assert!(status.logged_in);
532        assert_eq!(status.user, Some("octocat".to_string()));
533    }
534
535    #[tokio::test]
536    async fn test_should_return_token_when_authenticated() {
537        let runner = MockCommandRunner::success("gco_test_token_12345\n");
538        let provider = GitCodeAuthProvider::with_runner(runner);
539
540        let token = provider.token().await.expect("successful token retrieval");
541
542        assert_eq!(token, "gco_test_token_12345");
543    }
544}