1use 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#[derive(Clone, Debug, PartialEq, Default)]
57pub struct EntityTag(u64);
58
59static ENTITY_TAG_GENERATOR: AtomicU64 = AtomicU64::new(0);
60impl EntityTag {
61 pub fn new() -> Self {
63 let value = ENTITY_TAG_GENERATOR.fetch_add(1, Ordering::SeqCst);
64 Self(value)
65 }
66}
67
68#[derive(Clone, PartialEq, Debug)]
75#[allow(clippy::exhaustive_enums)]
76pub enum CacheableResource<T> {
77 NotModified,
79 New {
81 entity_tag: EntityTag,
83 data: T,
85 },
86}
87
88#[derive(Clone, Debug)]
121pub struct Credentials {
122 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 pub async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
176 self.inner.headers(extensions).await
177 }
178
179 pub async fn universe_domain(&self) -> Option<String> {
190 self.inner.universe_domain().await
191 }
192}
193
194#[derive(Clone, Debug)]
202pub struct AccessTokenCredentials {
203 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 pub async fn access_token(&self) -> Result<AccessToken> {
228 self.inner.access_token().await
229 }
230}
231
232impl 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#[derive(Clone)]
246pub struct AccessToken {
247 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
277pub trait AccessTokenCredentialsProvider: CredentialsProvider + std::fmt::Debug {
283 fn access_token(&self) -> impl Future<Output = Result<AccessToken>> + Send;
285}
286
287pub trait CredentialsProvider: std::fmt::Debug {
327 fn headers(
349 &self,
350 extensions: Extensions,
351 ) -> impl Future<Output = Result<CacheableResource<HeaderMap>>> + Send;
352
353 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 #[async_trait::async_trait]
363 pub trait CredentialsProvider: Send + Sync + std::fmt::Debug {
364 async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>>;
386
387 async fn universe_domain(&self) -> Option<String> {
389 Some("googleapis.com".to_string())
390 }
391 }
392
393 #[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 #[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#[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 fn default() -> Self {
499 Self {
500 quota_project_id: None,
501 scopes: None,
502 universe_domain: None,
503 }
504 }
505}
506
507impl Builder {
508 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 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 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 pub fn build(self) -> BuildResult<Credentials> {
593 Ok(self.build_access_token_credentials()?.into())
594 }
595
596 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 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
693macro_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
713macro_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
893fn 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#[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#[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#[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 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 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 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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 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); let _e3 = ScopedEnv::set("APPDATA", path); 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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"); let _e3 = ScopedEnv::remove("APPDATA"); 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}