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        Ok(AuthStatus {
172            logged_in: user.is_some(),
173            user,
174            scopes: vec![], // gh auth status 不直接返回 scopes 列表
175        })
176    }
177
178    /// 获取当前有效的访问 Token。
179    ///
180    /// # Errors
181    ///
182    /// 当 `gh` 命令执行失败、用户未登录或 Token 为空时返回错误。
183    async fn token(&self) -> Result<String> {
184        debug!("spawning `gh auth token`");
185
186        let output = self
187            .runner
188            .run("gh", &["auth", "token"])
189            .await
190            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh auth token: {e}")))?;
191
192        if !output.status.success() {
193            return Err(parse_gh_error(&output.stderr).into());
194        }
195
196        let token = String::from_utf8_lossy(&output.stdout);
197        let trimmed = token.trim().to_string();
198        if trimmed.is_empty() {
199            return Err(CoreError::Platform(
200                "gh auth token returned empty output".into(),
201            ));
202        }
203        Ok(trimmed)
204    }
205}
206
207// AuthChecker 是同步 trait,必须使用 std::process::Command
208#[allow(clippy::disallowed_types, reason = "AuthChecker is synchronous")]
209impl<R: CommandRunner> gitflow_core::AuthChecker for GitHubAuthProvider<R> {
210    fn is_authenticated(&self) -> bool {
211        if std::env::var("GH_TOKEN").is_ok() {
212            return true;
213        }
214
215        let output = std::process::Command::new("gh")
216            .args(["auth", "status"])
217            .output();
218
219        matches!(output, Ok(out) if out.status.success())
220    }
221
222    fn check_status(&self) -> gitflow_core::AuthCheckResult {
223        // 1. 检查环境变量
224        if std::env::var("GH_TOKEN").is_ok() {
225            return gitflow_core::AuthCheckResult {
226                authenticated: true,
227                user: None,
228                reason: None,
229                hint: None,
230            };
231        }
232
233        // 2. 执行 gh auth status
234        let output = match std::process::Command::new("gh")
235            .args(["auth", "status"])
236            .output()
237        {
238            Ok(out) => out,
239            Err(e) => {
240                return gitflow_core::AuthCheckResult {
241                    authenticated: false,
242                    user: None,
243                    reason: Some(format!("Failed to execute gh: {e}")),
244                    hint: Some("Install GitHub CLI: https://cli.github.com".into()),
245                };
246            }
247        };
248
249        // 3. 解析结果
250        if output.status.success() {
251            let stdout = String::from_utf8_lossy(&output.stdout);
252            let user = parse_user_from_status(&stdout);
253
254            gitflow_core::AuthCheckResult {
255                authenticated: true,
256                user,
257                reason: None,
258                hint: None,
259            }
260        } else {
261            let stderr = String::from_utf8_lossy(&output.stderr);
262
263            gitflow_core::AuthCheckResult {
264                authenticated: false,
265                user: None,
266                reason: Some(stderr.to_string()),
267                hint: Some("Run `gh auth login` to authenticate".into()),
268            }
269        }
270    }
271}
272
273/// 从 `gh auth status` 的输出中解析用户名。
274///
275/// 支持两种 `gh` CLI 输出格式:
276/// - 旧版:`"Logged in to github.com as <username>"`
277/// - 新版:`"Logged in to github.com account <username>"`
278fn parse_user_from_status(output: &str) -> Option<String> {
279    let separators = [" as ", " account "];
280    for line in output.lines() {
281        // Only parse lines that contain "Logged in to" to avoid false matches
282        if !line.contains("Logged in to") {
283            continue;
284        }
285        for sep in &separators {
286            if let Some(pos) = line.find(sep) {
287                let after = &line[pos + sep.len()..];
288                // 用户名后面可能跟 " (" 或空格或其他
289                if let Some(end) = after.find(' ') {
290                    let user = &after[..end];
291                    if !user.is_empty() {
292                        return Some(user.to_string());
293                    }
294                } else if !after.is_empty() {
295                    return Some(after.trim().to_string());
296                }
297            }
298        }
299    }
300    None
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306    use crate::runner::MockCommandRunner;
307
308    #[test]
309    fn test_should_construct_github_auth_provider() {
310        let provider = GitHubAuthProvider::new();
311        let _ = format!("{provider:?}");
312    }
313
314    #[test]
315    fn test_should_default_github_auth_provider() {
316        let provider = GitHubAuthProvider::default();
317        let _ = format!("{provider:?}");
318    }
319
320    #[test]
321    fn test_should_clone_github_auth_provider() {
322        let original = GitHubAuthProvider::new();
323        let cloned = original.clone();
324        let _ = format!("{cloned:?}");
325    }
326
327    #[test]
328    fn test_should_parse_user_from_status_output() {
329        let status = r"github.com
330  ✓ Logged in to github.com as octocat (keyring)
331  ✓ Git operations for github.com configured to use ssh protocol.
332  ✓ API calls for github.com should use https protocol
333";
334        assert_eq!(parse_user_from_status(status), Some("octocat".to_string()));
335    }
336
337    #[test]
338    fn test_should_parse_user_from_status_with_different_host() {
339        let status = r"github.com
340  ✓ Logged in to github.com as alice (oauth_token)
341  ✓ Token: gho_****
342";
343        assert_eq!(parse_user_from_status(status), Some("alice".to_string()));
344    }
345
346    #[test]
347    fn test_should_return_none_when_no_user_in_status() {
348        let status = "No active account found";
349        assert!(parse_user_from_status(status).is_none());
350    }
351
352    #[test]
353    fn test_should_return_none_for_empty_status() {
354        assert!(parse_user_from_status("").is_none());
355    }
356
357    #[test]
358    fn test_should_parse_user_without_suffix() {
359        let status = "Logged in to github.com as bob";
360        assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
361    }
362
363    #[test]
364    fn test_should_parse_user_from_account_format() {
365        let status = r"github.com
366  ✓ Logged in to github.com account octocat (keyring)
367  ✓ Git operations for github.com configured to use ssh protocol.
368  ✓ API calls for github.com should use https protocol
369";
370        assert_eq!(parse_user_from_status(status), Some("octocat".to_string()));
371    }
372
373    #[test]
374    fn test_should_parse_user_from_account_format_without_suffix() {
375        let status = "Logged in to github.com account bob";
376        assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
377    }
378
379    #[test]
380    fn test_auth_checker_is_authenticated_with_env_var() {
381        use gitflow_core::AuthChecker;
382        temp_env::with_var("GH_TOKEN", Some("test_token"), || {
383            let provider = GitHubAuthProvider::new();
384            assert!(provider.is_authenticated());
385        });
386    }
387
388    #[test]
389    fn test_auth_checker_check_status_with_env_var() {
390        use gitflow_core::AuthChecker;
391        temp_env::with_var("GH_TOKEN", Some("test_token"), || {
392            let provider = GitHubAuthProvider::new();
393            let result = provider.check_status();
394            assert!(result.authenticated);
395            assert!(result.reason.is_none());
396        });
397    }
398
399    // --- Failure-path tests using an injected MockCommandRunner ---
400
401    #[tokio::test]
402    async fn test_should_return_platform_error_when_gh_login_fails() {
403        let runner = MockCommandRunner::failure("login failed", 1);
404        let provider = GitHubAuthProvider::with_runner(runner);
405
406        let result = provider.login(None).await;
407
408        assert!(result.is_err());
409        assert!(matches!(
410            result.unwrap_err(),
411            gitflow_core::CoreError::Platform(_)
412        ));
413    }
414
415    #[tokio::test]
416    async fn test_should_login_with_token_via_stdin() {
417        let runner = MockCommandRunner::success("");
418        let provider = GitHubAuthProvider::with_runner(runner);
419
420        let result = provider.login(Some("ghp_secret_token")).await;
421
422        assert!(result.is_ok());
423    }
424
425    #[tokio::test]
426    async fn test_should_return_platform_error_when_gh_login_with_token_fails() {
427        let runner = MockCommandRunner::failure("token login failed", 1);
428        let provider = GitHubAuthProvider::with_runner(runner);
429
430        let result = provider.login(Some("ghp_secret_token")).await;
431
432        assert!(result.is_err());
433        assert!(matches!(
434            result.unwrap_err(),
435            gitflow_core::CoreError::Platform(_)
436        ));
437    }
438
439    #[tokio::test]
440    async fn test_should_return_platform_error_when_gh_logout_fails() {
441        let runner = MockCommandRunner::failure("logout failed", 1);
442        let provider = GitHubAuthProvider::with_runner(runner);
443
444        let result = provider.logout().await;
445
446        assert!(result.is_err());
447        assert!(matches!(
448            result.unwrap_err(),
449            gitflow_core::CoreError::Cli(_)
450        ));
451    }
452
453    #[tokio::test]
454    async fn test_should_return_not_logged_in_when_gh_status_spawn_fails() {
455        let runner = MockCommandRunner::spawn_error();
456        let provider = GitHubAuthProvider::with_runner(runner);
457
458        let result = provider.status().await;
459
460        assert!(result.is_ok());
461        let status = result.unwrap();
462        assert!(!status.logged_in);
463        assert!(status.user.is_none());
464        assert!(status.scopes.is_empty());
465    }
466
467    #[tokio::test]
468    async fn test_should_return_platform_error_when_gh_token_fails() {
469        let runner = MockCommandRunner::failure("token failed", 1);
470        let provider = GitHubAuthProvider::with_runner(runner);
471
472        let result = provider.token().await;
473
474        assert!(result.is_err());
475        assert!(matches!(
476            result.unwrap_err(),
477            gitflow_core::CoreError::Cli(_)
478        ));
479    }
480
481    #[tokio::test]
482    async fn test_should_return_error_when_gh_token_returns_empty() {
483        let runner = MockCommandRunner::success("");
484        let provider = GitHubAuthProvider::with_runner(runner);
485
486        let result = provider.token().await;
487
488        assert!(result.is_err());
489        assert!(matches!(
490            result.unwrap_err(),
491            gitflow_core::CoreError::Platform(_)
492        ));
493    }
494}