1use async_trait::async_trait;
9use gitflow_core::{
10 CoreError, Result,
11 auth::{AuthProvider, AuthStatus},
12};
13use tracing::debug;
14
15use crate::{
16 error::parse_glab_error,
17 runner::{CommandRunner, RealCommandRunner},
18};
19
20#[derive(Debug, Clone)]
33pub struct GitLabAuthProvider<R: CommandRunner = RealCommandRunner> {
34 runner: R,
36}
37
38impl GitLabAuthProvider<RealCommandRunner> {
39 #[must_use]
41 pub fn new() -> Self {
42 Self {
43 runner: RealCommandRunner,
44 }
45 }
46}
47
48impl<R: CommandRunner> GitLabAuthProvider<R> {
49 #[must_use]
53 pub fn with_runner(runner: R) -> Self {
54 Self { runner }
55 }
56}
57
58impl Default for GitLabAuthProvider<RealCommandRunner> {
59 fn default() -> Self {
60 Self::new()
61 }
62}
63
64#[async_trait]
65impl<R: CommandRunner + 'static> AuthProvider for GitLabAuthProvider<R> {
66 async fn login(&self, token: Option<&str>) -> Result<()> {
67 debug!("spawning `glab auth login`");
68
69 let output = if let Some(token) = token {
72 self.runner
73 .run_with_stdin("glab", &["auth", "login", "--stdin"], token.as_bytes())
74 .await
75 .map_err(|e| CoreError::Platform(format!("Failed to spawn glab auth login: {e}")))?
76 } else {
77 self.runner
78 .run("glab", &["auth", "login"])
79 .await
80 .map_err(|e| CoreError::Platform(format!("Failed to spawn glab auth login: {e}")))?
81 };
82
83 if !output.status.success() {
84 return Err(parse_glab_error(&output.stderr).into());
85 }
86
87 Ok(())
88 }
89
90 async fn logout(&self) -> Result<()> {
91 debug!("spawning `glab auth logout`");
92
93 let output = self
94 .runner
95 .run("glab", &["auth", "logout"])
96 .await
97 .map_err(|e| CoreError::Platform(format!("Failed to spawn glab auth logout: {e}")))?;
98
99 if !output.status.success() {
100 return Err(parse_glab_error(&output.stderr).into());
101 }
102
103 Ok(())
104 }
105
106 async fn status(&self) -> Result<AuthStatus> {
107 debug!("spawning `glab auth status`");
108
109 let output = self
110 .runner
111 .run("glab", &["auth", "status"])
112 .await
113 .map_err(|e| CoreError::Platform(format!("Failed to spawn glab auth status: {e}")))?;
114
115 let stdout = String::from_utf8_lossy(&output.stdout);
116 let stderr = String::from_utf8_lossy(&output.stderr);
117
118 if !output.status.success() {
119 let text = format!("{stdout}{stderr}").to_lowercase();
120 if text.contains("not logged in")
121 || text.contains("no active account")
122 || text.contains("not authenticated")
123 {
124 return Ok(AuthStatus {
125 logged_in: false,
126 user: None,
127 scopes: vec![],
128 });
129 }
130
131 return Err(parse_glab_error(&output.stderr).into());
132 }
133
134 let combined = format!("{stdout}{stderr}");
136 let user = parse_user_from_status(&combined);
137
138 Ok(AuthStatus {
139 logged_in: user.is_some(),
140 user,
141 scopes: vec![],
142 })
143 }
144
145 async fn token(&self) -> Result<String> {
146 debug!("spawning `glab auth token`");
147
148 let output = self
149 .runner
150 .run("glab", &["auth", "token"])
151 .await
152 .map_err(|e| CoreError::Platform(format!("Failed to spawn glab auth token: {e}")))?;
153
154 if !output.status.success() {
155 return Err(parse_glab_error(&output.stderr).into());
156 }
157
158 let token = String::from_utf8_lossy(&output.stdout);
159 Ok(token.trim().to_string())
160 }
161}
162
163#[allow(clippy::disallowed_types, reason = "AuthChecker is synchronous")]
165impl<R: CommandRunner> gitflow_core::AuthChecker for GitLabAuthProvider<R> {
166 fn is_authenticated(&self) -> bool {
167 if std::env::var("GL_TOKEN").is_ok() {
168 return true;
169 }
170
171 let output = std::process::Command::new("glab")
172 .args(["auth", "status"])
173 .output();
174
175 matches!(output, Ok(out) if out.status.success())
176 }
177
178 fn check_status(&self) -> gitflow_core::AuthCheckResult {
179 if std::env::var("GL_TOKEN").is_ok() {
181 return gitflow_core::AuthCheckResult {
182 authenticated: true,
183 user: None,
184 reason: None,
185 hint: None,
186 };
187 }
188
189 let output = match std::process::Command::new("glab")
191 .args(["auth", "status"])
192 .output()
193 {
194 Ok(out) => out,
195 Err(e) => {
196 return gitflow_core::AuthCheckResult {
197 authenticated: false,
198 user: None,
199 reason: Some(format!("Failed to execute glab: {e}")),
200 hint: Some("Install GitLab CLI: brew install glab".into()),
201 };
202 }
203 };
204
205 if output.status.success() {
207 let stdout = String::from_utf8_lossy(&output.stdout);
208 let user = parse_user_from_status(&stdout);
209
210 gitflow_core::AuthCheckResult {
211 authenticated: true,
212 user,
213 reason: None,
214 hint: None,
215 }
216 } else {
217 let stderr = String::from_utf8_lossy(&output.stderr);
218
219 gitflow_core::AuthCheckResult {
220 authenticated: false,
221 user: None,
222 reason: Some(stderr.to_string()),
223 hint: Some("Run `glab auth login` to authenticate".into()),
224 }
225 }
226 }
227}
228
229fn parse_user_from_status(output: &str) -> Option<String> {
230 for line in output.lines() {
231 if let Some(pos) = line.find(" as ") {
232 let after_as = &line[pos + 4..];
233 if let Some(end) = after_as.find(' ') {
234 let user = &after_as[..end];
235 if !user.is_empty() {
236 return Some(user.to_string());
237 }
238 } else if !after_as.is_empty() {
239 return Some(after_as.trim().to_string());
240 }
241 }
242 }
243 None
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249 use crate::runner::MockCommandRunner;
250
251 #[test]
252 fn test_should_construct_gitlab_auth_provider() {
253 let provider = GitLabAuthProvider::new();
254 let _ = format!("{provider:?}");
255 }
256
257 #[test]
258 fn test_should_default_gitlab_auth_provider() {
259 let provider = GitLabAuthProvider::default();
260 let _ = format!("{provider:?}");
261 }
262
263 #[test]
264 fn test_should_clone_gitlab_auth_provider() {
265 let original = GitLabAuthProvider::new();
266 let cloned = original.clone();
267 let _ = format!("{cloned:?}");
268 }
269
270 #[test]
271 fn test_should_parse_user_from_status_output() {
272 let status = r"gitlab.com
273 ✓ Logged in to gitlab.com as root (keyring)
274 ✓ Git operations for gitlab.com configured to use ssh protocol.
275";
276 assert_eq!(parse_user_from_status(status), Some("root".to_string()));
277 }
278
279 #[test]
280 fn test_should_parse_user_from_status_with_different_host() {
281 let status = r"gitlab.com
282 ✓ Logged in to gitlab.com as alice (oauth_token)
283 ✓ Token: glpat-****
284";
285 assert_eq!(parse_user_from_status(status), Some("alice".to_string()));
286 }
287
288 #[test]
289 fn test_should_return_none_when_no_user_in_status() {
290 let status = "No active account found";
291 assert!(parse_user_from_status(status).is_none());
292 }
293
294 #[test]
295 fn test_should_return_none_for_empty_status() {
296 assert!(parse_user_from_status("").is_none());
297 }
298
299 #[test]
300 fn test_should_parse_user_without_suffix() {
301 let status = "Logged in to gitlab.com as bob";
302 assert_eq!(parse_user_from_status(status), Some("bob".to_string()));
303 }
304
305 #[test]
306 fn test_auth_checker_is_authenticated_with_env_var() {
307 use gitflow_core::AuthChecker;
308 temp_env::with_var("GL_TOKEN", Some("test_token"), || {
309 let provider = GitLabAuthProvider::new();
310 assert!(provider.is_authenticated());
311 });
312 }
313
314 #[test]
315 fn test_auth_checker_check_status_with_env_var() {
316 use gitflow_core::AuthChecker;
317 temp_env::with_var("GL_TOKEN", Some("test_token"), || {
318 let provider = GitLabAuthProvider::new();
319 let result = provider.check_status();
320 assert!(result.authenticated);
321 assert!(result.reason.is_none());
322 });
323 }
324
325 #[tokio::test]
328 async fn test_should_return_platform_error_when_glab_fails_for_login() {
329 let runner = MockCommandRunner::failure("authentication failed", 256);
330 let provider = GitLabAuthProvider::with_runner(runner);
331
332 let result = provider.login(Some("glpat-token")).await;
333
334 assert!(matches!(
335 result.unwrap_err(),
336 gitflow_core::CoreError::Cli(_)
337 ));
338 }
339
340 #[tokio::test]
341 async fn test_should_return_platform_error_when_glab_fails_for_logout() {
342 let runner = MockCommandRunner::failure("not logged in", 256);
343 let provider = GitLabAuthProvider::with_runner(runner);
344
345 let result = provider.logout().await;
346
347 assert!(matches!(
348 result.unwrap_err(),
349 gitflow_core::CoreError::Cli(_)
350 ));
351 }
352
353 #[tokio::test]
354 async fn test_should_return_logged_out_status_when_glab_reports_not_logged_in() {
355 let runner = MockCommandRunner::failure("not logged in to any GitLab hosts", 256);
356 let provider = GitLabAuthProvider::with_runner(runner);
357
358 let status = provider.status().await.expect("graceful logged-out status");
359
360 assert!(!status.logged_in);
361 assert!(status.user.is_none());
362 }
363
364 #[tokio::test]
365 async fn test_should_return_platform_error_when_status_fails_unexpectedly() {
366 let runner = MockCommandRunner::failure("internal server error", 256);
367 let provider = GitLabAuthProvider::with_runner(runner);
368
369 let result = provider.status().await;
370
371 assert!(matches!(
372 result.unwrap_err(),
373 gitflow_core::CoreError::Cli(_)
374 ));
375 }
376
377 #[tokio::test]
378 async fn test_should_return_platform_error_when_glab_fails_for_token() {
379 let runner = MockCommandRunner::failure("no token found", 256);
380 let provider = GitLabAuthProvider::with_runner(runner);
381
382 let result = provider.token().await;
383
384 assert!(matches!(
385 result.unwrap_err(),
386 gitflow_core::CoreError::Cli(_)
387 ));
388 }
389
390 #[tokio::test]
391 async fn test_should_return_empty_token_when_stdout_is_empty() {
392 let runner = MockCommandRunner::success("");
393 let provider = GitLabAuthProvider::with_runner(runner);
394
395 let token = provider
396 .token()
397 .await
398 .expect("empty stdout yields empty token");
399
400 assert!(token.is_empty());
401 }
402}