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
44    return Ok(token.to_string());
45  }
46
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  log::debug!("Retrieving credentials from gcloud CLI...");
59  match get_gcloud_credentials() {
60    Ok(token) => return Ok(token),
61    Err(err) => {
62      log::debug!("Failed to retrieve gcloud credentials: {err}");
63    }
64  }
65
66  Err(AuthError::CredentialsUnavailable)
67}
68
69async fn get_adc_credentials() -> Result<String, AuthError> {
70  let provider = gcp_auth::provider()
71    .await
72    .map_err(|e| AuthError::Authentication(format!("ADC provider initialization failed: {e}")))?;
73
74  let token = provider
75    .token(&[CLOUD_PLATFORM_SCOPE])
76    .await
77    .map_err(|e| AuthError::Authentication(format!("ADC token acquisition failed: {e}")))?;
78
79  let token_str = token.as_str().to_string();
80  validate_token(&token_str)?;
81  Ok(token_str)
82}
83
84fn get_gcloud_credentials() -> Result<String, AuthError> {
85  let binaries = if cfg!(windows) {
86    vec!["gcloud.cmd", "gcloud.bat", "gcloud"]
87  } else {
88    vec!["gcloud"]
89  };
90
91  let mut last_error = String::new();
92
93  for bin in binaries {
94    log::debug!("Running `{bin} auth print-access-token`...");
95
96    match Command::new(bin)
97      .args(["auth", "print-access-token"])
98      .output()
99    {
100      Ok(output) if output.status.success() => {
101        let stdout = String::from_utf8(output.stdout).map_err(|e| {
102          AuthError::Authentication(format!("gcloud returned a non-UTF-8 token: {e}"))
103        })?;
104
105        let token = stdout.trim_end_matches(['\r', '\n']);
106        validate_token(token)?;
107
108        log::debug!("Successfully retrieved credentials from gcloud CLI.");
109
110        return Ok(token.to_string());
111      }
112      Ok(output) => {
113        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
114        last_error = format!("`{bin}` exited with {}: {stderr}", output.status);
115      }
116      Err(e) => {
117        last_error = format!("Failed to spawn `{bin}`: {e}");
118      }
119    }
120  }
121
122  Err(AuthError::Authentication(last_error))
123}
124
125#[cfg(test)]
126mod tests {
127  use super::*;
128
129  #[tokio::test]
130  async fn test_explicit_token() {
131    let token = get_credentials(Some("my-explicit-token")).await.unwrap();
132    assert_eq!(token, "my-explicit-token");
133  }
134
135  #[tokio::test]
136  async fn test_explicit_token_rejects_unsafe_characters() {
137    assert!(
138      get_credentials(Some("  my-token-with-spaces  \n"))
139        .await
140        .is_err()
141    );
142  }
143}