1use super::dynamic::CredentialsProvider;
109use super::external_account_sources::aws_sourced::AwsSourcedCredentials;
110use super::external_account_sources::executable_sourced::ExecutableSourcedCredentials;
111use super::external_account_sources::file_sourced::FileSourcedCredentials;
112use super::external_account_sources::url_sourced::UrlSourcedCredentials;
113use super::impersonated;
114use super::internal::sts_exchange::{ClientAuthentication, ExchangeTokenRequest, STSHandler};
115use super::{CacheableResource, Credentials};
116use crate::access_boundary::{CredentialsWithAccessBoundary, external_account_lookup_url};
117use crate::build_errors::Error as BuilderError;
118use crate::constants::{DEFAULT_SCOPE, DEFAULT_UNIVERSE_DOMAIN, STS_TOKEN_URL};
119use crate::credentials::dynamic::AccessTokenCredentialsProvider;
120use crate::credentials::external_account_sources::programmatic_sourced::ProgrammaticSourcedCredentials;
121use crate::credentials::subject_token::dynamic;
122use crate::credentials::{AccessToken, AccessTokenCredentials};
123use crate::errors::non_retryable;
124use crate::headers_util::AuthHeadersBuilder;
125use crate::retry::Builder as RetryTokenProviderBuilder;
126use crate::token::{CachedTokenProvider, Token, TokenProvider};
127use crate::token_cache::TokenCache;
128use crate::{BuildResult, Result};
129use google_cloud_gax::backoff_policy::BackoffPolicyArg;
130use google_cloud_gax::retry_policy::RetryPolicyArg;
131use google_cloud_gax::retry_throttler::RetryThrottlerArg;
132use http::{Extensions, HeaderMap};
133use serde::{Deserialize, Serialize};
134use serde_json::Value;
135use std::collections::HashMap;
136use std::sync::Arc;
137use tokio::time::{Duration, Instant};
138
139const IAM_SCOPE: &str = "https://www.googleapis.com/auth/iam";
140
141#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
142pub(crate) struct CredentialSourceFormat {
143 #[serde(rename = "type")]
144 pub format_type: String,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 pub subject_token_field_name: Option<String>,
147}
148
149#[derive(Serialize, Deserialize, Debug, Clone, Default)]
150pub(crate) struct ExecutableConfig {
151 pub command: String,
152 pub timeout_millis: Option<u32>,
153 pub output_file: Option<String>,
154}
155
156#[derive(Serialize, Deserialize, Debug, Clone)]
157#[serde(untagged)]
158enum CredentialSourceFile {
159 Aws {
161 environment_id: String,
162 region_url: Option<String>,
163 url: Option<String>,
164 regional_cred_verification_url: Option<String>,
165 imdsv2_session_token_url: Option<String>,
166 },
167 Executable {
168 executable: ExecutableConfig,
169 },
170 Url {
171 url: String,
172 headers: Option<HashMap<String, String>>,
173 format: Option<CredentialSourceFormat>,
174 },
175 File {
176 file: String,
177 format: Option<CredentialSourceFormat>,
178 },
179}
180
181fn is_valid_workforce_pool_audience(audience: &str) -> bool {
184 let path = audience
185 .strip_prefix("//iam.googleapis.com/")
186 .unwrap_or(audience);
187
188 let mut s = path.split('/');
189 matches!((s.next(), s.next(), s.next(), s.next(), s.next(), s.next(), s.next()), (
190 Some("locations"),
191 Some(_location),
192 Some("workforcePools"),
193 Some(pool),
194 Some("providers"),
195 Some(provider),
196 None,
197 ) if !pool.is_empty() && !provider.is_empty())
198}
199
200#[derive(Serialize, Deserialize, Debug, Clone)]
204struct ExternalAccountFile {
205 audience: String,
206 subject_token_type: String,
207 service_account_impersonation_url: Option<String>,
208 token_url: String,
209 client_id: Option<String>,
210 client_secret: Option<String>,
211 scopes: Option<Vec<String>>,
212 credential_source: CredentialSourceFile,
213 workforce_pool_user_project: Option<String>,
214 universe_domain: Option<String>,
215}
216
217impl From<ExternalAccountFile> for ExternalAccountConfig {
218 fn from(config: ExternalAccountFile) -> Self {
219 let mut scope = config.scopes.unwrap_or_default();
220 if scope.is_empty() {
221 scope.push(DEFAULT_SCOPE.to_string());
222 }
223 Self {
224 audience: config.audience.clone(),
225 client_id: config.client_id,
226 client_secret: config.client_secret,
227 subject_token_type: config.subject_token_type,
228 token_url: config.token_url,
229 service_account_impersonation_url: config.service_account_impersonation_url,
230 credential_source: CredentialSource::from_file(
231 config.credential_source,
232 &config.audience,
233 ),
234 scopes: scope,
235 workforce_pool_user_project: config.workforce_pool_user_project,
236 universe_domain: config.universe_domain,
237 }
238 }
239}
240
241impl CredentialSource {
242 fn from_file(source: CredentialSourceFile, audience: &str) -> Self {
243 match source {
244 CredentialSourceFile::Url {
245 url,
246 headers,
247 format,
248 } => Self::Url(UrlSourcedCredentials::new(url, headers, format)),
249 CredentialSourceFile::Executable { executable } => {
250 Self::Executable(ExecutableSourcedCredentials::new(executable))
251 }
252 CredentialSourceFile::File { file, format } => {
253 Self::File(FileSourcedCredentials::new(file, format))
254 }
255 CredentialSourceFile::Aws {
256 region_url,
257 url,
258 regional_cred_verification_url,
259 imdsv2_session_token_url,
260 ..
261 } => Self::Aws(AwsSourcedCredentials::new(
262 region_url,
263 url,
264 regional_cred_verification_url,
265 imdsv2_session_token_url,
266 audience.to_string(),
267 )),
268 }
269 }
270}
271
272#[derive(Debug, Clone)]
273struct ExternalAccountConfig {
274 audience: String,
275 subject_token_type: String,
276 token_url: String,
277 service_account_impersonation_url: Option<String>,
278 client_id: Option<String>,
279 client_secret: Option<String>,
280 scopes: Vec<String>,
281 credential_source: CredentialSource,
282 workforce_pool_user_project: Option<String>,
283 universe_domain: Option<String>,
284}
285
286#[derive(Debug, Default)]
287struct ExternalAccountConfigBuilder {
288 audience: Option<String>,
289 subject_token_type: Option<String>,
290 token_url: Option<String>,
291 service_account_impersonation_url: Option<String>,
292 client_id: Option<String>,
293 client_secret: Option<String>,
294 scopes: Option<Vec<String>>,
295 credential_source: Option<CredentialSource>,
296 workforce_pool_user_project: Option<String>,
297 universe_domain: Option<String>,
298}
299
300impl ExternalAccountConfigBuilder {
301 fn with_audience<S: Into<String>>(mut self, audience: S) -> Self {
302 self.audience = Some(audience.into());
303 self
304 }
305
306 fn with_subject_token_type<S: Into<String>>(mut self, subject_token_type: S) -> Self {
307 self.subject_token_type = Some(subject_token_type.into());
308 self
309 }
310
311 fn with_token_url<S: Into<String>>(mut self, token_url: S) -> Self {
312 self.token_url = Some(token_url.into());
313 self
314 }
315
316 fn with_service_account_impersonation_url<S: Into<String>>(mut self, url: S) -> Self {
317 self.service_account_impersonation_url = Some(url.into());
318 self
319 }
320
321 fn with_client_id<S: Into<String>>(mut self, client_id: S) -> Self {
322 self.client_id = Some(client_id.into());
323 self
324 }
325
326 fn with_client_secret<S: Into<String>>(mut self, client_secret: S) -> Self {
327 self.client_secret = Some(client_secret.into());
328 self
329 }
330
331 fn with_scopes(mut self, scopes: Vec<String>) -> Self {
332 self.scopes = Some(scopes);
333 self
334 }
335
336 fn with_credential_source(mut self, source: CredentialSource) -> Self {
337 self.credential_source = Some(source);
338 self
339 }
340
341 fn with_workforce_pool_user_project<S: Into<String>>(mut self, project: S) -> Self {
342 self.workforce_pool_user_project = Some(project.into());
343 self
344 }
345
346 fn with_universe_domain<S: Into<String>>(mut self, universe_domain: S) -> Self {
347 self.universe_domain = Some(universe_domain.into());
348 self
349 }
350
351 fn build(self) -> BuildResult<ExternalAccountConfig> {
352 let audience = self
353 .audience
354 .clone()
355 .ok_or(BuilderError::missing_field("audience"))?;
356
357 if self.workforce_pool_user_project.is_some()
358 && !is_valid_workforce_pool_audience(&audience)
359 {
360 return Err(BuilderError::parsing(
361 "workforce_pool_user_project should not be set for non-workforce pool credentials",
362 ));
363 }
364
365 Ok(ExternalAccountConfig {
366 audience,
367 subject_token_type: self
368 .subject_token_type
369 .ok_or(BuilderError::missing_field("subject_token_type"))?,
370 token_url: self
371 .token_url
372 .ok_or(BuilderError::missing_field("token_url"))?,
373 scopes: self.scopes.ok_or(BuilderError::missing_field("scopes"))?,
374 credential_source: self
375 .credential_source
376 .ok_or(BuilderError::missing_field("credential_source"))?,
377 service_account_impersonation_url: self.service_account_impersonation_url,
378 client_id: self.client_id,
379 client_secret: self.client_secret,
380 workforce_pool_user_project: self.workforce_pool_user_project,
381 universe_domain: self.universe_domain,
382 })
383 }
384}
385
386#[derive(Debug, Clone)]
387enum CredentialSource {
388 Url(UrlSourcedCredentials),
389 Executable(ExecutableSourcedCredentials),
390 File(FileSourcedCredentials),
391 Aws(AwsSourcedCredentials),
392 Programmatic(ProgrammaticSourcedCredentials),
393}
394
395impl ExternalAccountConfig {
396 fn make_credentials(
397 self,
398 quota_project_id: Option<String>,
399 retry_builder: RetryTokenProviderBuilder,
400 ) -> ExternalAccountCredentials<TokenCache> {
401 let config = self.clone();
402 let source: Box<dyn dynamic::SubjectTokenProvider> = match self.credential_source {
403 CredentialSource::Url(source) => Box::new(source),
404 CredentialSource::Executable(source) => Box::new(source),
405 CredentialSource::Programmatic(source) => Box::new(source),
406 CredentialSource::File(source) => Box::new(source),
407 CredentialSource::Aws(source) => Box::new(source),
408 };
409 Self::make_credentials_from_source(source, config, quota_project_id, retry_builder)
410 }
411
412 fn make_credentials_from_source(
413 subject_token_provider: Box<dyn dynamic::SubjectTokenProvider>,
414 config: ExternalAccountConfig,
415 quota_project_id: Option<String>,
416 retry_builder: RetryTokenProviderBuilder,
417 ) -> ExternalAccountCredentials<TokenCache> {
418 let universe_domain = config.universe_domain.clone();
419 let token_provider = ExternalAccountTokenProvider {
420 subject_token_provider,
421 config,
422 };
423 let token_provider_with_retry = retry_builder.build(token_provider);
424 let cache = TokenCache::new(token_provider_with_retry);
425 ExternalAccountCredentials {
426 token_provider: cache,
427 quota_project_id,
428 universe_domain,
429 }
430 }
431}
432
433#[derive(Debug)]
434struct ExternalAccountTokenProvider {
435 subject_token_provider: Box<dyn dynamic::SubjectTokenProvider>,
436 config: ExternalAccountConfig,
437}
438
439#[async_trait::async_trait]
440impl TokenProvider for ExternalAccountTokenProvider {
441 async fn token(&self) -> Result<Token> {
442 let subject_token = self.subject_token_provider.subject_token().await?;
443
444 let audience = self.config.audience.clone();
445 let subject_token_type = self.config.subject_token_type.clone();
446 let user_scopes = self.config.scopes.clone();
447 let url = self.config.token_url.clone();
448
449 let extra_options =
450 if self.config.client_id.is_none() && self.config.client_secret.is_none() {
451 let workforce_pool_user_project = self.config.workforce_pool_user_project.clone();
452 workforce_pool_user_project.map(|project| {
453 let mut options = HashMap::new();
454 options.insert("userProject".to_string(), project);
455 options
456 })
457 } else {
458 None
459 };
460
461 let sts_scope = if self.config.service_account_impersonation_url.is_some() {
467 vec![IAM_SCOPE.to_string()]
468 } else {
469 user_scopes.clone()
470 };
471
472 let req = ExchangeTokenRequest {
473 url,
474 audience: Some(audience),
475 subject_token: subject_token.token,
476 subject_token_type,
477 scope: sts_scope,
478 authentication: ClientAuthentication {
479 client_id: self.config.client_id.clone(),
480 client_secret: self.config.client_secret.clone(),
481 },
482 extra_options,
483 ..ExchangeTokenRequest::default()
484 };
485
486 let token_res = STSHandler::default().exchange_token(req).await?;
487
488 if let Some(impersonation_url) = &self.config.service_account_impersonation_url {
489 let mut headers = HeaderMap::new();
490 headers.insert(
491 http::header::AUTHORIZATION,
492 http::HeaderValue::from_str(&format!("Bearer {}", token_res.access_token))
493 .map_err(non_retryable)?,
494 );
495
496 return impersonated::generate_access_token(
497 headers,
498 None,
499 user_scopes,
500 impersonated::DEFAULT_LIFETIME,
501 impersonation_url,
502 )
503 .await;
504 }
505
506 let token = Token {
507 token: token_res.access_token,
508 token_type: token_res.token_type,
509 expires_at: Some(Instant::now() + Duration::from_secs(token_res.expires_in)),
510 metadata: None,
511 };
512 Ok(token)
513 }
514}
515
516#[derive(Debug)]
517pub(crate) struct ExternalAccountCredentials<T>
518where
519 T: CachedTokenProvider,
520{
521 token_provider: T,
522 quota_project_id: Option<String>,
523 universe_domain: Option<String>,
524}
525
526pub struct Builder {
570 external_account_config: Value,
571 quota_project_id: Option<String>,
572 scopes: Option<Vec<String>>,
573 universe_domain: Option<String>,
574 retry_builder: RetryTokenProviderBuilder,
575 iam_endpoint_override: Option<String>,
576}
577
578impl Builder {
579 pub fn new(external_account_config: Value) -> Self {
583 Self {
584 external_account_config,
585 quota_project_id: None,
586 scopes: None,
587 universe_domain: None,
588 retry_builder: RetryTokenProviderBuilder::default(),
589 iam_endpoint_override: None,
590 }
591 }
592
593 pub fn with_quota_project_id<S: Into<String>>(mut self, quota_project_id: S) -> Self {
602 self.quota_project_id = Some(quota_project_id.into());
603 self
604 }
605
606 pub fn with_universe_domain<S: Into<String>>(mut self, universe_domain: S) -> Self {
630 self.universe_domain = Some(universe_domain.into());
631 self
632 }
633
634 pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
638 where
639 I: IntoIterator<Item = S>,
640 S: Into<String>,
641 {
642 self.scopes = Some(scopes.into_iter().map(|s| s.into()).collect());
643 self
644 }
645
646 pub fn with_retry_policy<V: Into<RetryPolicyArg>>(mut self, v: V) -> Self {
668 self.retry_builder = self.retry_builder.with_retry_policy(v.into());
669 self
670 }
671
672 pub fn with_backoff_policy<V: Into<BackoffPolicyArg>>(mut self, v: V) -> Self {
695 self.retry_builder = self.retry_builder.with_backoff_policy(v.into());
696 self
697 }
698
699 pub fn with_retry_throttler<V: Into<RetryThrottlerArg>>(mut self, v: V) -> Self {
727 self.retry_builder = self.retry_builder.with_retry_throttler(v.into());
728 self
729 }
730
731 #[cfg(all(test, google_cloud_unstable_trust_boundaries))]
732 fn maybe_iam_endpoint_override(mut self, iam_endpoint_override: Option<String>) -> Self {
733 self.iam_endpoint_override = iam_endpoint_override;
734 self
735 }
736
737 pub fn build(self) -> BuildResult<Credentials> {
751 Ok(self.build_credentials()?.into())
752 }
753
754 pub fn build_access_token_credentials(self) -> BuildResult<AccessTokenCredentials> {
768 Ok(self.build_credentials()?.into())
769 }
770
771 fn build_credentials(
772 self,
773 ) -> BuildResult<CredentialsWithAccessBoundary<ExternalAccountCredentials<TokenCache>>> {
774 let mut file: ExternalAccountFile =
775 serde_json::from_value(self.external_account_config).map_err(BuilderError::parsing)?;
776
777 if let Some(scopes) = self.scopes {
778 file.scopes = Some(scopes);
779 }
780
781 if let Some(ref ud) = self.universe_domain {
782 file.universe_domain = Some(ud.clone());
783 }
784
785 if file.workforce_pool_user_project.is_some()
786 && !is_valid_workforce_pool_audience(&file.audience)
787 {
788 return Err(BuilderError::parsing(
789 "workforce_pool_user_project should not be set for non-workforce pool credentials",
790 ));
791 }
792
793 let config: ExternalAccountConfig = file.into();
794
795 let access_boundary_url =
796 external_account_lookup_url(&config.audience, self.iam_endpoint_override.as_deref());
797
798 let creds = config.make_credentials(self.quota_project_id, self.retry_builder);
799
800 Ok(CredentialsWithAccessBoundary::new(
801 creds,
802 access_boundary_url,
803 ))
804 }
805}
806
807pub struct ProgrammaticBuilder {
855 quota_project_id: Option<String>,
856 config: ExternalAccountConfigBuilder,
857 retry_builder: RetryTokenProviderBuilder,
858}
859
860impl ProgrammaticBuilder {
861 pub fn new(subject_token_provider: Arc<dyn dynamic::SubjectTokenProvider>) -> Self {
894 let config = ExternalAccountConfigBuilder::default().with_credential_source(
895 CredentialSource::Programmatic(ProgrammaticSourcedCredentials::new(
896 subject_token_provider,
897 )),
898 );
899 Self {
900 quota_project_id: None,
901 config,
902 retry_builder: RetryTokenProviderBuilder::default(),
903 }
904 }
905
906 pub fn with_quota_project_id<S: Into<String>>(mut self, quota_project_id: S) -> Self {
945 self.quota_project_id = Some(quota_project_id.into());
946 self
947 }
948
949 pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
984 where
985 I: IntoIterator<Item = S>,
986 S: Into<String>,
987 {
988 self.config = self.config.with_scopes(
989 scopes
990 .into_iter()
991 .map(|s| s.into())
992 .collect::<Vec<String>>(),
993 );
994 self
995 }
996
997 pub fn with_universe_domain<S: Into<String>>(mut self, universe_domain: S) -> Self {
1022 self.config = self.config.with_universe_domain(universe_domain);
1023 self
1024 }
1025
1026 pub fn with_audience<S: Into<String>>(mut self, audience: S) -> Self {
1061 self.config = self.config.with_audience(audience);
1062 self
1063 }
1064
1065 pub fn with_subject_token_type<S: Into<String>>(mut self, subject_token_type: S) -> Self {
1099 self.config = self.config.with_subject_token_type(subject_token_type);
1100 self
1101 }
1102
1103 pub fn with_token_url<S: Into<String>>(mut self, token_url: S) -> Self {
1136 self.config = self.config.with_token_url(token_url);
1137 self
1138 }
1139
1140 pub fn with_client_id<S: Into<String>>(mut self, client_id: S) -> Self {
1172 self.config = self.config.with_client_id(client_id.into());
1173 self
1174 }
1175
1176 pub fn with_client_secret<S: Into<String>>(mut self, client_secret: S) -> Self {
1208 self.config = self.config.with_client_secret(client_secret.into());
1209 self
1210 }
1211
1212 pub fn with_target_principal<S: Into<String>>(mut self, target_principal: S) -> Self {
1246 let url = format!(
1247 "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:generateAccessToken",
1248 target_principal.into()
1249 );
1250 self.config = self.config.with_service_account_impersonation_url(url);
1251 self
1252 }
1253
1254 pub fn with_workforce_pool_user_project<S: Into<String>>(mut self, project: S) -> Self {
1288 self.config = self.config.with_workforce_pool_user_project(project);
1289 self
1290 }
1291
1292 pub fn with_retry_policy<V: Into<RetryPolicyArg>>(mut self, v: V) -> Self {
1332 self.retry_builder = self.retry_builder.with_retry_policy(v.into());
1333 self
1334 }
1335
1336 pub fn with_backoff_policy<V: Into<BackoffPolicyArg>>(mut self, v: V) -> Self {
1376 self.retry_builder = self.retry_builder.with_backoff_policy(v.into());
1377 self
1378 }
1379
1380 pub fn with_retry_throttler<V: Into<RetryThrottlerArg>>(mut self, v: V) -> Self {
1426 self.retry_builder = self.retry_builder.with_retry_throttler(v.into());
1427 self
1428 }
1429
1430 pub fn build(self) -> BuildResult<Credentials> {
1437 let (config, quota_project_id, retry_builder) = self.build_components()?;
1438 let creds = config.make_credentials(quota_project_id, retry_builder);
1439 Ok(Credentials {
1440 inner: Arc::new(creds),
1441 })
1442 }
1443
1444 fn build_components(
1446 self,
1447 ) -> BuildResult<(
1448 ExternalAccountConfig,
1449 Option<String>,
1450 RetryTokenProviderBuilder,
1451 )> {
1452 let Self {
1453 quota_project_id,
1454 config,
1455 retry_builder,
1456 } = self;
1457
1458 let mut config_builder = config;
1459 if config_builder.scopes.is_none() {
1460 config_builder = config_builder.with_scopes(vec![DEFAULT_SCOPE.to_string()]);
1461 }
1462 if config_builder.token_url.is_none() {
1463 let mut token_url = STS_TOKEN_URL.to_string();
1464 if let Some(ref ud) = config_builder.universe_domain
1465 && ud != DEFAULT_UNIVERSE_DOMAIN
1466 {
1467 token_url = token_url.replace(DEFAULT_UNIVERSE_DOMAIN, ud);
1468 }
1469 config_builder = config_builder.with_token_url(token_url);
1470 }
1471 let final_config = config_builder.build()?;
1472
1473 Ok((final_config, quota_project_id, retry_builder))
1474 }
1475}
1476
1477#[async_trait::async_trait]
1478impl<T> CredentialsProvider for ExternalAccountCredentials<T>
1479where
1480 T: CachedTokenProvider,
1481{
1482 async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
1483 let token = self.token_provider.token(extensions).await?;
1484
1485 AuthHeadersBuilder::new(&token)
1486 .maybe_quota_project_id(self.quota_project_id.as_deref())
1487 .build()
1488 }
1489
1490 async fn universe_domain(&self) -> Option<String> {
1491 self.universe_domain.clone()
1492 }
1493}
1494
1495#[async_trait::async_trait]
1496impl<T> AccessTokenCredentialsProvider for ExternalAccountCredentials<T>
1497where
1498 T: CachedTokenProvider,
1499{
1500 async fn access_token(&self) -> Result<AccessToken> {
1501 let token = self.token_provider.token(Extensions::new()).await?;
1502 token.into()
1503 }
1504}
1505
1506#[cfg(test)]
1507mod tests {
1508 use super::*;
1509 use crate::constants::{
1510 ACCESS_TOKEN_TYPE, DEFAULT_SCOPE, JWT_TOKEN_TYPE, TOKEN_EXCHANGE_GRANT_TYPE,
1511 };
1512 use crate::credentials::subject_token::{
1513 Builder as SubjectTokenBuilder, SubjectToken, SubjectTokenProvider,
1514 };
1515 use crate::credentials::tests::{
1516 find_source_error, get_mock_auth_retry_policy, get_mock_backoff_policy,
1517 get_mock_retry_throttler, get_token_from_headers,
1518 };
1519 use crate::errors::{CredentialsError, SubjectTokenProviderError};
1520 use httptest::{
1521 Expectation, Server, cycle,
1522 matchers::{all_of, contains, request, url_decoded},
1523 responders::{json_encoded, status_code},
1524 };
1525 use serde_json::*;
1526 use std::collections::HashMap;
1527 use std::error::Error;
1528 use std::fmt;
1529 use test_case::test_case;
1530 use time::OffsetDateTime;
1531
1532 #[derive(Debug)]
1533 struct TestProviderError;
1534 impl fmt::Display for TestProviderError {
1535 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1536 write!(f, "TestProviderError")
1537 }
1538 }
1539 impl Error for TestProviderError {}
1540 impl SubjectTokenProviderError for TestProviderError {
1541 fn is_transient(&self) -> bool {
1542 false
1543 }
1544 }
1545
1546 #[derive(Debug)]
1547 struct TestSubjectTokenProvider;
1548 impl SubjectTokenProvider for TestSubjectTokenProvider {
1549 type Error = TestProviderError;
1550 async fn subject_token(&self) -> std::result::Result<SubjectToken, Self::Error> {
1551 Ok(SubjectTokenBuilder::new("test-subject-token".to_string()).build())
1552 }
1553 }
1554
1555 #[tokio::test]
1556 async fn create_external_account_builder() {
1557 let contents = json!({
1558 "type": "external_account",
1559 "audience": "audience",
1560 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1561 "token_url": "https://sts.googleapis.com/v1beta/token",
1562 "credential_source": {
1563 "url": "https://example.com/token",
1564 "format": {
1565 "type": "json",
1566 "subject_token_field_name": "access_token"
1567 }
1568 }
1569 });
1570
1571 let creds = Builder::new(contents)
1572 .with_quota_project_id("test_project")
1573 .with_scopes(["a", "b"])
1574 .build()
1575 .unwrap();
1576
1577 let fmt = format!("{creds:?}");
1579 assert!(fmt.contains("ExternalAccountCredentials"));
1580 }
1581
1582 #[tokio::test]
1583 async fn create_external_account_with_universe_domain() {
1584 let contents = json!({
1585 "type": "external_account",
1586 "audience": "audience",
1587 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1588 "token_url": "https://sts.my-custom-universe.com/v1beta/token",
1589 "credential_source": {
1590 "url": "https://example.com/token",
1591 "format": {
1592 "type": "json",
1593 "subject_token_field_name": "access_token"
1594 }
1595 },
1596 "universe_domain": "my-custom-universe.com"
1597 });
1598
1599 let creds = Builder::new(contents).build().unwrap();
1600
1601 assert_eq!(
1602 creds.universe_domain().await,
1603 Some("my-custom-universe.com".to_string())
1604 );
1605 }
1606
1607 #[tokio::test]
1608 async fn create_external_account_with_universe_domain_override() {
1609 let contents = json!({
1610 "type": "external_account",
1611 "audience": "audience",
1612 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1613 "token_url": "https://sts.my-custom-universe.com/v1beta/token",
1614 "credential_source": {
1615 "url": "https://example.com/token",
1616 "format": {
1617 "type": "json",
1618 "subject_token_field_name": "access_token"
1619 }
1620 },
1621 "universe_domain": "my-custom-universe.com"
1622 });
1623
1624 let creds = Builder::new(contents)
1625 .with_universe_domain("my-overridden-universe.com")
1626 .build()
1627 .unwrap();
1628
1629 assert_eq!(
1630 creds.universe_domain().await,
1631 Some("my-overridden-universe.com".to_string())
1632 );
1633 }
1634
1635 #[tokio::test]
1636 async fn test_programmatic_builder_with_universe_domain() {
1637 let provider = Arc::new(TestSubjectTokenProvider);
1638 let builder = ProgrammaticBuilder::new(provider)
1639 .with_audience("test-audience")
1640 .with_subject_token_type("test-token-type")
1641 .with_token_url(STS_TOKEN_URL)
1642 .with_universe_domain("my-custom-universe.com");
1643
1644 let creds = builder.build().unwrap();
1645
1646 assert_eq!(
1647 creds.universe_domain().await,
1648 Some("my-custom-universe.com".to_string())
1649 );
1650 }
1651
1652 #[tokio::test]
1653 async fn test_programmatic_builder_sts_url_updates_with_universe_domain() {
1654 let provider = Arc::new(TestSubjectTokenProvider);
1655 let builder = ProgrammaticBuilder::new(provider)
1656 .with_audience("test-audience")
1657 .with_subject_token_type("test-token-type")
1658 .with_universe_domain("my-custom-universe.com");
1659
1660 let (config, _, _) = builder.build_components().unwrap();
1661
1662 assert_eq!(
1663 config.token_url,
1664 "https://sts.my-custom-universe.com/v1/token"
1665 );
1666 }
1667
1668 #[tokio::test]
1669 async fn create_external_account_detect_url_sourced() {
1670 let contents = json!({
1671 "type": "external_account",
1672 "audience": "audience",
1673 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1674 "token_url": "https://sts.googleapis.com/v1beta/token",
1675 "credential_source": {
1676 "url": "https://example.com/token",
1677 "headers": {
1678 "Metadata": "True"
1679 },
1680 "format": {
1681 "type": "json",
1682 "subject_token_field_name": "access_token"
1683 }
1684 }
1685 });
1686
1687 let file: ExternalAccountFile =
1688 serde_json::from_value(contents).expect("failed to parse external account config");
1689 let config: ExternalAccountConfig = file.into();
1690 let source = config.credential_source;
1691
1692 match source {
1693 CredentialSource::Url(source) => {
1694 assert_eq!(source.url, "https://example.com/token");
1695 assert_eq!(
1696 source.headers,
1697 HashMap::from([("Metadata".to_string(), "True".to_string()),]),
1698 );
1699 assert_eq!(source.format, "json");
1700 assert_eq!(source.subject_token_field_name, "access_token");
1701 }
1702 _ => {
1703 unreachable!("expected Url Sourced credential")
1704 }
1705 }
1706 }
1707
1708 #[tokio::test]
1709 async fn create_external_account_detect_executable_sourced() {
1710 let contents = json!({
1711 "type": "external_account",
1712 "audience": "audience",
1713 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1714 "token_url": "https://sts.googleapis.com/v1beta/token",
1715 "credential_source": {
1716 "executable": {
1717 "command": "cat /some/file",
1718 "output_file": "/some/file",
1719 "timeout_millis": 5000
1720 }
1721 }
1722 });
1723
1724 let file: ExternalAccountFile =
1725 serde_json::from_value(contents).expect("failed to parse external account config");
1726 let config: ExternalAccountConfig = file.into();
1727 let source = config.credential_source;
1728
1729 match source {
1730 CredentialSource::Executable(source) => {
1731 assert_eq!(source.command, "cat");
1732 assert_eq!(source.args, vec!["/some/file"]);
1733 assert_eq!(source.output_file.as_deref(), Some("/some/file"));
1734 assert_eq!(source.timeout, Duration::from_secs(5));
1735 }
1736 _ => {
1737 unreachable!("expected Executable Sourced credential")
1738 }
1739 }
1740 }
1741
1742 #[tokio::test]
1743 async fn create_external_account_detect_file_sourced() {
1744 let contents = json!({
1745 "type": "external_account",
1746 "audience": "audience",
1747 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1748 "token_url": "https://sts.googleapis.com/v1beta/token",
1749 "credential_source": {
1750 "file": "/foo/bar",
1751 "format": {
1752 "type": "json",
1753 "subject_token_field_name": "token"
1754 }
1755 }
1756 });
1757
1758 let file: ExternalAccountFile =
1759 serde_json::from_value(contents).expect("failed to parse external account config");
1760 let config: ExternalAccountConfig = file.into();
1761 let source = config.credential_source;
1762
1763 match source {
1764 CredentialSource::File(source) => {
1765 assert_eq!(source.file, "/foo/bar");
1766 assert_eq!(source.format, "json");
1767 assert_eq!(source.subject_token_field_name, "token");
1768 }
1769 _ => {
1770 unreachable!("expected File Sourced credential")
1771 }
1772 }
1773 }
1774
1775 #[tokio::test]
1776 async fn test_external_account_with_impersonation_success() {
1777 let subject_token_server = Server::run();
1778 let sts_server = Server::run();
1779 let impersonation_server = Server::run();
1780
1781 let impersonation_path = "/projects/-/serviceAccounts/sa@test.com:generateAccessToken";
1782 let contents = json!({
1783 "type": "external_account",
1784 "audience": "audience",
1785 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1786 "token_url": sts_server.url("/token").to_string(),
1787 "service_account_impersonation_url": impersonation_server.url(impersonation_path).to_string(),
1788 "credential_source": {
1789 "url": subject_token_server.url("/subject_token").to_string(),
1790 "format": {
1791 "type": "json",
1792 "subject_token_field_name": "access_token"
1793 }
1794 }
1795 });
1796
1797 subject_token_server.expect(
1798 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
1799 json_encoded(json!({
1800 "access_token": "subject_token",
1801 })),
1802 ),
1803 );
1804
1805 sts_server.expect(
1806 Expectation::matching(all_of![
1807 request::method_path("POST", "/token"),
1808 request::body(url_decoded(contains((
1809 "grant_type",
1810 TOKEN_EXCHANGE_GRANT_TYPE
1811 )))),
1812 request::body(url_decoded(contains(("subject_token", "subject_token")))),
1813 request::body(url_decoded(contains((
1814 "requested_token_type",
1815 ACCESS_TOKEN_TYPE
1816 )))),
1817 request::body(url_decoded(contains((
1818 "subject_token_type",
1819 JWT_TOKEN_TYPE
1820 )))),
1821 request::body(url_decoded(contains(("audience", "audience")))),
1822 request::body(url_decoded(contains(("scope", IAM_SCOPE)))),
1823 ])
1824 .respond_with(json_encoded(json!({
1825 "access_token": "sts-token",
1826 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
1827 "token_type": "Bearer",
1828 "expires_in": 3600,
1829 }))),
1830 );
1831
1832 let expire_time = (OffsetDateTime::now_utc() + time::Duration::hours(1))
1833 .format(&time::format_description::well_known::Rfc3339)
1834 .unwrap();
1835 impersonation_server.expect(
1836 Expectation::matching(all_of![
1837 request::method_path("POST", impersonation_path),
1838 request::headers(contains(("authorization", "Bearer sts-token"))),
1839 ])
1840 .respond_with(json_encoded(json!({
1841 "accessToken": "final-impersonated-token",
1842 "expireTime": expire_time
1843 }))),
1844 );
1845
1846 let creds = Builder::new(contents).build().unwrap();
1847 let headers = creds.headers(Extensions::new()).await.unwrap();
1848 match headers {
1849 CacheableResource::New { data, .. } => {
1850 let token = data.get("authorization").unwrap().to_str().unwrap();
1851 assert_eq!(token, "Bearer final-impersonated-token");
1852 }
1853 CacheableResource::NotModified => panic!("Expected new headers"),
1854 }
1855 }
1856
1857 #[tokio::test]
1858 async fn test_external_account_without_impersonation_success() {
1859 let subject_token_server = Server::run();
1860 let sts_server = Server::run();
1861
1862 let contents = json!({
1863 "type": "external_account",
1864 "audience": "audience",
1865 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1866 "token_url": sts_server.url("/token").to_string(),
1867 "credential_source": {
1868 "url": subject_token_server.url("/subject_token").to_string(),
1869 "format": {
1870 "type": "json",
1871 "subject_token_field_name": "access_token"
1872 }
1873 }
1874 });
1875
1876 subject_token_server.expect(
1877 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
1878 json_encoded(json!({
1879 "access_token": "subject_token",
1880 })),
1881 ),
1882 );
1883
1884 sts_server.expect(
1885 Expectation::matching(all_of![
1886 request::method_path("POST", "/token"),
1887 request::body(url_decoded(contains((
1888 "grant_type",
1889 TOKEN_EXCHANGE_GRANT_TYPE
1890 )))),
1891 request::body(url_decoded(contains(("subject_token", "subject_token")))),
1892 request::body(url_decoded(contains((
1893 "requested_token_type",
1894 ACCESS_TOKEN_TYPE
1895 )))),
1896 request::body(url_decoded(contains((
1897 "subject_token_type",
1898 JWT_TOKEN_TYPE
1899 )))),
1900 request::body(url_decoded(contains(("audience", "audience")))),
1901 request::body(url_decoded(contains(("scope", DEFAULT_SCOPE)))),
1902 ])
1903 .respond_with(json_encoded(json!({
1904 "access_token": "sts-only-token",
1905 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
1906 "token_type": "Bearer",
1907 "expires_in": 3600,
1908 }))),
1909 );
1910
1911 let creds = Builder::new(contents).build().unwrap();
1912 let headers = creds.headers(Extensions::new()).await.unwrap();
1913 match headers {
1914 CacheableResource::New { data, .. } => {
1915 let token = data.get("authorization").unwrap().to_str().unwrap();
1916 assert_eq!(token, "Bearer sts-only-token");
1917 }
1918 CacheableResource::NotModified => panic!("Expected new headers"),
1919 }
1920 }
1921
1922 #[tokio::test]
1923 async fn test_external_account_access_token_credentials_success() {
1924 let server = Server::run();
1925
1926 let contents = json!({
1927 "type": "external_account",
1928 "audience": "audience",
1929 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1930 "token_url": server.url("/token").to_string(),
1931 "credential_source": {
1932 "url": server.url("/subject_token").to_string(),
1933 "format": {
1934 "type": "json",
1935 "subject_token_field_name": "access_token"
1936 }
1937 }
1938 });
1939
1940 server.expect(
1941 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
1942 json_encoded(json!({
1943 "access_token": "subject_token",
1944 })),
1945 ),
1946 );
1947
1948 server.expect(
1949 Expectation::matching(all_of![
1950 request::method_path("POST", "/token"),
1951 request::body(url_decoded(contains((
1952 "grant_type",
1953 TOKEN_EXCHANGE_GRANT_TYPE
1954 )))),
1955 request::body(url_decoded(contains(("subject_token", "subject_token")))),
1956 request::body(url_decoded(contains((
1957 "requested_token_type",
1958 ACCESS_TOKEN_TYPE
1959 )))),
1960 request::body(url_decoded(contains((
1961 "subject_token_type",
1962 JWT_TOKEN_TYPE
1963 )))),
1964 request::body(url_decoded(contains(("audience", "audience")))),
1965 request::body(url_decoded(contains(("scope", DEFAULT_SCOPE)))),
1966 ])
1967 .respond_with(json_encoded(json!({
1968 "access_token": "sts-only-token",
1969 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
1970 "token_type": "Bearer",
1971 "expires_in": 3600,
1972 }))),
1973 );
1974
1975 let creds = Builder::new(contents)
1976 .build_access_token_credentials()
1977 .unwrap();
1978 let access_token = creds.access_token().await.unwrap();
1979 assert_eq!(access_token.token, "sts-only-token");
1980 }
1981
1982 #[tokio::test]
1983 async fn test_impersonation_flow_sts_call_fails() {
1984 let subject_token_server = Server::run();
1985 let sts_server = Server::run();
1986 let impersonation_server = Server::run();
1987
1988 let impersonation_path = "/projects/-/serviceAccounts/sa@test.com:generateAccessToken";
1989 let contents = json!({
1990 "type": "external_account",
1991 "audience": "audience",
1992 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
1993 "token_url": sts_server.url("/token").to_string(),
1994 "service_account_impersonation_url": impersonation_server.url(impersonation_path).to_string(),
1995 "credential_source": {
1996 "url": subject_token_server.url("/subject_token").to_string(),
1997 "format": {
1998 "type": "json",
1999 "subject_token_field_name": "access_token"
2000 }
2001 }
2002 });
2003
2004 subject_token_server.expect(
2005 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
2006 json_encoded(json!({
2007 "access_token": "subject_token",
2008 })),
2009 ),
2010 );
2011
2012 sts_server.expect(
2013 Expectation::matching(request::method_path("POST", "/token"))
2014 .respond_with(status_code(500)),
2015 );
2016
2017 let creds = Builder::new(contents).build().unwrap();
2018 let err = creds.headers(Extensions::new()).await.unwrap_err();
2019 let original_err = find_source_error::<CredentialsError>(&err).unwrap();
2020 assert!(
2021 original_err
2022 .to_string()
2023 .contains("failed to exchange token")
2024 );
2025 assert!(original_err.is_transient());
2026 }
2027
2028 #[tokio::test]
2029 async fn test_impersonation_flow_iam_call_fails() {
2030 let subject_token_server = Server::run();
2031 let sts_server = Server::run();
2032 let impersonation_server = Server::run();
2033
2034 let impersonation_path = "/projects/-/serviceAccounts/sa@test.com:generateAccessToken";
2035 let contents = json!({
2036 "type": "external_account",
2037 "audience": "audience",
2038 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2039 "token_url": sts_server.url("/token").to_string(),
2040 "service_account_impersonation_url": impersonation_server.url(impersonation_path).to_string(),
2041 "credential_source": {
2042 "url": subject_token_server.url("/subject_token").to_string(),
2043 "format": {
2044 "type": "json",
2045 "subject_token_field_name": "access_token"
2046 }
2047 }
2048 });
2049
2050 subject_token_server.expect(
2051 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
2052 json_encoded(json!({
2053 "access_token": "subject_token",
2054 })),
2055 ),
2056 );
2057
2058 sts_server.expect(
2059 Expectation::matching(request::method_path("POST", "/token")).respond_with(
2060 json_encoded(json!({
2061 "access_token": "sts-token",
2062 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2063 "token_type": "Bearer",
2064 "expires_in": 3600,
2065 })),
2066 ),
2067 );
2068
2069 impersonation_server.expect(
2070 Expectation::matching(request::method_path("POST", impersonation_path))
2071 .respond_with(status_code(403)),
2072 );
2073
2074 let creds = Builder::new(contents).build().unwrap();
2075 let err = creds.headers(Extensions::new()).await.unwrap_err();
2076 let original_err = find_source_error::<CredentialsError>(&err).unwrap();
2077 assert!(original_err.to_string().contains("failed to fetch token"));
2078 assert!(!original_err.is_transient());
2079 }
2080
2081 #[test_case(Some(vec!["scope1", "scope2"]), Some("http://custom.com/token") ; "with custom scopes and token_url")]
2082 #[test_case(None, Some("http://custom.com/token") ; "with default scopes and custom token_url")]
2083 #[test_case(Some(vec!["scope1", "scope2"]), None ; "with custom scopes and default token_url")]
2084 #[test_case(None, None ; "with default scopes and default token_url")]
2085 #[tokio::test]
2086 async fn create_programmatic_builder(scopes: Option<Vec<&str>>, token_url: Option<&str>) {
2087 let provider = Arc::new(TestSubjectTokenProvider);
2088 let mut builder = ProgrammaticBuilder::new(provider)
2089 .with_audience("test-audience")
2090 .with_subject_token_type("test-token-type")
2091 .with_client_id("test-client-id")
2092 .with_client_secret("test-client-secret")
2093 .with_target_principal("test-principal");
2094
2095 let expected_scopes = if let Some(scopes) = scopes.clone() {
2096 scopes.iter().map(|s| s.to_string()).collect()
2097 } else {
2098 vec![DEFAULT_SCOPE.to_string()]
2099 };
2100
2101 let expected_token_url = token_url.unwrap_or(STS_TOKEN_URL).to_string();
2102
2103 if let Some(scopes) = scopes {
2104 builder = builder.with_scopes(scopes);
2105 }
2106 if let Some(token_url) = token_url {
2107 builder = builder.with_token_url(token_url);
2108 }
2109
2110 let (config, _, _) = builder.build_components().unwrap();
2111
2112 assert_eq!(config.audience, "test-audience");
2113 assert_eq!(config.subject_token_type, "test-token-type");
2114 assert_eq!(config.client_id, Some("test-client-id".to_string()));
2115 assert_eq!(config.client_secret, Some("test-client-secret".to_string()));
2116 assert_eq!(config.scopes, expected_scopes);
2117 assert_eq!(config.token_url, expected_token_url);
2118 assert_eq!(
2119 config.service_account_impersonation_url,
2120 Some("https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/test-principal:generateAccessToken".to_string())
2121 );
2122 }
2123
2124 #[tokio::test]
2125 async fn create_programmatic_builder_with_quota_project_id() {
2126 let provider = Arc::new(TestSubjectTokenProvider);
2127 let builder = ProgrammaticBuilder::new(provider)
2128 .with_audience("test-audience")
2129 .with_subject_token_type("test-token-type")
2130 .with_token_url(STS_TOKEN_URL)
2131 .with_quota_project_id("test-quota-project");
2132
2133 let creds = builder.build().unwrap();
2134
2135 let fmt = format!("{creds:?}");
2136 assert!(
2137 fmt.contains("ExternalAccountCredentials"),
2138 "Expected 'ExternalAccountCredentials', got: {fmt}"
2139 );
2140 assert!(
2141 fmt.contains("test-quota-project"),
2142 "Expected 'test-quota-project', got: {fmt}"
2143 );
2144 }
2145
2146 #[tokio::test]
2147 async fn programmatic_builder_returns_correct_headers() {
2148 let provider = Arc::new(TestSubjectTokenProvider);
2149 let sts_server = Server::run();
2150 let builder = ProgrammaticBuilder::new(provider)
2151 .with_audience("test-audience")
2152 .with_subject_token_type("test-token-type")
2153 .with_token_url(sts_server.url("/token").to_string())
2154 .with_quota_project_id("test-quota-project");
2155
2156 let creds = builder.build().unwrap();
2157
2158 sts_server.expect(
2159 Expectation::matching(all_of![
2160 request::method_path("POST", "/token"),
2161 request::body(url_decoded(contains((
2162 "grant_type",
2163 TOKEN_EXCHANGE_GRANT_TYPE
2164 )))),
2165 request::body(url_decoded(contains((
2166 "subject_token",
2167 "test-subject-token"
2168 )))),
2169 request::body(url_decoded(contains((
2170 "requested_token_type",
2171 ACCESS_TOKEN_TYPE
2172 )))),
2173 request::body(url_decoded(contains((
2174 "subject_token_type",
2175 "test-token-type"
2176 )))),
2177 request::body(url_decoded(contains(("audience", "test-audience")))),
2178 request::body(url_decoded(contains(("scope", DEFAULT_SCOPE)))),
2179 ])
2180 .respond_with(json_encoded(json!({
2181 "access_token": "sts-only-token",
2182 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2183 "token_type": "Bearer",
2184 "expires_in": 3600,
2185 }))),
2186 );
2187
2188 let headers = creds.headers(Extensions::new()).await.unwrap();
2189 match headers {
2190 CacheableResource::New { data, .. } => {
2191 let token = data.get("authorization").unwrap().to_str().unwrap();
2192 assert_eq!(token, "Bearer sts-only-token");
2193 let quota_project = data.get("x-goog-user-project").unwrap().to_str().unwrap();
2194 assert_eq!(quota_project, "test-quota-project");
2195 }
2196 CacheableResource::NotModified => panic!("Expected new headers"),
2197 }
2198 }
2199
2200 #[tokio::test]
2201 async fn create_programmatic_builder_fails_on_missing_required_field() {
2202 let provider = Arc::new(TestSubjectTokenProvider);
2203 let result = ProgrammaticBuilder::new(provider)
2204 .with_subject_token_type("test-token-type")
2205 .with_token_url("http://test.com/token")
2207 .build();
2208
2209 assert!(result.is_err(), "{result:?}");
2210 let error_string = result.unwrap_err().to_string();
2211 assert!(
2212 error_string.contains("missing required field: audience"),
2213 "Expected error about missing 'audience', got: {error_string}"
2214 );
2215 }
2216
2217 #[tokio::test]
2218 async fn test_external_account_retries_on_transient_failures() {
2219 let mut subject_token_server = Server::run();
2220 let mut sts_server = Server::run();
2221
2222 let contents = json!({
2223 "type": "external_account",
2224 "audience": "audience",
2225 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2226 "token_url": sts_server.url("/token").to_string(),
2227 "credential_source": {
2228 "url": subject_token_server.url("/subject_token").to_string(),
2229 }
2230 });
2231
2232 subject_token_server.expect(
2233 Expectation::matching(request::method_path("GET", "/subject_token"))
2234 .times(3)
2235 .respond_with(json_encoded(json!({
2236 "access_token": "subject_token",
2237 }))),
2238 );
2239
2240 sts_server.expect(
2241 Expectation::matching(request::method_path("POST", "/token"))
2242 .times(3)
2243 .respond_with(status_code(503)),
2244 );
2245
2246 let creds = Builder::new(contents)
2247 .with_retry_policy(get_mock_auth_retry_policy(3))
2248 .with_backoff_policy(get_mock_backoff_policy())
2249 .with_retry_throttler(get_mock_retry_throttler())
2250 .build()
2251 .unwrap();
2252
2253 let err = creds.headers(Extensions::new()).await.unwrap_err();
2254 assert!(err.is_transient(), "{err:?}");
2255 sts_server.verify_and_clear();
2256 subject_token_server.verify_and_clear();
2257 }
2258
2259 #[tokio::test]
2260 async fn test_external_account_does_not_retry_on_non_transient_failures() {
2261 let subject_token_server = Server::run();
2262 let mut sts_server = Server::run();
2263
2264 let contents = json!({
2265 "type": "external_account",
2266 "audience": "audience",
2267 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2268 "token_url": sts_server.url("/token").to_string(),
2269 "credential_source": {
2270 "url": subject_token_server.url("/subject_token").to_string(),
2271 }
2272 });
2273
2274 subject_token_server.expect(
2275 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
2276 json_encoded(json!({
2277 "access_token": "subject_token",
2278 })),
2279 ),
2280 );
2281
2282 sts_server.expect(
2283 Expectation::matching(request::method_path("POST", "/token"))
2284 .times(1)
2285 .respond_with(status_code(401)),
2286 );
2287
2288 let creds = Builder::new(contents)
2289 .with_retry_policy(get_mock_auth_retry_policy(1))
2290 .with_backoff_policy(get_mock_backoff_policy())
2291 .with_retry_throttler(get_mock_retry_throttler())
2292 .build()
2293 .unwrap();
2294
2295 let err = creds.headers(Extensions::new()).await.unwrap_err();
2296 assert!(!err.is_transient());
2297 sts_server.verify_and_clear();
2298 }
2299
2300 #[tokio::test]
2301 async fn test_external_account_retries_for_success() {
2302 let mut subject_token_server = Server::run();
2303 let mut sts_server = Server::run();
2304
2305 let contents = json!({
2306 "type": "external_account",
2307 "audience": "audience",
2308 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2309 "token_url": sts_server.url("/token").to_string(),
2310 "credential_source": {
2311 "url": subject_token_server.url("/subject_token").to_string(),
2312 }
2313 });
2314
2315 subject_token_server.expect(
2316 Expectation::matching(request::method_path("GET", "/subject_token"))
2317 .times(3)
2318 .respond_with(json_encoded(json!({
2319 "access_token": "subject_token",
2320 }))),
2321 );
2322
2323 sts_server.expect(
2324 Expectation::matching(request::method_path("POST", "/token"))
2325 .times(3)
2326 .respond_with(cycle![
2327 status_code(503).body("try-again"),
2328 status_code(503).body("try-again"),
2329 json_encoded(json!({
2330 "access_token": "sts-only-token",
2331 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2332 "token_type": "Bearer",
2333 "expires_in": 3600,
2334 }))
2335 ]),
2336 );
2337
2338 let creds = Builder::new(contents)
2339 .with_retry_policy(get_mock_auth_retry_policy(3))
2340 .with_backoff_policy(get_mock_backoff_policy())
2341 .with_retry_throttler(get_mock_retry_throttler())
2342 .build()
2343 .unwrap();
2344
2345 let headers = creds.headers(Extensions::new()).await.unwrap();
2346 match headers {
2347 CacheableResource::New { data, .. } => {
2348 let token = data.get("authorization").unwrap().to_str().unwrap();
2349 assert_eq!(token, "Bearer sts-only-token");
2350 }
2351 CacheableResource::NotModified => panic!("Expected new headers"),
2352 }
2353 sts_server.verify_and_clear();
2354 subject_token_server.verify_and_clear();
2355 }
2356
2357 #[tokio::test]
2358 async fn test_programmatic_builder_retries_on_transient_failures() {
2359 let provider = Arc::new(TestSubjectTokenProvider);
2360 let mut sts_server = Server::run();
2361
2362 sts_server.expect(
2363 Expectation::matching(request::method_path("POST", "/token"))
2364 .times(3)
2365 .respond_with(status_code(503)),
2366 );
2367
2368 let creds = ProgrammaticBuilder::new(provider)
2369 .with_audience("test-audience")
2370 .with_subject_token_type("test-token-type")
2371 .with_token_url(sts_server.url("/token").to_string())
2372 .with_retry_policy(get_mock_auth_retry_policy(3))
2373 .with_backoff_policy(get_mock_backoff_policy())
2374 .with_retry_throttler(get_mock_retry_throttler())
2375 .build()
2376 .unwrap();
2377
2378 let err = creds.headers(Extensions::new()).await.unwrap_err();
2379 assert!(err.is_transient(), "{err:?}");
2380 sts_server.verify_and_clear();
2381 }
2382
2383 #[tokio::test]
2384 async fn test_programmatic_builder_does_not_retry_on_non_transient_failures() {
2385 let provider = Arc::new(TestSubjectTokenProvider);
2386 let mut sts_server = Server::run();
2387
2388 sts_server.expect(
2389 Expectation::matching(request::method_path("POST", "/token"))
2390 .times(1)
2391 .respond_with(status_code(401)),
2392 );
2393
2394 let creds = ProgrammaticBuilder::new(provider)
2395 .with_audience("test-audience")
2396 .with_subject_token_type("test-token-type")
2397 .with_token_url(sts_server.url("/token").to_string())
2398 .with_retry_policy(get_mock_auth_retry_policy(1))
2399 .with_backoff_policy(get_mock_backoff_policy())
2400 .with_retry_throttler(get_mock_retry_throttler())
2401 .build()
2402 .unwrap();
2403
2404 let err = creds.headers(Extensions::new()).await.unwrap_err();
2405 assert!(!err.is_transient());
2406 sts_server.verify_and_clear();
2407 }
2408
2409 #[tokio::test]
2410 async fn test_programmatic_builder_retries_for_success() {
2411 let provider = Arc::new(TestSubjectTokenProvider);
2412 let mut sts_server = Server::run();
2413
2414 sts_server.expect(
2415 Expectation::matching(request::method_path("POST", "/token"))
2416 .times(3)
2417 .respond_with(cycle![
2418 status_code(503).body("try-again"),
2419 status_code(503).body("try-again"),
2420 json_encoded(json!({
2421 "access_token": "sts-only-token",
2422 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2423 "token_type": "Bearer",
2424 "expires_in": 3600,
2425 }))
2426 ]),
2427 );
2428
2429 let creds = ProgrammaticBuilder::new(provider)
2430 .with_audience("test-audience")
2431 .with_subject_token_type("test-token-type")
2432 .with_token_url(sts_server.url("/token").to_string())
2433 .with_retry_policy(get_mock_auth_retry_policy(3))
2434 .with_backoff_policy(get_mock_backoff_policy())
2435 .with_retry_throttler(get_mock_retry_throttler())
2436 .build()
2437 .unwrap();
2438
2439 let headers = creds.headers(Extensions::new()).await.unwrap();
2440 match headers {
2441 CacheableResource::New { data, .. } => {
2442 let token = data.get("authorization").unwrap().to_str().unwrap();
2443 assert_eq!(token, "Bearer sts-only-token");
2444 }
2445 CacheableResource::NotModified => panic!("Expected new headers"),
2446 }
2447 sts_server.verify_and_clear();
2448 }
2449
2450 #[test_case(
2451 "//iam.googleapis.com/projects/12345/locations/global/workloadIdentityPools/my-pool/providers/my-provider",
2452 "/v1/projects/12345/locations/global/workloadIdentityPools/my-pool/allowedLocations";
2453 "workload_identity_pool"
2454 )]
2455 #[test_case(
2456 "//iam.googleapis.com/locations/global/workforcePools/my-pool/providers/my-provider",
2457 "/v1/locations/global/workforcePools/my-pool/allowedLocations";
2458 "workforce_pool"
2459 )]
2460 #[tokio::test]
2461 #[cfg(google_cloud_unstable_trust_boundaries)]
2462 async fn e2e_access_boundary(audience: &str, iam_path: &str) -> anyhow::Result<()> {
2463 use crate::credentials::tests::get_access_boundary_from_headers;
2464
2465 let audience = audience.to_string();
2466 let iam_path = iam_path.to_string();
2467
2468 let server = Server::run();
2469
2470 server.expect(
2471 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
2472 json_encoded(json!({
2473 "access_token": "subject_token",
2474 })),
2475 ),
2476 );
2477
2478 server.expect(
2479 Expectation::matching(all_of![
2480 request::method_path("POST", "/token"),
2481 request::body(url_decoded(contains(("subject_token", "subject_token")))),
2482 request::body(url_decoded(contains(("audience", audience.clone())))),
2483 ])
2484 .respond_with(json_encoded(json!({
2485 "access_token": "sts-only-token",
2486 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2487 "token_type": "Bearer",
2488 "expires_in": 3600,
2489 }))),
2490 );
2491
2492 server.expect(
2493 Expectation::matching(all_of![request::method_path("GET", iam_path.clone()),])
2494 .respond_with(json_encoded(json!({
2495 "locations": ["us-central1"],
2496 "encodedLocations": "0x1234"
2497 }))),
2498 );
2499
2500 let contents = json!({
2501 "type": "external_account",
2502 "audience": audience.to_string(),
2503 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2504 "token_url": server.url("/token").to_string(),
2505 "credential_source": {
2506 "url": server.url("/subject_token").to_string(),
2507 "format": {
2508 "type": "json",
2509 "subject_token_field_name": "access_token"
2510 }
2511 }
2512 });
2513
2514 let iam_endpoint = server
2515 .url("/")
2516 .to_string()
2517 .trim_end_matches('/')
2518 .to_string();
2519
2520 let creds = Builder::new(contents)
2521 .maybe_iam_endpoint_override(Some(iam_endpoint))
2522 .build_credentials()?;
2523
2524 creds.wait_for_boundary().await;
2526
2527 let headers = creds.headers(Extensions::new()).await?;
2528 let token = get_token_from_headers(headers.clone());
2529 let access_boundary = get_access_boundary_from_headers(headers);
2530
2531 assert!(token.is_some(), "should have some token");
2532 assert_eq!(access_boundary.as_deref(), Some("0x1234"));
2533
2534 Ok(())
2535 }
2536
2537 #[tokio::test]
2538 async fn test_kubernetes_wif_direct_identity_parsing() {
2539 let contents = json!({
2540 "audience": "//iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/pool-name/providers/k8s-cluster",
2541 "credential_source": {
2542 "file": "/var/run/service-account/token"
2543 },
2544 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2545 "token_url": "https://sts.googleapis.com/v1/token",
2546 "type": "external_account"
2547 });
2548
2549 let file: ExternalAccountFile = serde_json::from_value(contents)
2550 .expect("failed to parse kubernetes WIF direct identity config");
2551 let config: ExternalAccountConfig = file.into();
2552
2553 match config.credential_source {
2554 CredentialSource::File(source) => {
2555 assert_eq!(source.file, "/var/run/service-account/token");
2556 assert_eq!(source.format, "text"); assert_eq!(source.subject_token_field_name, ""); }
2559 _ => {
2560 unreachable!("expected File sourced credential")
2561 }
2562 }
2563 }
2564
2565 #[tokio::test]
2566 async fn test_kubernetes_wif_impersonation_parsing() {
2567 let contents = json!({
2568 "audience": "//iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/pool-name/providers/k8s-cluster",
2569 "credential_source": {
2570 "file": "/var/run/service-account/token",
2571 "format": {
2572 "type": "text"
2573 }
2574 },
2575 "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/test-sa@test-project.iam.gserviceaccount.com:generateAccessToken",
2576 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2577 "token_url": "https://sts.googleapis.com/v1/token",
2578 "type": "external_account",
2579 "universe_domain": "googleapis.com"
2580 });
2581
2582 let file: ExternalAccountFile = serde_json::from_value(contents)
2583 .expect("failed to parse kubernetes WIF impersonation config");
2584 let config: ExternalAccountConfig = file.into();
2585
2586 match config.credential_source {
2587 CredentialSource::File(source) => {
2588 assert_eq!(source.file, "/var/run/service-account/token");
2589 assert_eq!(source.format, "text");
2590 assert_eq!(source.subject_token_field_name, ""); }
2592 _ => {
2593 unreachable!("expected File sourced credential")
2594 }
2595 }
2596
2597 assert_eq!(
2598 config.service_account_impersonation_url,
2599 Some("https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/test-sa@test-project.iam.gserviceaccount.com:generateAccessToken".to_string())
2600 );
2601 }
2602
2603 #[tokio::test]
2604 async fn test_aws_parsing() {
2605 let contents = json!({
2606 "audience": "audience",
2607 "credential_source": {
2608 "environment_id": "aws1",
2609 "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone",
2610 "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
2611 "regional_cred_verification_url": "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15",
2612 "imdsv2_session_token_url": "http://169.254.169.254/latest/api/token"
2613 },
2614 "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request",
2615 "token_url": "https://sts.googleapis.com/v1/token",
2616 "type": "external_account"
2617 });
2618
2619 let file: ExternalAccountFile =
2620 serde_json::from_value(contents).expect("failed to parse AWS config");
2621 let config: ExternalAccountConfig = file.into();
2622
2623 match config.credential_source {
2624 CredentialSource::Aws(source) => {
2625 assert_eq!(
2626 source.region_url,
2627 Some(
2628 "http://169.254.169.254/latest/meta-data/placement/availability-zone"
2629 .to_string()
2630 )
2631 );
2632 assert_eq!(
2633 source.regional_cred_verification_url,
2634 Some(
2635 "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"
2636 .to_string()
2637 )
2638 );
2639 assert_eq!(
2640 source.imdsv2_session_token_url,
2641 Some("http://169.254.169.254/latest/api/token".to_string())
2642 );
2643 }
2644 _ => {
2645 unreachable!("expected Aws sourced credential")
2646 }
2647 }
2648 }
2649
2650 #[tokio::test]
2651 async fn builder_workforce_pool_user_project_fails_without_workforce_pool_audience() {
2652 let contents = json!({
2653 "type": "external_account",
2654 "audience": "not-a-workforce-pool",
2655 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2656 "token_url": "http://test.com/token",
2657 "credential_source": {
2658 "url": "http://test.com/subject_token",
2659 },
2660 "workforce_pool_user_project": "test-project"
2661 });
2662
2663 let result = Builder::new(contents).build();
2664
2665 assert!(result.is_err(), "{result:?}");
2666 let err = result.unwrap_err();
2667 assert!(err.is_parsing(), "{err:?}");
2668 }
2669
2670 #[tokio::test]
2671 async fn sts_handler_ignores_workforce_pool_user_project_with_client_auth()
2672 -> std::result::Result<(), Box<dyn std::error::Error>> {
2673 let subject_token_server = Server::run();
2674 let sts_server = Server::run();
2675
2676 let contents = json!({
2677 "type": "external_account",
2678 "audience": "//iam.googleapis.com/locations/global/workforcePools/pool/providers/provider",
2679 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2680 "token_url": sts_server.url("/token").to_string(),
2681 "client_id": "client-id",
2682 "credential_source": {
2683 "url": subject_token_server.url("/subject_token").to_string(),
2684 },
2685 "workforce_pool_user_project": "test-project"
2686 });
2687
2688 subject_token_server.expect(
2689 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
2690 json_encoded(json!({
2691 "access_token": "subject_token",
2692 })),
2693 ),
2694 );
2695
2696 sts_server.expect(
2697 Expectation::matching(all_of![request::method_path("POST", "/token"),]).respond_with(
2698 json_encoded(json!({
2699 "access_token": "sts-only-token",
2700 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2701 "token_type": "Bearer",
2702 "expires_in": 3600,
2703 })),
2704 ),
2705 );
2706
2707 let creds = Builder::new(contents).build()?;
2708 let headers = creds.headers(Extensions::new()).await?;
2709 let token = get_token_from_headers(headers);
2710 assert_eq!(token.as_deref(), Some("sts-only-token"));
2711
2712 Ok(())
2713 }
2714
2715 #[tokio::test]
2716 async fn sts_handler_receives_workforce_pool_user_project()
2717 -> std::result::Result<(), Box<dyn std::error::Error>> {
2718 let subject_token_server = Server::run();
2719 let sts_server = Server::run();
2720
2721 let contents = json!({
2722 "type": "external_account",
2723 "audience": "//iam.googleapis.com/locations/global/workforcePools/pool/providers/provider",
2724 "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
2725 "token_url": sts_server.url("/token").to_string(),
2726 "credential_source": {
2727 "url": subject_token_server.url("/subject_token").to_string(),
2728 },
2729 "workforce_pool_user_project": "test-project-123"
2730 });
2731
2732 subject_token_server.expect(
2733 Expectation::matching(request::method_path("GET", "/subject_token")).respond_with(
2734 json_encoded(json!({
2735 "access_token": "subject_token",
2736 })),
2737 ),
2738 );
2739
2740 sts_server.expect(
2741 Expectation::matching(all_of![
2742 request::method_path("POST", "/token"),
2743 request::body(url_decoded(contains((
2744 "options",
2745 "{\"userProject\":\"test-project-123\"}"
2746 )))),
2747 ])
2748 .respond_with(json_encoded(json!({
2749 "access_token": "sts-only-token",
2750 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
2751 "token_type": "Bearer",
2752 "expires_in": 3600,
2753 }))),
2754 );
2755
2756 let creds = Builder::new(contents).build()?;
2757 let headers = creds.headers(Extensions::new()).await?;
2758 let token = get_token_from_headers(headers);
2759 assert_eq!(token.as_deref(), Some("sts-only-token"));
2760
2761 Ok(())
2762 }
2763}