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