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
15use crate::build_errors::Error as BuilderError;
16use crate::constants::GOOGLE_CLOUD_QUOTA_PROJECT_VAR;
17use crate::errors::{self, CredentialsError};
18use crate::token::Token;
19use crate::{BuildResult, Result};
20use http::{Extensions, HeaderMap};
21use serde_json::Value;
22use std::future::Future;
23use std::sync::Arc;
24use std::sync::atomic::{AtomicU64, Ordering};
25pub mod anonymous;
26pub mod api_key_credentials;
27pub mod external_account;
28pub(crate) mod external_account_sources;
29#[cfg(feature = "idtoken")]
30pub mod idtoken;
31pub mod impersonated;
32pub(crate) mod internal;
33pub mod mds;
34pub mod service_account;
35pub mod subject_token;
36pub mod user_account;
37pub(crate) const QUOTA_PROJECT_KEY: &str = "x-goog-user-project";
38
39#[cfg(test)]
40pub(crate) const DEFAULT_UNIVERSE_DOMAIN: &str = "googleapis.com";
41
42/// Represents an Entity Tag for a [CacheableResource].
43///
44/// An `EntityTag` is an opaque token that can be used to determine if a
45/// cached resource has changed. The specific format of this tag is an
46/// implementation detail.
47///
48/// As the name indicates, these are inspired by the ETags prevalent in HTTP
49/// caching protocols. Their implementation is very different, and are only
50/// intended for use within a single program.
51#[derive(Clone, Debug, PartialEq, Default)]
52pub struct EntityTag(u64);
53
54static ENTITY_TAG_GENERATOR: AtomicU64 = AtomicU64::new(0);
55impl EntityTag {
56    pub fn new() -> Self {
57        let value = ENTITY_TAG_GENERATOR.fetch_add(1, Ordering::SeqCst);
58        Self(value)
59    }
60}
61
62/// Represents a resource that can be cached, along with its [EntityTag].
63///
64/// This enum is used to provide cacheable data to the consumers of the credential provider.
65/// It allows a data provider to return either new data (with an [EntityTag]) or
66/// indicate that the caller's cached version (identified by a previously provided [EntityTag])
67/// is still valid.
68#[derive(Clone, PartialEq, Debug)]
69pub enum CacheableResource<T> {
70    NotModified,
71    New { entity_tag: EntityTag, data: T },
72}
73
74/// An implementation of [crate::credentials::CredentialsProvider].
75///
76/// Represents a [Credentials] used to obtain the auth request headers.
77///
78/// In general, [Credentials][credentials-link] are "digital object that provide
79/// proof of identity", the archetype may be a username and password
80/// combination, but a private RSA key may be a better example.
81///
82/// Modern authentication protocols do not send the credentials to authenticate
83/// with a service. Even when sent over encrypted transports, the credentials
84/// may be accidentally exposed via logging or may be captured if there are
85/// errors in the transport encryption. Because the credentials are often
86/// long-lived, that risk of exposure is also long-lived.
87///
88/// Instead, modern authentication protocols exchange the credentials for a
89/// time-limited [Token][token-link], a digital object that shows the caller was
90/// in possession of the credentials. Because tokens are time limited, risk of
91/// misuse is also time limited. Tokens may be further restricted to only a
92/// certain subset of the RPCs in the service, or even to specific resources, or
93/// only when used from a given machine (virtual or not). Further limiting the
94/// risks associated with any leaks of these tokens.
95///
96/// This struct also abstracts token sources that are not backed by a specific
97/// digital object. The canonical example is the [Metadata Service]. This
98/// service is available in many Google Cloud environments, including
99/// [Google Compute Engine], and [Google Kubernetes Engine].
100///
101/// [credentials-link]: https://cloud.google.com/docs/authentication#credentials
102/// [token-link]: https://cloud.google.com/docs/authentication#token
103/// [Metadata Service]: https://cloud.google.com/compute/docs/metadata/overview
104/// [Google Compute Engine]: https://cloud.google.com/products/compute
105/// [Google Kubernetes Engine]: https://cloud.google.com/kubernetes-engine
106#[derive(Clone, Debug)]
107pub struct Credentials {
108    // We use an `Arc` to hold the inner implementation.
109    //
110    // Credentials may be shared across threads (`Send + Sync`), so an `Rc`
111    // will not do.
112    //
113    // They also need to derive `Clone`, as the
114    // `gax::http_client::ReqwestClient`s which hold them derive `Clone`. So a
115    // `Box` will not do.
116    inner: Arc<dyn dynamic::CredentialsProvider>,
117}
118
119impl<T> std::convert::From<T> for Credentials
120where
121    T: crate::credentials::CredentialsProvider + Send + Sync + 'static,
122{
123    fn from(value: T) -> Self {
124        Self {
125            inner: Arc::new(value),
126        }
127    }
128}
129
130impl Credentials {
131    pub async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
132        self.inner.headers(extensions).await
133    }
134
135    pub async fn universe_domain(&self) -> Option<String> {
136        self.inner.universe_domain().await
137    }
138}
139
140/// An implementation of [crate::credentials::CredentialsProvider] that can also
141/// provide direct access to the underlying access token.
142///
143/// This struct is returned by the `build_access_token_credentials()` method on
144/// the various credential builders. It can be used to obtain an access token
145/// directly via the `access_token()` method, or it can be converted into a `Credentials`
146/// object to be used with the Google Cloud client libraries.
147#[derive(Clone, Debug)]
148pub struct AccessTokenCredentials {
149    // We use an `Arc` to hold the inner implementation.
150    //
151    // AccessTokenCredentials may be shared across threads (`Send + Sync`), so an `Rc`
152    // will not do.
153    //
154    // They also need to derive `Clone`, as the
155    // `gax::http_client::ReqwestClient`s which hold them derive `Clone`. So a
156    // `Box` will not do.
157    inner: Arc<dyn dynamic::AccessTokenCredentialsProvider>,
158}
159
160impl<T> std::convert::From<T> for AccessTokenCredentials
161where
162    T: crate::credentials::AccessTokenCredentialsProvider + Send + Sync + 'static,
163{
164    fn from(value: T) -> Self {
165        Self {
166            inner: Arc::new(value),
167        }
168    }
169}
170
171impl AccessTokenCredentials {
172    pub async fn access_token(&self) -> Result<AccessToken> {
173        self.inner.access_token().await
174    }
175}
176
177/// Makes [AccessTokenCredentials] compatible with clients that expect
178/// a [Credentials] and/or a [CredentialsProvider].
179impl CredentialsProvider for AccessTokenCredentials {
180    async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
181        self.inner.headers(extensions).await
182    }
183
184    async fn universe_domain(&self) -> Option<String> {
185        self.inner.universe_domain().await
186    }
187}
188
189/// Represents an OAuth 2.0 access token.
190#[derive(Clone)]
191pub struct AccessToken {
192    /// The access token string.
193    pub token: String,
194}
195
196impl std::fmt::Debug for AccessToken {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        f.debug_struct("AccessToken")
199            .field("token", &"[censored]")
200            .finish()
201    }
202}
203
204impl std::convert::From<CacheableResource<Token>> for Result<AccessToken> {
205    fn from(token: CacheableResource<Token>) -> Self {
206        match token {
207            CacheableResource::New { data, .. } => Ok(data.into()),
208            CacheableResource::NotModified => Err(errors::CredentialsError::from_msg(
209                false,
210                "Expecting token to be present",
211            )),
212        }
213    }
214}
215
216impl std::convert::From<Token> for AccessToken {
217    fn from(token: Token) -> Self {
218        Self { token: token.token }
219    }
220}
221
222/// A trait for credential types that can provide direct access to an access token.
223///
224/// This trait is primarily intended for interoperability with other libraries that
225/// require a raw access token, or for calling Google Cloud APIs that are not yet
226/// supported by the SDK.
227pub trait AccessTokenCredentialsProvider: CredentialsProvider + std::fmt::Debug {
228    /// Asynchronously retrieves an access token.
229    fn access_token(&self) -> impl Future<Output = Result<AccessToken>> + Send;
230}
231
232/// Represents a [Credentials] used to obtain auth request headers.
233///
234/// In general, [Credentials][credentials-link] are "digital object that
235/// provide proof of identity", the archetype may be a username and password
236/// combination, but a private RSA key may be a better example.
237///
238/// Modern authentication protocols do not send the credentials to
239/// authenticate with a service. Even when sent over encrypted transports,
240/// the credentials may be accidentally exposed via logging or may be
241/// captured if there are errors in the transport encryption. Because the
242/// credentials are often long-lived, that risk of exposure is also
243/// long-lived.
244///
245/// Instead, modern authentication protocols exchange the credentials for a
246/// time-limited [Token][token-link], a digital object that shows the caller
247/// was in possession of the credentials. Because tokens are time limited,
248/// risk of misuse is also time limited. Tokens may be further restricted to
249/// only a certain subset of the RPCs in the service, or even to specific
250/// resources, or only when used from a given machine (virtual or not).
251/// Further limiting the risks associated with any leaks of these tokens.
252///
253/// This struct also abstracts token sources that are not backed by a
254/// specific digital object. The canonical example is the
255/// [Metadata Service]. This service is available in many Google Cloud
256/// environments, including [Google Compute Engine], and
257/// [Google Kubernetes Engine].
258///
259/// # Notes
260///
261/// Application developers who directly use the Auth SDK can use this trait,
262/// along with [crate::credentials::Credentials::from()] to mock the credentials.
263/// Application developers who use the Google Cloud Rust SDK directly should not
264/// need this functionality.
265///
266/// [credentials-link]: https://cloud.google.com/docs/authentication#credentials
267/// [token-link]: https://cloud.google.com/docs/authentication#token
268/// [Metadata Service]: https://cloud.google.com/compute/docs/metadata/overview
269/// [Google Compute Engine]: https://cloud.google.com/products/compute
270/// [Google Kubernetes Engine]: https://cloud.google.com/kubernetes-engine
271pub trait CredentialsProvider: std::fmt::Debug {
272    /// Asynchronously constructs the auth headers.
273    ///
274    /// Different auth tokens are sent via different headers. The
275    /// [Credentials] constructs the headers (and header values) that should be
276    /// sent with a request.
277    ///
278    /// # Parameters
279    /// * `extensions` - An `http::Extensions` map that can be used to pass additional
280    ///   context to the credential provider. For caching purposes, this can include
281    ///   an [EntityTag] from a previously returned [`CacheableResource<HeaderMap>`].
282    ///   If a valid `EntityTag` is provided and the underlying authentication data
283    ///   has not changed, this method returns `Ok(CacheableResource::NotModified)`.
284    ///
285    /// # Returns
286    /// A `Future` that resolves to a `Result` containing:
287    /// * `Ok(CacheableResource::New { entity_tag, data })`: If new or updated headers
288    ///   are available.
289    /// * `Ok(CacheableResource::NotModified)`: If the headers have not changed since
290    ///   the ETag provided via `extensions` was issued.
291    /// * `Err(CredentialsError)`: If an error occurs while trying to fetch or
292    ///   generating the headers.
293    fn headers(
294        &self,
295        extensions: Extensions,
296    ) -> impl Future<Output = Result<CacheableResource<HeaderMap>>> + Send;
297
298    /// Retrieves the universe domain associated with the credentials, if any.
299    fn universe_domain(&self) -> impl Future<Output = Option<String>> + Send;
300}
301
302pub(crate) mod dynamic {
303    use super::Result;
304    use super::{CacheableResource, Extensions, HeaderMap};
305
306    /// A dyn-compatible, crate-private version of `CredentialsProvider`.
307    #[async_trait::async_trait]
308    pub trait CredentialsProvider: Send + Sync + std::fmt::Debug {
309        /// Asynchronously constructs the auth headers.
310        ///
311        /// Different auth tokens are sent via different headers. The
312        /// [Credentials] constructs the headers (and header values) that should be
313        /// sent with a request.
314        ///
315        /// # Parameters
316        /// * `extensions` - An `http::Extensions` map that can be used to pass additional
317        ///   context to the credential provider. For caching purposes, this can include
318        ///   an [EntityTag] from a previously returned [CacheableResource<HeaderMap>].
319        ///   If a valid `EntityTag` is provided and the underlying authentication data
320        ///   has not changed, this method returns `Ok(CacheableResource::NotModified)`.
321        ///
322        /// # Returns
323        /// A `Future` that resolves to a `Result` containing:
324        /// * `Ok(CacheableResource::New { entity_tag, data })`: If new or updated headers
325        ///   are available.
326        /// * `Ok(CacheableResource::NotModified)`: If the headers have not changed since
327        ///   the ETag provided via `extensions` was issued.
328        /// * `Err(CredentialsError)`: If an error occurs while trying to fetch or
329        ///   generating the headers.
330        async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>>;
331
332        /// Retrieves the universe domain associated with the credentials, if any.
333        async fn universe_domain(&self) -> Option<String> {
334            Some("googleapis.com".to_string())
335        }
336    }
337
338    /// The public CredentialsProvider implements the dyn-compatible CredentialsProvider.
339    #[async_trait::async_trait]
340    impl<T> CredentialsProvider for T
341    where
342        T: super::CredentialsProvider + Send + Sync,
343    {
344        async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
345            T::headers(self, extensions).await
346        }
347        async fn universe_domain(&self) -> Option<String> {
348            T::universe_domain(self).await
349        }
350    }
351
352    /// A dyn-compatible, crate-private version of `AccessTokenCredentialsProvider`.
353    #[async_trait::async_trait]
354    pub trait AccessTokenCredentialsProvider:
355        CredentialsProvider + Send + Sync + std::fmt::Debug
356    {
357        async fn access_token(&self) -> Result<super::AccessToken>;
358    }
359
360    #[async_trait::async_trait]
361    impl<T> AccessTokenCredentialsProvider for T
362    where
363        T: super::AccessTokenCredentialsProvider + Send + Sync,
364    {
365        async fn access_token(&self) -> Result<super::AccessToken> {
366            T::access_token(self).await
367        }
368    }
369}
370
371/// A builder for constructing [`Credentials`] instances.
372///
373/// This builder loads credentials according to the standard
374/// [Application Default Credentials (ADC)][ADC-link] strategy.
375/// ADC is the recommended approach for most applications and conforms to
376/// [AIP-4110]. If you need to load credentials from a non-standard location
377/// or source, you can use Builders on the specific credential types.
378///
379/// Common use cases where using ADC would is useful include:
380/// - Your application is deployed to a Google Cloud environment such as
381///   [Google Compute Engine (GCE)][gce-link],
382///   [Google Kubernetes Engine (GKE)][gke-link], or [Cloud Run]. Each of these
383///   deployment environments provides a default service account to the
384///   application, and offers mechanisms to change this default service account
385///   without any code changes to your application.
386/// - You are testing or developing the application on a workstation (physical
387///   or virtual). These credentials will use your preferences as set with
388///   [gcloud auth application-default]. These preferences can be your own
389///   Google Cloud user credentials, or some service account.
390/// - Regardless of where your application is running, you can use the
391///   `GOOGLE_APPLICATION_CREDENTIALS` environment variable to override the
392///   defaults. This environment variable should point to a file containing a
393///   service account key file, or a JSON object describing your user
394///   credentials.
395///
396/// The headers returned by these credentials should be used in the
397/// Authorization HTTP header.
398///
399/// The Google Cloud client libraries for Rust will typically find and use these
400/// credentials automatically if a credentials file exists in the standard ADC
401/// search paths. You might instantiate these credentials if you need to:
402/// - Override the OAuth 2.0 **scopes** being requested for the access token.
403/// - Override the **quota project ID** for billing and quota management.
404///
405/// # Example: fetching headers using ADC
406/// ```
407/// # use google_cloud_auth::credentials::Builder;
408/// # use http::Extensions;
409/// # tokio_test::block_on(async {
410/// let credentials = Builder::default()
411///     .with_quota_project_id("my-project")
412///     .build()?;
413/// let headers = credentials.headers(Extensions::new()).await?;
414/// println!("Headers: {headers:?}");
415/// # Ok::<(), anyhow::Error>(())
416/// # });
417/// ```
418///
419/// [ADC-link]: https://cloud.google.com/docs/authentication/application-default-credentials
420/// [AIP-4110]: https://google.aip.dev/auth/4110
421/// [Cloud Run]: https://cloud.google.com/run
422/// [gce-link]: https://cloud.google.com/products/compute
423/// [gcloud auth application-default]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default
424/// [gke-link]: https://cloud.google.com/kubernetes-engine
425#[derive(Debug)]
426pub struct Builder {
427    quota_project_id: Option<String>,
428    scopes: Option<Vec<String>>,
429}
430
431impl Default for Builder {
432    /// Creates a new builder where credentials will be obtained via [application-default login].
433    ///
434    /// # Example
435    /// ```
436    /// # use google_cloud_auth::credentials::Builder;
437    /// # tokio_test::block_on(async {
438    /// let credentials = Builder::default().build();
439    /// # });
440    /// ```
441    ///
442    /// [application-default login]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login
443    fn default() -> Self {
444        Self {
445            quota_project_id: None,
446            scopes: None,
447        }
448    }
449}
450
451impl Builder {
452    /// Sets the [quota project] for these credentials.
453    ///
454    /// In some services, you can use an account in one project for authentication
455    /// and authorization, and charge the usage to a different project. This requires
456    /// that the user has `serviceusage.services.use` permissions on the quota project.
457    ///
458    /// ## Important: Precedence
459    /// If the `GOOGLE_CLOUD_QUOTA_PROJECT` environment variable is set,
460    /// its value will be used **instead of** the value provided to this method.
461    ///
462    /// # Example
463    /// ```
464    /// # use google_cloud_auth::credentials::Builder;
465    /// # tokio_test::block_on(async {
466    /// let credentials = Builder::default()
467    ///     .with_quota_project_id("my-project")
468    ///     .build();
469    /// # });
470    /// ```
471    ///
472    /// [quota project]: https://cloud.google.com/docs/quotas/quota-project
473    pub fn with_quota_project_id<S: Into<String>>(mut self, quota_project_id: S) -> Self {
474        self.quota_project_id = Some(quota_project_id.into());
475        self
476    }
477
478    /// Sets the [scopes] for these credentials.
479    ///
480    /// `scopes` act as an additional restriction in addition to the IAM permissions
481    /// granted to the principal (user or service account) that creates the token.
482    ///
483    /// `scopes` define the *permissions being requested* for this specific access token
484    /// when interacting with a service. For example,
485    /// `https://www.googleapis.com/auth/devstorage.read_write`.
486    ///
487    /// IAM permissions, on the other hand, define the *underlying capabilities*
488    /// the principal possesses within a system. For example, `storage.buckets.delete`.
489    ///
490    /// The credentials certify that a particular token was created by a certain principal.
491    ///
492    /// When a token generated with specific scopes is used, the request must be permitted
493    /// by both the the principals's underlying IAM permissions and the scopes requested
494    /// for the token.
495    ///
496    /// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
497    pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
498    where
499        I: IntoIterator<Item = S>,
500        S: Into<String>,
501    {
502        self.scopes = Some(scopes.into_iter().map(|s| s.into()).collect());
503        self
504    }
505
506    /// Returns a [Credentials] instance with the configured settings.
507    ///
508    /// # Errors
509    ///
510    /// Returns a [CredentialsError] if an unsupported credential type is provided
511    /// or if the JSON value is either malformed or missing required fields.
512    ///
513    /// For more information, on how to generate the JSON for a credential,
514    /// consult the relevant section in the [application-default credentials] guide.
515    ///
516    /// [application-default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials
517    pub fn build(self) -> BuildResult<Credentials> {
518        Ok(self.build_access_token_credentials()?.into())
519    }
520
521    /// Returns an [AccessTokenCredentials] instance with the configured settings.
522    ///
523    /// # Example
524    ///
525    /// ```no_run
526    /// # use google_cloud_auth::credentials::{Builder, AccessTokenCredentials, AccessTokenCredentialsProvider};
527    /// # tokio_test::block_on(async {
528    /// // This will search for Application Default Credentials and build AccessTokenCredentials.
529    /// let credentials: AccessTokenCredentials = Builder::default()
530    ///     .build_access_token_credentials()?;
531    /// let access_token = credentials.access_token().await?;
532    /// println!("Token: {}", access_token.token);
533    /// # Ok::<(), anyhow::Error>(())
534    /// # });
535    /// ```
536    ///
537    /// # Errors
538    ///
539    /// Returns a [CredentialsError] if an unsupported credential type is provided
540    /// or if the JSON value is either malformed or missing required fields.
541    ///
542    /// For more information, on how to generate the JSON for a credential,
543    /// consult the relevant section in the [application-default credentials] guide.
544    ///
545    /// [application-default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials
546    pub fn build_access_token_credentials(self) -> BuildResult<AccessTokenCredentials> {
547        let json_data = match load_adc()? {
548            AdcContents::Contents(contents) => {
549                Some(serde_json::from_str(&contents).map_err(BuilderError::parsing)?)
550            }
551            AdcContents::FallbackToMds => None,
552        };
553        let quota_project_id = std::env::var(GOOGLE_CLOUD_QUOTA_PROJECT_VAR)
554            .ok()
555            .or(self.quota_project_id);
556        build_credentials(json_data, quota_project_id, self.scopes)
557    }
558}
559
560#[derive(Debug, PartialEq)]
561enum AdcPath {
562    FromEnv(String),
563    WellKnown(String),
564}
565
566#[derive(Debug, PartialEq)]
567enum AdcContents {
568    Contents(String),
569    FallbackToMds,
570}
571
572fn extract_credential_type(json: &Value) -> BuildResult<&str> {
573    json.get("type")
574        .ok_or_else(|| BuilderError::parsing("no `type` field found."))?
575        .as_str()
576        .ok_or_else(|| BuilderError::parsing("`type` field is not a string."))
577}
578
579/// Applies common optional configurations (quota project ID, scopes) to a
580/// specific credential builder instance and then builds it.
581///
582/// This macro centralizes the logic for optionally calling `.with_quota_project_id()`
583/// and `.with_scopes()` on different underlying credential builders (like
584/// `mds::Builder`, `service_account::Builder`, etc.) before calling `.build()`.
585/// It helps avoid repetitive code in the `build_credentials` function.
586macro_rules! config_builder {
587    ($builder_instance:expr, $quota_project_id_option:expr, $scopes_option:expr, $apply_scopes_closure:expr) => {{
588        let builder = $builder_instance;
589        let builder = $quota_project_id_option
590            .into_iter()
591            .fold(builder, |b, qp| b.with_quota_project_id(qp));
592
593        let builder = $scopes_option
594            .into_iter()
595            .fold(builder, |b, s| $apply_scopes_closure(b, s));
596
597        builder.build_access_token_credentials()
598    }};
599}
600
601fn build_credentials(
602    json: Option<Value>,
603    quota_project_id: Option<String>,
604    scopes: Option<Vec<String>>,
605) -> BuildResult<AccessTokenCredentials> {
606    match json {
607        None => config_builder!(
608            mds::Builder::from_adc(),
609            quota_project_id,
610            scopes,
611            |b: mds::Builder, s: Vec<String>| b.with_scopes(s)
612        ),
613        Some(json) => {
614            let cred_type = extract_credential_type(&json)?;
615            match cred_type {
616                "authorized_user" => {
617                    config_builder!(
618                        user_account::Builder::new(json),
619                        quota_project_id,
620                        scopes,
621                        |b: user_account::Builder, s: Vec<String>| b.with_scopes(s)
622                    )
623                }
624                "service_account" => config_builder!(
625                    service_account::Builder::new(json),
626                    quota_project_id,
627                    scopes,
628                    |b: service_account::Builder, s: Vec<String>| b
629                        .with_access_specifier(service_account::AccessSpecifier::from_scopes(s))
630                ),
631                "impersonated_service_account" => {
632                    config_builder!(
633                        impersonated::Builder::new(json),
634                        quota_project_id,
635                        scopes,
636                        |b: impersonated::Builder, s: Vec<String>| b.with_scopes(s)
637                    )
638                }
639                "external_account" => config_builder!(
640                    external_account::Builder::new(json),
641                    quota_project_id,
642                    scopes,
643                    |b: external_account::Builder, s: Vec<String>| b.with_scopes(s)
644                ),
645                _ => Err(BuilderError::unknown_type(cred_type)),
646            }
647        }
648    }
649}
650
651fn path_not_found(path: String) -> BuilderError {
652    BuilderError::loading(format!(
653        "{path}. {}",
654        concat!(
655            "This file name was found in the `GOOGLE_APPLICATION_CREDENTIALS` ",
656            "environment variable. Verify this environment variable points to ",
657            "a valid file."
658        )
659    ))
660}
661
662fn load_adc() -> BuildResult<AdcContents> {
663    match adc_path() {
664        None => Ok(AdcContents::FallbackToMds),
665        Some(AdcPath::FromEnv(path)) => match std::fs::read_to_string(&path) {
666            Ok(contents) => Ok(AdcContents::Contents(contents)),
667            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(path_not_found(path)),
668            Err(e) => Err(BuilderError::loading(e)),
669        },
670        Some(AdcPath::WellKnown(path)) => match std::fs::read_to_string(path) {
671            Ok(contents) => Ok(AdcContents::Contents(contents)),
672            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(AdcContents::FallbackToMds),
673            Err(e) => Err(BuilderError::loading(e)),
674        },
675    }
676}
677
678/// The path to Application Default Credentials (ADC), as specified in [AIP-4110].
679///
680/// [AIP-4110]: https://google.aip.dev/auth/4110
681fn adc_path() -> Option<AdcPath> {
682    if let Ok(path) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") {
683        return Some(AdcPath::FromEnv(path));
684    }
685    Some(AdcPath::WellKnown(adc_well_known_path()?))
686}
687
688/// The well-known path to ADC on Windows, as specified in [AIP-4113].
689///
690/// [AIP-4113]: https://google.aip.dev/auth/4113
691#[cfg(target_os = "windows")]
692fn adc_well_known_path() -> Option<String> {
693    std::env::var("APPDATA")
694        .ok()
695        .map(|root| root + "/gcloud/application_default_credentials.json")
696}
697
698/// The well-known path to ADC on Linux and Mac, as specified in [AIP-4113].
699///
700/// [AIP-4113]: https://google.aip.dev/auth/4113
701#[cfg(not(target_os = "windows"))]
702fn adc_well_known_path() -> Option<String> {
703    std::env::var("HOME")
704        .ok()
705        .map(|root| root + "/.config/gcloud/application_default_credentials.json")
706}
707
708/// A module providing invalid credentials where authentication does not matter.
709///
710/// These credentials are a convenient way to avoid errors from loading
711/// Application Default Credentials in tests.
712///
713/// This module is mainly relevant to other `google-cloud-*` crates, but some
714/// external developers (i.e. consumers, not developers of `google-cloud-rust`)
715/// may find it useful.
716// Skipping mutation testing for this module. As it exclusively provides
717// hardcoded credential stubs for testing purposes.
718#[cfg_attr(test, mutants::skip)]
719#[doc(hidden)]
720pub mod testing {
721    use super::CacheableResource;
722    use crate::Result;
723    use crate::credentials::Credentials;
724    use crate::credentials::dynamic::CredentialsProvider;
725    use http::{Extensions, HeaderMap};
726    use std::sync::Arc;
727
728    /// A simple credentials implementation to use in tests.
729    ///
730    /// Always return an error in `headers()`.
731    pub fn error_credentials(retryable: bool) -> Credentials {
732        Credentials {
733            inner: Arc::from(ErrorCredentials(retryable)),
734        }
735    }
736
737    #[derive(Debug, Default)]
738    struct ErrorCredentials(bool);
739
740    #[async_trait::async_trait]
741    impl CredentialsProvider for ErrorCredentials {
742        async fn headers(&self, _extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
743            Err(super::CredentialsError::from_msg(self.0, "test-only"))
744        }
745
746        async fn universe_domain(&self) -> Option<String> {
747            None
748        }
749    }
750}
751
752#[cfg(test)]
753pub(crate) mod tests {
754    use super::*;
755    use base64::Engine;
756    use gax::backoff_policy::BackoffPolicy;
757    use gax::retry_policy::RetryPolicy;
758    use gax::retry_result::RetryResult;
759    use gax::retry_state::RetryState;
760    use gax::retry_throttler::RetryThrottler;
761    use mockall::mock;
762    use reqwest::header::AUTHORIZATION;
763    use rsa::BigUint;
764    use rsa::RsaPrivateKey;
765    use rsa::pkcs8::{EncodePrivateKey, LineEnding};
766    use scoped_env::ScopedEnv;
767    use std::error::Error;
768    use std::sync::LazyLock;
769    use test_case::test_case;
770    use tokio::time::Duration;
771    use tokio::time::Instant;
772
773    pub(crate) fn find_source_error<'a, T: Error + 'static>(
774        error: &'a (dyn Error + 'static),
775    ) -> Option<&'a T> {
776        let mut source = error.source();
777        while let Some(err) = source {
778            if let Some(target_err) = err.downcast_ref::<T>() {
779                return Some(target_err);
780            }
781            source = err.source();
782        }
783        None
784    }
785
786    mock! {
787        #[derive(Debug)]
788        pub RetryPolicy {}
789        impl RetryPolicy for RetryPolicy {
790            fn on_error(
791                &self,
792                state: &RetryState,
793                error: gax::error::Error,
794            ) -> RetryResult;
795        }
796    }
797
798    mock! {
799        #[derive(Debug)]
800        pub BackoffPolicy {}
801        impl BackoffPolicy for BackoffPolicy {
802            fn on_failure(&self, state: &RetryState) -> std::time::Duration;
803        }
804    }
805
806    mockall::mock! {
807        #[derive(Debug)]
808        pub RetryThrottler {}
809        impl RetryThrottler for RetryThrottler {
810            fn throttle_retry_attempt(&self) -> bool;
811            fn on_retry_failure(&mut self, error: &RetryResult);
812            fn on_success(&mut self);
813        }
814    }
815
816    type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
817
818    pub(crate) fn get_mock_auth_retry_policy(attempts: usize) -> MockRetryPolicy {
819        let mut retry_policy = MockRetryPolicy::new();
820        retry_policy
821            .expect_on_error()
822            .returning(move |state, error| {
823                if state.attempt_count >= attempts as u32 {
824                    return RetryResult::Exhausted(error);
825                }
826                let is_transient = error
827                    .source()
828                    .and_then(|e| e.downcast_ref::<CredentialsError>())
829                    .is_some_and(|ce| ce.is_transient());
830                if is_transient {
831                    RetryResult::Continue(error)
832                } else {
833                    RetryResult::Permanent(error)
834                }
835            });
836        retry_policy
837    }
838
839    pub(crate) fn get_mock_backoff_policy() -> MockBackoffPolicy {
840        let mut backoff_policy = MockBackoffPolicy::new();
841        backoff_policy
842            .expect_on_failure()
843            .return_const(Duration::from_secs(0));
844        backoff_policy
845    }
846
847    pub(crate) fn get_mock_retry_throttler() -> MockRetryThrottler {
848        let mut throttler = MockRetryThrottler::new();
849        throttler.expect_on_retry_failure().return_const(());
850        throttler
851            .expect_throttle_retry_attempt()
852            .return_const(false);
853        throttler.expect_on_success().return_const(());
854        throttler
855    }
856
857    pub(crate) fn get_headers_from_cache(
858        headers: CacheableResource<HeaderMap>,
859    ) -> Result<HeaderMap> {
860        match headers {
861            CacheableResource::New { data, .. } => Ok(data),
862            CacheableResource::NotModified => Err(CredentialsError::from_msg(
863                false,
864                "Expecting headers to be present",
865            )),
866        }
867    }
868
869    pub(crate) fn get_token_from_headers(headers: CacheableResource<HeaderMap>) -> Option<String> {
870        match headers {
871            CacheableResource::New { data, .. } => data
872                .get(AUTHORIZATION)
873                .and_then(|token_value| token_value.to_str().ok())
874                .and_then(|s| s.split_whitespace().nth(1))
875                .map(|s| s.to_string()),
876            CacheableResource::NotModified => None,
877        }
878    }
879
880    pub(crate) fn get_token_type_from_headers(
881        headers: CacheableResource<HeaderMap>,
882    ) -> Option<String> {
883        match headers {
884            CacheableResource::New { data, .. } => data
885                .get(AUTHORIZATION)
886                .and_then(|token_value| token_value.to_str().ok())
887                .and_then(|s| s.split_whitespace().next())
888                .map(|s| s.to_string()),
889            CacheableResource::NotModified => None,
890        }
891    }
892
893    pub static RSA_PRIVATE_KEY: LazyLock<RsaPrivateKey> = LazyLock::new(|| {
894        let p_str: &str = "141367881524527794394893355677826002829869068195396267579403819572502936761383874443619453704612633353803671595972343528718438130450055151198231345212263093247511629886734453413988207866331439612464122904648042654465604881130663408340669956544709445155137282157402427763452856646879397237752891502149781819597";
895        let q_str: &str = "179395413952110013801471600075409598322058038890563483332288896635704255883613060744402506322679437982046475766067250097809676406576067239936945362857700460740092421061356861438909617220234758121022105150630083703531219941303688818533566528599328339894969707615478438750812672509434761181735933851075292740309";
896        let e_str: &str = "65537";
897
898        let p = BigUint::parse_bytes(p_str.as_bytes(), 10).expect("Failed to parse prime P");
899        let q = BigUint::parse_bytes(q_str.as_bytes(), 10).expect("Failed to parse prime Q");
900        let public_exponent =
901            BigUint::parse_bytes(e_str.as_bytes(), 10).expect("Failed to parse public exponent");
902
903        RsaPrivateKey::from_primes(vec![p, q], public_exponent)
904            .expect("Failed to create RsaPrivateKey from primes")
905    });
906
907    pub static PKCS8_PK: LazyLock<String> = LazyLock::new(|| {
908        RSA_PRIVATE_KEY
909            .to_pkcs8_pem(LineEnding::LF)
910            .expect("Failed to encode key to PKCS#8 PEM")
911            .to_string()
912    });
913
914    pub fn b64_decode_to_json(s: String) -> serde_json::Value {
915        let decoded = String::from_utf8(
916            base64::engine::general_purpose::URL_SAFE_NO_PAD
917                .decode(s)
918                .unwrap(),
919        )
920        .unwrap();
921        serde_json::from_str(&decoded).unwrap()
922    }
923
924    #[cfg(target_os = "windows")]
925    #[test]
926    #[serial_test::serial]
927    fn adc_well_known_path_windows() {
928        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
929        let _appdata = ScopedEnv::set("APPDATA", "C:/Users/foo");
930        assert_eq!(
931            adc_well_known_path(),
932            Some("C:/Users/foo/gcloud/application_default_credentials.json".to_string())
933        );
934        assert_eq!(
935            adc_path(),
936            Some(AdcPath::WellKnown(
937                "C:/Users/foo/gcloud/application_default_credentials.json".to_string()
938            ))
939        );
940    }
941
942    #[cfg(target_os = "windows")]
943    #[test]
944    #[serial_test::serial]
945    fn adc_well_known_path_windows_no_appdata() {
946        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
947        let _appdata = ScopedEnv::remove("APPDATA");
948        assert_eq!(adc_well_known_path(), None);
949        assert_eq!(adc_path(), None);
950    }
951
952    #[cfg(not(target_os = "windows"))]
953    #[test]
954    #[serial_test::serial]
955    fn adc_well_known_path_posix() {
956        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
957        let _home = ScopedEnv::set("HOME", "/home/foo");
958        assert_eq!(
959            adc_well_known_path(),
960            Some("/home/foo/.config/gcloud/application_default_credentials.json".to_string())
961        );
962        assert_eq!(
963            adc_path(),
964            Some(AdcPath::WellKnown(
965                "/home/foo/.config/gcloud/application_default_credentials.json".to_string()
966            ))
967        );
968    }
969
970    #[cfg(not(target_os = "windows"))]
971    #[test]
972    #[serial_test::serial]
973    fn adc_well_known_path_posix_no_home() {
974        let _creds = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
975        let _appdata = ScopedEnv::remove("HOME");
976        assert_eq!(adc_well_known_path(), None);
977        assert_eq!(adc_path(), None);
978    }
979
980    #[test]
981    #[serial_test::serial]
982    fn adc_path_from_env() {
983        let _creds = ScopedEnv::set(
984            "GOOGLE_APPLICATION_CREDENTIALS",
985            "/usr/bar/application_default_credentials.json",
986        );
987        assert_eq!(
988            adc_path(),
989            Some(AdcPath::FromEnv(
990                "/usr/bar/application_default_credentials.json".to_string()
991            ))
992        );
993    }
994
995    #[test]
996    #[serial_test::serial]
997    fn load_adc_no_well_known_path_fallback_to_mds() {
998        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
999        let _e2 = ScopedEnv::remove("HOME"); // For posix
1000        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1001        assert_eq!(load_adc().unwrap(), AdcContents::FallbackToMds);
1002    }
1003
1004    #[test]
1005    #[serial_test::serial]
1006    fn load_adc_no_file_at_well_known_path_fallback_to_mds() {
1007        // Create a new temp directory. There is not an ADC file in here.
1008        let dir = tempfile::TempDir::new().unwrap();
1009        let path = dir.path().to_str().unwrap();
1010        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1011        let _e2 = ScopedEnv::set("HOME", path); // For posix
1012        let _e3 = ScopedEnv::set("APPDATA", path); // For windows
1013        assert_eq!(load_adc().unwrap(), AdcContents::FallbackToMds);
1014    }
1015
1016    #[test]
1017    #[serial_test::serial]
1018    fn load_adc_no_file_at_env_is_error() {
1019        let _e = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", "file-does-not-exist.json");
1020        let err = load_adc().unwrap_err();
1021        assert!(err.is_loading(), "{err:?}");
1022        let msg = format!("{err:?}");
1023        assert!(msg.contains("file-does-not-exist.json"), "{err:?}");
1024        assert!(msg.contains("GOOGLE_APPLICATION_CREDENTIALS"), "{err:?}");
1025    }
1026
1027    #[test]
1028    #[serial_test::serial]
1029    fn load_adc_success() {
1030        let file = tempfile::NamedTempFile::new().unwrap();
1031        let path = file.into_temp_path();
1032        std::fs::write(&path, "contents").expect("Unable to write to temporary file.");
1033        let _e = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", path.to_str().unwrap());
1034
1035        assert_eq!(
1036            load_adc().unwrap(),
1037            AdcContents::Contents("contents".to_string())
1038        );
1039    }
1040
1041    #[test_case(true; "retryable")]
1042    #[test_case(false; "non-retryable")]
1043    #[tokio::test]
1044    async fn error_credentials(retryable: bool) {
1045        let credentials = super::testing::error_credentials(retryable);
1046        assert!(
1047            credentials.universe_domain().await.is_none(),
1048            "{credentials:?}"
1049        );
1050        let err = credentials.headers(Extensions::new()).await.err().unwrap();
1051        assert_eq!(err.is_transient(), retryable, "{err:?}");
1052        let err = credentials.headers(Extensions::new()).await.err().unwrap();
1053        assert_eq!(err.is_transient(), retryable, "{err:?}");
1054    }
1055
1056    #[tokio::test]
1057    #[serial_test::serial]
1058    async fn create_access_token_credentials_fallback_to_mds_with_quota_project_override() {
1059        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1060        let _e2 = ScopedEnv::remove("HOME"); // For posix
1061        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1062        let _e4 = ScopedEnv::set(GOOGLE_CLOUD_QUOTA_PROJECT_VAR, "env-quota-project");
1063
1064        let mds = Builder::default()
1065            .with_quota_project_id("test-quota-project")
1066            .build()
1067            .unwrap();
1068        let fmt = format!("{mds:?}");
1069        assert!(fmt.contains("MDSCredentials"));
1070        assert!(
1071            fmt.contains("env-quota-project"),
1072            "Expected 'env-quota-project', got: {fmt}"
1073        );
1074    }
1075
1076    #[tokio::test]
1077    #[serial_test::serial]
1078    async fn create_access_token_credentials_with_quota_project_from_builder() {
1079        let _e1 = ScopedEnv::remove("GOOGLE_APPLICATION_CREDENTIALS");
1080        let _e2 = ScopedEnv::remove("HOME"); // For posix
1081        let _e3 = ScopedEnv::remove("APPDATA"); // For windows
1082        let _e4 = ScopedEnv::remove(GOOGLE_CLOUD_QUOTA_PROJECT_VAR);
1083
1084        let creds = Builder::default()
1085            .with_quota_project_id("test-quota-project")
1086            .build()
1087            .unwrap();
1088        let fmt = format!("{creds:?}");
1089        assert!(
1090            fmt.contains("test-quota-project"),
1091            "Expected 'test-quota-project', got: {fmt}"
1092        );
1093    }
1094
1095    #[tokio::test]
1096    #[serial_test::serial]
1097    async fn create_access_token_service_account_credentials_with_scopes() -> TestResult {
1098        let _e1 = ScopedEnv::remove(GOOGLE_CLOUD_QUOTA_PROJECT_VAR);
1099        let mut service_account_key = serde_json::json!({
1100            "type": "service_account",
1101            "project_id": "test-project-id",
1102            "private_key_id": "test-private-key-id",
1103            "private_key": "-----BEGIN PRIVATE KEY-----\nBLAHBLAHBLAH\n-----END PRIVATE KEY-----\n",
1104            "client_email": "test-client-email",
1105            "universe_domain": "test-universe-domain"
1106        });
1107
1108        let scopes =
1109            ["https://www.googleapis.com/auth/pubsub, https://www.googleapis.com/auth/translate"];
1110
1111        service_account_key["private_key"] = Value::from(PKCS8_PK.clone());
1112
1113        let file = tempfile::NamedTempFile::new().unwrap();
1114        let path = file.into_temp_path();
1115        std::fs::write(&path, service_account_key.to_string())
1116            .expect("Unable to write to temporary file.");
1117        let _e = ScopedEnv::set("GOOGLE_APPLICATION_CREDENTIALS", path.to_str().unwrap());
1118
1119        let sac = Builder::default()
1120            .with_quota_project_id("test-quota-project")
1121            .with_scopes(scopes)
1122            .build()
1123            .unwrap();
1124
1125        let headers = sac.headers(Extensions::new()).await?;
1126        let token = get_token_from_headers(headers).unwrap();
1127        let parts: Vec<_> = token.split('.').collect();
1128        assert_eq!(parts.len(), 3);
1129        let claims = b64_decode_to_json(parts.get(1).unwrap().to_string());
1130
1131        let fmt = format!("{sac:?}");
1132        assert!(fmt.contains("ServiceAccountCredentials"));
1133        assert!(fmt.contains("test-quota-project"));
1134        assert_eq!(claims["scope"], scopes.join(" "));
1135
1136        Ok(())
1137    }
1138
1139    #[test]
1140    fn debug_access_token() {
1141        let expires_at = Instant::now() + Duration::from_secs(3600);
1142        let token = Token {
1143            token: "token-test-only".into(),
1144            token_type: "Bearer".into(),
1145            expires_at: Some(expires_at),
1146            metadata: None,
1147        };
1148        let access_token: AccessToken = token.into();
1149        let got = format!("{access_token:?}");
1150        assert!(!got.contains("token-test-only"), "{got}");
1151        assert!(got.contains("token: \"[censored]\""), "{got}");
1152    }
1153}