|
15 | 15 | use crate::build_errors::Error as BuilderError; |
16 | 16 | use crate::constants::GOOGLE_CLOUD_QUOTA_PROJECT_VAR; |
17 | 17 | use crate::errors::{self, CredentialsError}; |
| 18 | +use crate::token::Token; |
18 | 19 | use crate::{BuildResult, Result}; |
19 | 20 | use http::{Extensions, HeaderMap}; |
20 | 21 | use serde_json::Value; |
21 | 22 | use std::future::Future; |
22 | 23 | use std::sync::Arc; |
23 | 24 | use std::sync::atomic::{AtomicU64, Ordering}; |
24 | | - |
25 | 25 | pub mod anonymous; |
26 | 26 | pub mod api_key_credentials; |
27 | 27 | pub mod external_account; |
@@ -137,6 +137,98 @@ impl Credentials { |
137 | 137 | } |
138 | 138 | } |
139 | 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)] |
| 148 | +pub 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 | + |
| 160 | +impl<T> std::convert::From<T> for AccessTokenCredentials |
| 161 | +where |
| 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 | + |
| 171 | +impl 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]. |
| 179 | +impl 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)] |
| 191 | +pub struct AccessToken { |
| 192 | + /// The access token string. |
| 193 | + pub token: String, |
| 194 | +} |
| 195 | + |
| 196 | +impl 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 | + |
| 204 | +impl 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 | + |
| 216 | +impl 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. |
| 227 | +pub 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 | + |
140 | 232 | /// Represents a [Credentials] used to obtain auth request headers. |
141 | 233 | /// |
142 | 234 | /// In general, [Credentials][credentials-link] are "digital object that |
@@ -256,6 +348,24 @@ pub(crate) mod dynamic { |
256 | 348 | T::universe_domain(self).await |
257 | 349 | } |
258 | 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 | + } |
259 | 369 | } |
260 | 370 |
|
261 | 371 | /// A builder for constructing [`Credentials`] instances. |
@@ -397,13 +507,43 @@ impl Builder { |
397 | 507 | /// |
398 | 508 | /// # Errors |
399 | 509 | /// |
400 | | - /// Returns a [CredentialsError] if a unsupported credential type is provided |
401 | | - /// or if the JSON value is either malformed |
402 | | - /// or missing required fields. For more information, on how to generate |
403 | | - /// json, consult the relevant section in the [application-default credentials] guide. |
| 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. |
404 | 515 | /// |
405 | 516 | /// [application-default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials |
406 | 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> { |
407 | 547 | let json_data = match load_adc()? { |
408 | 548 | AdcContents::Contents(contents) => { |
409 | 549 | Some(serde_json::from_str(&contents).map_err(BuilderError::parsing)?) |
@@ -454,15 +594,15 @@ macro_rules! config_builder { |
454 | 594 | .into_iter() |
455 | 595 | .fold(builder, |b, s| $apply_scopes_closure(b, s)); |
456 | 596 |
|
457 | | - builder.build() |
| 597 | + builder.build_access_token_credentials() |
458 | 598 | }}; |
459 | 599 | } |
460 | 600 |
|
461 | 601 | fn build_credentials( |
462 | 602 | json: Option<Value>, |
463 | 603 | quota_project_id: Option<String>, |
464 | 604 | scopes: Option<Vec<String>>, |
465 | | -) -> BuildResult<Credentials> { |
| 605 | +) -> BuildResult<AccessTokenCredentials> { |
466 | 606 | match json { |
467 | 607 | None => config_builder!( |
468 | 608 | mds::Builder::from_adc(), |
@@ -628,6 +768,7 @@ pub(crate) mod tests { |
628 | 768 | use std::sync::LazyLock; |
629 | 769 | use test_case::test_case; |
630 | 770 | use tokio::time::Duration; |
| 771 | + use tokio::time::Instant; |
631 | 772 |
|
632 | 773 | pub(crate) fn find_source_error<'a, T: Error + 'static>( |
633 | 774 | error: &'a (dyn Error + 'static), |
@@ -994,4 +1135,19 @@ pub(crate) mod tests { |
994 | 1135 |
|
995 | 1136 | Ok(()) |
996 | 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 | + } |
997 | 1153 | } |
0 commit comments