Skip to main content

google_cloud_auth/credentials/
external_account.rs

1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [Workload Identity Federation] (or External Account) credentials.
16//!
17//! Workload identity federation allows applications running outside of Google Cloud
18//! to access Google Cloud resources without using a [Service Account Key]. Instead of
19//! a long-lived credential (like a service account key), you can exchange a credential
20//! from your workload's identity provider for a short-lived Google Cloud access token.
21//! As per [best practices], Workload Identity Federation is the recommended method of
22//! authentication if your workload is using an external identity provider.
23//!
24//! Refer to [Obtain short-lived tokens for Workforce Identity Federation] for
25//! creating configurations that can be used with this library for loading credentials
26//! using various external toke provider sources such as file, URL, or an executable.
27//!
28//! ## Example: Creating credentials from a JSON object
29//!
30//! ```
31//! # use google_cloud_auth::credentials::external_account;
32//! # use http::Extensions;
33//! #
34//! # async fn sample() -> anyhow::Result<()> {
35//! let project_id = "your-gcp-project-id";
36//! let pool_id = "your-workload-identity-pool-id";
37//! let provider_id = "your-provider-id";
38//!
39//! let audience = format!(
40//!     "//iam.googleapis.com/projects/{}/locations/global/workloadIdentityPools/{}/providers/{}",
41//!     project_id, pool_id, provider_id
42//! );
43//!
44//! // This is an example of a configuration for a file-sourced credential.
45//! // The actual configuration will depend on your identity provider.
46//! let external_account_config = serde_json::json!({
47//!     "type": "external_account",
48//!     "audience": audience,
49//!     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
50//!     "token_url": "https://sts.googleapis.com/v1/token",
51//!     "credential_source": {
52//!         "file": "/path/to/your/oidc/token.jwt"
53//!     }
54//! });
55//!
56//! let credentials = external_account::Builder::new(external_account_config)
57//!     .build()
58//!     .unwrap();
59//! let headers = credentials.headers(Extensions::new()).await?;
60//! println!("Headers: {headers:?}");
61//! # Ok(()) }
62//! ```
63//!
64//! ## Example: Creating credentials with custom retry behavior
65//!
66//! ```
67//! # use google_cloud_auth::credentials::external_account;
68//! # use http::Extensions;
69//! # use std::time::Duration;
70//! # async fn sample() -> anyhow::Result<()> {
71//! use google_cloud_gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
72//! use google_cloud_gax::exponential_backoff::ExponentialBackoff;
73//! # let project_id = "your-gcp-project-id";
74//! # let pool_id = "your-workload-identity-pool-id";
75//! # let provider_id = "your-provider-id";
76//! #
77//! # let audience = format!(
78//! #     "//iam.googleapis.com/projects/{}/locations/global/workloadIdentityPools/{}/providers/{}",
79//! #     project_id, pool_id, provider_id
80//! # );
81//! #
82//! # let external_account_config = serde_json::json!({
83//! #     "type": "external_account",
84//! #     "audience": audience,
85//! #     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
86//! #     "token_url": "https://sts.googleapis.com/v1/token",
87//! #     "credential_source": {
88//! #         "file": "/path/to/your/oidc/token.jwt"
89//! #     }
90//! # });
91//! let backoff = ExponentialBackoff::default();
92//! let credentials = external_account::Builder::new(external_account_config)
93//!     .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
94//!     .with_backoff_policy(backoff)
95//!     .build()
96//!     .unwrap();
97//! let headers = credentials.headers(Extensions::new()).await?;
98//! println!("Headers: {headers:?}");
99//! # Ok(()) }
100//! ```
101//!
102//! [Workload Identity Federation]: https://cloud.google.com/iam/docs/workload-identity-federation
103//! [AIP-4117]: https://google.aip.dev/auth/4117
104//! [Service Account Key]: https://cloud.google.com/iam/docs/service-account-creds#key-types
105//! [best practices]: https://cloud.google.com/docs/authentication#auth-decision-tree
106//! [Obtain short-lived tokens for Workforce Identity Federation]: https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#use_configuration_files_for_sign-in
107
108use 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    // Most specific variants first for untagged enum
160    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
181/// Check if the audience parameter matches the pattern for a valid workforce pool.
182/// Example: https://iam.googleapis.com/locations/global/workforcePools/pool/providers/provider
183fn 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/// A representation of a [external account config file].
201///
202/// [external account config file]: https://google.aip.dev/auth/4117#configuration-file-generation-and-usage
203#[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        // User provides the scopes to be set on the final token they receive. The scopes they
462        // provide does not necessarily have to include the IAM scope or cloud-platform scope
463        // which are needed to make the call to `iamcredentials` endpoint. So when minting the
464        // STS token, we use the user provided or IAM scope depending on whether the STS provided
465        // token is to be used with impersonation or directly.
466        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
526/// A builder for external account [Credentials] instances.
527///
528/// # Example
529/// ```
530/// # use google_cloud_auth::credentials::external_account::Builder;
531/// # async fn sample() -> anyhow::Result<()> {
532/// let project_id = project_id();
533/// let workload_identity_pool_id = workload_identity_pool();
534/// let provider_id = workload_identity_provider();
535/// let provider_name = format!(
536///     "//iam.googleapis.com/projects/{project_id}/locations/global/workloadIdentityPools/{workload_identity_pool_id}/providers/{provider_id}"
537/// );
538/// let config = serde_json::json!({
539///     "type": "external_account",
540///     "audience": provider_name,
541///     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
542///     "token_url": "https://sts.googleapis.com/v1beta/token",
543///     "credential_source": {
544///         "url": format!("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource={provider_name}"),
545///         "headers": {
546///           "Metadata": "True"
547///         },
548///         "format": {
549///           "type": "json",
550///           "subject_token_field_name": "access_token"
551///         }
552///     }
553/// });
554/// let credentials = Builder::new(config)
555///     .with_quota_project_id("quota_project")
556///     .build()?;
557/// # Ok(()) }
558///
559/// # fn project_id() -> String {
560/// #     "test-only".to_string()
561/// # }
562/// # fn workload_identity_pool() -> String {
563/// #     "test-only".to_string()
564/// # }
565/// # fn workload_identity_provider() -> String {
566/// #     "test-only".to_string()
567/// # }
568/// ```
569pub 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    /// Creates a new builder using [external_account_credentials] JSON value.
580    ///
581    /// [external_account_credentials]: https://google.aip.dev/auth/4117#configuration-file-generation-and-usage
582    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    /// Sets the [quota project] for this credentials.
594    ///
595    /// In some services, you can use a service account in
596    /// one project for authentication and authorization, and charge
597    /// the usage to a different project. This requires that the
598    /// service account has `serviceusage.services.use` permissions on the quota project.
599    ///
600    /// [quota project]: https://cloud.google.com/docs/quotas/quota-project
601    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    /// Sets the Google Cloud universe domain for these credentials.
607    ///
608    /// Any value provided here overrides a `universe_domain` value from the input service account JSON.
609    ///
610    /// # Example
611    /// ```
612    /// # use google_cloud_auth::credentials::external_account::Builder;
613    /// # use serde_json::json;
614    /// # async fn sample() -> anyhow::Result<()> {
615    /// # let config = json!({
616    /// #     "type": "external_account",
617    /// #     "audience": "audience",
618    /// #     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
619    /// #     "token_url": "https://sts.googleapis.com/v1beta/token",
620    /// #     "credential_source": { "url": "url" }
621    /// # });
622    /// let credentials = Builder::new(config)
623    ///     .with_universe_domain("googleapis.com")
624    ///     .build()?;
625    /// # Ok(()) }
626    /// ```
627    ///
628    /// [universe domain]: https://cloud.google.com/docs/authentication/universe-domain
629    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    /// Overrides the [scopes] for this credentials.
635    ///
636    /// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
637    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    /// Configure the retry policy for fetching tokens.
647    ///
648    /// The retry policy controls how to handle retries, and sets limits on
649    /// the number of attempts or the total time spent retrying.
650    ///
651    /// ```
652    /// # use google_cloud_auth::credentials::external_account::Builder;
653    /// # async fn sample() -> anyhow::Result<()> {
654    /// use google_cloud_gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
655    /// let config = serde_json::json!({
656    ///     "type": "external_account",
657    ///     "audience": "audience",
658    ///     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
659    ///     "token_url": "https://sts.googleapis.com/v1beta/token",
660    ///     "credential_source": { "file": "/path/to/your/oidc/token.jwt" }
661    /// });
662    /// let credentials = Builder::new(config)
663    ///     .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
664    ///     .build()?;
665    /// # Ok(()) }
666    /// ```
667    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    /// Configure the retry backoff policy.
673    ///
674    /// The backoff policy controls how long to wait in between retry attempts.
675    ///
676    /// ```
677    /// # use google_cloud_auth::credentials::external_account::Builder;
678    /// # use std::time::Duration;
679    /// # async fn sample() -> anyhow::Result<()> {
680    /// use google_cloud_gax::exponential_backoff::ExponentialBackoff;
681    /// let config = serde_json::json!({
682    ///     "type": "external_account",
683    ///     "audience": "audience",
684    ///     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
685    ///     "token_url": "https://sts.googleapis.com/v1beta/token",
686    ///     "credential_source": { "file": "/path/to/your/oidc/token.jwt" }
687    /// });
688    /// let policy = ExponentialBackoff::default();
689    /// let credentials = Builder::new(config)
690    ///     .with_backoff_policy(policy)
691    ///     .build()?;
692    /// # Ok(()) }
693    /// ```
694    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    /// Configure the retry throttler.
700    ///
701    /// Advanced applications may want to configure a retry throttler to
702    /// [Address Cascading Failures] and when [Handling Overload] conditions.
703    /// The authentication library throttles its retry loop, using a policy to
704    /// control the throttling algorithm. Use this method to fine tune or
705    /// customize the default retry throttler.
706    ///
707    /// [Handling Overload]: https://sre.google/sre-book/handling-overload/
708    /// [Address Cascading Failures]: https://sre.google/sre-book/addressing-cascading-failures/
709    ///
710    /// ```
711    /// # use google_cloud_auth::credentials::external_account::Builder;
712    /// # async fn sample() -> anyhow::Result<()> {
713    /// use google_cloud_gax::retry_throttler::AdaptiveThrottler;
714    /// let config = serde_json::json!({
715    ///     "type": "external_account",
716    ///     "audience": "audience",
717    ///     "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
718    ///     "token_url": "https://sts.googleapis.com/v1beta/token",
719    ///     "credential_source": { "file": "/path/to/your/oidc/token.jwt" }
720    /// });
721    /// let credentials = Builder::new(config)
722    ///     .with_retry_throttler(AdaptiveThrottler::default())
723    ///     .build()?;
724    /// # Ok(()) }
725    /// ```
726    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    /// Returns a [Credentials] instance with the configured settings.
738    ///
739    /// # Errors
740    ///
741    /// Returns a [BuilderError] if the `external_account_config`
742    /// provided to [`Builder::new`] cannot be successfully deserialized into the
743    /// expected format for an external account configuration. This typically happens if the
744    /// JSON value is malformed or missing required fields.
745    ///
746    /// For more information, on the expected format, consult the relevant
747    /// section in the [external_account_credentials] guide.
748    ///
749    /// [external_account_credentials]: https://google.aip.dev/auth/4117#configuration-file-generation-and-usage
750    pub fn build(self) -> BuildResult<Credentials> {
751        Ok(self.build_credentials()?.into())
752    }
753
754    /// Returns an [AccessTokenCredentials] instance with the configured settings.
755    ///
756    /// # Errors
757    ///
758    /// Returns a [BuilderError] if the `external_account_config`
759    /// provided to [`Builder::new`] cannot be successfully deserialized into the
760    /// expected format for an external account configuration. This typically happens if the
761    /// JSON value is malformed or missing required fields.
762    ///
763    /// For more information, on the expected format, consult the relevant
764    /// section in the [external_account_credentials] guide.
765    ///
766    /// [external_account_credentials]: https://google.aip.dev/auth/4117#configuration-file-generation-and-usage
767    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
807/// A builder for external account [Credentials] that uses a user provided subject
808/// token provider.
809///
810/// This builder is designed for advanced use cases where the subject token is
811/// provided directly by the application through a custom implementation of the
812/// [SubjectTokenProvider] trait.
813///
814/// # Example
815///
816/// ```
817/// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
818/// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
819/// # use google_cloud_auth::errors::SubjectTokenProviderError;
820/// # use std::error::Error;
821/// # use std::fmt;
822/// # use std::sync::Arc;
823/// #
824/// # #[derive(Debug)]
825/// # struct MyTokenProvider;
826/// #
827/// # #[derive(Debug)]
828/// # struct MyProviderError;
829/// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
830/// # impl Error for MyProviderError {}
831/// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
832/// #
833/// # impl SubjectTokenProvider for MyTokenProvider {
834/// #     type Error = MyProviderError;
835/// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
836/// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
837/// #     }
838/// # }
839/// #
840/// # async fn sample() -> anyhow::Result<()> {
841/// let provider = Arc::new(MyTokenProvider);
842///
843/// let credentials = ProgrammaticBuilder::new(provider)
844///     .with_audience("//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/my-pool/providers/my-provider".to_string())
845///     .with_subject_token_type("urn:ietf:params:oauth:token-type:jwt".to_string())
846///     .with_token_url("https://sts.googleapis.com/v1beta/token".to_string())
847///     .with_quota_project_id("my-quota-project")
848///     .with_scopes(vec!["https://www.googleapis.com/auth/devstorage.read_only".to_string()])
849///     .build()
850///     .unwrap();
851/// # Ok(()) }
852/// ```
853/// [SubjectTokenProvider]: crate::credentials::subject_token::SubjectTokenProvider
854pub struct ProgrammaticBuilder {
855    quota_project_id: Option<String>,
856    config: ExternalAccountConfigBuilder,
857    retry_builder: RetryTokenProviderBuilder,
858}
859
860impl ProgrammaticBuilder {
861    /// Creates a new builder that uses the provided [SubjectTokenProvider] to
862    /// fetch the third-party subject token.
863    ///
864    /// # Example
865    ///
866    /// ```
867    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
868    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
869    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
870    /// # use std::error::Error;
871    /// # use std::fmt;
872    /// # use std::sync::Arc;
873    /// #
874    /// # #[derive(Debug)]
875    /// # struct MyTokenProvider;
876    /// #
877    /// # #[derive(Debug)]
878    /// # struct MyProviderError;
879    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
880    /// # impl Error for MyProviderError {}
881    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
882    /// #
883    /// # impl SubjectTokenProvider for MyTokenProvider {
884    /// #     type Error = MyProviderError;
885    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
886    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
887    /// #     }
888    /// # }
889    /// let provider = Arc::new(MyTokenProvider);
890    /// let builder = ProgrammaticBuilder::new(provider);
891    /// ```
892    /// [SubjectTokenProvider]: crate::credentials::subject_token::SubjectTokenProvider
893    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    /// Sets the optional [quota project] for this credentials.
907    ///
908    /// In some services, you can use a service account in
909    /// one project for authentication and authorization, and charge
910    /// the usage to a different project. This requires that the
911    /// service account has `serviceusage.services.use` permissions on the quota project.
912    ///
913    /// # Example
914    ///
915    /// ```
916    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
917    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
918    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
919    /// # use std::error::Error;
920    /// # use std::fmt;
921    /// # use std::sync::Arc;
922    /// #
923    /// # #[derive(Debug)]
924    /// # struct MyTokenProvider;
925    /// #
926    /// # #[derive(Debug)]
927    /// # struct MyProviderError;
928    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
929    /// # impl Error for MyProviderError {}
930    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
931    /// #
932    /// # impl SubjectTokenProvider for MyTokenProvider {
933    /// #     type Error = MyProviderError;
934    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
935    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
936    /// #     }
937    /// # }
938    /// # let provider = Arc::new(MyTokenProvider);
939    /// let builder = ProgrammaticBuilder::new(provider)
940    ///     .with_quota_project_id("my-quota-project");
941    /// ```
942    ///
943    /// [quota project]: https://cloud.google.com/docs/quotas/quota-project
944    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    /// Overrides the optional [scopes] for this credentials. If this method is not
950    /// called, a default scope will be used.
951    ///
952    /// # Example
953    ///
954    /// ```
955    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
956    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
957    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
958    /// # use std::error::Error;
959    /// # use std::fmt;
960    /// # use std::sync::Arc;
961    /// #
962    /// # #[derive(Debug)]
963    /// # struct MyTokenProvider;
964    /// #
965    /// # #[derive(Debug)]
966    /// # struct MyProviderError;
967    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
968    /// # impl Error for MyProviderError {}
969    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
970    /// #
971    /// # impl SubjectTokenProvider for MyTokenProvider {
972    /// #     type Error = MyProviderError;
973    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
974    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
975    /// #     }
976    /// # }
977    /// # let provider = Arc::new(MyTokenProvider);
978    /// let builder = ProgrammaticBuilder::new(provider)
979    ///     .with_scopes(vec!["scope1", "scope2"]);
980    /// ```
981    ///
982    /// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
983    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    /// Sets the Google Cloud universe domain for these credentials.
998    ///
999    /// Any value provided here overrides a `universe_domain` value from the input service account JSON.
1000    ///
1001    /// # Example
1002    /// ```
1003    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1004    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1005    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1006    /// # use std::sync::Arc;
1007    /// # #[derive(Debug)] struct MyProvider;
1008    /// # #[derive(Debug)] struct MyError;
1009    /// # impl std::fmt::Display for MyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "err") } }
1010    /// # impl std::error::Error for MyError {}
1011    /// # impl SubjectTokenProviderError for MyError { fn is_transient(&self) -> bool { false } }
1012    /// # impl SubjectTokenProvider for MyProvider { type Error = MyError; async fn subject_token(&self) -> Result<SubjectToken, Self::Error> { Ok(SubjectTokenBuilder::new("token".to_string()).build()) } }
1013    /// # async fn sample() -> anyhow::Result<()> {
1014    /// # let provider = Arc::new(MyProvider);
1015    /// let credentials = ProgrammaticBuilder::new(provider)
1016    ///     .with_universe_domain("googleapis.com");
1017    /// # Ok(()) }
1018    /// ```
1019    ///
1020    /// [universe domain]: https://cloud.google.com/docs/authentication/universe-domain
1021    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    /// Sets the required audience for the token exchange.
1027    ///
1028    /// This is the resource name for the workload identity pool and the provider
1029    /// identifier in that pool.
1030    ///
1031    /// # Example
1032    ///
1033    /// ```
1034    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1035    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1036    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1037    /// # use std::error::Error;
1038    /// # use std::fmt;
1039    /// # use std::sync::Arc;
1040    /// #
1041    /// # #[derive(Debug)]
1042    /// # struct MyTokenProvider;
1043    /// #
1044    /// # #[derive(Debug)]
1045    /// # struct MyProviderError;
1046    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1047    /// # impl Error for MyProviderError {}
1048    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1049    /// #
1050    /// # impl SubjectTokenProvider for MyTokenProvider {
1051    /// #     type Error = MyProviderError;
1052    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1053    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1054    /// #     }
1055    /// # }
1056    /// # let provider = Arc::new(MyTokenProvider);
1057    /// let builder = ProgrammaticBuilder::new(provider)
1058    ///     .with_audience("my-audience");
1059    /// ```
1060    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    /// Sets the required subject token type.
1066    ///
1067    /// This is the STS subject token type based on the OAuth 2.0 token exchange spec.
1068    ///
1069    /// # Example
1070    ///
1071    /// ```
1072    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1073    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1074    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1075    /// # use std::error::Error;
1076    /// # use std::fmt;
1077    /// # use std::sync::Arc;
1078    /// #
1079    /// # #[derive(Debug)]
1080    /// # struct MyTokenProvider;
1081    /// #
1082    /// # #[derive(Debug)]
1083    /// # struct MyProviderError;
1084    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1085    /// # impl Error for MyProviderError {}
1086    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1087    /// #
1088    /// # impl SubjectTokenProvider for MyTokenProvider {
1089    /// #     type Error = MyProviderError;
1090    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1091    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1092    /// #     }
1093    /// # }
1094    /// # let provider = Arc::new(MyTokenProvider);
1095    /// let builder = ProgrammaticBuilder::new(provider)
1096    ///     .with_subject_token_type("my-token-type");
1097    /// ```
1098    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    /// Sets the optional token URL for the STS token exchange. If not provided,
1104    /// `https://sts.googleapis.com/v1/token` is used.
1105    ///
1106    /// # Example
1107    ///
1108    /// ```
1109    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1110    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1111    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1112    /// # use std::error::Error;
1113    /// # use std::fmt;
1114    /// # use std::sync::Arc;
1115    /// #
1116    /// # #[derive(Debug)]
1117    /// # struct MyTokenProvider;
1118    /// #
1119    /// # #[derive(Debug)]
1120    /// # struct MyProviderError;
1121    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1122    /// # impl Error for MyProviderError {}
1123    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1124    /// #
1125    /// # impl SubjectTokenProvider for MyTokenProvider {
1126    /// #     type Error = MyProviderError;
1127    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1128    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1129    /// #     }
1130    /// # }
1131    /// # let provider = Arc::new(MyTokenProvider);
1132    /// let builder = ProgrammaticBuilder::new(provider)
1133    ///     .with_token_url("http://my-token-url.com");
1134    /// ```
1135    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    /// Sets the optional client ID for client authentication.
1141    ///
1142    /// # Example
1143    ///
1144    /// ```
1145    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1146    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1147    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1148    /// # use std::error::Error;
1149    /// # use std::fmt;
1150    /// # use std::sync::Arc;
1151    /// #
1152    /// # #[derive(Debug)]
1153    /// # struct MyTokenProvider;
1154    /// #
1155    /// # #[derive(Debug)]
1156    /// # struct MyProviderError;
1157    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1158    /// # impl Error for MyProviderError {}
1159    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1160    /// #
1161    /// # impl SubjectTokenProvider for MyTokenProvider {
1162    /// #     type Error = MyProviderError;
1163    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1164    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1165    /// #     }
1166    /// # }
1167    /// # let provider = Arc::new(MyTokenProvider);
1168    /// let builder = ProgrammaticBuilder::new(provider)
1169    ///     .with_client_id("my-client-id");
1170    /// ```
1171    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    /// Sets the optional client secret for client authentication.
1177    ///
1178    /// # Example
1179    ///
1180    /// ```
1181    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1182    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1183    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1184    /// # use std::error::Error;
1185    /// # use std::fmt;
1186    /// # use std::sync::Arc;
1187    /// #
1188    /// # #[derive(Debug)]
1189    /// # struct MyTokenProvider;
1190    /// #
1191    /// # #[derive(Debug)]
1192    /// # struct MyProviderError;
1193    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1194    /// # impl Error for MyProviderError {}
1195    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1196    /// #
1197    /// # impl SubjectTokenProvider for MyTokenProvider {
1198    /// #     type Error = MyProviderError;
1199    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1200    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1201    /// #     }
1202    /// # }
1203    /// # let provider = Arc::new(MyTokenProvider);
1204    /// let builder = ProgrammaticBuilder::new(provider)
1205    ///     .with_client_secret("my-client-secret");
1206    /// ```
1207    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    /// Sets the optional target principal.
1213    ///
1214    /// Target principal is the email of the service account to impersonate.
1215    ///
1216    /// # Example
1217    ///
1218    /// ```
1219    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1220    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1221    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1222    /// # use std::error::Error;
1223    /// # use std::fmt;
1224    /// # use std::sync::Arc;
1225    /// #
1226    /// # #[derive(Debug)]
1227    /// # struct MyTokenProvider;
1228    /// #
1229    /// # #[derive(Debug)]
1230    /// # struct MyProviderError;
1231    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1232    /// # impl Error for MyProviderError {}
1233    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1234    /// #
1235    /// # impl SubjectTokenProvider for MyTokenProvider {
1236    /// #     type Error = MyProviderError;
1237    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1238    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1239    /// #     }
1240    /// # }
1241    /// # let provider = Arc::new(MyTokenProvider);
1242    /// let builder = ProgrammaticBuilder::new(provider)
1243    ///     .with_target_principal("test-principal");
1244    /// ```
1245    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    /// Sets the optional workforce pool user project.
1255    ///
1256    /// This is the project ID used for quota and billing in the workforce pool context.
1257    ///
1258    /// # Example
1259    ///
1260    /// ```
1261    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1262    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1263    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1264    /// # use std::error::Error;
1265    /// # use std::fmt;
1266    /// # use std::sync::Arc;
1267    /// #
1268    /// # #[derive(Debug)]
1269    /// # struct MyTokenProvider;
1270    /// #
1271    /// # #[derive(Debug)]
1272    /// # struct MyProviderError;
1273    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1274    /// # impl Error for MyProviderError {}
1275    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1276    /// #
1277    /// # impl SubjectTokenProvider for MyTokenProvider {
1278    /// #     type Error = MyProviderError;
1279    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1280    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1281    /// #     }
1282    /// # }
1283    /// # let provider = Arc::new(MyTokenProvider);
1284    /// let builder = ProgrammaticBuilder::new(provider)
1285    ///     .with_workforce_pool_user_project("my-project-id");
1286    /// ```
1287    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    /// Configure the retry policy for fetching tokens.
1293    ///
1294    /// The retry policy controls how to handle retries, and sets limits on
1295    /// the number of attempts or the total time spent retrying.
1296    ///
1297    /// ```
1298    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1299    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1300    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1301    /// # use std::error::Error;
1302    /// # use std::fmt;
1303    /// # use std::sync::Arc;
1304    /// #
1305    /// # #[derive(Debug)]
1306    /// # struct MyTokenProvider;
1307    /// #
1308    /// # #[derive(Debug)]
1309    /// # struct MyProviderError;
1310    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1311    /// # impl Error for MyProviderError {}
1312    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1313    /// #
1314    /// # impl SubjectTokenProvider for MyTokenProvider {
1315    /// #     type Error = MyProviderError;
1316    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1317    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1318    /// #     }
1319    /// # }
1320    /// #
1321    /// # async fn sample() -> anyhow::Result<()> {
1322    /// use google_cloud_gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
1323    /// let provider = Arc::new(MyTokenProvider);
1324    /// let credentials = ProgrammaticBuilder::new(provider)
1325    ///     .with_audience("test-audience")
1326    ///     .with_subject_token_type("test-token-type")
1327    ///     .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
1328    ///     .build()?;
1329    /// # Ok(()) }
1330    /// ```
1331    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    /// Configure the retry backoff policy.
1337    ///
1338    /// The backoff policy controls how long to wait in between retry attempts.
1339    ///
1340    /// ```
1341    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1342    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1343    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1344    /// # use std::error::Error;
1345    /// # use std::fmt;
1346    /// # use std::sync::Arc;
1347    /// #
1348    /// # #[derive(Debug)]
1349    /// # struct MyTokenProvider;
1350    /// #
1351    /// # #[derive(Debug)]
1352    /// # struct MyProviderError;
1353    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1354    /// # impl Error for MyProviderError {}
1355    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1356    /// #
1357    /// # impl SubjectTokenProvider for MyTokenProvider {
1358    /// #     type Error = MyProviderError;
1359    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1360    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1361    /// #     }
1362    /// # }
1363    /// #
1364    /// # async fn sample() -> anyhow::Result<()> {
1365    /// use google_cloud_gax::exponential_backoff::ExponentialBackoff;
1366    /// let provider = Arc::new(MyTokenProvider);
1367    /// let policy = ExponentialBackoff::default();
1368    /// let credentials = ProgrammaticBuilder::new(provider)
1369    ///     .with_audience("test-audience")
1370    ///     .with_subject_token_type("test-token-type")
1371    ///     .with_backoff_policy(policy)
1372    ///     .build()?;
1373    /// # Ok(()) }
1374    /// ```
1375    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    /// Configure the retry throttler.
1381    ///
1382    /// Advanced applications may want to configure a retry throttler to
1383    /// [Address Cascading Failures] and when [Handling Overload] conditions.
1384    /// The authentication library throttles its retry loop, using a policy to
1385    /// control the throttling algorithm. Use this method to fine tune or
1386    /// customize the default retry throttler.
1387    ///
1388    /// [Handling Overload]: https://sre.google/sre-book/handling-overload/
1389    /// [Address Cascading Failures]: https://sre.google/sre-book/addressing-cascading-failures/
1390    ///
1391    /// ```
1392    /// # use google_cloud_auth::credentials::external_account::ProgrammaticBuilder;
1393    /// # use google_cloud_auth::credentials::subject_token::{SubjectTokenProvider, SubjectToken, Builder as SubjectTokenBuilder};
1394    /// # use google_cloud_auth::errors::SubjectTokenProviderError;
1395    /// # use std::error::Error;
1396    /// # use std::fmt;
1397    /// # use std::sync::Arc;
1398    /// #
1399    /// # #[derive(Debug)]
1400    /// # struct MyTokenProvider;
1401    /// #
1402    /// # #[derive(Debug)]
1403    /// # struct MyProviderError;
1404    /// # impl fmt::Display for MyProviderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MyProviderError") } }
1405    /// # impl Error for MyProviderError {}
1406    /// # impl SubjectTokenProviderError for MyProviderError { fn is_transient(&self) -> bool { false } }
1407    /// #
1408    /// # impl SubjectTokenProvider for MyTokenProvider {
1409    /// #     type Error = MyProviderError;
1410    /// #     async fn subject_token(&self) -> Result<SubjectToken, Self::Error> {
1411    /// #         Ok(SubjectTokenBuilder::new("my-programmatic-token".to_string()).build())
1412    /// #     }
1413    /// # }
1414    /// #
1415    /// # async fn sample() -> anyhow::Result<()> {
1416    /// use google_cloud_gax::retry_throttler::AdaptiveThrottler;
1417    /// let provider = Arc::new(MyTokenProvider);
1418    /// let credentials = ProgrammaticBuilder::new(provider)
1419    ///     .with_audience("test-audience")
1420    ///     .with_subject_token_type("test-token-type")
1421    ///     .with_retry_throttler(AdaptiveThrottler::default())
1422    ///     .build()?;
1423    /// # Ok(()) }
1424    /// ```
1425    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    /// Returns a [Credentials] instance with the configured settings.
1431    ///
1432    /// # Errors
1433    ///
1434    /// Returns a [BuilderError] if any of the required fields (such as
1435    /// `audience` or `subject_token_type`) have not been set.
1436    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    /// Consumes the builder and returns its configured components.
1445    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        // Use the debug output to verify the right kind of credentials are created.
1578        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            // Missing .with_audience(...)
2206            .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        // wait for the access boundary background thread to update
2525        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"); // Default format
2557                assert_eq!(source.subject_token_field_name, ""); // Default empty
2558            }
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, ""); // Empty for text format
2591            }
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}