google_cloud_auth/credentials/
service_account.rs

1// Copyright 2025 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
15//! [Service Account] Credentials type.
16//!
17//! A service account is an account for an application or compute workload
18//! instead of an individual end user. The default credentials used by the
19//! client libraries may be, and often are, associated with a service account.
20//! Therefore, you can use service accounts by configuring your environment,
21//! without any code changes.
22//!
23//! Sometimes the application needs to use a [service account key] directly.
24//! The types in this module will help you in this case. For more information
25//! on when service account keys are appropriate, consult the
26//! relevant section in the [Best practices for using service accounts] guide.
27//!
28//! You can create multiple service account keys for a single service account.
29//! When you [create a service account key], the key is returned as a string.
30//! This string contains an ID for the service account, as well as the
31//! cryptographic materials (an RSA private key) required to authenticate the caller.
32//!
33//! Therefore, service account keys should be treated as any other secret
34//! with security implications. Think of them as unencrypted passwords. Do not
35//! store them where unauthorized persons or programs may read them.
36//!
37//! The types in this module allow you to create access tokens, based on
38//! service account keys and can be used with the Google Cloud client
39//! libraries for Rust.
40//!
41//! While the Google Cloud client libraries for Rust automatically use the types
42//! in this module when ADC finds a service account key file, you may want to
43//! use these types directly when the service account key is obtained from
44//! Cloud Secret Manager or a similar service.
45//!
46//! # Example
47//! ```
48//! # use google_cloud_auth::credentials::service_account::Builder;
49//! # use google_cloud_auth::credentials::Credentials;
50//! # use http::Extensions;
51//! # tokio_test::block_on(async {
52//! let service_account_key = serde_json::json!({
53//!     "client_email": "test-client-email",
54//!     "private_key_id": "test-private-key-id",
55//!     "private_key": "<YOUR_PKCS8_PEM_KEY_HERE>",
56//!     "project_id": "test-project-id",
57//!     "universe_domain": "test-universe-domain",
58//! });
59//! let credentials: Credentials = Builder::new(service_account_key)
60//!     .with_quota_project_id("my-quota-project")
61//!     .build()?;
62//! let headers = credentials.headers(Extensions::new()).await?;
63//! println!("Headers: {headers:?}");
64//! # Ok::<(), anyhow::Error>(())
65//! # });
66//! ```
67//!
68//! [Best practices for using service accounts]: https://cloud.google.com/iam/docs/best-practices-service-accounts#choose-when-to-use
69//! [create a service account key]: https://cloud.google.com/iam/docs/keys-create-delete#creating
70//! [Service Account]: https://cloud.google.com/iam/docs/service-account-overview
71//! [service account key]: https://cloud.google.com/iam/docs/keys-create-delete#creating
72
73mod jws;
74
75use crate::build_errors::Error as BuilderError;
76use crate::constants::DEFAULT_SCOPE;
77use crate::credentials::dynamic::CredentialsProvider;
78use crate::credentials::{CacheableResource, Credentials};
79use crate::errors::{self, CredentialsError};
80use crate::headers_util::build_cacheable_headers;
81use crate::token::{CachedTokenProvider, Token, TokenProvider};
82use crate::token_cache::TokenCache;
83use crate::{BuildResult, Result};
84use async_trait::async_trait;
85use http::{Extensions, HeaderMap};
86use jws::{CLOCK_SKEW_FUDGE, DEFAULT_TOKEN_TIMEOUT, JwsClaims, JwsHeader};
87use rustls::crypto::CryptoProvider;
88use rustls::sign::Signer;
89use rustls_pemfile::Item;
90use serde_json::Value;
91use std::sync::Arc;
92use time::OffsetDateTime;
93use tokio::time::Instant;
94
95/// Represents the access specifier for a service account based token,
96/// specifying either OAuth 2.0 [scopes] or a [JWT] audience.
97///
98/// It ensures that only one of these access specifiers can be applied
99/// for a given credential setup.
100///
101/// [JWT]: https://google.aip.dev/auth/4111
102/// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
103#[derive(Clone, Debug, PartialEq)]
104pub enum AccessSpecifier {
105    /// Use [AccessSpecifier::Audience] for setting audience in the token.
106    /// `aud` is a [JWT] claim specifying intended recipient of the token,
107    /// that is, a service.
108    /// Only one of audience or scopes can be specified for a credentials.
109    ///
110    /// [JWT]: https://google.aip.dev/auth/4111
111    Audience(String),
112
113    /// Use [AccessSpecifier::Scopes] for setting [scopes] in the token.
114    ///
115    /// `scopes` is a [JWT] claim specifying requested permission(s) for the token.
116    /// Only one of audience or scopes can be specified for a credentials.
117    ///
118    /// `scopes` define the *permissions being requested* for this specific session
119    /// when interacting with a service. For example, `https://www.googleapis.com/auth/devstorage.read_write`.
120    /// IAM permissions, on the other hand, define the *underlying capabilities*
121    /// the service account possesses within a system. For example, `storage.buckets.delete`.
122    /// When a token generated with specific scopes is used, the request must be permitted
123    /// by both the service account's underlying IAM permissions and the scopes requested
124    /// for the token. Therefore, scopes act as an additional restriction on what the token
125    /// can be used for. Please see relevant section in [service account authorization] to learn
126    /// more about scopes and IAM permissions.
127    ///
128    /// [JWT]: https://google.aip.dev/auth/4111
129    /// [service account authorization]: https://cloud.google.com/compute/docs/access/service-accounts#authorization
130    /// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
131    Scopes(Vec<String>),
132}
133
134impl AccessSpecifier {
135    fn audience(&self) -> Option<&String> {
136        match self {
137            AccessSpecifier::Audience(aud) => Some(aud),
138            AccessSpecifier::Scopes(_) => None,
139        }
140    }
141
142    fn scopes(&self) -> Option<&[String]> {
143        match self {
144            AccessSpecifier::Scopes(scopes) => Some(scopes),
145            AccessSpecifier::Audience(_) => None,
146        }
147    }
148
149    /// Creates [AccessSpecifier] with [scopes].
150    ///
151    /// # Example
152    /// ```
153    /// # use google_cloud_auth::credentials::service_account::{AccessSpecifier, Builder};
154    /// let access_specifier = AccessSpecifier::from_scopes(["https://www.googleapis.com/auth/pubsub"]);
155    /// let service_account_key = serde_json::json!({ /* add details here */ });
156    /// let credentials = Builder::new(service_account_key)
157    ///     .with_access_specifier(access_specifier)
158    ///     .build();
159    /// ```
160    ///
161    /// [scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
162    pub fn from_scopes<I, S>(scopes: I) -> Self
163    where
164        I: IntoIterator<Item = S>,
165        S: Into<String>,
166    {
167        AccessSpecifier::Scopes(scopes.into_iter().map(|s| s.into()).collect())
168    }
169
170    /// Creates [AccessSpecifier] with an audience.
171    ///
172    /// The value should be `https://{SERVICE}/`, e.g., `https://pubsub.googleapis.com/`
173    ///
174    /// # Example
175    /// ```
176    /// # use google_cloud_auth::credentials::service_account::{AccessSpecifier, Builder};
177    /// let access_specifier = AccessSpecifier::from_audience("https://bigtable.googleapis.com/");
178    /// let service_account_key = serde_json::json!({ /* add details here */ });
179    /// let credentials = Builder::new(service_account_key)
180    ///     .with_access_specifier(access_specifier)
181    ///     .build();
182    /// ```
183    pub fn from_audience<S: Into<String>>(audience: S) -> Self {
184        AccessSpecifier::Audience(audience.into())
185    }
186}
187
188/// A builder for constructing service account [Credentials] instances.
189///
190/// # Example
191/// ```
192/// # use google_cloud_auth::credentials::service_account::{AccessSpecifier, Builder};
193/// # tokio_test::block_on(async {
194/// let key = serde_json::json!({
195///     "client_email": "test-client-email",
196///     "private_key_id": "test-private-key-id",
197///     "private_key": "<YOUR_PKCS8_PEM_KEY_HERE>",
198///     "project_id": "test-project-id",
199///     "universe_domain": "test-universe-domain",
200/// });
201/// let credentials = Builder::new(key)
202///     .with_access_specifier(AccessSpecifier::from_audience("https://pubsub.googleapis.com"))
203///     .build();
204/// })
205/// ```
206pub struct Builder {
207    service_account_key: Value,
208    access_specifier: AccessSpecifier,
209    quota_project_id: Option<String>,
210}
211
212impl Builder {
213    /// Creates a new builder using [service_account_key] JSON value.
214    /// By default, the builder is configured with [cloud-platform] scope.
215    /// This can be overridden using the [with_access_specifier][Builder::with_access_specifier] method.
216    ///
217    /// [cloud-platform]:https://cloud.google.com/compute/docs/access/service-accounts#scopes_best_practice
218    /// [service_account_key]: https://cloud.google.com/iam/docs/keys-create-delete#creating
219    pub fn new(service_account_key: Value) -> Self {
220        Self {
221            service_account_key,
222            access_specifier: AccessSpecifier::Scopes([DEFAULT_SCOPE].map(str::to_string).to_vec()),
223            quota_project_id: None,
224        }
225    }
226
227    /// Sets the [AccessSpecifier] representing either scopes or audience for this credentials.
228    ///
229    /// # Example for setting audience
230    /// ```
231    /// # use google_cloud_auth::credentials::service_account::{AccessSpecifier, Builder};
232    /// let access_specifier = AccessSpecifier::from_audience("https://bigtable.googleapis.com/");
233    /// let service_account_key = serde_json::json!({ /* add details here */ });
234    /// let credentials = Builder::new(service_account_key)
235    ///     .with_access_specifier(access_specifier)
236    ///     .build();
237    /// ```
238    ///
239    /// # Example for setting scopes
240    /// ```
241    /// # use google_cloud_auth::credentials::service_account::{AccessSpecifier, Builder};
242    /// let access_specifier = AccessSpecifier::from_scopes(["https://www.googleapis.com/auth/pubsub"]);
243    /// let service_account_key = serde_json::json!({ /* add details here */ });
244    /// let credentials = Builder::new(service_account_key)
245    ///     .with_access_specifier(access_specifier)
246    ///     .build();
247    /// ```
248    pub fn with_access_specifier(mut self, access_specifier: AccessSpecifier) -> Self {
249        self.access_specifier = access_specifier;
250        self
251    }
252
253    /// Sets the [quota project] for this credentials.
254    ///
255    /// In some services, you can use a service account in
256    /// one project for authentication and authorization, and charge
257    /// the usage to a different project. This requires that the
258    /// service account has `serviceusage.services.use` permissions on the quota project.
259    ///
260    /// [quota project]: https://cloud.google.com/docs/quotas/quota-project
261    pub fn with_quota_project_id<S: Into<String>>(mut self, quota_project_id: S) -> Self {
262        self.quota_project_id = Some(quota_project_id.into());
263        self
264    }
265
266    fn build_token_provider(self) -> BuildResult<ServiceAccountTokenProvider> {
267        let service_account_key =
268            serde_json::from_value::<ServiceAccountKey>(self.service_account_key)
269                .map_err(BuilderError::parsing)?;
270
271        Ok(ServiceAccountTokenProvider {
272            service_account_key,
273            access_specifier: self.access_specifier,
274        })
275    }
276
277    /// Returns a [Credentials] instance with the configured settings.
278    ///
279    /// # Errors
280    ///
281    /// Returns a [CredentialsError] if the `service_account_key`
282    /// provided to [`Builder::new`] cannot be successfully deserialized into the
283    /// expected format for a service account key. This typically happens if the
284    /// JSON value is malformed or missing required fields. For more information,
285    /// on the expected format for a service account key, consult the
286    /// relevant section in the [service account keys] guide.
287    ///
288    /// [creating service account keys]: https://cloud.google.com/iam/docs/keys-create-delete#creating
289    pub fn build(self) -> BuildResult<Credentials> {
290        Ok(Credentials {
291            inner: Arc::new(ServiceAccountCredentials {
292                quota_project_id: self.quota_project_id.clone(),
293                token_provider: TokenCache::new(self.build_token_provider()?),
294            }),
295        })
296    }
297}
298
299/// A representation of a [service account key].
300///
301/// [Service Account Key]: https://cloud.google.com/iam/docs/keys-create-delete#creating
302#[derive(serde::Deserialize, Default, Clone)]
303struct ServiceAccountKey {
304    /// The client email address of the service account.
305    /// (e.g., "my-sa@my-project.iam.gserviceaccount.com").
306    client_email: String,
307    /// ID of the service account's private key.
308    private_key_id: String,
309    /// The PEM-encoded PKCS#8 private key string associated with the service account.
310    /// Begins with `-----BEGIN PRIVATE KEY-----`.
311    private_key: String,
312    /// The project id the service account belongs to.
313    project_id: String,
314    /// The universe domain this service account belongs to.
315    universe_domain: Option<String>,
316}
317
318impl std::fmt::Debug for ServiceAccountKey {
319    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320        f.debug_struct("ServiceAccountKey")
321            .field("client_email", &self.client_email)
322            .field("private_key_id", &self.private_key_id)
323            .field("private_key", &"[censored]")
324            .field("project_id", &self.project_id)
325            .field("universe_domain", &self.universe_domain)
326            .finish()
327    }
328}
329
330#[derive(Debug)]
331struct ServiceAccountCredentials<T>
332where
333    T: CachedTokenProvider,
334{
335    token_provider: T,
336    quota_project_id: Option<String>,
337}
338
339#[derive(Debug)]
340struct ServiceAccountTokenProvider {
341    service_account_key: ServiceAccountKey,
342    access_specifier: AccessSpecifier,
343}
344
345fn token_issue_time(current_time: OffsetDateTime) -> OffsetDateTime {
346    current_time - CLOCK_SKEW_FUDGE
347}
348
349fn token_expiry_time(current_time: OffsetDateTime) -> OffsetDateTime {
350    current_time + CLOCK_SKEW_FUDGE + DEFAULT_TOKEN_TIMEOUT
351}
352
353#[async_trait]
354impl TokenProvider for ServiceAccountTokenProvider {
355    async fn token(&self) -> Result<Token> {
356        let signer = self.signer(&self.service_account_key.private_key)?;
357
358        let expires_at = Instant::now() + CLOCK_SKEW_FUDGE + DEFAULT_TOKEN_TIMEOUT;
359        // The claims encode a unix timestamp. `std::time::Instant` has no
360        // epoch, so we use `time::OffsetDateTime`, which reads system time, in
361        // the implementation.
362        let current_time = OffsetDateTime::now_utc();
363
364        let claims = JwsClaims {
365            iss: self.service_account_key.client_email.clone(),
366            scope: self
367                .access_specifier
368                .scopes()
369                .map(|scopes| scopes.join(" ")),
370            aud: self.access_specifier.audience().cloned(),
371            exp: token_expiry_time(current_time),
372            iat: token_issue_time(current_time),
373            typ: None,
374            sub: Some(self.service_account_key.client_email.clone()),
375        };
376
377        let header = JwsHeader {
378            alg: "RS256",
379            typ: "JWT",
380            kid: &self.service_account_key.private_key_id,
381        };
382        let encoded_header_claims = format!("{}.{}", header.encode()?, claims.encode()?);
383        let sig = signer
384            .sign(encoded_header_claims.as_bytes())
385            .map_err(errors::non_retryable)?;
386        use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
387        let token = format!(
388            "{}.{}",
389            encoded_header_claims,
390            &BASE64_URL_SAFE_NO_PAD.encode(sig)
391        );
392
393        let token = Token {
394            token,
395            token_type: "Bearer".to_string(),
396            expires_at: Some(expires_at),
397            metadata: None,
398        };
399        Ok(token)
400    }
401}
402
403impl ServiceAccountTokenProvider {
404    // Creates a signer using the private key stored in the service account file.
405    fn signer(&self, private_key: &String) -> Result<Box<dyn Signer>> {
406        let key_provider = CryptoProvider::get_default().map_or_else(
407            || rustls::crypto::ring::default_provider().key_provider,
408            |p| p.key_provider,
409        );
410
411        let private_key = rustls_pemfile::read_one(&mut private_key.as_bytes())
412            .map_err(errors::non_retryable)?
413            .ok_or_else(|| {
414                errors::non_retryable_from_str("missing PEM section in service account key")
415            })?;
416        let pk = match private_key {
417            Item::Pkcs8Key(item) => key_provider.load_private_key(item.into()),
418            other => {
419                return Err(Self::unexpected_private_key_error(other));
420            }
421        };
422        let sk = pk.map_err(errors::non_retryable)?;
423        sk.choose_scheme(&[rustls::SignatureScheme::RSA_PKCS1_SHA256])
424            .ok_or_else(|| errors::non_retryable_from_str("Unable to choose RSA_PKCS1_SHA256 signing scheme as it is not supported by current signer"))
425    }
426
427    fn unexpected_private_key_error(private_key_format: Item) -> CredentialsError {
428        errors::non_retryable_from_str(format!(
429            "expected key to be in form of PKCS8, found {private_key_format:?}",
430        ))
431    }
432}
433
434#[async_trait::async_trait]
435impl<T> CredentialsProvider for ServiceAccountCredentials<T>
436where
437    T: CachedTokenProvider,
438{
439    async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
440        let token = self.token_provider.token(extensions).await?;
441        build_cacheable_headers(&token, &self.quota_project_id)
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use crate::credentials::QUOTA_PROJECT_KEY;
449    use crate::credentials::tests::{
450        PKCS8_PK, b64_decode_to_json, get_headers_from_cache, get_token_from_headers,
451    };
452    use crate::token::tests::MockTokenProvider;
453    use http::HeaderValue;
454    use http::header::AUTHORIZATION;
455    use rsa::pkcs1::EncodeRsaPrivateKey;
456    use rsa::pkcs8::LineEnding;
457    use rustls_pemfile::Item;
458    use serde_json::json;
459    use std::error::Error as _;
460    use std::time::Duration;
461
462    type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
463
464    const SSJ_REGEX: &str = r"(?<header>[^\.]+)\.(?<claims>[^\.]+)\.(?<sig>[^\.]+)";
465
466    #[test]
467    fn debug_token_provider() {
468        let expected = ServiceAccountKey {
469            client_email: "test-client-email".to_string(),
470            private_key_id: "test-private-key-id".to_string(),
471            private_key: "super-duper-secret-private-key".to_string(),
472            project_id: "test-project-id".to_string(),
473            universe_domain: Some("test-universe-domain".to_string()),
474        };
475        let fmt = format!("{expected:?}");
476        assert!(fmt.contains("test-client-email"), "{fmt}");
477        assert!(fmt.contains("test-private-key-id"), "{fmt}");
478        assert!(!fmt.contains("super-duper-secret-private-key"), "{fmt}");
479        assert!(fmt.contains("test-project-id"), "{fmt}");
480        assert!(fmt.contains("test-universe-domain"), "{fmt}");
481    }
482
483    #[test]
484    fn validate_token_issue_time() {
485        let current_time = OffsetDateTime::now_utc();
486        let token_issue_time = token_issue_time(current_time);
487        assert!(token_issue_time == current_time - CLOCK_SKEW_FUDGE);
488    }
489
490    #[test]
491    fn validate_token_expiry_time() {
492        let current_time = OffsetDateTime::now_utc();
493        let token_issue_time = token_expiry_time(current_time);
494        assert!(token_issue_time == current_time + CLOCK_SKEW_FUDGE + DEFAULT_TOKEN_TIMEOUT);
495    }
496
497    #[tokio::test]
498    async fn headers_success_without_quota_project() -> TestResult {
499        let token = Token {
500            token: "test-token".to_string(),
501            token_type: "Bearer".to_string(),
502            expires_at: None,
503            metadata: None,
504        };
505
506        let mut mock = MockTokenProvider::new();
507        mock.expect_token().times(1).return_once(|| Ok(token));
508
509        let sac = ServiceAccountCredentials {
510            token_provider: TokenCache::new(mock),
511            quota_project_id: None,
512        };
513
514        let mut extensions = Extensions::new();
515        let cached_headers = sac.headers(extensions.clone()).await.unwrap();
516        let (headers, entity_tag) = match cached_headers {
517            CacheableResource::New { entity_tag, data } => (data, entity_tag),
518            CacheableResource::NotModified => unreachable!("expecting new headers"),
519        };
520        let token = headers.get(AUTHORIZATION).unwrap();
521
522        assert_eq!(headers.len(), 1, "{headers:?}");
523        assert_eq!(token, HeaderValue::from_static("Bearer test-token"));
524        assert!(token.is_sensitive());
525
526        extensions.insert(entity_tag);
527
528        let cached_headers = sac.headers(extensions).await?;
529
530        match cached_headers {
531            CacheableResource::New { .. } => unreachable!("expecting new headers"),
532            CacheableResource::NotModified => CacheableResource::<HeaderMap>::NotModified,
533        };
534        Ok(())
535    }
536
537    #[tokio::test]
538    async fn headers_success_with_quota_project() -> TestResult {
539        let token = Token {
540            token: "test-token".to_string(),
541            token_type: "Bearer".to_string(),
542            expires_at: None,
543            metadata: None,
544        };
545
546        let quota_project = "test-quota-project";
547
548        let mut mock = MockTokenProvider::new();
549        mock.expect_token().times(1).return_once(|| Ok(token));
550
551        let sac = ServiceAccountCredentials {
552            token_provider: TokenCache::new(mock),
553            quota_project_id: Some(quota_project.to_string()),
554        };
555
556        let headers = get_headers_from_cache(sac.headers(Extensions::new()).await.unwrap())?;
557        let token = headers.get(AUTHORIZATION).unwrap();
558        let quota_project_header = headers.get(QUOTA_PROJECT_KEY).unwrap();
559
560        assert_eq!(headers.len(), 2, "{headers:?}");
561        assert_eq!(token, HeaderValue::from_static("Bearer test-token"));
562        assert!(token.is_sensitive());
563        assert_eq!(
564            quota_project_header,
565            HeaderValue::from_static(quota_project)
566        );
567        assert!(!quota_project_header.is_sensitive());
568        Ok(())
569    }
570
571    #[tokio::test]
572    async fn headers_failure() {
573        let mut mock = MockTokenProvider::new();
574        mock.expect_token()
575            .times(1)
576            .return_once(|| Err(errors::non_retryable_from_str("fail")));
577
578        let sac = ServiceAccountCredentials {
579            token_provider: TokenCache::new(mock),
580            quota_project_id: None,
581        };
582        assert!(sac.headers(Extensions::new()).await.is_err());
583    }
584
585    fn get_mock_service_key() -> Value {
586        json!({
587            "client_email": "test-client-email",
588            "private_key_id": "test-private-key-id",
589            "private_key": "",
590            "project_id": "test-project-id",
591        })
592    }
593
594    #[tokio::test]
595    async fn get_service_account_headers_pkcs1_private_key_failure() -> TestResult {
596        let mut service_account_key = get_mock_service_key();
597
598        let key = crate::credentials::tests::RSA_PRIVATE_KEY
599            .to_pkcs1_pem(LineEnding::LF)
600            .expect("Failed to encode key to PKCS#1 PEM")
601            .to_string();
602
603        service_account_key["private_key"] = Value::from(key);
604        let cred = Builder::new(service_account_key).build()?;
605        let expected_error_message = "expected key to be in form of PKCS8, found Pkcs1Key";
606        assert!(
607            cred.headers(Extensions::new())
608                .await
609                .is_err_and(|e| e.to_string().contains(expected_error_message))
610        );
611        Ok(())
612    }
613
614    #[tokio::test]
615    async fn get_service_account_token_pkcs8_key_success() -> TestResult {
616        let mut service_account_key = get_mock_service_key();
617        service_account_key["private_key"] = Value::from(PKCS8_PK.clone());
618        let tp = Builder::new(service_account_key.clone()).build_token_provider()?;
619
620        let token = tp.token().await?;
621        let re = regex::Regex::new(SSJ_REGEX).unwrap();
622        let captures = re.captures(&token.token).ok_or_else(|| {
623            format!(
624                r#"Expected token in form: "<header>.<claims>.<sig>". Found token: {}"#,
625                token.token
626            )
627        })?;
628        let header = b64_decode_to_json(captures["header"].to_string());
629        assert_eq!(header["alg"], "RS256");
630        assert_eq!(header["typ"], "JWT");
631        assert_eq!(header["kid"], service_account_key["private_key_id"]);
632
633        let claims = b64_decode_to_json(captures["claims"].to_string());
634        assert_eq!(claims["iss"], service_account_key["client_email"]);
635        assert_eq!(claims["scope"], DEFAULT_SCOPE);
636        assert!(claims["iat"].is_number());
637        assert!(claims["exp"].is_number());
638        assert_eq!(claims["sub"], service_account_key["client_email"]);
639
640        Ok(())
641    }
642
643    #[tokio::test]
644    async fn header_caching() -> TestResult {
645        let private_key = PKCS8_PK.clone();
646
647        let json_value = json!({
648            "client_email": "test-client-email",
649            "private_key_id": "test-private-key-id",
650            "private_key": private_key,
651            "project_id": "test-project-id",
652            "universe_domain": "test-universe-domain"
653        });
654
655        let credentials = Builder::new(json_value).build()?;
656
657        let headers = credentials.headers(Extensions::new()).await?;
658
659        let re = regex::Regex::new(SSJ_REGEX).unwrap();
660        let token = get_token_from_headers(headers).unwrap();
661
662        let captures = re.captures(&token).unwrap();
663
664        let claims = b64_decode_to_json(captures["claims"].to_string());
665        let first_iat = claims["iat"].as_i64().unwrap();
666
667        // The issued at claim (`iat`) encodes a unix timestamp, in seconds.
668        // Sleeping for one second ensures that a subsequent claim has a
669        // different `iat`. We need a real sleep, because we cannot fake the
670        // current unix timestamp.
671        std::thread::sleep(Duration::from_secs(1));
672
673        // Get the token again.
674        let token = get_token_from_headers(credentials.headers(Extensions::new()).await?).unwrap();
675        let captures = re.captures(&token).unwrap();
676
677        let claims = b64_decode_to_json(captures["claims"].to_string());
678        let second_iat = claims["iat"].as_i64().unwrap();
679
680        // Validate that the issued at claim is the same for the two tokens. If
681        // the 2nd token is not from the cache, its `iat` will be different.
682        assert_eq!(first_iat, second_iat);
683
684        Ok(())
685    }
686
687    #[tokio::test]
688    async fn get_service_account_headers_invalid_key_failure() -> TestResult {
689        let mut service_account_key = get_mock_service_key();
690        let pem_data = "-----BEGIN PRIVATE KEY-----\nMIGkAg==\n-----END PRIVATE KEY-----";
691        service_account_key["private_key"] = Value::from(pem_data);
692        let cred = Builder::new(service_account_key).build()?;
693
694        let token = cred.headers(Extensions::new()).await;
695        let err = token.unwrap_err();
696        assert!(!err.is_transient(), "{err:?}");
697        let source = err.source().and_then(|e| e.downcast_ref::<rustls::Error>());
698        assert!(matches!(source, Some(rustls::Error::General(_))), "{err:?}");
699        Ok(())
700    }
701
702    #[tokio::test]
703    async fn get_service_account_invalid_json_failure() -> TestResult {
704        let service_account_key = Value::from(" ");
705        let e = Builder::new(service_account_key).build().unwrap_err();
706        assert!(e.is_parsing(), "{e:?}");
707
708        Ok(())
709    }
710
711    #[test]
712    fn signer_failure() -> TestResult {
713        let tp = Builder::new(get_mock_service_key()).build_token_provider()?;
714
715        let signer = tp.signer(&tp.service_account_key.private_key);
716        let expected_error_message = "missing PEM section in service account key";
717        assert!(signer.is_err_and(|e| e.to_string().contains(expected_error_message)));
718        Ok(())
719    }
720
721    #[test]
722    fn unexpected_private_key_error_message() -> TestResult {
723        let expected_message = format!(
724            "expected key to be in form of PKCS8, found {:?}",
725            Item::Crl(Vec::new().into()) // Example unsupported key type
726        );
727
728        let error =
729            ServiceAccountTokenProvider::unexpected_private_key_error(Item::Crl(Vec::new().into()));
730        assert!(error.to_string().contains(&expected_message));
731        Ok(())
732    }
733
734    #[tokio::test]
735    async fn get_service_account_headers_with_audience() -> TestResult {
736        let mut service_account_key = get_mock_service_key();
737        service_account_key["private_key"] = Value::from(PKCS8_PK.clone());
738        let headers = Builder::new(service_account_key.clone())
739            .with_access_specifier(AccessSpecifier::from_audience("test-audience"))
740            .build()?
741            .headers(Extensions::new())
742            .await?;
743
744        let re = regex::Regex::new(SSJ_REGEX).unwrap();
745        let token = get_token_from_headers(headers).unwrap();
746        let captures = re.captures(&token).ok_or_else(|| {
747            format!(r#"Expected token in form: "<header>.<claims>.<sig>". Found token: {token}"#)
748        })?;
749        let token_header = b64_decode_to_json(captures["header"].to_string());
750        assert_eq!(token_header["alg"], "RS256");
751        assert_eq!(token_header["typ"], "JWT");
752        assert_eq!(token_header["kid"], service_account_key["private_key_id"]);
753
754        let claims = b64_decode_to_json(captures["claims"].to_string());
755        assert_eq!(claims["iss"], service_account_key["client_email"]);
756        assert_eq!(claims["scope"], Value::Null);
757        assert_eq!(claims["aud"], "test-audience");
758        assert!(claims["iat"].is_number());
759        assert!(claims["exp"].is_number());
760        assert_eq!(claims["sub"], service_account_key["client_email"]);
761        Ok(())
762    }
763
764    #[tokio::test(start_paused = true)]
765    async fn get_service_account_token_verify_expiry_time() -> TestResult {
766        let now = Instant::now();
767        let mut service_account_key = get_mock_service_key();
768        service_account_key["private_key"] = Value::from(PKCS8_PK.clone());
769        let token = Builder::new(service_account_key)
770            .build_token_provider()?
771            .token()
772            .await?;
773
774        let expected_expiry = now + CLOCK_SKEW_FUDGE + DEFAULT_TOKEN_TIMEOUT;
775
776        assert_eq!(token.expires_at.unwrap(), expected_expiry);
777        Ok(())
778    }
779
780    #[tokio::test]
781    async fn get_service_account_headers_with_custom_scopes() -> TestResult {
782        let mut service_account_key = get_mock_service_key();
783        let scopes = vec![
784            "https://www.googleapis.com/auth/pubsub, https://www.googleapis.com/auth/translate",
785        ];
786        service_account_key["private_key"] = Value::from(PKCS8_PK.clone());
787        let headers = Builder::new(service_account_key.clone())
788            .with_access_specifier(AccessSpecifier::from_scopes(scopes.clone()))
789            .build()?
790            .headers(Extensions::new())
791            .await?;
792
793        let re = regex::Regex::new(SSJ_REGEX).unwrap();
794        let token = get_token_from_headers(headers).unwrap();
795        let captures = re.captures(&token).ok_or_else(|| {
796            format!(r#"Expected token in form: "<header>.<claims>.<sig>". Found token: {token}"#)
797        })?;
798        let token_header = b64_decode_to_json(captures["header"].to_string());
799        assert_eq!(token_header["alg"], "RS256");
800        assert_eq!(token_header["typ"], "JWT");
801        assert_eq!(token_header["kid"], service_account_key["private_key_id"]);
802
803        let claims = b64_decode_to_json(captures["claims"].to_string());
804        assert_eq!(claims["iss"], service_account_key["client_email"]);
805        assert_eq!(claims["scope"], scopes.join(" "));
806        assert_eq!(claims["aud"], Value::Null);
807        assert!(claims["iat"].is_number());
808        assert!(claims["exp"].is_number());
809        assert_eq!(claims["sub"], service_account_key["client_email"]);
810        Ok(())
811    }
812}