Skip to main content

google_cloud_auth/
credentials.rs

1// Copyright 2024 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//! Types and functions to work with Google Cloud authentication [Credentials].
16//!
17//! [Credentials]: https://cloud.google.com/docs/authentication#credentials
18
19use crate::build_errors::Error as BuilderError;
20use crate::constants::GOOGLE_CLOUD_QUOTA_PROJECT_VAR;
21use crate::errors::{self, CredentialsError};
22use crate::token::Token;
23use crate::{BuildResult, Result};
24use http::{Extensions, HeaderMap};
25use serde_json::Value;
26use std::future::Future;
27use std::sync::Arc;
28use std::sync::atomic::{AtomicU64, Ordering};
29pub mod anonymous;
30pub mod api_key_credentials;
31pub(crate) mod crypto_provider;
32pub mod external_account;
33pub mod external_account_authorized_user;
34pub(crate) mod external_account_sources;
35#[cfg(feature = "gdch")]
36pub mod gdch;
37#[cfg(feature = "idtoken")]
38pub mod idtoken;
39pub mod impersonated;
40pub(crate) mod internal;
41pub mod mds;
42pub mod service_account;
43pub mod subject_token;
44pub mod user_account;
45pub(crate) const QUOTA_PROJECT_KEY: &str = "x-goog-user-project";
46
47/// Represents an Entity Tag for a [CacheableResource].
48///
49/// An `EntityTag` is an opaque token that can be used to determine if a
50/// cached resource has changed. The specific format of this tag is an
51/// implementation detail.
52///
53/// As the name indicates, these are inspired by the ETags prevalent in HTTP
54/// caching protocols. Their implementation is very different, and are only
55/// intended for use within a single program.
56#[derive(Clone, Debug, PartialEq, Default)]
57pub struct EntityTag(u64);
58
59static ENTITY_TAG_GENERATOR: AtomicU64 = AtomicU64::new(0);
60impl EntityTag {
61    /// Creates a new, unique [EntityTag].
62    pub fn new() -> Self {
63        let value = ENTITY_TAG_GENERATOR.fetch_add(1, Ordering::SeqCst);
64        Self(value)
65    }
66}
67
68/// Represents a resource that can be cached, along with its [EntityTag].
69///
70/// This enum is used to provide cacheable data to the consumers of the credential provider.
71/// It allows a data provider to return either new data (with an [EntityTag]) or
72/// indicate that the caller's cached version (identified by a previously provided [EntityTag])
73/// is still valid.
74#[derive(Clone, PartialEq, Debug)]
75#[allow(clippy::exhaustive_enums)]
76pub enum CacheableResource<T> {
77    /// Indicates that the resource has not been modified and the cached version is still valid.
78    NotModified,
79    /// Contains the new resource data and its associated [EntityTag].
80    New {
81        /// The entity tag for the new resource.
82        entity_tag: EntityTag,
83        /// The new resource data.
84        data: T,
85    },
86}
87
88/// An implementation of [crate::credentials::CredentialsProvider].
89///
90/// Represents a [Credentials] used to obtain the auth request headers.
91///
92/// In general, [Credentials][credentials-link] are "digital object that provide
93/// proof of identity", the archetype may be a username and password
94/// combination, but a private RSA key may be a better example.
95///
96/// Modern authentication protocols do not send the credentials to authenticate
97/// with a service. Even when sent over encrypted transports, the credentials
98/// may be accidentally exposed via logging or may be captured if there are
99/// errors in the transport encryption. Because the credentials are often
100/// long-lived, that risk of exposure is also long-lived.
101///
102/// Instead, modern authentication protocols exchange the credentials for a
103/// time-limited [Token][token-link], a digital object that shows the caller was
104/// in possession of the credentials. Because tokens are time limited, risk of
105/// misuse is also time limited. Tokens may be further restricted to only a
106/// certain subset of the RPCs in the service, or even to specific resources, or
107/// only when used from a given machine (virtual or not). Further limiting the
108/// risks associated with any leaks of these tokens.
109///
110/// This struct also abstracts token sources that are not backed by a specific
111/// digital object. The canonical example is the [Metadata Service]. This
112/// service is available in many Google Cloud environments, including
113/// [Google Compute Engine], and [Google Kubernetes Engine].
114///
115/// [credentials-link]: https://cloud.google.com/docs/authentication#credentials
116/// [token-link]: https://cloud.google.com/docs/authentication#token
117/// [Metadata Service]: https://cloud.google.com/compute/docs/metadata/overview
118/// [Google Compute Engine]: https://cloud.google.com/products/compute
119/// [Google Kubernetes Engine]: https://cloud.google.com/kubernetes-engine
120#[derive(Clone, Debug)]
121pub struct Credentials {
122    // We use an `Arc` to hold the inner implementation.
123    //
124    // Credentials may be shared across threads (`Send + Sync`), so an `Rc`
125    // will not do.
126    //
127    // They also need to derive `Clone`, as the
128    // `google_cloud_gax::http_client::ReqwestClient`s which hold them derive `Clone`. So a
129    // `Box` will not do.
130    inner: Arc<dyn dynamic::CredentialsProvider>,
131}
132
133impl<T> std::convert::From<T> for Credentials
134where
135    T: crate::credentials::CredentialsProvider + Send + Sync + 'static,
136{
137    fn from(value: T) -> Self {
138        Self {
139            inner: Arc::new(value),
140        }
141    }
142}
143
144impl Credentials {
145    /// Asynchronously constructs the auth headers.
146    ///
147    /// Different auth tokens are sent via different headers. The
148    /// [Credentials] constructs the headers (and header values) that should be
149    /// sent with a request. If the authentication provider requires it, headers
150    /// are cached, and a background task periodically refreshes any expired
151    /// tokens.
152    ///
153    /// # Parameters
154    /// * `extensions` - An `http::Extensions` map that can be used to pass additional
155    ///   context to the credential provider. If the caller does not need to compute derived values
156    ///   from the headers then do not provide an `EntityTag`. The credentials will either return
157    ///   `Err(...)` or `Ok(CacheableResource::New {})` in this case. Since the credentials
158    ///   already cache the headers, then it can use the results directly. Some applications need
159    ///   to compute values derived from the result, and want to avoid that computation if the
160    ///   headers have not changed. In that case, provide the `EntityTag` returned from a previous
161    ///   call. If the underlying authentication data has not changed, this method returns
162    ///   `Ok(CacheableResource::NotModified)` and you can use the same derived data. If the
163    ///   caller provides an `EntityTag` and the underlying authentication data has changed, this
164    ///   function returns `Ok(CacheableResource::New { ... })`. That result invalidates the
165    ///   tag, and provides new values for the headers.
166    ///
167    /// # Returns
168    /// A `Result` containing:
169    /// * `Ok(CacheableResource::New { entity_tag, data })`: If new or updated headers
170    ///   are available.
171    /// * `Ok(CacheableResource::NotModified)`: If the headers have not changed since
172    ///   the ETag provided via `extensions` was issued.
173    /// * `Err(CredentialsError)`: If an error occurs while trying to fetch or
174    ///   generating the headers.
175    pub async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
176        self.inner.headers(extensions).await
177    }
178
179    /// Retrieves the universe domain associated with the credentials, if any.
180    ///
181    /// A "universe" is an isolated Google Cloud environment, such as the public
182    /// cloud or a sovereign/air-gapped deployment. The universe domain is used to
183    /// construct base URLs for API endpoints within that environment.
184    ///
185    /// By default, this returns `None`, which means the default universe domain of
186    /// `googleapis.com`. You should only override this if your application is operating
187    /// within a custom Cloud universe and needs to direct authentication and service
188    /// requests to a different base endpoint.
189    pub async fn universe_domain(&self) -> Option<String> {
190        self.inner.universe_domain().await
191    }
192}
193
194/// An implementation of [crate::credentials::CredentialsProvider] that can also
195/// provide direct access to the underlying access token.
196///
197/// This struct is returned by the `build_access_token_credentials()` method on
198/// the various credential builders. It can be used to obtain an access token
199/// directly via the `access_token()` method, or it can be converted into a `Credentials`
200/// object to be used with the Google Cloud client libraries.
201#[derive(Clone, Debug)]
202pub struct AccessTokenCredentials {
203    // We use an `Arc` to hold the inner implementation.
204    //
205    // AccessTokenCredentials may be shared across threads (`Send + Sync`), so an `Rc`
206    // will not do.
207    //
208    // They also need to derive `Clone`, as the
209    // `google_cloud_gax::http_client::ReqwestClient`s which hold them derive `Clone`. So a
210    // `Box` will not do.
211    inner: Arc<dyn dynamic::AccessTokenCredentialsProvider>,
212}
213
214impl<T> std::convert::From<T> for AccessTokenCredentials
215where
216    T: crate::credentials::AccessTokenCredentialsProvider + Send + Sync + 'static,
217{
218    fn from(value: T) -> Self {
219        Self {
220            inner: Arc::new(value),
221        }
222    }
223}
224
225impl AccessTokenCredentials {
226    /// Asynchronously retrieves an access token.
227    pub async fn access_token(&self) -> Result<AccessToken> {
228        self.inner.access_token().await
229    }
230}
231
232/// Makes [AccessTokenCredentials] compatible with clients that expect
233/// a [Credentials] and/or a [CredentialsProvider].
234impl CredentialsProvider for AccessTokenCredentials {
235    async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
236        self.inner.headers(extensions).await
237    }
238
239    async fn universe_domain(&self) -> Option<String> {
240        self.inner.universe_domain().await
241    }
242}
243
244/// Represents an OAuth 2.0 access token.
245#[derive(Clone)]
246pub struct AccessToken {
247    /// The access token string.
248    pub token: String,
249}
250
251impl std::fmt::Debug for AccessToken {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("AccessToken")
254            .field("token", &"[censored]")
255            .finish()
256    }
257}
258
259impl std::convert::From<CacheableResource<Token>> for Result<AccessToken> {
260    fn from(token: CacheableResource<Token>) -> Self {
261        match token {
262            CacheableResource::New { data, .. } => Ok(data.into()),
263            CacheableResource::NotModified => Err(errors::CredentialsError::from_msg(
264                false,
265                "Expecting token to be present",
266            )),
267        }
268    }
269}
270
271impl std::convert::From<Token> for AccessToken {
272    fn from(token: Token) -> Self {
273        Self { token: token.token }
274    }
275}
276
277/// A trait for credential types that can provide direct access to an access token.
278///
279/// This trait is primarily intended for interoperability with other libraries that
280/// require a raw access token, or for calling Google Cloud APIs that are not yet
281/// supported by the SDK.
282pub trait AccessTokenCredentialsProvider: CredentialsProvider + std::fmt::Debug {
283    /// Asynchronously retrieves an access token.
284    fn access_token(&self) -> impl Future<Output = Result<AccessToken>> + Send;
285}
286
287/// Represents a [Credentials] used to obtain auth request headers.
288///
289/// In general, [Credentials][credentials-link] are "digital object that
290/// provide proof of identity", the archetype may be a username and password
291/// combination, but a private RSA key may be a better example.
292///
293/// Modern authentication protocols do not send the credentials to
294/// authenticate with a service. Even when sent over encrypted transports,
295/// the credentials may be accidentally exposed via logging or may be
296/// captured if there are errors in the transport encryption. Because the
297/// credentials are often long-lived, that risk of exposure is also
298/// long-lived.
299///
300/// Instead, modern authentication protocols exchange the credentials for a
301/// time-limited [Token][token-link], a digital object that shows the caller
302/// was in possession of the credentials. Because tokens are time limited,
303/// risk of misuse is also time limited. Tokens may be further restricted to
304/// only a certain subset of the RPCs in the service, or even to specific
305/// resources, or only when used from a given machine (virtual or not).
306/// Further limiting the risks associated with any leaks of these tokens.
307///
308/// This struct also abstracts token sources that are not backed by a
309/// specific digital object. The canonical example is the
310/// [Metadata Service]. This service is available in many Google Cloud
311/// environments, including [Google Compute Engine], and
312/// [Google Kubernetes Engine].
313///
314/// # Notes
315///
316/// Application developers who directly use the Auth SDK can use this trait,
317/// along with [crate::credentials::Credentials::from()] to mock the credentials.
318/// Application developers who use the Google Cloud Rust SDK directly should not
319/// need this functionality.
320///
321/// [credentials-link]: https://cloud.google.com/docs/authentication#credentials
322/// [token-link]: https://cloud.google.com/docs/authentication#token
323/// [Metadata Service]: https://cloud.google.com/compute/docs/metadata/overview
324/// [Google Compute Engine]: https://cloud.google.com/products/compute
325/// [Google Kubernetes Engine]: https://cloud.google.com/kubernetes-engine
326pub trait CredentialsProvider: std::fmt::Debug {
327    /// Asynchronously constructs the auth headers.
328    ///
329    /// Different auth tokens are sent via different headers. The
330    /// [Credentials] constructs the headers (and header values) that should be
331    /// sent with a request.
332    ///
333    /// # Parameters
334    /// * `extensions` - An `http::Extensions` map that can be used to pass additional
335    ///   context to the credential provider. For caching purposes, this can include
336    ///   an [EntityTag] from a previously returned [`CacheableResource<HeaderMap>`].
337    ///   If a valid `EntityTag` is provided and the underlying authentication data
338    ///   has not changed, this method returns `Ok(CacheableResource::NotModified)`.
339    ///
340    /// # Returns
341    /// A `Future` that resolves to a `Result` containing:
342    /// * `Ok(CacheableResource::New { entity_tag, data })`: If new or updated headers
343    ///   are available.
344    /// * `Ok(CacheableResource::NotModified)`: If the headers have not changed since
345    ///   the ETag provided via `extensions` was issued.
346    /// * `Err(CredentialsError)`: If an error occurs while trying to fetch or
347    ///   generating the headers.
348    fn headers(
349        &self,
350        extensions: Extensions,
351    ) -> impl Future<Output = Result<CacheableResource<HeaderMap>>> + Send;
352
353    /// Retrieves the universe domain associated with the credentials, if any.
354    fn universe_domain(&self) -> impl Future<Output = Option<String>> + Send;
355}
356
357pub(crate) mod dynamic {
358    use super::Result;
359    use super::{CacheableResource, Extensions, HeaderMap};
360
361    /// A dyn-compatible, crate-private version of `CredentialsProvider`.
362    #[async_trait::async_trait]
363    pub trait CredentialsProvider: Send + Sync + std::fmt::Debug {
364        /// Asynchronously constructs the auth headers.
365        ///
366        /// Different auth tokens are sent via different headers. The
367        /// [Credentials] constructs the headers (and header values) that should be
368        /// sent with a request.
369        ///
370        /// # Parameters
371        /// * `extensions` - An `http::Extensions` map that can be used to pass additional
372        ///   context to the credential provider. For caching purposes, this can include
373        ///   an [EntityTag] from a previously returned [CacheableResource<HeaderMap>].
374        ///   If a valid `EntityTag` is provided and the underlying authentication data
375        ///   has not changed, this method returns `Ok(CacheableResource::NotModified)`.
376        ///
377        /// # Returns
378        /// A `Future` that resolves to a `Result` containing:
379        /// * `Ok(CacheableResource::New { entity_tag, data })`: If new or updated headers
380        ///   are available.
381        /// * `Ok(CacheableResource::NotModified)`: If the headers have not changed since
382        ///   the ETag provided via `extensions` was issued.
383        /// * `Err(CredentialsError)`: If an error occurs while trying to fetch or
384        ///   generating the headers.
385        async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>>;
386
387        /// Retrieves the universe domain associated with the credentials, if any.
388        async fn universe_domain(&self) -> Option<String> {
389            Some("googleapis.com".to_string())
390        }
391    }
392
393    /// The public CredentialsProvider implements the dyn-compatible CredentialsProvider.
394    #[async_trait::async_trait]
395    impl<T> CredentialsProvider for T
396    where
397        T: super::CredentialsProvider + Send + Sync,
398    {
399        async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
400            T::headers(self, extensions).await
401        }
402        async fn universe_domain(&self) -> Option<String> {
403            T::universe_domain(self).await
404        }
405    }
406
407    /// A dyn-compatible, crate-private version of `AccessTokenCredentialsProvider`.
408    #[async_trait::async_trait]
409    pub trait AccessTokenCredentialsProvider:
410        CredentialsProvider + Send + Sync + std::fmt::Debug
411    {
412        async fn access_token(&self) -> Result<super::AccessToken>;
413    }
414
415    #[async_trait::async_trait]
416    impl<T> AccessTokenCredentialsProvider for T
417    where
418        T: super::AccessTokenCredentialsProvider + Send + Sync,
419    {
420        async fn access_token(&self) -> Result<super::AccessToken> {
421            T::access_token(self).await
422        }
423    }
424}
425
426/// A builder for constructing [`Credentials`] instances.
427///
428/// This builder loads credentials according to the standard
429/// [Application Default Credentials (ADC)][ADC-link] strategy.
430/// ADC is the recommended approach for most applications and conforms to
431/// [AIP-4110]. If you need to load credentials from a non-standard location
432/// or source, you can use Builders on the specific credential types.
433///
434/// Common use cases where using ADC would is useful include:
435/// - Your application is deployed to a Google Cloud environment such as
436///   [Google Compute Engine (GCE)][gce-link],
437///   [Google Kubernetes Engine (GKE)][gke-link], or [Cloud Run]. Each of these
438///   deployment environments provides a default service account to the
439///   application, and offers mechanisms to change this default service account
440///   without any code changes to your application.
441/// - You are testing or developing the application on a workstation (physical
442///   or virtual). These credentials will use your preferences as set with
443///   [gcloud auth application-default]. These preferences can be your own
444///   Google Cloud user credentials, or some service account.
445/// - Regardless of where your application is running, you can use the
446///   `GOOGLE_APPLICATION_CREDENTIALS` environment variable to override the
447///   defaults. This environment variable should point to a file containing a
448///   service account key file, or a JSON object describing your user
449///   credentials.
450///
451/// The headers returned by these credentials should be used in the
452/// Authorization HTTP header.
453///
454/// The Google Cloud client libraries for Rust will typically find and use these
455/// credentials automatically if a credentials file exists in the standard ADC
456/// search paths. You might instantiate these credentials if you need to:
457/// - Override the OAuth 2.0 **scopes** being requested for the access token.
458/// - Override the **quota project ID** for billing and quota management.
459///
460/// # Example: fetching headers using ADC
461/// ```
462/// # use google_cloud_auth::credentials::Builder;
463/// # use http::Extensions;
464/// # async fn sample() -> anyhow::Result<()> {
465/// let credentials = Builder::default()
466///     .with_quota_project_id("my-project")
467///     .build()?;
468/// let headers = credentials.headers(Extensions::new()).await?;
469/// println!("Headers: {headers:?}");
470/// # Ok(()) }
471/// ```
472///
473/// [ADC-link]: https://cloud.google.com/docs/authentication/application-default-credentials
474/// [AIP-4110]: https://google.aip.dev/auth/4110
475/// [Cloud Run]: https://cloud.google.com/run
476/// [gce-link]: https://cloud.google.com/products/compute
477/// [gcloud auth application-default]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default
478/// [gke-link]: https://cloud.google.com/kubernetes-engine
479#[derive(Debug)]
480pub struct Builder {
481    quota_project_id: Option<String>,
482    scopes: Option<Vec<String>>,
483    universe_domain: Option<String>,
484}
485
486impl Default for Builder {
487    /// Creates a new builder where credentials will be obtained via [application-default login].
488    ///
489    /// # Example
490    /// ```
491    /// # use google_cloud_auth::credentials::Builder;
492    /// # fn sample() -> anyhow::Result<()> {
493    /// let credentials = Builder::default().build()?;
494    /// # Ok(()) }
495    /// ```
496    ///
497    /// [application-default login]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login
498    fn default() -> Self {
499        Self {
500            quota_project_id: None,
501            scopes: None,
502            universe_domain: None,
503        }
504    }
505}
506
507impl Builder {
508    /// Sets the [quota project] for these credentials.
509    ///
510    /// In some services, you can use an account in one project for authentication
511    /// and authorization, and charge the usage to a different project. This requires
512    /// that the user has `serviceusage.services.use` permissions on the quota project.
513    ///
514    /// ## Important: Precedence
515    /// If the `GOOGLE_CLOUD_QUOTA_PROJECT` environment variable is set,
516    /// its value will be used **instead of** the value provided to this method.
517    ///
518    /// # Example
519    /// ```
520    /// # use google_cloud_auth::credentials::Builder;
521    /// # fn sample() -> anyhow::Result<()> {
522    /// let credentials = Builder::default()
523    ///     .with_quota_project_id("my-project")
524    ///     .build()?;
525    /// # Ok(()) }
526    /// ```
527    ///
528    /// [quota project]: https://cloud.google.com/docs/quotas/quota-project
529    pub fn with_quota_project_id<S: Into<String>>(mut self, quota_project_id: S) -> Self {
530        self.quota_project_id = Some(quota_project_id.into());
531        self
532    }
533
534    /// Sets the [scopes] for these credentials.
535    ///
536    /// `scopes` act as an additional restriction in addition to the IAM permissions
537    /// granted to the principal (user or service account) that creates the token.
538    ///
539    /// `scopes` define the *permissions being requested* for this specific access token
540    /// when interacting with a service. For example,
541    /// `https://www.googleapis.com/auth/devstorage.read_write`.
542    ///
543    /// IAM permissions, on the other hand, define the *underlying capabilities*
544    /// the principal possesses within a system. For example, `storage.buckets.delete`.
545    ///
546    /// The credentials certify that a particular token was created by a certain principal.
547    ///
548    /// When a token generated with specific scopes is used, the request must be permitted
549    /// by both the the principals's underlying IAM permissions and the scopes requested
550    /// for the token.
551    ///
552    /// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
553    pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
554    where
555        I: IntoIterator<Item = S>,
556        S: Into<String>,
557    {
558        self.scopes = Some(scopes.into_iter().map(|s| s.into()).collect());
559        self
560    }
561
562    /// Sets the Google Cloud universe domain for these credentials.
563    ///
564    /// The universe domain is the default service domain for a given Cloud universe.
565    /// If not set, the default will be used.
566    ///
567    /// # Example
568    /// ```
569    /// # use google_cloud_auth::credentials::Builder;
570    /// # fn sample() -> anyhow::Result<()> {
571    /// let credentials = Builder::default()
572    ///     .with_universe_domain("googleapis.com")
573    ///     .build()?;
574    /// # Ok(()) }
575    /// ```
576    pub fn with_universe_domain<S: Into<String>>(mut self, universe_domain: S) -> Self {
577        self.universe_domain = Some(universe_domain.into());
578        self
579    }
580
581    /// Returns a [Credentials] instance with the configured settings.
582    ///
583    /// # Errors
584    ///
585    /// Returns a [CredentialsError] if an unsupported credential type is provided
586    /// or if the JSON value is either malformed or missing required fields.
587    ///
588    /// For more information, on how to generate the JSON for a credential,
589    /// consult the relevant section in the [application-default credentials] guide.
590    ///
591    /// [application-default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials
592    pub fn build(self) -> BuildResult<Credentials> {
593        Ok(self.build_access_token_credentials()?.into())
594    }
595
596    /// Returns an [AccessTokenCredentials] instance with the configured settings.
597    ///
598    /// # Example
599    ///
600    /// ```
601    /// # use google_cloud_auth::credentials::{Builder, AccessTokenCredentials, AccessTokenCredentialsProvider};
602    /// # async fn sample() -> anyhow::Result<()> {
603    /// // This will search for Application Default Credentials and build AccessTokenCredentials.
604    /// let credentials: AccessTokenCredentials = Builder::default()
605    ///     .build_access_token_credentials()?;
606    /// let access_token = credentials.access_token().await?;
607    /// println!("Token: {}", access_token.token);
608    /// # Ok(()) }
609    /// ```
610    ///
611    /// # Errors
612    ///
613    /// Returns a [CredentialsError] if an unsupported credential type is provided
614    /// or if the JSON value is either malformed or missing required fields.
615    ///
616    /// For more information, on how to generate the JSON for a credential,
617    /// consult the relevant section in the [application-default credentials] guide.
618    ///
619    /// [application-default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials
620    pub fn build_access_token_credentials(self) -> BuildResult<AccessTokenCredentials> {
621        let json_data = match load_adc()? {
622            AdcContents::Contents(contents) => {
623                Some(serde_json::from_str(&contents).map_err(BuilderError::parsing)?)
624            }
625            AdcContents::FallbackToMds => None,
626        };
627        let quota_project_id = std::env::var(GOOGLE_CLOUD_QUOTA_PROJECT_VAR)
628            .ok()
629            .or(self.quota_project_id);
630        build_credentials(
631            json_data,
632            quota_project_id,
633            self.scopes,
634            self.universe_domain,
635        )
636    }
637
638    /// Returns a [crate::signer::Signer] instance with the configured settings.
639    ///
640    /// This method automatically loads Application Default Credentials (ADC)
641    /// from the environment and uses them to create a signer.
642    ///
643    /// The returned [crate::signer::Signer] might perform signing locally (e.g. if a service
644    /// account key is found) or via a remote API (e.g. if running on GCE).
645    ///
646    /// # Example
647    ///
648    /// ```
649    /// # use google_cloud_auth::credentials::Builder;
650    /// # use google_cloud_auth::signer::Signer;
651    /// # fn sample() -> anyhow::Result<()> {
652    /// let signer: Signer = Builder::default().build_signer()?;
653    /// # Ok(()) }
654    /// ```
655    pub fn build_signer(self) -> BuildResult<crate::signer::Signer> {
656        let json_data = match load_adc()? {
657            AdcContents::Contents(contents) => {
658                Some(serde_json::from_str(&contents).map_err(BuilderError::parsing)?)
659            }
660            AdcContents::FallbackToMds => None,
661        };
662        let quota_project_id = std::env::var(GOOGLE_CLOUD_QUOTA_PROJECT_VAR)
663            .ok()
664            .or(self.quota_project_id);
665        build_signer(
666            json_data,
667            quota_project_id,
668            self.scopes,
669            self.universe_domain,
670        )
671    }
672}
673
674#[derive(Debug, PartialEq)]
675enum AdcPath {
676    FromEnv(std::path::PathBuf),
677    WellKnown(std::path::PathBuf),
678}
679
680#[derive(Debug, PartialEq)]
681enum AdcContents {
682    Contents(String),
683    FallbackToMds,
684}
685
686fn extract_credential_type(json: &Value) -> BuildResult<&str> {
687    json.get("type")
688        .ok_or_else(|| BuilderError::parsing("no `type` field found."))?
689        .as_str()
690        .ok_or_else(|| BuilderError::parsing("`type` field is not a string."))
691}
692
693/// Applies common optional configurations (quota project ID, scopes) to a
694/// specific credential builder instance and then builds it.
695///
696/// This macro centralizes the logic for optionally calling `.with_quota_project_id()`
697/// and `.with_scopes()` on different underlying credential builders (like
698/// `mds::Builder`, `service_account::Builder`, etc.) before calling `.build()`.
699/// It helps avoid repetitive code in the `build_credentials` function.
700macro_rules! config_builder {
701    ($builder_instance:expr, $quota_project_id_option:expr, $scopes_option:expr, $universe_domain_option:expr, $apply_scopes_closure:expr) => {{
702        let builder = config_common_builder!(
703            $builder_instance,
704            $quota_project_id_option,
705            $scopes_option,
706            $universe_domain_option,
707            $apply_scopes_closure
708        );
709        builder.build_access_token_credentials()
710    }};
711}
712
713/// Applies common optional configurations (quota project ID, scopes) to a
714/// specific credential builder instance and then return a signer for it.
715macro_rules! config_signer {
716    ($builder_instance:expr, $quota_project_id_option:expr, $scopes_option:expr, $universe_domain_option:expr, $apply_scopes_closure:expr) => {{
717        let builder = config_common_builder!(
718            $builder_instance,
719            $quota_project_id_option,
720            $scopes_option,
721            $universe_domain_option,
722            $apply_scopes_closure
723        );
724        builder.build_signer()
725    }};
726}
727
728macro_rules! config_common_builder {
729    ($builder_instance:expr, $quota_project_id_option:expr, $scopes_option:expr, $universe_domain_option:expr, $apply_scopes_closure:expr) => {{
730        let builder = $builder_instance;
731        let builder = $quota_project_id_option
732            .into_iter()
733            .fold(builder, |b, qp| b.with_quota_project_id(qp));
734
735        let builder = $universe_domain_option
736            .into_iter()
737            .fold(builder, |b, ud| b.with_universe_domain(ud));
738
739        let builder = $scopes_option
740            .into_iter()
741            .fold(builder, |b, s| $apply_scopes_closure(b, s));
742
743        builder
744    }};
745}
746
747fn build_credentials(
748    json: Option<Value>,
749    quota_project_id: Option<String>,
750    scopes: Option<Vec<String>>,
751    universe_domain: Option<String>,
752) -> BuildResult<AccessTokenCredentials> {
753    match json {
754        None => config_builder!(
755            mds::Builder::from_adc(),
756            quota_project_id,
757            scopes,
758            universe_domain.clone(),
759            |b: mds::Builder, s: Vec<String>| b.with_scopes(s)
760        ),
761        Some(json) => {
762            let cred_type = extract_credential_type(&json)?;
763            match cred_type {
764                "authorized_user" => {
765                    config_builder!(
766                        user_account::Builder::new(json),
767                        quota_project_id,
768                        scopes,
769                        universe_domain.clone(),
770                        |b: user_account::Builder, s: Vec<String>| b.with_scopes(s)
771                    )
772                }
773                "service_account" => config_builder!(
774                    service_account::Builder::new(json),
775                    quota_project_id,
776                    scopes,
777                    universe_domain.clone(),
778                    |b: service_account::Builder, s: Vec<String>| b
779                        .with_access_specifier(service_account::AccessSpecifier::from_scopes(s))
780                ),
781                "impersonated_service_account" => {
782                    config_builder!(
783                        impersonated::Builder::new(json),
784                        quota_project_id,
785                        scopes,
786                        universe_domain.clone(),
787                        |b: impersonated::Builder, s: Vec<String>| b.with_scopes(s)
788                    )
789                }
790                "external_account" => config_builder!(
791                    external_account::Builder::new(json),
792                    quota_project_id,
793                    scopes,
794                    universe_domain.clone(),
795                    |b: external_account::Builder, s: Vec<String>| b.with_scopes(s)
796                ),
797                "external_account_authorized_user" => config_builder!(
798                    external_account_authorized_user::Builder::new(json),
799                    quota_project_id,
800                    scopes,
801                    universe_domain.clone(),
802                    |b: external_account_authorized_user::Builder, s: Vec<String>| b.with_scopes(s)
803                ),
804                "gdch_service_account" => Err(BuilderError::not_supported(format!(
805                    "{cred_type}, use gdch::Builder directly."
806                ))),
807                _ => Err(BuilderError::unknown_type(cred_type)),
808            }
809        }
810    }
811}
812
813fn build_signer(
814    json: Option<Value>,
815    quota_project_id: Option<String>,
816    scopes: Option<Vec<String>>,
817    universe_domain: Option<String>,
818) -> BuildResult<crate::signer::Signer> {
819    match json {
820        None => config_signer!(
821            mds::Builder::from_adc(),
822            quota_project_id,
823            scopes,
824            universe_domain.clone(),
825            |b: mds::Builder, s: Vec<String>| b.with_scopes(s)
826        ),
827        Some(json) => {
828            let cred_type = extract_credential_type(&json)?;
829            match cred_type {
830                "authorized_user" => Err(BuilderError::not_supported(
831                    "authorized_user signer is not supported",
832                )),
833                "service_account" => config_signer!(
834                    service_account::Builder::new(json),
835                    quota_project_id,
836                    scopes,
837                    universe_domain.clone(),
838                    |b: service_account::Builder, s: Vec<String>| b
839                        .with_access_specifier(service_account::AccessSpecifier::from_scopes(s))
840                ),
841                "impersonated_service_account" => {
842                    config_signer!(
843                        impersonated::Builder::new(json),
844                        quota_project_id,
845                        scopes,
846                        universe_domain.clone(),
847                        |b: impersonated::Builder, s: Vec<String>| b.with_scopes(s)
848                    )
849                }
850                "external_account" => Err(BuilderError::not_supported(
851                    "external_account signer is not supported",
852                )),
853                "external_account_authorized_user" => Err(BuilderError::not_supported(
854                    "external_account_authorized_user signer is not supported",
855                )),
856                "gdch_service_account" => Err(BuilderError::not_supported(
857                    "gdch_service_account signer is not supported",
858                )),
859                _ => Err(BuilderError::unknown_type(cred_type)),
860            }
861        }
862    }
863}
864
865fn path_not_found(path: std::path::PathBuf) -> BuilderError {
866    BuilderError::loading(format!(
867        "{}. {}",
868        path.display(),
869        concat!(
870            "This file name was found in the `GOOGLE_APPLICATION_CREDENTIALS` ",
871            "environment variable. Verify this environment variable points to ",
872            "a valid file."
873        )
874    ))
875}
876
877fn load_adc() -> BuildResult<AdcContents> {
878    match adc_path() {
879        None => Ok(AdcContents::FallbackToMds),
880        Some(AdcPath::FromEnv(path)) => match std::fs::read_to_string(&path) {
881            Ok(contents) => Ok(AdcContents::Contents(contents)),
882            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(path_not_found(path)),
883            Err(e) => Err(BuilderError::loading(e)),
884        },
885        Some(AdcPath::WellKnown(path)) => match std::fs::read_to_string(&path) {
886            Ok(contents) => Ok(AdcContents::Contents(contents)),
887            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(AdcContents::FallbackToMds),
888            Err(e) => Err(BuilderError::loading(e)),
889        },
890    }
891}
892
893/// The path to Application Default Credentials (ADC), as specified in [AIP-4110].
894///
895/// [AIP-4110]: https://google.aip.dev/auth/4110
896fn adc_path() -> Option<AdcPath> {
897    if let Some(path) = std::env::var_os("GOOGLE_APPLICATION_CREDENTIALS") {
898        return Some(AdcPath::FromEnv(std::path::PathBuf::from(path)));
899    }
900    Some(AdcPath::WellKnown(adc_well_known_path()?))
901}
902
903/// The well-known path to ADC on Windows, as specified in [AIP-4113].
904///
905/// [AIP-4113]: https://google.aip.dev/auth/4113
906#[cfg(target_os = "windows")]
907fn adc_well_known_path() -> Option<std::path::PathBuf> {
908    std::env::var_os("APPDATA").map(|root| {
909        std::path::PathBuf::from(root).join("gcloud/application_default_credentials.json")
910    })
911}
912
913/// The well-known path to ADC on Linux and Mac, as specified in [AIP-4113].
914///
915/// [AIP-4113]: https://google.aip.dev/auth/4113
916#[cfg(not(target_os = "windows"))]
917fn adc_well_known_path() -> Option<std::path::PathBuf> {
918    std::env::var_os("HOME").map(|root| {
919        std::path::PathBuf::from(root).join(".config/gcloud/application_default_credentials.json")
920    })
921}
922
923/// A module providing invalid credentials where authentication does not matter.
924///
925/// These credentials are a convenient way to avoid errors from loading
926/// Application Default Credentials in tests.
927///
928/// This module is mainly relevant to other `google-cloud-*` crates, but some
929/// external developers (i.e. consumers, not developers of `google-cloud-rust`)
930/// may find it useful.
931// Skipping mutation testing for this module. As it exclusively provides
932// hardcoded credential stubs for testing purposes.
933#[cfg_attr(test, mutants::skip)]
934#[doc(hidden)]
935pub mod testing {
936    use super::CacheableResource;
937    use crate::Result;
938    use crate::credentials::Credentials;
939    use crate::credentials::dynamic::CredentialsProvider;
940    use http::{Extensions, HeaderMap};
941    use std::sync::Arc;
942
943    /// A simple credentials implementation to use in tests.
944    ///
945    /// Always return an error in `headers()`.
946    pub fn error_credentials(retryable: bool) -> Credentials {
947        Credentials {
948            inner: Arc::from(ErrorCredentials(retryable)),
949        }
950    }
951
952    #[derive(Debug, Default)]
953    struct ErrorCredentials(bool);
954
955    #[async_trait::async_trait]
956    impl CredentialsProvider for ErrorCredentials {
957        async fn headers(&self, _extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
958            Err(super::CredentialsError::from_msg(self.0, "test-only"))
959        }
960
961        async fn universe_domain(&self) -> Option<String> {
962            None
963        }
964    }
965}
966
967#[cfg(test)]
968pub(crate) mod tests {
969    use super::*;
970    use crate::constants::TRUST_BOUNDARY_HEADER;
971    use crate::errors::is_gax_error_retryable;
972    use base64::Engine;
973    use google_cloud_gax::backoff_policy::BackoffPolicy;
974    use google_cloud_gax::retry_policy::RetryPolicy;
975    use google_cloud_gax::retry_result::RetryResult;
976    use google_cloud_gax::retry_state::RetryState;
977    use google_cloud_gax::retry_throttler::RetryThrottler;
978    use mockall::mock;
979    use reqwest::header::AUTHORIZATION;
980    use rsa::BigUint;
981    use rsa::RsaPrivateKey;
982    use rsa::pkcs8::{EncodePrivateKey, LineEnding};
983    use scoped_env::ScopedEnv;
984    use std::error::Error;
985    use std::sync::LazyLock;
986    use test_case::test_case;
987    use tokio::time::Duration;
988    use tokio::time::Instant;
989
990    // find the last/root error in the chain that matches the given type
991    pub(crate) fn find_source_error<'a, T: Error + 'static>(
992        error: &'a (dyn Error + 'static),
993    ) -> Option<&'a T> {
994        let mut last_err = None;
995        let mut source = error.source();
996        while let Some(err) = source {
997            if let Some(target_err) = err.downcast_ref::<T>() {
998                last_err = Some(target_err);
999            }
1000            source = err.source();
1001        }
1002        last_err
1003    }
1004
1005    mock! {
1006        #[derive(Debug)]
1007        pub RetryPolicy {}
1008        impl RetryPolicy for RetryPolicy {
1009            fn on_error(
1010                &self,
1011                state: &RetryState,
1012                error: google_cloud_gax::error::Error,
1013            ) -> RetryResult;
1014        }
1015    }
1016
1017    mock! {
1018        #[derive(Debug)]
1019        pub BackoffPolicy {}
1020        impl BackoffPolicy for BackoffPolicy {
1021            fn on_failure(&self, state: &RetryState) -> std::time::Duration;
1022        }
1023    }
1024
1025    mockall::mock! {
1026        #[derive(Debug)]
1027        pub RetryThrottler {}
1028        impl RetryThrottler for RetryThrottler {
1029            fn throttle_retry_attempt(&self) -> bool;
1030            fn on_retry_failure(&mut self, error: &RetryResult);
1031            fn on_success(&mut self);
1032        }
1033    }
1034
1035    // Used by tests in other modules.
1036    mockall::mock! {
1037        #[derive(Debug)]
1038        pub Credentials {}
1039
1040        impl crate::credentials::CredentialsProvider for Credentials {
1041            async fn headers(&self, extensions: http::Extensions) -> std::result::Result<crate::credentials::CacheableResource<http::HeaderMap>, crate::errors::CredentialsError>;
1042            async fn universe_domain(&self) -> Option<String>;
1043        }
1044
1045        impl crate::credentials::AccessTokenCredentialsProvider for Credentials {
1046            async fn access_token(&self) -> std::result::Result<crate::credentials::AccessToken, crate::errors::CredentialsError>;
1047        }
1048    }
1049
1050    type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
1051
1052    pub(crate) fn get_mock_auth_retry_policy(attempts: usize) -> MockRetryPolicy {
1053        let mut retry_policy = MockRetryPolicy::new();
1054        retry_policy
1055            .expect_on_error()
1056            .returning(move |state, error| {
1057                if state.attempt_count >= attempts as u32 {
1058                    return RetryResult::Exhausted(error);
1059                }
1060                let is_retryable = is_gax_error_retryable(&error);
1061                if is_retryable {
1062                    RetryResult::Continue(error)
1063                } else {
1064                    RetryResult::Permanent(error)
1065                }
1066            });
1067        retry_policy
1068    }
1069
1070    pub(crate) fn get_mock_backoff_policy() -> MockBackoffPolicy {
1071        let mut backoff_policy = MockBackoffPolicy::new();
1072        backoff_policy
1073            .expect_on_failure()
1074            .return_const(Duration::from_secs(0));
1075        backoff_policy
1076    }
1077
1078    pub(crate) fn get_mock_retry_throttler() -> MockRetryThrottler {
1079        let mut throttler = MockRetryThrottler::new();
1080        throttler.expect_on_retry_failure().return_const(());
1081        throttler
1082            .expect_throttle_retry_attempt()
1083            .return_const(false);
1084        throttler.expect_on_success().return_const(());
1085        throttler
1086    }
1087
1088    pub(crate) fn get_headers_from_cache(
1089        headers: CacheableResource<HeaderMap>,
1090    ) -> Result<HeaderMap> {
1091        match headers {
1092            CacheableResource::New { data, .. } => Ok(data),
1093            CacheableResource::NotModified => Err(CredentialsError::from_msg(
1094                false,
1095                "Expecting headers to be present",
1096            )),
1097        }
1098    }
1099
1100    pub(crate) fn get_token_from_headers(headers: CacheableResource<HeaderMap>) -> Option<String> {
1101        match headers {
1102            CacheableResource::New { data, .. } => data
1103                .get(AUTHORIZATION)
1104                .and_then(|token_value| token_value.to_str().ok())
1105                .and_then(|s| s.split_whitespace().nth(1))
1106                .map(|s| s.to_string()),
1107            CacheableResource::NotModified => None,
1108        }
1109    }
1110
1111    pub(crate) fn get_access_boundary_from_headers(
1112        headers: CacheableResource<HeaderMap>,
1113    ) -> Option<String> {
1114        match headers {
1115            CacheableResource::New { data, .. } => data
1116                .get(TRUST_BOUNDARY_HEADER)
1117                .and_then(|token_value| token_value.to_str().ok())
1118                .map(|s| s.to_string()),
1119            CacheableResource::NotModified => None,
1120        }
1121    }
1122
1123    pub(crate) fn get_token_type_from_headers(
1124        headers: CacheableResource<HeaderMap>,
1125    ) -> Option<String> {
1126        match headers {
1127            CacheableResource::New { data, .. } => data
1128                .get(AUTHORIZATION)
1129                .and_then(|token_value| token_value.to_str().ok())
1130                .and_then(|s| s.split_whitespace().next())
1131                .map(|s| s.to_string()),
1132            CacheableResource::NotModified => None,
1133        }
1134    }
1135
1136    pub static RSA_PRIVATE_KEY: LazyLock<RsaPrivateKey> = LazyLock::new(|| {
1137        let p_str: &str = "141367881524527794394893355677826002829869068195396267579403819572502936761383874443619453704612633353803671595972343528718438130450055151198231345212263093247511629886734453413988207866331439612464122904648042654465604881130663408340669956544709445155137282157402427763452856646879397237752891502149781819597";
1138        let q_str: &str = "179395413952110013801471600075409598322058038890563483332288896635704255883613060744402506322679437982046475766067250097809676406576067239936945362857700460740092421061356861438909617220234758121022105150630083703531219941303688818533566528599328339894969707615478438750812672509434761181735933851075292740309";
1139        let e_str: &str = "65537";
1140
1141        let p = BigUint::parse_bytes(p_str.as_bytes(), 10).expect("Failed to parse prime P");
1142        let q = BigUint::parse_bytes(q_str.as_bytes(), 10).expect("Failed to parse prime Q");
1143        let public_exponent =
1144            BigUint::parse_bytes(e_str.as_bytes(), 10).expect("Failed to parse public exponent");
1145
1146        RsaPrivateKey::from_primes(vec![p, q], public_exponent)
1147            .expect("Failed to create RsaPrivateKey from primes")
1148    });
1149
1150    #[cfg(any(feature = "idtoken", feature = "gdch"))]
1151    pub static ES256_PRIVATE_KEY: LazyLock<p256::SecretKey> = LazyLock::new(|| {
1152        let secret_key_bytes = [
1153            0x4c, 0x0c, 0x11, 0x6e, 0x6e, 0xb0, 0x07, 0xbd, 0x48, 0x0c, 0xc0, 0x48, 0xc0, 0x1f,
1154            0xac, 0x3d, 0x82, 0x82, 0x0e, 0x6c, 0x3d, 0x76, 0x61, 0x4d, 0x06, 0x4e, 0xdb, 0x05,
1155            0x26, 0x6c, 0x75, 0xdf,
1156        ];
1157        p256::SecretKey::from_bytes((&secret_key_bytes).into()).unwrap()
1158    });
1159
1160    #[cfg(feature = "gdch")]
1161    pub static ES256_PEM: LazyLock<String> = LazyLock::new(|| {
1162        (*ES256_PRIVATE_KEY)
1163            .to_sec1_pem(LineEnding::LF)
1164            .expect("Failed to encode EC key to PEM")
1165            .to_string()
1166    });
1167
1168    pub static PKCS8_PK: LazyLock<String> = LazyLock::new(|| {
1169        RSA_PRIVATE_KEY
1170            .to_pkcs8_pem(LineEnding::LF)
1171            .expect("Failed to encode key to PKCS#8 PEM")
1172            .to_string()
1173    });
1174
1175    pub fn b64_decode_to_json(s: String) -> serde_json::Value {
1176        let decoded = String::from_utf8(
1177            base64::engine::general_purpose::URL_SAFE_NO_PAD
1178                .decode(s)
1179                .unwrap(),
1180        )
1181        .unwrap();
1182        serde_json::from_str(&decoded).unwrap()
1183    }
1184
1185    #[cfg(target_os = "windows")]
1186    #[test]
1187    #[serial_test::serial]
1188    fn adc_well_known_path_windows() {
1189        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1190        let _appdata = ScopedEnv::set("APPDATA", "C:/Users/foo");
1191        assert_eq!(
1192            adc_well_known_path(),
1193            Some(std::path::PathBuf::from(
1194                "C:/Users/foo/gcloud/application_default_credentials.json"
1195            ))
1196        );
1197        assert_eq!(
1198            adc_path(),
1199            Some(AdcPath::WellKnown(std::path::PathBuf::from(
1200                "C:/Users/foo/gcloud/application_default_credentials.json"
1201            )))
1202        );
1203    }
1204
1205    #[cfg(target_os = "windows")]
1206    #[test]
1207    #[serial_test::serial]
1208    fn adc_well_known_path_windows_no_appdata() {
1209        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1210        let _appdata = ScopedEnv::remove("APPDATA");
1211        assert_eq!(adc_well_known_path(), None);
1212        assert_eq!(adc_path(), None);
1213    }
1214
1215    #[cfg(not(target_os = "windows"))]
1216    #[test]
1217    #[serial_test::serial]
1218    fn adc_well_known_path_posix() {
1219        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1220        let _home = ScopedEnv::set("HOME", "/home/foo");
1221        assert_eq!(
1222            adc_well_known_path(),
1223            Some(std::path::PathBuf::from(
1224                "/home/foo/.config/gcloud/application_default_credentials.json"
1225            ))
1226        );
1227        assert_eq!(
1228            adc_path(),
1229            Some(AdcPath::WellKnown(std::path::PathBuf::from(
1230                "/home/foo/.config/gcloud/application_default_credentials.json"
1231            )))
1232        );
1233    }
1234
1235    #[cfg(not(target_os = "windows"))]
1236    #[test]
1237    #[serial_test::serial]
1238    fn adc_well_known_path_posix_no_home() {
1239        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1240        let _appdata = ScopedEnv::remove("HOME");
1241        assert_eq!(adc_well_known_path(), None);
1242        assert_eq!(adc_path(), None);
1243    }
1244
1245    #[test]
1246    #[serial_test::serial]
1247    fn adc_path_from_env() {
1248        let _creds = ScopedEnv::set(
1249            "GOOGLE_APPLICATION_CREDENTIALS",
1250            "/usr/bar/application_default_credentials.json",
1251        );
1252        assert_eq!(
1253            adc_path(),
1254            Some(AdcPath::FromEnv(std::path::PathBuf::from(
1255                "/usr/bar/application_default_credentials.json"
1256            )))
1257        );
1258    }
1259
1260    #[cfg(unix)]
1261    #[test]
1262    #[serial_test::serial]
1263    fn adc_path_from_env_non_utf8() {
1264        use std::os::unix::ffi::OsStringExt;
1265        let non_utf8_bytes = vec![
1266            b'/', b'u', b's', b'r', b'/', b'b', b'a', b'r', b'/', 0xff, b'.', b'j', b's', b'o',
1267            b'n',
1268        ];
1269        let non_utf8_os_str = std::ffi::OsString::from_vec(non_utf8_bytes);
1270
1271        let _creds = ScopedEnv::set(
1272            std::ffi::OsStr::new("GOOGLE_APPLICATION_CREDENTIALS"),
1273            non_utf8_os_str.as_os_str(),
1274        );
1275
1276        assert_eq!(
1277            adc_path(),
1278            Some(AdcPath::FromEnv(std::path::PathBuf::from(
1279                non_utf8_os_str.clone()
1280            )))
1281        );
1282    }
1283
1284    #[cfg(unix)]
1285    #[test]
1286    #[serial_test::serial]
1287    fn load_adc_no_file_at_env_is_error_non_utf8() {
1288        use std::os::unix::ffi::OsStringExt;
1289        let non_utf8_bytes = vec![
1290            b'f', b'i', b'l', b'e', b'-', 0xff, b'.', b'j', b's', b'o', b'n',
1291        ];
1292        let non_utf8_os_str = std::ffi::OsString::from_vec(non_utf8_bytes);
1293
1294        let _creds = ScopedEnv::set(
1295            std::ffi::OsStr::new("GOOGLE_APPLICATION_CREDENTIALS"),
1296            non_utf8_os_str.as_os_str(),
1297        );
1298
1299        let err = load_adc().unwrap_err();
1300        assert!(err.is_loading(), "{err:?}");
1301        let msg = format!("{err:?}");
1302        assert!(msg.contains("file-"), "{err:?}");
1303        assert!(msg.contains("GOOGLE_APPLICATION_CREDENTIALS"), "{err:?}");
1304    }
1305
1306    #[cfg(target_os = "windows")]
1307    #[test]
1308    #[serial_test::serial]
1309    fn adc_path_from_env_non_utf16() {
1310        use std::os::windows::ffi::OsStringExt;
1311        let non_utf16_wide = vec![
1312            b'C' as u16,
1313            b':' as u16,
1314            b'/' as u16,
1315            0xD800,
1316            b'.' as u16,
1317            b'j' as u16,
1318            b's' as u16,
1319            b'o' as u16,
1320            b'n' as u16,
1321        ];
1322        let non_utf16_os_str = std::ffi::OsString::from_wide(&non_utf16_wide);
1323
1324        let _creds = ScopedEnv::set(
1325            std::ffi::OsStr::new("GOOGLE_APPLICATION_CREDENTIALS"),
1326            non_utf16_os_str.as_os_str(),
1327        );
1328
1329        assert_eq!(
1330            adc_path(),
1331            Some(AdcPath::FromEnv(std::path::PathBuf::from(
1332                non_utf16_os_str.clone()
1333            )))
1334        );
1335    }
1336
1337    #[cfg(target_os = "windows")]
1338    #[test]
1339    #[serial_test::serial]
1340    fn load_adc_no_file_at_env_is_error_non_utf16() {
1341        use std::os::windows::ffi::OsStringExt;
1342        let non_utf16_wide = vec![
1343            b'f' as u16,
1344            b'i' as u16,
1345            b'l' as u16,
1346            b'e' as u16,
1347            b'-' as u16,
1348            0xD800,
1349            b'.' as u16,
1350            b'j' as u16,
1351            b's' as u16,
1352            b'o' as u16,
1353            b'n' as u16,
1354        ];
1355        let non_utf16_os_str = std::ffi::OsString::from_wide(&non_utf16_wide);
1356
1357        let _creds = ScopedEnv::set(
1358            std::ffi::OsStr::new("GOOGLE_APPLICATION_CREDENTIALS"),
1359            non_utf16_os_str.as_os_str(),
1360        );
1361
1362        let err = load_adc().unwrap_err();
1363        assert!(err.is_loading(), "{err:?}");
1364        let msg = format!("{err:?}");
1365        assert!(msg.contains("file-"), "{err:?}");
1366        assert!(msg.contains("GOOGLE_APPLICATION_CREDENTIALS"), "{err:?}");
1367    }
1368
1369    #[test]
1370    #[serial_test::serial]
1371    fn load_adc_no_well_known_path_fallback_to_mds() {
1372        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1373        let _e2 = ScopedEnv::remove("HOME"); // For posix
1374        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1375        assert_eq!(load_adc().unwrap(), AdcContents::FallbackToMds);
1376    }
1377
1378    #[test]
1379    #[serial_test::serial]
1380    fn load_adc_no_file_at_well_known_path_fallback_to_mds() {
1381        // Create a new temp directory. There is not an ADC file in here.
1382        let dir = tempfile::TempDir::new().unwrap();
1383        let path = dir.path().to_str().unwrap();
1384        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1385        let _e2 = ScopedEnv::set("HOME", path); // For posix
1386        let _e3 = ScopedEnv::set("APPDATA", path); // For windows
1387        assert_eq!(load_adc().unwrap(), AdcContents::FallbackToMds);
1388    }
1389
1390    #[test]
1391    #[serial_test::serial]
1392    fn load_adc_no_file_at_env_is_error() {
1393        let _e = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", "file-does-not-exist.json");
1394        let err = load_adc().unwrap_err();
1395        assert!(err.is_loading(), "{err:?}");
1396        let msg = format!("{err:?}");
1397        assert!(msg.contains("file-does-not-exist.json"), "{err:?}");
1398        assert!(msg.contains("GOOGLE_APPLICATION_CREDENTIALS"), "{err:?}");
1399    }
1400
1401    #[test]
1402    #[serial_test::serial]
1403    fn load_adc_success() {
1404        let file = tempfile::NamedTempFile::new().unwrap();
1405        let path = file.into_temp_path();
1406        std::fs::write(&path, "contents").expect("Unable to write to temporary file.");
1407        let _e = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", path.to_str().unwrap());
1408
1409        assert_eq!(
1410            load_adc().unwrap(),
1411            AdcContents::Contents("contents".to_string())
1412        );
1413    }
1414
1415    #[test_case(true; "retryable")]
1416    #[test_case(false; "non-retryable")]
1417    #[tokio::test]
1418    async fn error_credentials(retryable: bool) {
1419        let credentials = super::testing::error_credentials(retryable);
1420        assert!(
1421            credentials.universe_domain().await.is_none(),
1422            "{credentials:?}"
1423        );
1424        let err = credentials.headers(Extensions::new()).await.err().unwrap();
1425        assert_eq!(err.is_transient(), retryable, "{err:?}");
1426        let err = credentials.headers(Extensions::new()).await.err().unwrap();
1427        assert_eq!(err.is_transient(), retryable, "{err:?}");
1428    }
1429
1430    #[tokio::test]
1431    #[serial_test::serial]
1432    async fn create_access_token_credentials_fallback_to_mds_with_quota_project_override() {
1433        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1434        let _e2 = ScopedEnv::remove("HOME"); // For posix
1435        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1436        let _e4 = ScopedEnv::set(GOOGLE_CLOUD_QUOTA_PROJECT_VAR, "env-quota-project");
1437
1438        let mds = Builder::default()
1439            .with_quota_project_id("test-quota-project")
1440            .build()
1441            .unwrap();
1442        let fmt = format!("{mds:?}");
1443        assert!(fmt.contains("MDSCredentials"));
1444        assert!(
1445            fmt.contains("env-quota-project"),
1446            "Expected 'env-quota-project', got: {fmt}"
1447        );
1448    }
1449
1450    #[tokio::test]
1451    #[serial_test::serial]
1452    async fn create_access_token_credentials_with_quota_project_from_builder() {
1453        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1454        let _e2 = ScopedEnv::remove("HOME"); // For posix
1455        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1456        let _e4 = ScopedEnv::remove(GOOGLE_CLOUD_QUOTA_PROJECT_VAR);
1457
1458        let creds = Builder::default()
1459            .with_quota_project_id("test-quota-project")
1460            .build()
1461            .unwrap();
1462        let fmt = format!("{creds:?}");
1463        assert!(
1464            fmt.contains("test-quota-project"),
1465            "Expected 'test-quota-project', got: {fmt}"
1466        );
1467    }
1468
1469    #[tokio::test]
1470    #[serial_test::serial]
1471    async fn create_access_token_credentials_with_universe_domain_from_builder() {
1472        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1473        let _e2 = ScopedEnv::remove("HOME"); // For posix
1474        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1475        let _e4 = ScopedEnv::remove(GOOGLE_CLOUD_QUOTA_PROJECT_VAR);
1476
1477        let creds = Builder::default()
1478            .with_universe_domain("my-custom-universe.com")
1479            .build()
1480            .unwrap();
1481
1482        let universe_domain = creds.universe_domain().await;
1483        assert_eq!(universe_domain, Some("my-custom-universe.com".to_string()));
1484    }
1485
1486    #[tokio::test]
1487    #[serial_test::serial]
1488    async fn create_external_account_authorized_user_credentials() -> TestResult {
1489        use httptest::{Expectation, Server, matchers::request, responders::json_encoded};
1490
1491        let _e1 = ScopedEnv::remove(GOOGLE_CLOUD_QUOTA_PROJECT_VAR);
1492        let server = Server::run();
1493        server.expect(
1494            Expectation::matching(request::method_path("POST", "/token")).respond_with(
1495                json_encoded(serde_json::json!({
1496                    "access_token": "test-access-token",
1497                    "token_type": "Bearer",
1498                    "expires_in": 3600,
1499                })),
1500            ),
1501        );
1502        let contents = serde_json::json!({
1503            "type": "external_account_authorized_user",
1504            "audience": "//iam.googleapis.com/locations/global/workforcePools/pool/providers/provider",
1505            "client_id": "test-client-id",
1506            "client_secret": "test-client-secret",
1507            "refresh_token": "test-refresh-token",
1508            "token_url": server.url("/token").to_string(),
1509            "token_info_url": "https://sts.googleapis.com/v1/introspect",
1510        });
1511        let file = tempfile::NamedTempFile::new().unwrap();
1512        let path = file.into_temp_path();
1513        std::fs::write(&path, contents.to_string()).expect("Unable to write to temporary file.");
1514        let _e2 = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", path.to_str().unwrap());
1515
1516        let creds = Builder::default()
1517            .with_quota_project_id("test-quota-project")
1518            .build()?;
1519        let headers = get_headers_from_cache(creds.headers(Extensions::new()).await?)?;
1520        assert_eq!(
1521            headers.get(AUTHORIZATION).unwrap(),
1522            "Bearer test-access-token"
1523        );
1524        assert_eq!(
1525            headers.get(QUOTA_PROJECT_KEY).unwrap(),
1526            "test-quota-project"
1527        );
1528
1529        let err = Builder::default().build_signer().unwrap_err();
1530        assert!(err.is_not_supported(), "{err:?}");
1531        Ok(())
1532    }
1533
1534    #[tokio::test]
1535    #[serial_test::serial]
1536    async fn create_access_token_service_account_credentials_with_scopes() -> TestResult {
1537        let _e1 = ScopedEnv::remove(GOOGLE_CLOUD_QUOTA_PROJECT_VAR);
1538        let mut service_account_key = serde_json::json!({
1539            "type": "service_account",
1540            "project_id": "test-project-id",
1541            "private_key_id": "test-private-key-id",
1542            "private_key": "-----BEGIN PRIVATE KEY-----\nBLAHBLAHBLAH\n-----END PRIVATE KEY-----\n",
1543            "client_email": "test-client-email",
1544            "universe_domain": "test-universe-domain"
1545        });
1546
1547        let scopes =
1548            ["https://www.googleapis.com/auth/pubsub, https://www.googleapis.com/auth/translate"];
1549
1550        service_account_key["private_key"] = Value::from(PKCS8_PK.clone());
1551
1552        let file = tempfile::NamedTempFile::new().unwrap();
1553        let path = file.into_temp_path();
1554        std::fs::write(&path, service_account_key.to_string())
1555            .expect("Unable to write to temporary file.");
1556        let _e = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", path.to_str().unwrap());
1557
1558        let sac = Builder::default()
1559            .with_quota_project_id("test-quota-project")
1560            .with_scopes(scopes)
1561            .build()
1562            .unwrap();
1563
1564        let headers = sac.headers(Extensions::new()).await?;
1565        let token = get_token_from_headers(headers).unwrap();
1566        let parts: Vec<_> = token.split('.').collect();
1567        assert_eq!(parts.len(), 3);
1568        let claims = b64_decode_to_json(parts.get(1).unwrap().to_string());
1569
1570        let fmt = format!("{sac:?}");
1571        assert!(fmt.contains("ServiceAccountCredentials"));
1572        assert!(fmt.contains("test-quota-project"));
1573        assert_eq!(claims["scope"], scopes.join(" "));
1574
1575        Ok(())
1576    }
1577
1578    #[test]
1579    fn debug_access_token() {
1580        let expires_at = Instant::now() + Duration::from_secs(3600);
1581        let token = Token {
1582            token: "token-test-only".into(),
1583            token_type: "Bearer".into(),
1584            expires_at: Some(expires_at),
1585            metadata: None,
1586        };
1587        let access_token: AccessToken = token.into();
1588        let got = format!("{access_token:?}");
1589        assert!(!got.contains("token-test-only"), "{got}");
1590        assert!(got.contains("token: \"[censored]\""), "{got}");
1591    }
1592}