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