Skip to main content

node_auth/
auth.rs

1//! Google Cloud credential retrieval and authentication handling.
2//!
3//! Supports obtaining OAuth2 access tokens through multiple strategies:
4//! 1. Explicitly supplied tokens.
5//! 2. Google Application Default Credentials (ADC) via service accounts or user login.
6//! 3. Active `gcloud` CLI session fallback (`gcloud auth print-access-token`).
7
8use crate::error::AuthError;
9use crate::token::validate_token;
10use std::process::Command;
11
12const CLOUD_PLATFORM_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform";
13
14/// Retrieves an OAuth2 access token for Google Cloud Artifact Registry.
15///
16/// Credential resolution order:
17/// 1. `explicit_token` (used unchanged if valid).
18/// 2. Google Application Default Credentials (ADC) via service account file or user ADC.
19/// 3. Fallback to `gcloud auth print-access-token` CLI command.
20///
21/// # Arguments
22///
23/// * `explicit_token` - Optional override token passed by the user.
24/// # Errors
25///
26/// Returns [`AuthError::CredentialsUnavailable`] if both credential providers fail, or
27/// [`AuthError::Config`] if an explicit token is invalid.
28///
29/// # Example
30///
31/// ```no_run
32/// # async fn doc() -> Result<(), node_auth::AuthError> {
33/// use node_auth::auth::get_credentials;
34///
35/// let token = get_credentials(Some("custom-token")).await?;
36/// assert_eq!(token, "custom-token");
37/// # Ok(())
38/// # }
39/// ```
40pub async fn get_credentials(explicit_token: Option<&str>) -> Result<String, AuthError> {
41  if let Some(token) = explicit_token {
42    validate_token(token)?;
43    return Ok(token.to_string());
44  }
45
46  // 1. Try Google Application Default Credentials (ADC)
47  log::debug!("Retrieving application default credentials...");
48  match get_adc_credentials().await {
49    Ok(token) => {
50      log::debug!("Successfully retrieved Application Default Credentials.");
51      return Ok(token);
52    }
53    Err(err) => {
54      log::debug!("Failed to retrieve ADC: {err}. Falling back to gcloud...");
55    }
56  }
57
58  // 2. Fall back to gcloud CLI
59  log::debug!("Retrieving credentials from gcloud CLI...");
60  match get_gcloud_credentials() {
61    Ok(token) => return Ok(token),
62    Err(err) => {
63      log::debug!("Failed to retrieve gcloud credentials: {err}");
64    }
65  }
66
67  Err(AuthError::CredentialsUnavailable)
68}
69
70async fn get_adc_credentials() -> Result<String, AuthError> {
71  let provider = gcp_auth::provider()
72    .await
73    .map_err(|e| AuthError::Authentication(format!("ADC provider initialization failed: {e}")))?;
74
75  let token = provider
76    .token(&[CLOUD_PLATFORM_SCOPE])
77    .await
78    .map_err(|e| AuthError::Authentication(format!("ADC token acquisition failed: {e}")))?;
79
80  let token_str = token.as_str().to_string();
81  validate_token(&token_str)?;
82  Ok(token_str)
83}
84
85fn get_gcloud_credentials() -> Result<String, AuthError> {
86  let binaries = if cfg!(windows) {
87    vec!["gcloud.cmd", "gcloud.bat", "gcloud"]
88  } else {
89    vec!["gcloud"]
90  };
91
92  let mut last_error = String::new();
93
94  for bin in binaries {
95    log::debug!("Running `{bin} auth print-access-token`...");
96
97    match Command::new(bin)
98      .args(["auth", "print-access-token"])
99      .output()
100    {
101      Ok(output) if output.status.success() => {
102        let stdout = String::from_utf8(output.stdout).map_err(|e| {
103          AuthError::Authentication(format!("gcloud returned a non-UTF-8 token: {e}"))
104        })?;
105        let token = stdout.trim_end_matches(['\r', '\n']);
106        validate_token(token)?;
107        log::debug!("Successfully retrieved credentials from gcloud CLI.");
108        return Ok(token.to_string());
109      }
110      Ok(output) => {
111        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
112        last_error = format!("`{bin}` exited with {}: {stderr}", output.status);
113      }
114      Err(e) => {
115        last_error = format!("Failed to spawn `{bin}`: {e}");
116      }
117    }
118  }
119
120  Err(AuthError::Authentication(last_error))
121}
122
123#[cfg(test)]
124mod tests {
125  use super::*;
126
127  #[tokio::test]
128  async fn test_explicit_token() {
129    let token = get_credentials(Some("my-explicit-token")).await.unwrap();
130    assert_eq!(token, "my-explicit-token");
131  }
132
133  #[tokio::test]
134  async fn test_explicit_token_rejects_unsafe_characters() {
135    assert!(
136      get_credentials(Some("  my-token-with-spaces  \n"))
137        .await
138        .is_err()
139    );
140  }
141}