Skip to main content

google_cloud_auth/credentials/
external_account_authorized_user.rs

1// Copyright 2026 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//! [Workforce Identity Federation] user Credentials type.
16//!
17//! Workforce Identity Federation lets users from an external identity
18//! provider (IdP), such as Microsoft Entra ID or Okta, access Google Cloud
19//! resources. When such a user signs in using
20//! `gcloud auth application-default login --login-config=...`, gcloud writes
21//! an `external_account_authorized_user` credentials file. This file contains
22//! an OAuth 2.0 refresh token issued by the [Security Token Service] (STS).
23//!
24//! This module provides [Credentials] that use that refresh token to obtain
25//! access tokens from STS.
26//!
27//! The Google Cloud client libraries for Rust will typically find and use these
28//! credentials automatically if a credentials file exists in the
29//! standard ADC search paths. You might instantiate these credentials
30//! directly using the [`Builder`] if you need to:
31//! * Load credentials from a non-standard location or source.
32//! * Override the **quota project ID** for billing and quota management.
33//! * Override the **token URL** used to refresh access tokens.
34//! * Customize the **retry behavior** when fetching access tokens.
35//!
36//! ## Example: Creating credentials from a JSON object
37//!
38//! ```
39//! # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
40//! # use google_cloud_auth::credentials::Credentials;
41//! # use http::Extensions;
42//! # async fn sample() -> anyhow::Result<()> {
43//! let authorized_user = serde_json::json!({
44//!     "type": "external_account_authorized_user",
45//!     "audience": "//iam.googleapis.com/locations/global/workforcePools/POOL_ID/providers/PROVIDER_ID",
46//!     "client_id": "YOUR_CLIENT_ID",
47//!     "client_secret": "YOUR_CLIENT_SECRET", // LOAD SECURELY!
48//!     "refresh_token": "YOUR_REFRESH_TOKEN", // LOAD SECURELY!
49//!     "token_url": "https://sts.googleapis.com/v1/oauthtoken",
50//!     "token_info_url": "https://sts.googleapis.com/v1/introspect",
51//!     // "quota_project_id": "your-billing-project-id", // Optional: Set if needed
52//! });
53//! let credentials: Credentials = Builder::new(authorized_user).build()?;
54//! let headers = credentials.headers(Extensions::new()).await?;
55//! println!("Headers: {headers:?}");
56//! # Ok(()) }
57//! ```
58//!
59//! [Security Token Service]: https://cloud.google.com/iam/docs/reference/sts/rest
60//! [Workforce Identity Federation]: https://cloud.google.com/iam/docs/workforce-identity-federation
61
62use crate::access_boundary::{CredentialsWithAccessBoundary, external_account_lookup_url};
63use crate::build_errors::Error as BuilderError;
64use crate::constants::STS_OAUTH_TOKEN_URL;
65use crate::credentials::dynamic::{AccessTokenCredentialsProvider, CredentialsProvider};
66use crate::credentials::{AccessToken, AccessTokenCredentials, CacheableResource, Credentials};
67use crate::errors::{self, CredentialsError};
68use crate::headers_util::AuthHeadersBuilder;
69use crate::retry::Builder as RetryTokenProviderBuilder;
70use crate::token::{CachedTokenProvider, Token, TokenProvider};
71use crate::token_cache::TokenCache;
72use crate::{BuildResult, Result};
73use google_cloud_gax::backoff_policy::BackoffPolicyArg;
74use google_cloud_gax::retry_policy::RetryPolicyArg;
75use google_cloud_gax::retry_throttler::RetryThrottlerArg;
76use http::{Extensions, HeaderMap};
77use reqwest::Client;
78use serde_json::Value;
79use std::sync::Mutex;
80use tokio::time::{Duration, Instant};
81
82/// A builder for constructing `external_account_authorized_user` [Credentials].
83///
84/// # Example
85/// ```
86/// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
87/// # async fn sample() -> anyhow::Result<()> {
88/// let authorized_user = serde_json::json!({ /* add details here */ });
89/// let credentials = Builder::new(authorized_user).build()?;
90/// # Ok(()) }
91/// ```
92pub struct Builder {
93    authorized_user: Value,
94    quota_project_id: Option<String>,
95    token_url: Option<String>,
96    universe_domain: Option<String>,
97    retry_builder: RetryTokenProviderBuilder,
98    iam_endpoint_override: Option<String>,
99}
100
101impl Builder {
102    /// Creates a new builder using an `external_account_authorized_user` JSON value.
103    ///
104    /// This JSON is typically generated when a workforce identity federation
105    /// user authenticates using `gcloud auth application-default login`.
106    pub fn new(authorized_user: Value) -> Self {
107        Self {
108            authorized_user,
109            quota_project_id: None,
110            token_url: None,
111            universe_domain: None,
112            retry_builder: RetryTokenProviderBuilder::default(),
113            iam_endpoint_override: None,
114        }
115    }
116
117    /// Sets the URL of the STS endpoint used to refresh access tokens.
118    ///
119    /// Any value provided here overrides a `token_url` value from the input JSON.
120    /// Defaults to `https://sts.googleapis.com/v1/oauthtoken` if not
121    /// specified here or in the JSON.
122    ///
123    /// # Example
124    /// ```
125    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
126    /// let authorized_user = serde_json::json!({ /* add details here */ });
127    /// let credentials = Builder::new(authorized_user)
128    ///     .with_token_url("https://sts-FOOBAR.p.googleapis.com/v1/oauthtoken")
129    ///     .build();
130    /// ```
131    pub fn with_token_url<S: Into<String>>(mut self, token_url: S) -> Self {
132        self.token_url = Some(token_url.into());
133        self
134    }
135
136    /// Sets the [quota project] for these credentials.
137    ///
138    /// Any value set here overrides a `quota_project_id` value from the
139    /// input JSON.
140    ///
141    /// # Example
142    /// ```
143    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
144    /// let authorized_user = serde_json::json!({ /* add details here */ });
145    /// let credentials = Builder::new(authorized_user)
146    ///     .with_quota_project_id("my-project")
147    ///     .build();
148    /// ```
149    ///
150    /// [quota project]: https://cloud.google.com/docs/quotas/quota-project
151    pub fn with_quota_project_id<S: Into<String>>(mut self, quota_project_id: S) -> Self {
152        self.quota_project_id = Some(quota_project_id.into());
153        self
154    }
155
156    /// Sets the universe domain for these credentials.
157    ///
158    /// Any value set here overrides a `universe_domain` value from the
159    /// input JSON.
160    ///
161    /// # Example
162    /// ```
163    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
164    /// let authorized_user = serde_json::json!({ /* add details here */ });
165    /// let credentials = Builder::new(authorized_user)
166    ///     .with_universe_domain("googleapis.com")
167    ///     .build();
168    /// ```
169    pub fn with_universe_domain<S: Into<String>>(mut self, universe_domain: S) -> Self {
170        self.universe_domain = Some(universe_domain.into());
171        self
172    }
173
174    // Only to satisfy ADC credential builder. The STS refresh token grant
175    // does not accept scopes; the token has the scopes granted at login.
176    pub(crate) fn with_scopes<I, S>(self, _scopes: I) -> Self
177    where
178        I: IntoIterator<Item = S>,
179        S: Into<String>,
180    {
181        self
182    }
183
184    /// Configure the retry policy for fetching tokens.
185    ///
186    /// The retry policy controls how to handle retries, and sets limits on
187    /// the number of attempts or the total time spent retrying.
188    ///
189    /// ```
190    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
191    /// # async fn sample() -> anyhow::Result<()> {
192    /// use google_cloud_gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
193    /// let authorized_user = serde_json::json!({
194    ///     "type": "external_account_authorized_user",
195    ///     "client_id": "YOUR_CLIENT_ID",
196    ///     "client_secret": "YOUR_CLIENT_SECRET",
197    ///     "refresh_token": "YOUR_REFRESH_TOKEN",
198    /// });
199    /// let credentials = Builder::new(authorized_user)
200    ///     .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
201    ///     .build()?;
202    /// # Ok(()) }
203    /// ```
204    pub fn with_retry_policy<V: Into<RetryPolicyArg>>(mut self, v: V) -> Self {
205        self.retry_builder = self.retry_builder.with_retry_policy(v.into());
206        self
207    }
208
209    /// Configure the retry backoff policy.
210    ///
211    /// The backoff policy controls how long to wait in between retry attempts.
212    ///
213    /// ```
214    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
215    /// # async fn sample() -> anyhow::Result<()> {
216    /// use google_cloud_gax::exponential_backoff::ExponentialBackoff;
217    /// let authorized_user = serde_json::json!({
218    ///     "type": "external_account_authorized_user",
219    ///     "client_id": "YOUR_CLIENT_ID",
220    ///     "client_secret": "YOUR_CLIENT_SECRET",
221    ///     "refresh_token": "YOUR_REFRESH_TOKEN",
222    /// });
223    /// let credentials = Builder::new(authorized_user)
224    ///     .with_backoff_policy(ExponentialBackoff::default())
225    ///     .build()?;
226    /// # Ok(()) }
227    /// ```
228    pub fn with_backoff_policy<V: Into<BackoffPolicyArg>>(mut self, v: V) -> Self {
229        self.retry_builder = self.retry_builder.with_backoff_policy(v.into());
230        self
231    }
232
233    /// Configure the retry throttler.
234    ///
235    /// Advanced applications may want to configure a retry throttler to
236    /// [Address Cascading Failures] and when [Handling Overload] conditions.
237    /// The authentication library throttles its retry loop, using a policy to
238    /// control the throttling algorithm. Use this method to fine tune or
239    /// customize the default retry throttler.
240    ///
241    /// [Handling Overload]: https://sre.google/sre-book/handling-overload/
242    /// [Address Cascading Failures]: https://sre.google/sre-book/addressing-cascading-failures/
243    ///
244    /// ```
245    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
246    /// # async fn sample() -> anyhow::Result<()> {
247    /// use google_cloud_gax::retry_throttler::AdaptiveThrottler;
248    /// let authorized_user = serde_json::json!({
249    ///     "type": "external_account_authorized_user",
250    ///     "client_id": "YOUR_CLIENT_ID",
251    ///     "client_secret": "YOUR_CLIENT_SECRET",
252    ///     "refresh_token": "YOUR_REFRESH_TOKEN",
253    /// });
254    /// let credentials = Builder::new(authorized_user)
255    ///     .with_retry_throttler(AdaptiveThrottler::default())
256    ///     .build()?;
257    /// # Ok(()) }
258    /// ```
259    pub fn with_retry_throttler<V: Into<RetryThrottlerArg>>(mut self, v: V) -> Self {
260        self.retry_builder = self.retry_builder.with_retry_throttler(v.into());
261        self
262    }
263
264    #[cfg(all(test, google_cloud_unstable_trust_boundaries))]
265    fn maybe_iam_endpoint_override(mut self, iam_endpoint_override: Option<String>) -> Self {
266        self.iam_endpoint_override = iam_endpoint_override;
267        self
268    }
269
270    /// Returns a [Credentials] instance with the configured settings.
271    ///
272    /// # Errors
273    ///
274    /// Returns a [BuilderError] if the JSON provided to [`Builder::new`]
275    /// cannot be deserialized into the expected format. This typically happens
276    /// if the JSON value is malformed or missing required fields.
277    pub fn build(self) -> BuildResult<Credentials> {
278        Ok(self.build_credentials()?.into())
279    }
280
281    /// Returns an [AccessTokenCredentials] instance with the configured settings.
282    ///
283    /// # Example
284    ///
285    /// ```
286    /// # use google_cloud_auth::credentials::external_account_authorized_user::Builder;
287    /// # use google_cloud_auth::credentials::{AccessTokenCredentials, AccessTokenCredentialsProvider};
288    /// # async fn sample() -> anyhow::Result<()> {
289    /// let authorized_user = serde_json::json!({
290    ///     "type": "external_account_authorized_user",
291    ///     "client_id": "YOUR_CLIENT_ID",
292    ///     "client_secret": "YOUR_CLIENT_SECRET",
293    ///     "refresh_token": "YOUR_REFRESH_TOKEN",
294    /// });
295    /// let credentials: AccessTokenCredentials = Builder::new(authorized_user)
296    ///     .build_access_token_credentials()?;
297    /// let access_token = credentials.access_token().await?;
298    /// println!("Token: {}", access_token.token);
299    /// # Ok(()) }
300    /// ```
301    ///
302    /// # Errors
303    ///
304    /// Returns a [BuilderError] if the JSON provided to [`Builder::new`]
305    /// cannot be deserialized into the expected format. This typically happens
306    /// if the JSON value is malformed or missing required fields.
307    pub fn build_access_token_credentials(self) -> BuildResult<AccessTokenCredentials> {
308        Ok(self.build_credentials()?.into())
309    }
310
311    fn build_credentials(
312        self,
313    ) -> BuildResult<
314        CredentialsWithAccessBoundary<ExternalAccountAuthorizedUserCredentials<TokenCache>>,
315    > {
316        let authorized_user =
317            serde_json::from_value::<ExternalAccountAuthorizedUser>(self.authorized_user)
318                .map_err(BuilderError::parsing)?;
319
320        let universe_domain = self.universe_domain.or(authorized_user.universe_domain);
321        let token_url = self
322            .token_url
323            .or(authorized_user.token_url)
324            .unwrap_or_else(|| STS_OAUTH_TOKEN_URL.to_string());
325        let quota_project_id = self.quota_project_id.or(authorized_user.quota_project_id);
326
327        let access_boundary_url = authorized_user.audience.as_deref().and_then(|audience| {
328            external_account_lookup_url(audience, self.iam_endpoint_override.as_deref())
329        });
330
331        let token_provider = ExternalAccountAuthorizedUserTokenProvider {
332            client: Client::new(),
333            client_id: authorized_user.client_id,
334            client_secret: authorized_user.client_secret,
335            refresh_token: Mutex::new(authorized_user.refresh_token),
336            token_url,
337        };
338        let token_provider = TokenCache::new(self.retry_builder.build(token_provider));
339
340        let creds = ExternalAccountAuthorizedUserCredentials {
341            token_provider,
342            quota_project_id,
343            universe_domain,
344        };
345
346        Ok(CredentialsWithAccessBoundary::new(
347            creds,
348            access_boundary_url,
349        ))
350    }
351}
352
353struct ExternalAccountAuthorizedUserTokenProvider {
354    client: Client,
355    client_id: String,
356    client_secret: String,
357    // STS may rotate the refresh token, returning a new one with each access
358    // token. The most recent refresh token is used for the next request.
359    refresh_token: Mutex<String>,
360    token_url: String,
361}
362
363impl std::fmt::Debug for ExternalAccountAuthorizedUserTokenProvider {
364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365        f.debug_struct("ExternalAccountAuthorizedUserTokenProvider")
366            .field("client_id", &self.client_id)
367            .field("client_secret", &"[censored]")
368            .field("refresh_token", &"[censored]")
369            .field("token_url", &self.token_url)
370            .finish()
371    }
372}
373
374#[async_trait::async_trait]
375impl TokenProvider for ExternalAccountAuthorizedUserTokenProvider {
376    async fn token(&self) -> Result<Token> {
377        let refresh_token = self
378            .refresh_token
379            .lock()
380            .expect("refresh token mutex is never poisoned")
381            .clone();
382        let params = [
383            ("grant_type", "refresh_token"),
384            ("refresh_token", refresh_token.as_str()),
385        ];
386        let resp = self
387            .client
388            .post(self.token_url.as_str())
389            .basic_auth(&self.client_id, Some(&self.client_secret))
390            .form(&params)
391            .send()
392            .await
393            .map_err(|e| errors::from_http_error(e, MSG))?;
394
395        if !resp.status().is_success() {
396            let err = errors::from_http_response(resp, MSG).await;
397            return Err(err);
398        }
399        let response = resp.json::<RefreshResponse>().await.map_err(|e| {
400            let retryable = !e.is_decode();
401            CredentialsError::from_source(retryable, e)
402        })?;
403
404        if let Some(new_refresh_token) = response.refresh_token {
405            *self
406                .refresh_token
407                .lock()
408                .expect("refresh token mutex is never poisoned") = new_refresh_token;
409        }
410
411        Ok(Token {
412            token: response.access_token,
413            token_type: response.token_type,
414            expires_at: Some(Instant::now() + Duration::from_secs(response.expires_in)),
415            metadata: None,
416        })
417    }
418}
419
420const MSG: &str = "failed to refresh external account authorized user access token";
421
422#[derive(Debug)]
423struct ExternalAccountAuthorizedUserCredentials<T>
424where
425    T: CachedTokenProvider,
426{
427    token_provider: T,
428    quota_project_id: Option<String>,
429    universe_domain: Option<String>,
430}
431
432#[async_trait::async_trait]
433impl<T> CredentialsProvider for ExternalAccountAuthorizedUserCredentials<T>
434where
435    T: CachedTokenProvider,
436{
437    async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
438        let token = self.token_provider.token(extensions).await?;
439
440        AuthHeadersBuilder::new(&token)
441            .maybe_quota_project_id(self.quota_project_id.as_deref())
442            .build()
443    }
444
445    async fn universe_domain(&self) -> Option<String> {
446        self.universe_domain.clone()
447    }
448}
449
450#[async_trait::async_trait]
451impl<T> AccessTokenCredentialsProvider for ExternalAccountAuthorizedUserCredentials<T>
452where
453    T: CachedTokenProvider,
454{
455    async fn access_token(&self) -> Result<AccessToken> {
456        let token = self.token_provider.token(Extensions::new()).await?;
457        token.into()
458    }
459}
460
461/// The `external_account_authorized_user` file format.
462///
463/// The file may also contain `token_info_url` and `revoke_url`, which are
464/// not needed to refresh access tokens and are ignored.
465#[derive(Debug, PartialEq, serde::Deserialize)]
466struct ExternalAccountAuthorizedUser {
467    audience: Option<String>,
468    client_id: String,
469    client_secret: String,
470    refresh_token: String,
471    token_url: Option<String>,
472    quota_project_id: Option<String>,
473    universe_domain: Option<String>,
474}
475
476#[derive(Debug, PartialEq, serde::Deserialize, serde::Serialize)]
477struct RefreshResponse {
478    access_token: String,
479    token_type: String,
480    expires_in: u64,
481    #[serde(skip_serializing_if = "Option::is_none")]
482    refresh_token: Option<String>,
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use crate::credentials::QUOTA_PROJECT_KEY;
489    use crate::credentials::tests::{
490        get_headers_from_cache, get_mock_auth_retry_policy, get_mock_backoff_policy,
491        get_mock_retry_throttler, get_token_from_headers,
492    };
493    use base64::Engine;
494    use http::header::AUTHORIZATION;
495    use httptest::matchers::{all_of, contains, request, url_decoded};
496    use httptest::responders::{json_encoded, status_code};
497    use httptest::{Expectation, Server, cycle};
498
499    type TestResult = anyhow::Result<()>;
500
501    fn authorized_user_json(token_url: String) -> Value {
502        serde_json::json!({
503            "type": "external_account_authorized_user",
504            "audience": "//iam.googleapis.com/locations/global/workforcePools/pool/providers/provider",
505            "client_id": "test-client-id",
506            "client_secret": "test-client-secret",
507            "refresh_token": "test-refresh-token",
508            "token_url": token_url,
509            "token_info_url": "https://sts.googleapis.com/v1/introspect",
510        })
511    }
512
513    fn expected_basic_auth() -> String {
514        let encoded =
515            base64::engine::general_purpose::STANDARD.encode("test-client-id:test-client-secret");
516        format!("Basic {encoded}")
517    }
518
519    fn response(refresh_token: Option<&str>) -> RefreshResponse {
520        RefreshResponse {
521            access_token: "test-access-token".to_string(),
522            token_type: "Bearer".to_string(),
523            expires_in: 3600,
524            refresh_token: refresh_token.map(str::to_string),
525        }
526    }
527
528    #[test]
529    fn from_json_full() {
530        let json = serde_json::json!({
531            "type": "external_account_authorized_user",
532            "audience": "test-audience",
533            "client_id": "test-client-id",
534            "client_secret": "test-client-secret",
535            "refresh_token": "test-refresh-token",
536            "token_url": "test-token-url",
537            "token_info_url": "test-token-info-url",
538            "revoke_url": "test-revoke-url",
539            "quota_project_id": "test-project",
540            "universe_domain": "test-universe",
541        });
542        let expected = ExternalAccountAuthorizedUser {
543            audience: Some("test-audience".to_string()),
544            client_id: "test-client-id".to_string(),
545            client_secret: "test-client-secret".to_string(),
546            refresh_token: "test-refresh-token".to_string(),
547            token_url: Some("test-token-url".to_string()),
548            quota_project_id: Some("test-project".to_string()),
549            universe_domain: Some("test-universe".to_string()),
550        };
551        let actual = serde_json::from_value::<ExternalAccountAuthorizedUser>(json).unwrap();
552        assert_eq!(actual, expected);
553    }
554
555    #[test]
556    fn builder_missing_required_fields() {
557        let json_full = authorized_user_json("test-token-url".to_string());
558        for required_field in ["client_id", "client_secret", "refresh_token"] {
559            let mut json = json_full.clone();
560            json[required_field].take();
561            let err = Builder::new(json).build().unwrap_err();
562            assert!(err.is_parsing(), "{required_field}: {err:?}");
563        }
564    }
565
566    #[test]
567    fn debug_token_provider() {
568        let provider = ExternalAccountAuthorizedUserTokenProvider {
569            client: Client::new(),
570            client_id: "test-client-id".to_string(),
571            client_secret: "test-client-secret".to_string(),
572            refresh_token: Mutex::new("test-refresh-token".to_string()),
573            token_url: STS_OAUTH_TOKEN_URL.to_string(),
574        };
575        let fmt = format!("{provider:?}");
576        assert!(fmt.contains("test-client-id"), "{fmt}");
577        assert!(!fmt.contains("test-client-secret"), "{fmt}");
578        assert!(!fmt.contains("test-refresh-token"), "{fmt}");
579        assert!(fmt.contains(STS_OAUTH_TOKEN_URL), "{fmt}");
580    }
581
582    #[tokio::test]
583    async fn universe_domain() -> TestResult {
584        let json = authorized_user_json("test-token-url".to_string());
585        let creds = Builder::new(json.clone()).build()?;
586        assert_eq!(creds.universe_domain().await, None);
587
588        let mut json = json;
589        json["universe_domain"] = "my-universe.com".into();
590        let creds = Builder::new(json.clone()).build()?;
591        assert_eq!(
592            creds.universe_domain().await.as_deref(),
593            Some("my-universe.com")
594        );
595
596        let creds = Builder::new(json)
597            .with_universe_domain("my-override.com")
598            .build()?;
599        assert_eq!(
600            creds.universe_domain().await.as_deref(),
601            Some("my-override.com")
602        );
603        Ok(())
604    }
605
606    #[tokio::test(start_paused = true)]
607    async fn token_provider_success() -> TestResult {
608        let server = Server::run();
609        server.expect(
610            Expectation::matching(all_of![
611                request::method_path("POST", "/token"),
612                request::headers(contains(("authorization", expected_basic_auth()))),
613                request::headers(contains((
614                    "content-type",
615                    "application/x-www-form-urlencoded"
616                ))),
617                request::body(url_decoded(contains(("grant_type", "refresh_token")))),
618                request::body(url_decoded(contains((
619                    "refresh_token",
620                    "test-refresh-token"
621                )))),
622            ])
623            .respond_with(json_encoded(response(None))),
624        );
625
626        let tp = ExternalAccountAuthorizedUserTokenProvider {
627            client: Client::new(),
628            client_id: "test-client-id".to_string(),
629            client_secret: "test-client-secret".to_string(),
630            refresh_token: Mutex::new("test-refresh-token".to_string()),
631            token_url: server.url("/token").to_string(),
632        };
633        let now = Instant::now();
634        let token = tp.token().await?;
635        assert_eq!(token.token, "test-access-token");
636        assert_eq!(token.token_type, "Bearer");
637        assert_eq!(token.expires_at, Some(now + Duration::from_secs(3600)));
638        Ok(())
639    }
640
641    #[tokio::test]
642    async fn token_provider_missing_response_fields_fails() -> TestResult {
643        let server = Server::run();
644        server.expect(
645            Expectation::matching(request::path("/token")).respond_with(cycle![
646                json_encoded(serde_json::json!({
647                    "access_token": "test-access-token",
648                    "expires_in": 3600,
649                })),
650                json_encoded(serde_json::json!({
651                    "access_token": "test-access-token",
652                    "token_type": "Bearer",
653                })),
654            ]),
655        );
656
657        let creds = Builder::new(authorized_user_json(server.url("/token").to_string())).build()?;
658        for _ in 0..2 {
659            let err = creds.headers(Extensions::new()).await.unwrap_err();
660            assert!(!err.is_transient(), "{err:?}");
661        }
662        Ok(())
663    }
664
665    #[tokio::test]
666    async fn token_provider_rotates_refresh_token() -> TestResult {
667        let server = Server::run();
668        server.expect(
669            Expectation::matching(all_of![
670                request::path("/token"),
671                request::body(url_decoded(contains((
672                    "refresh_token",
673                    "test-refresh-token"
674                )))),
675            ])
676            .times(1)
677            .respond_with(json_encoded(response(Some("rotated-refresh-token")))),
678        );
679        server.expect(
680            Expectation::matching(all_of![
681                request::path("/token"),
682                request::body(url_decoded(contains((
683                    "refresh_token",
684                    "rotated-refresh-token"
685                )))),
686            ])
687            .times(1)
688            .respond_with(json_encoded(response(None))),
689        );
690
691        let tp = ExternalAccountAuthorizedUserTokenProvider {
692            client: Client::new(),
693            client_id: "test-client-id".to_string(),
694            client_secret: "test-client-secret".to_string(),
695            refresh_token: Mutex::new("test-refresh-token".to_string()),
696            token_url: server.url("/token").to_string(),
697        };
698        tp.token().await?;
699        tp.token().await?;
700        assert_eq!(
701            *tp.refresh_token.lock().unwrap(),
702            "rotated-refresh-token".to_string()
703        );
704        Ok(())
705    }
706
707    #[tokio::test]
708    async fn credentials_with_quota_project_and_caching() -> TestResult {
709        let mut server = Server::run();
710        server.expect(
711            Expectation::matching(request::path("/token"))
712                .times(1)
713                .respond_with(json_encoded(response(None))),
714        );
715
716        let mut json = authorized_user_json("unused".to_string());
717        json["quota_project_id"] = "json-project".into();
718        let creds = Builder::new(json)
719            .with_token_url(server.url("/token").to_string())
720            .with_quota_project_id("test-project")
721            .build()?;
722
723        for _ in 0..2 {
724            let headers = get_headers_from_cache(creds.headers(Extensions::new()).await?)?;
725            assert_eq!(headers.len(), 2, "{headers:?}");
726            let token = headers.get(AUTHORIZATION).unwrap();
727            assert_eq!(token, "Bearer test-access-token");
728            assert!(token.is_sensitive());
729            assert_eq!(headers.get(QUOTA_PROJECT_KEY).unwrap(), "test-project");
730        }
731        server.verify_and_clear();
732        Ok(())
733    }
734
735    #[tokio::test]
736    async fn access_token_credentials() -> TestResult {
737        let server = Server::run();
738        server.expect(
739            Expectation::matching(request::path("/token"))
740                .respond_with(json_encoded(response(None))),
741        );
742
743        let creds = Builder::new(authorized_user_json(server.url("/token").to_string()))
744            .build_access_token_credentials()?;
745        let token = creds.access_token().await?;
746        assert_eq!(token.token, "test-access-token");
747        Ok(())
748    }
749
750    #[tokio::test]
751    async fn retries_on_transient_failures() -> TestResult {
752        let mut server = Server::run();
753        server.expect(
754            Expectation::matching(request::path("/token"))
755                .times(3)
756                .respond_with(cycle![
757                    status_code(503).body("try-again"),
758                    status_code(503).body("try-again"),
759                    json_encoded(response(None)),
760                ]),
761        );
762
763        let creds = Builder::new(authorized_user_json(server.url("/token").to_string()))
764            .with_retry_policy(get_mock_auth_retry_policy(3))
765            .with_backoff_policy(get_mock_backoff_policy())
766            .with_retry_throttler(get_mock_retry_throttler())
767            .build()?;
768        let token = get_token_from_headers(creds.headers(Extensions::new()).await?);
769        assert_eq!(token.as_deref(), Some("test-access-token"));
770        server.verify_and_clear();
771        Ok(())
772    }
773
774    #[tokio::test]
775    async fn does_not_retry_on_non_transient_failures() -> TestResult {
776        let mut server = Server::run();
777        server.expect(
778            Expectation::matching(request::path("/token"))
779                .times(1)
780                .respond_with(status_code(401)),
781        );
782
783        let creds = Builder::new(authorized_user_json(server.url("/token").to_string()))
784            .with_retry_policy(get_mock_auth_retry_policy(3))
785            .with_backoff_policy(get_mock_backoff_policy())
786            .with_retry_throttler(get_mock_retry_throttler())
787            .build()?;
788        let err = creds.headers(Extensions::new()).await.unwrap_err();
789        assert!(!err.is_transient(), "{err:?}");
790        server.verify_and_clear();
791        Ok(())
792    }
793
794    #[tokio::test]
795    async fn malformed_response_is_not_retryable() -> TestResult {
796        let server = Server::run();
797        server.expect(
798            Expectation::matching(request::path("/token"))
799                .respond_with(json_encoded("bad json".to_string())),
800        );
801
802        let creds = Builder::new(authorized_user_json(server.url("/token").to_string())).build()?;
803        let err = creds.headers(Extensions::new()).await.unwrap_err();
804        assert!(!err.is_transient(), "{err:?}");
805        Ok(())
806    }
807
808    #[tokio::test]
809    #[cfg(google_cloud_unstable_trust_boundaries)]
810    async fn e2e_access_boundary() -> TestResult {
811        use crate::credentials::tests::get_access_boundary_from_headers;
812
813        let server = Server::run();
814        server.expect(
815            Expectation::matching(request::method_path("POST", "/token"))
816                .respond_with(json_encoded(response(None))),
817        );
818        server.expect(
819            Expectation::matching(request::method_path(
820                "GET",
821                "/v1/locations/global/workforcePools/pool/allowedLocations",
822            ))
823            .respond_with(json_encoded(serde_json::json!({
824                "locations": ["us-central1"],
825                "encodedLocations": "0x1234"
826            }))),
827        );
828
829        let iam_endpoint = server.url("").to_string().trim_end_matches('/').to_string();
830
831        let creds = Builder::new(authorized_user_json(server.url("/token").to_string()))
832            .maybe_iam_endpoint_override(Some(iam_endpoint))
833            .build_credentials()?;
834
835        creds.wait_for_boundary().await;
836
837        let headers = creds.headers(Extensions::new()).await?;
838        let token = get_token_from_headers(headers.clone());
839        let access_boundary = get_access_boundary_from_headers(headers);
840
841        assert_eq!(token.as_deref(), Some("test-access-token"));
842        assert_eq!(access_boundary.as_deref(), Some("0x1234"));
843        Ok(())
844    }
845}