Skip to content

Commit 37aef82

Browse files
authored
feat(auth): allow consuming access tokens directly (googleapis#3642)
Fixes googleapis#2929 and googleapis#3362
1 parent 50db8ff commit 37aef82

8 files changed

Lines changed: 720 additions & 39 deletions

File tree

‎src/auth/src/credentials.rs‎

Lines changed: 163 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
use crate::build_errors::Error as BuilderError;
1616
use crate::constants::GOOGLE_CLOUD_QUOTA_PROJECT_VAR;
1717
use crate::errors::{self, CredentialsError};
18+
use crate::token::Token;
1819
use crate::{BuildResult, Result};
1920
use http::{Extensions, HeaderMap};
2021
use serde_json::Value;
2122
use std::future::Future;
2223
use std::sync::Arc;
2324
use std::sync::atomic::{AtomicU64, Ordering};
24-
2525
pub mod anonymous;
2626
pub mod api_key_credentials;
2727
pub mod external_account;
@@ -137,6 +137,98 @@ impl Credentials {
137137
}
138138
}
139139

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+
140232
/// Represents a [Credentials] used to obtain auth request headers.
141233
///
142234
/// In general, [Credentials][credentials-link] are "digital object that
@@ -256,6 +348,24 @@ pub(crate) mod dynamic {
256348
T::universe_domain(self).await
257349
}
258350
}
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+
}
259369
}
260370

261371
/// A builder for constructing [`Credentials`] instances.
@@ -397,13 +507,43 @@ impl Builder {
397507
///
398508
/// # Errors
399509
///
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.
404515
///
405516
/// [application-default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials
406517
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> {
407547
let json_data = match load_adc()? {
408548
AdcContents::Contents(contents) => {
409549
Some(serde_json::from_str(&contents).map_err(BuilderError::parsing)?)
@@ -454,15 +594,15 @@ macro_rules! config_builder {
454594
.into_iter()
455595
.fold(builder, |b, s| $apply_scopes_closure(b, s));
456596

457-
builder.build()
597+
builder.build_access_token_credentials()
458598
}};
459599
}
460600

461601
fn build_credentials(
462602
json: Option<Value>,
463603
quota_project_id: Option<String>,
464604
scopes: Option<Vec<String>>,
465-
) -> BuildResult<Credentials> {
605+
) -> BuildResult<AccessTokenCredentials> {
466606
match json {
467607
None => config_builder!(
468608
mds::Builder::from_adc(),
@@ -628,6 +768,7 @@ pub(crate) mod tests {
628768
use std::sync::LazyLock;
629769
use test_case::test_case;
630770
use tokio::time::Duration;
771+
use tokio::time::Instant;
631772

632773
pub(crate) fn find_source_error<'a, T: Error + 'static>(
633774
error: &'a (dyn Error + 'static),
@@ -994,4 +1135,19 @@ pub(crate) mod tests {
9941135

9951136
Ok(())
9961137
}
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+
}
9971153
}

0 commit comments

Comments
 (0)