1use 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#[derive(Debug, Clone)]
37pub struct GitCodeAuthProvider<R: CommandRunner = RealCommandRunner, E: EnvSource = RealEnv> {
38 runner: R,
40 env: E,
42}
43
44impl GitCodeAuthProvider<RealCommandRunner, RealEnv> {
45 #[must_use]
47 pub fn new() -> Self {
48 Self {
49 runner: RealCommandRunner,
50 env: RealEnv,
51 }
52 }
53
54 #[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 #[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 #[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 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 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 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 if !output.status.success() {
186 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 let user = parse_user_from_status(&stdout);
205
206 Ok(AuthStatus {
207 logged_in: user.is_some(),
208 user,
209 scopes: vec![], hosts: vec![],
211 })
212 }
213
214 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#[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 if self.env.var("GITCODE_TOKEN").is_some() {
244 return true;
245 }
246
247 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 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 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 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
324fn parse_user_from_status(output: &str) -> Option<String> {
330 for line in output.lines() {
332 if let Some(pos) = line.find(" as ") {
333 let after_as = &line[pos + 4..];
334 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 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 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 #[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 #[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}