1use 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
14pub 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 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...");
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::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}