1use 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#[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#[derive(Clone, PartialEq, Debug)]
69pub enum CacheableResource<T> {
70 NotModified,
71 New { entity_tag: EntityTag, data: T },
72}
73
74#[derive(Clone, Debug)]
107pub struct Credentials {
108 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#[derive(Clone, Debug)]
148pub struct AccessTokenCredentials {
149 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
177impl 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#[derive(Clone)]
191pub struct AccessToken {
192 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
222pub trait AccessTokenCredentialsProvider: CredentialsProvider + std::fmt::Debug {
228 fn access_token(&self) -> impl Future<Output = Result<AccessToken>> + Send;
230}
231
232pub trait CredentialsProvider: std::fmt::Debug {
272 fn headers(
294 &self,
295 extensions: Extensions,
296 ) -> impl Future<Output = Result<CacheableResource<HeaderMap>>> + Send;
297
298 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 #[async_trait::async_trait]
308 pub trait CredentialsProvider: Send + Sync + std::fmt::Debug {
309 async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>>;
331
332 async fn universe_domain(&self) -> Option<String> {
334 Some("googleapis.com".to_string())
335 }
336 }
337
338 #[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 #[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#[derive(Debug)]
426pub struct Builder {
427 quota_project_id: Option<String>,
428 scopes: Option<Vec<String>>,
429}
430
431impl Default for Builder {
432 fn default() -> Self {
444 Self {
445 quota_project_id: None,
446 scopes: None,
447 }
448 }
449}
450
451impl Builder {
452 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 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 pub fn build(self) -> BuildResult<Credentials> {
518 Ok(self.build_access_token_credentials()?.into())
519 }
520
521 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
579macro_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
678fn 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#[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#[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#[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 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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 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); let _e3 = ScopedEnv::set("APPDATA", path); 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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}