Skip to main content

gitflow_github/
auth.rs

1//! GitHub 认证提供者实现。
2//!
3//! 通过 `gh auth` CLI 命令实现 [`AuthProvider`] trait,支持登录、
4//! 登出、状态查询及 Token 管理。
5//! 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
6//! [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
7
8use async_trait::async_trait;
9use gitflow_core::{
10    CoreError, Result,
11    auth::{AuthProvider, AuthStatus},
12};
13use tracing::debug;
14
15use crate::{
16    error::parse_gh_error,
17    runner::{CommandRunner, RealCommandRunner},
18};
19
20/// GitHub 认证提供者,通过 `gh` CLI 操作认证。
21///
22/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
23/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
24///
25/// # Examples
26///
27/// ```no_run
28/// use gitflow_github::GitHubAuthProvider;
29///
30/// let provider = GitHubAuthProvider::new();
31/// ```
32#[derive(Debug, Clone)]
33pub struct GitHubAuthProvider<R: CommandRunner = RealCommandRunner> {
34    /// 用于执行 `gh` CLI 命令的 runner。
35    runner: R,
36}
37
38impl GitHubAuthProvider<RealCommandRunner> {
39    /// 创建新的 GitHub 认证提供者,使用真实的进程执行器。
40    #[must_use]
41    pub fn new() -> Self {
42        Self {
43            runner: RealCommandRunner,
44        }
45    }
46}
47
48impl<R: CommandRunner> GitHubAuthProvider<R> {
49    /// 使用自定义 [`CommandRunner`] 创建提供者。
50    ///
51    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
52    #[must_use]
53    pub fn with_runner(runner: R) -> Self {
54        Self { runner }
55    }
56}
57
58impl Default for GitHubAuthProvider {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64#[async_trait]
65impl<R: CommandRunner + 'static> AuthProvider for GitHubAuthProvider<R> {
66    /// 执行交互式登录。
67    ///
68    /// 调用 `gh auth login`,将子进程的 stdout/stderr 透传给终端。
69    /// 如果提供了 token,则通过 `--with-token` 参数进行非交互式登录,
70    /// 并将 token 写入子进程的标准输入,避免其出现在进程参数中。
71    ///
72    /// # Errors
73    ///
74    /// 当认证失败或 `gh` 调用失败时返回错误。
75    async fn login(&self, token: Option<&str>) -> Result<()> {
76        debug!("spawning `gh auth login`");
77
78        if let Some(token) = token {
79            // 非交互模式:通过 stdin 传入 token,避免在进程参数中暴露敏感值
80            let output = self
81                .runner
82                .run_with_stdin("gh", &["auth", "login", "--with-token"], token.as_bytes())
83                .await
84                .map_err(|e| CoreError::Platform(format!("Failed to spawn gh auth login: {e}")))?;
85
86            if !output.status.success() {
87                return Err(CoreError::Platform("gh auth login failed".into()));
88            }
89        } else {
90            // Interactive mode
91            let output = self
92                .runner
93                .run("gh", &["auth", "login"])
94                .await
95                .map_err(|e| CoreError::Platform(format!("Failed to spawn gh auth login: {e}")))?;
96
97            if !output.status.success() {
98                return Err(CoreError::Platform("gh auth login failed".into()));
99            }
100        }
101
102        Ok(())
103    }
104
105    /// 执行登出,清除本地凭据。
106    ///
107    /// # Errors
108    ///
109    /// 当 `gh` 调用失败时返回错误。
110    async fn logout(&self) -> Result<()> {
111        debug!("spawning `gh auth logout`");
112
113        let output = self
114            .runner
115            .run("gh", &["auth", "logout"])
116            .await
117            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh auth logout: {e}")))?;
118
119        if !output.status.success() {
120            return Err(parse_gh_error(&output.stderr).into());
121        }
122
123        Ok(())
124    }
125
126    /// 查询当前认证状态。
127    ///
128    /// 调用 `gh auth status` 并解析输出来构造 [`AuthStatus`]。
129    /// 当 `gh` 命令执行失败或用户未登录时,返回 `AuthStatus { logged_in: false }`
130    /// 而非传播错误。
131    ///
132    /// # Errors
133    ///
134    /// 仅在 `gh` 返回非零退出码且无法识别为"未登录"模式时返回错误。
135    async fn status(&self) -> Result<AuthStatus> {
136        debug!("spawning `gh auth status`");
137
138        let Ok(output) = self.runner.run("gh", &["auth", "status"]).await else {
139            // CLI 执行失败(如 gh 未安装)→ 视为未登录
140            return Ok(AuthStatus {
141                logged_in: false,
142                user: None,
143                scopes: vec![],
144            });
145        };
146
147        let stdout = String::from_utf8_lossy(&output.stdout);
148        let stderr = String::from_utf8_lossy(&output.stderr);
149
150        // gh auth status 在未登录时会返回非零退出码
151        if !output.status.success() {
152            // 检查是否为未登录状态(某些版本会返回特定错误)
153            let text = format!("{stdout}{stderr}");
154            if text.to_lowercase().contains("not logged in")
155                || text.to_lowercase().contains("no active account")
156                || text.to_lowercase().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_gh_error(&output.stderr).into());
166        }
167
168        // 解析登录用户:查找 "Logged in to github.com as <username>" 行
169        let user = parse_user_from_status(&stdout);
170
171        // 解析 token scopes:查找 "Token scopes: 'scope1', 'scope2'" 行
172        let scopes = parse_scopes_from_status(&stdout);
173
174        Ok(AuthStatus {
175            logged_in: user.is_some(),
176            user,
177            scopes,
178        })
179    }
180
181    /// 获取当前有效的访问 Token。
182    ///
183    /// # Errors
184    ///
185    /// 当 `gh` 命令执行失败、用户未登录或 Token 为空时返回错误。
186    async fn token(&self) -> Result<String> {
187        debug!("spawning `gh auth token`");
188
189        let output = self
190            .runner
191            .run("gh", &["auth", "token"])
192            .await
193            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh auth token: {e}")))?;
194
195        if !output.status.success() {
196            return Err(parse_gh_error(&output.stderr).into());
197        }
198
199        let token = String::from_utf8_lossy(&output.stdout);
200        let trimmed = token.trim().to_string();
201        if trimmed.is_empty() {
202            return Err(CoreError::Platform(
203                "gh auth token returned empty output".into(),
204            ));
205        }
206        Ok(trimmed)
207    }
208}
209
210// AuthChecker 是同步 trait,必须使用 std::process::Command
211#[allow(clippy::disallowed_types, reason = "AuthChecker is synchronous")]
212impl<R: CommandRunner> gitflow_core::AuthChecker for GitHubAuthProvider<R> {
213    fn is_authenticated(&self) -> bool {
214        if std::env::var("GH_TOKEN").is_ok() {
215            return true;
216        }
217
218        let output = std::process::Command::new("gh")
219            .args(["auth", "status"])
220            .output();
221
222        matches!(output, Ok(out) if out.status.success())
223    }
224
225    fn check_status(&self) -> gitflow_core::AuthCheckResult {
226        // 1. 检查环境变量
227        if std::env::var("GH_TOKEN").is_ok() {
228            return gitflow_core::AuthCheckResult {
229                authenticated: true,
230                user: None,
231                reason: None,
232                hint: None,
233            };
234        }
235
236        // 2. 执行 gh auth status
237        let output = match std::process::Command::new("gh")
238            .args(["auth", "status"])
239            .output()
240        {
241            Ok(out) => out,
242            Err(e) => {
243                return gitflow_core::AuthCheckResult {
244                    authenticated: false,
245                    user: None,
246                    reason: Some(format!("Failed to execute gh: {e}")),
247                    hint: Some("Install GitHub CLI: https://cli.github.com".into()),
248                };
249            }
250        };
251
252        // 3. 解析结果
253        if output.status.success() {
254            let stdout = String::from_utf8_lossy(&output.stdout);
255            let user = parse_user_from_status(&stdout);
256
257            gitflow_core::AuthCheckResult {
258                authenticated: true,
259                user,
260                reason: None,
261                hint: None,
262            }
263        } else {
264            let stderr = String::from_utf8_lossy(&output.stderr);
265
266            gitflow_core::AuthCheckResult {
267                authenticated: false,
268                user: None,
269                reason: Some(stderr.to_string()),
270                hint: Some("Run `gh auth login` to authenticate".into()),
271            }
272        }
273    }
274}
275
276/// 从 `gh auth status` 的输出中解析 token scopes。
277///
278/// 支持格式:`"Token scopes: 'scope1', 'scope2', ..."`
279/// 可能带 `✓` 或 `-` 前缀。
280fn parse_scopes_from_status(output: &str) -> Vec<String> {
281    for line in output.lines() {
282        // 查找包含 "Token scopes:" 的行
283        let Some(pos) = line.find("Token scopes:") else {
284            continue;
285        };
286        let after = &line[pos + "Token scopes:".len()..];
287        let trimmed = after.trim();
288
289        // 处理 "none" 或空值
290        if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("none") {
291            return vec![];
292        }
293
294        // 解析 'scope1', 'scope2' 格式
295        return trimmed
296            .split(',')
297            .map(|s| s.trim().trim_matches('\'').trim_matches('"').to_string())
298            .filter(|s| !s.is_empty())
299            .collect();
300    }
301    vec![]
302}
303
304/// 从 `gh auth status` 的输出中解析用户名。
305///
306/// 支持两种 `gh` CLI 输出格式:
307/// - 旧版:`"Logged in to github.com as <username>"`
308/// - 新版:`"Logged in to github.com account <username>"`
309fn parse_user_from_status(output: &str) -> Option<String> {
310    let separators = [" as ", " account "];
311    for line in output.lines() {
312        // Only parse lines that contain "Logged in to" to avoid false matches
313        if !line.contains("Logged in to") {
314            continue;
315        }
316        for sep in &separators {
317            if let Some(pos) = line.find(sep) {
318                let after = &line[pos + sep.len()..];
319                // 用户名后面可能跟 " (" 或空格或其他
320                if let Some(end) = after.find(' ') {
321                    let user = &after[..end];
322                    if !user.is_empty() {
323                        return Some(user.to_string());
324                    }
325                } else if !after.is_empty() {
326                    return Some(after.trim().to_string());
327                }
328            }
329        }
330    }
331    None
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use crate::runner::MockCommandRunner;
338
339    #[test]
340    fn test_should_construct_github_auth_provider() {
341        let provider = GitHubAuthProvider::new();
342        let debug = format!("{provider:?}");
343        assert!(debug.contains("GitHubAuthProvider"));
344    }
345
346    #[test]
347    fn test_should_default_github_auth_provider() {
348        let provider = GitHubAuthProvider::default();
349        let _ = format!("{provider:?}");
350    }
351
352    #[test]
353    fn test_should_clone_github_auth_provider() {
354        let original = GitHubAuthProvider::new();
355        let cloned = original.clone();
356        let _ = format!("{cloned:?}");
357    }
358
359    #[test]
360    fn test_should_parse_user_from_status_output() {
361        let status = r"github.com
362  ✓ Logged in to github.com as octocat (keyring)
363  ✓ Git operations for github.com configured to use ssh protocol.
364  ✓ API calls for github.com should use https protocol
365";
366        assert_eq!(parse_user_from_status(status), Some("octocat".to_string()));
367    }
368
369    #[test]
370    fn test_should_parse_user_from_status_with_different_host() {
371        let status = r"github.com
372  ✓ Logged in to github.com as alice (oauth_token)
373  ✓ Token: gho_****
374";
375        assert_eq!(parse_user_from_status(status), Some("alice".to_string()));
376    }
377
378    #[test]
379    fn test_should_return_none_when_no_user_in_status() {
380        let status = "No active account found";
381        assert!(parse_user_from_status(status).is_none());
382    }
383
384    #[test]
385    fn test_should_return_none_for_empty_status() {
386        assert!(parse_user_from_status("").is_none());
387    }
388
389    #[test]
390    fn test_should_parse_user_without_suffix() {
391        let status = "Logged in to github.com as bob";
392        assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
393    }
394
395    #[test]
396    fn test_should_parse_user_from_account_format() {
397        let status = r"github.com
398  ✓ Logged in to github.com account octocat (keyring)
399  ✓ Git operations for github.com configured to use ssh protocol.
400  ✓ API calls for github.com should use https protocol
401";
402        assert_eq!(parse_user_from_status(status), Some("octocat".to_string()));
403    }
404
405    #[test]
406    fn test_should_parse_user_from_account_format_without_suffix() {
407        let status = "Logged in to github.com account bob";
408        assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
409    }
410
411    #[test]
412    fn test_should_parse_scopes_from_status_output() {
413        let status = r"github.com
414  ✓ Logged in to github.com account octocat (keyring)
415  - Token scopes: 'delete_repo', 'gist', 'read:org', 'repo', 'workflow'
416";
417        let scopes = parse_scopes_from_status(status);
418        assert_eq!(
419            scopes,
420            vec!["delete_repo", "gist", "read:org", "repo", "workflow"]
421        );
422    }
423
424    #[test]
425    fn test_should_parse_scopes_with_checkmark_prefix() {
426        let status = "  ✓ Token scopes: 'repo', 'read:org'";
427        let scopes = parse_scopes_from_status(status);
428        assert_eq!(scopes, vec!["repo", "read:org"]);
429    }
430
431    #[test]
432    fn test_should_return_empty_scopes_when_none() {
433        let status = "  - Token scopes: none";
434        let scopes = parse_scopes_from_status(status);
435        assert!(scopes.is_empty());
436    }
437
438    #[test]
439    fn test_should_return_empty_scopes_when_line_missing() {
440        let status = "Logged in to github.com as octocat";
441        let scopes = parse_scopes_from_status(status);
442        assert!(scopes.is_empty());
443    }
444
445    #[test]
446    fn test_should_parse_single_scope() {
447        let status = "  - Token scopes: 'repo'";
448        let scopes = parse_scopes_from_status(status);
449        assert_eq!(scopes, vec!["repo"]);
450    }
451
452    #[test]
453    fn test_auth_checker_is_authenticated_with_env_var() {
454        use gitflow_core::AuthChecker;
455        temp_env::with_var("GH_TOKEN", Some("test_token"), || {
456            let provider = GitHubAuthProvider::new();
457            assert!(provider.is_authenticated());
458        });
459    }
460
461    #[test]
462    fn test_auth_checker_check_status_with_env_var() {
463        use gitflow_core::AuthChecker;
464        temp_env::with_var("GH_TOKEN", Some("test_token"), || {
465            let provider = GitHubAuthProvider::new();
466            let result = provider.check_status();
467            assert!(result.authenticated);
468            assert!(result.reason.is_none());
469        });
470    }
471
472    // --- Failure-path tests using an injected MockCommandRunner ---
473
474    #[tokio::test]
475    async fn test_should_return_platform_error_when_gh_login_fails() {
476        let runner = MockCommandRunner::failure("login failed", 1);
477        let provider = GitHubAuthProvider::with_runner(runner);
478
479        let result = provider.login(None).await;
480
481        assert!(result.is_err());
482        assert!(matches!(
483            result.unwrap_err(),
484            gitflow_core::CoreError::Platform(_)
485        ));
486    }
487
488    #[tokio::test]
489    async fn test_should_login_with_token_via_stdin() {
490        let runner = MockCommandRunner::success("");
491        let provider = GitHubAuthProvider::with_runner(runner);
492
493        let result = provider.login(Some("ghp_secret_token")).await;
494
495        assert!(result.is_ok());
496    }
497
498    #[tokio::test]
499    async fn test_should_return_platform_error_when_gh_login_with_token_fails() {
500        let runner = MockCommandRunner::failure("token login failed", 1);
501        let provider = GitHubAuthProvider::with_runner(runner);
502
503        let result = provider.login(Some("ghp_secret_token")).await;
504
505        assert!(result.is_err());
506        assert!(matches!(
507            result.unwrap_err(),
508            gitflow_core::CoreError::Platform(_)
509        ));
510    }
511
512    #[tokio::test]
513    async fn test_should_return_platform_error_when_gh_logout_fails() {
514        let runner = MockCommandRunner::failure("logout failed", 1);
515        let provider = GitHubAuthProvider::with_runner(runner);
516
517        let result = provider.logout().await;
518
519        assert!(result.is_err());
520        assert!(matches!(
521            result.unwrap_err(),
522            gitflow_core::CoreError::Cli(_)
523        ));
524    }
525
526    #[tokio::test]
527    async fn test_should_return_not_logged_in_when_gh_status_spawn_fails() {
528        let runner = MockCommandRunner::spawn_error();
529        let provider = GitHubAuthProvider::with_runner(runner);
530
531        let result = provider.status().await;
532
533        assert!(result.is_ok());
534        let status = result.unwrap();
535        assert!(!status.logged_in);
536        assert!(status.user.is_none());
537        assert!(status.scopes.is_empty());
538    }
539
540    #[tokio::test]
541    async fn test_should_return_platform_error_when_gh_token_fails() {
542        let runner = MockCommandRunner::failure("token failed", 1);
543        let provider = GitHubAuthProvider::with_runner(runner);
544
545        let result = provider.token().await;
546
547        assert!(result.is_err());
548        assert!(matches!(
549            result.unwrap_err(),
550            gitflow_core::CoreError::Cli(_)
551        ));
552    }
553
554    #[tokio::test]
555    async fn test_should_return_error_when_gh_token_returns_empty() {
556        let runner = MockCommandRunner::success("");
557        let provider = GitHubAuthProvider::with_runner(runner);
558
559        let result = provider.token().await;
560
561        assert!(result.is_err());
562        assert!(matches!(
563            result.unwrap_err(),
564            gitflow_core::CoreError::Platform(_)
565        ));
566    }
567
568    // --- Success-path tests using an injected MockCommandRunner ---
569
570    #[test]
571    fn test_should_construct_with_custom_runner() {
572        let runner = MockCommandRunner::success("");
573        let provider = GitHubAuthProvider::with_runner(runner);
574        let debug = format!("{provider:?}");
575        assert!(debug.contains("GitHubAuthProvider"));
576    }
577
578    #[tokio::test]
579    async fn test_should_login_interactively() {
580        let runner = MockCommandRunner::success("");
581        let provider = GitHubAuthProvider::with_runner(runner);
582
583        let result = provider.login(None).await;
584
585        assert!(result.is_ok());
586    }
587
588    #[tokio::test]
589    async fn test_should_logout_successfully() {
590        let runner = MockCommandRunner::success("");
591        let provider = GitHubAuthProvider::with_runner(runner);
592
593        let result = provider.logout().await;
594
595        assert!(result.is_ok());
596    }
597
598    #[tokio::test]
599    async fn test_should_return_logged_in_status_when_authenticated() {
600        let stdout =
601            "Logged in to github.com as testuser (keyring)\n  - Token scopes: 'repo', 'read:org'\n";
602        let runner = MockCommandRunner::success(stdout);
603        let provider = GitHubAuthProvider::with_runner(runner);
604
605        let result = provider.status().await;
606
607        assert!(result.is_ok());
608        let status = result.unwrap();
609        assert!(status.logged_in);
610        assert_eq!(status.user, Some("testuser".to_string()));
611        assert_eq!(status.scopes, vec!["repo", "read:org"]);
612    }
613
614    #[tokio::test]
615    async fn test_should_return_not_logged_in_when_gh_status_indicates_not_authenticated() {
616        let runner = MockCommandRunner::failure("not logged in", 1);
617        let provider = GitHubAuthProvider::with_runner(runner);
618
619        let result = provider.status().await;
620
621        assert!(result.is_ok());
622        let status = result.unwrap();
623        assert!(!status.logged_in);
624        assert!(status.user.is_none());
625    }
626
627    #[tokio::test]
628    async fn test_should_return_cli_error_when_gh_status_fails_unknown() {
629        let runner = MockCommandRunner::failure("unknown server error", 128);
630        let provider = GitHubAuthProvider::with_runner(runner);
631
632        let result = provider.status().await;
633
634        assert!(result.is_err());
635        assert!(matches!(
636            result.unwrap_err(),
637            gitflow_core::CoreError::Cli(_)
638        ));
639    }
640
641    #[tokio::test]
642    async fn test_should_return_token_successfully() {
643        let runner = MockCommandRunner::success("ghp_test12345\n");
644        let provider = GitHubAuthProvider::with_runner(runner);
645
646        let result = provider.token().await;
647
648        assert!(result.is_ok());
649        assert_eq!(result.unwrap(), "ghp_test12345");
650    }
651
652    #[tokio::test]
653    async fn test_should_trim_whitespace_from_token() {
654        let runner = MockCommandRunner::success("  ghp_test12345  \n\n");
655        let provider = GitHubAuthProvider::with_runner(runner);
656
657        let result = provider.token().await;
658
659        assert!(result.is_ok());
660        assert_eq!(result.unwrap(), "ghp_test12345");
661    }
662}