google-cloud-auth 1.10.0

Google Cloud Client Libraries for Rust - Authentication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::errors::CredentialsError;
use crate::token::Token;
use google_cloud_gax::backoff_policy::BackoffPolicyArg;
use google_cloud_gax::error::Error as GaxError;
use google_cloud_gax::exponential_backoff::ExponentialBackoff;
use google_cloud_gax::retry_loop_internal::retry_loop;
use google_cloud_gax::retry_policy::{NeverRetry, RetryPolicyArg};
use google_cloud_gax::retry_throttler::{
    AdaptiveThrottler, RetryThrottlerArg, SharedRetryThrottler,
};
use reqwest::{Client as ReqwestClient, RequestBuilder};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::Instant;

/// A client for GCP Compute Engine Metadata Service (MDS).
#[derive(Clone, Debug)]
pub(crate) struct Client {
    endpoint: String,
    /// True if the endpoint was NOT overridden by env var or constructor arg.
    pub(crate) is_default_endpoint: bool,
    retry_config: RetryConfig,
}

#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub(crate) struct MDSTokenResponse {
    pub(crate) access_token: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) expires_in: Option<u64>,
    pub(crate) token_type: String,
}

impl Client {
    /// Creates a new client for the Metadata Service.
    pub(crate) fn new(endpoint_override: Option<String>) -> Self {
        let (endpoint, is_default_endpoint) = Self::resolve_endpoint(endpoint_override);
        let endpoint = endpoint.trim_end_matches('/').to_string();

        Self {
            endpoint,
            is_default_endpoint,
            retry_config: Default::default(),
        }
    }

    /// Determine the endpoint and whether it was overridden
    fn resolve_endpoint(endpoint_override: Option<String>) -> (String, bool) {
        if let Ok(host) = std::env::var(super::GCE_METADATA_HOST_ENV_VAR) {
            // Check GCE_METADATA_HOST environment variable first
            (format!("http://{host}"), false)
        } else if let Some(e) = endpoint_override {
            // Else, check if an endpoint was provided to the mds::Builder
            (e, false)
        } else {
            // Else, use the default metadata root
            (super::METADATA_ROOT.to_string(), true)
        }
    }

    /// Creates a GET request to the MDS service with the correct headers.
    fn get(&self, path: &str) -> RequestBuilder {
        let url = format!("{}{}", self.endpoint, path);
        ReqwestClient::new()
            .get(url)
            .header(super::METADATA_FLAVOR, super::METADATA_FLAVOR_VALUE)
    }

    /// Fetches an access token for the default service account.
    pub(crate) fn access_token(&self, scopes: Option<Vec<String>>) -> AccessTokenRequest {
        AccessTokenRequest {
            client: self.clone(),
            scopes,
        }
    }

    /// Fetches an ID token for the default service account.
    /// Used by idtoken feature.
    #[cfg(feature = "idtoken")]
    pub(crate) fn id_token(
        &self,
        target_audience: &str,
        format: Option<String>,
        licenses: Option<String>,
    ) -> IdTokenRequest {
        IdTokenRequest {
            client: self.clone(),
            target_audience: target_audience.to_string(),
            format,
            licenses,
        }
    }

    /// Fetches the email address of the service account from the Metadata Service.
    pub(crate) fn email(&self) -> EmailRequest {
        EmailRequest {
            client: self.clone(),
        }
    }

    /// Fetches the universe domain from the Metadata Service.
    pub(crate) fn universe_domain(&self) -> UniverseDomainRequest {
        UniverseDomainRequest {
            client: self.clone(),
        }
    }

    async fn send(
        self,
        request: reqwest::RequestBuilder,
        error_message: &'static str,
    ) -> crate::Result<reqwest::Response> {
        let sleep = async |d| tokio::time::sleep(d).await;

        let error_message_str = error_message.to_string().clone();
        retry_loop(
            async move |_| {
                let req = request
                    .try_clone()
                    .expect("client libraries only create builders where `try_clone()` succeeds");
                let response = req.send().await.map_err(GaxError::io)?;

                let response =
                    Self::check_response_status(response, error_message_str.clone()).await?;

                Ok(response)
            },
            sleep,
            true, // GET requests are idempotent
            self.retry_config.retry_throttler,
            self.retry_config.retry_policy.into(),
            self.retry_config.backoff_policy.into(),
        )
        .await
        .map_err(|e| crate::errors::from_gax_error(e, error_message))
    }

    async fn check_response_status(
        response: reqwest::Response,
        error_message: String,
    ) -> Result<reqwest::Response, GaxError> {
        let status = response.status();
        if !status.is_success() {
            let err_headers = response.headers().clone();
            let err_payload = response
                .bytes()
                .await
                .map_err(|e| GaxError::transport(err_headers.clone(), e))?;
            return Err(GaxError::http(
                status.as_u16(),
                err_headers,
                format!("{error_message} :{err_payload:?}").into(),
            ));
        }
        Ok(response)
    }
}

#[derive(Clone, Debug)]
struct RetryConfig {
    retry_policy: RetryPolicyArg,
    backoff_policy: BackoffPolicyArg,
    retry_throttler: SharedRetryThrottler,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            retry_policy: NeverRetry.into(),
            backoff_policy: ExponentialBackoff::default().into(),
            retry_throttler: Arc::new(Mutex::new(AdaptiveThrottler::default())),
        }
    }
}

impl RetryConfig {
    fn with_retry_policy(mut self, retry_policy: RetryPolicyArg) -> Self {
        self.retry_policy = retry_policy;
        self
    }

    fn with_backoff_policy(mut self, backoff_policy: BackoffPolicyArg) -> Self {
        self.backoff_policy = backoff_policy;
        self
    }

    fn with_retry_throttler(mut self, retry_throttler: RetryThrottlerArg) -> Self {
        self.retry_throttler = retry_throttler.into();
        self
    }
}

#[derive(Clone)]
pub(crate) struct AccessTokenRequest {
    client: Client,
    scopes: Option<Vec<String>>,
}

impl AccessTokenRequest {
    pub(crate) async fn send(self) -> crate::Result<Token> {
        let path = format!("{}/token", super::MDS_DEFAULT_URI);
        let request = self.client.get(&path);

        // Use the `scopes` option if set, otherwise let the MDS use the default
        // scopes.
        let scopes = self.scopes.as_ref().map(|v| v.join(","));
        let request = scopes
            .into_iter()
            .fold(request, |r, s| r.query(&[("scopes", s)]));

        let error_message = "failed to fetch access token";

        // If the connection to MDS was not successful, it is useful to retry when really
        // running on MDS environments and not useful if there is no MDS. We will mark the error
        // as retryable and let the retry policy determine whether to retry or not. Whenever we
        // define a default retry policy, we can skip retrying this case.
        let response = self.client.send(request, error_message).await?;

        let response = response.json::<MDSTokenResponse>().await.map_err(|e| {
            // Decoding errors are not transient. Typically they indicate a badly
            // configured MDS endpoint, or DNS redirecting the request to a random
            // server, e.g., ISPs that redirect unknown services to HTTP.
            CredentialsError::from_source(!e.is_decode(), e)
        })?;

        Ok(Token {
            token: response.access_token,
            token_type: response.token_type,
            expires_at: response
                .expires_in
                .map(|d| Instant::now() + Duration::from_secs(d)),
            metadata: None,
        })
    }
}

#[cfg(feature = "idtoken")]
#[derive(Clone)]
pub(crate) struct IdTokenRequest {
    client: Client,
    target_audience: String,
    format: Option<String>,
    licenses: Option<String>,
}

#[cfg(feature = "idtoken")]
impl IdTokenRequest {
    pub(crate) async fn send(self) -> crate::Result<String> {
        let path = format!("{}/identity", super::MDS_DEFAULT_URI);
        let request = self
            .client
            .get(&path)
            .query(&[("audience", &self.target_audience)]);
        let request = self.format.iter().fold(request, |builder, format| {
            builder.query(&[("format", format)])
        });
        let request = self.licenses.iter().fold(request, |builder, licenses| {
            builder.query(&[("licenses", licenses)])
        });

        let error_message = "failed to fetch id token";
        let response = self.client.send(request, error_message).await?;

        let token = response
            .text()
            .await
            .map_err(|e| CredentialsError::from_source(!e.is_decode(), e))?;

        Ok(token)
    }
}

#[derive(Clone)]
pub(crate) struct EmailRequest {
    client: Client,
}

impl EmailRequest {
    pub(crate) async fn send(self) -> crate::Result<String> {
        let path = format!("{}/email", super::MDS_DEFAULT_URI);
        let request = self.client.get(&path);
        let error_message = "failed to fetch email";

        let response = self.client.send(request, error_message).await?;

        let email = response
            .text()
            .await
            .map_err(|e| CredentialsError::from_source(!e.is_decode(), e))?;

        Ok(email)
    }
}

#[derive(Clone)]
pub(crate) struct UniverseDomainRequest {
    client: Client,
}

impl UniverseDomainRequest {
    pub(crate) fn with_retry_policy(mut self, retry_policy: RetryPolicyArg) -> Self {
        self.client.retry_config = self.client.retry_config.with_retry_policy(retry_policy);
        self
    }

    pub(crate) fn with_backoff_policy(mut self, backoff_policy: BackoffPolicyArg) -> Self {
        self.client.retry_config = self.client.retry_config.with_backoff_policy(backoff_policy);
        self
    }

    pub(crate) fn with_retry_throttler(mut self, retry_throttler: RetryThrottlerArg) -> Self {
        self.client.retry_config = self
            .client
            .retry_config
            .with_retry_throttler(retry_throttler);
        self
    }

    pub(crate) async fn send(self) -> crate::Result<String> {
        let path = super::MDS_UNIVERSE_DOMAIN_URI;
        let request = self.client.get(path);
        let error_message = "failed to fetch universe domain";

        let response = self.client.send(request, error_message).await?;

        let universe_domain = response
            .text()
            .await
            .map_err(|e| CredentialsError::from_source(!e.is_decode(), e))?;

        Ok(universe_domain.trim().to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::credentials::tests::{
        get_mock_auth_retry_policy, get_mock_backoff_policy, get_mock_retry_throttler,
    };
    use crate::mds::{MDS_DEFAULT_URI, MDS_UNIVERSE_DOMAIN_URI};
    use httptest::{Expectation, Server, matchers::*, responders::*};
    use scoped_env::ScopedEnv;
    use serial_test::{parallel, serial};

    type TestResult = anyhow::Result<()>;

    #[tokio::test]
    #[parallel]
    async fn test_access_token_success() -> TestResult {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));
        let response = MDSTokenResponse {
            access_token: "test-token".to_string(),
            expires_in: Some(3600),
            token_type: "Bearer".to_string(),
        };

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(format!("{}/token", MDS_DEFAULT_URI)),
                request::query(url_decoded(contains((
                    "scopes",
                    "scope1,scope2".to_string()
                )))),
            ])
            .respond_with(
                status_code(200)
                    .insert_header("Content-Type", "application/json")
                    .body(serde_json::to_string(&response)?),
            ),
        );

        let token = client
            .access_token(Some(vec!["scope1".to_string(), "scope2".to_string()]))
            .send()
            .await?;
        assert_eq!(token.token, "test-token");
        assert_eq!(token.token_type, "Bearer");

        Ok(())
    }

    #[tokio::test]
    #[parallel]
    async fn test_access_token_failure() {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(format!("{}/token", MDS_DEFAULT_URI)),
            ])
            .respond_with(status_code(404).body("Not Found")),
        );

        let err = client.access_token(None).send().await.unwrap_err();
        assert!(err.to_string().contains("failed to fetch access token"));
    }

    #[tokio::test]
    #[parallel]
    #[cfg(feature = "idtoken")]
    async fn test_id_token_success() -> TestResult {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(format!("{}/identity", MDS_DEFAULT_URI)),
                request::query(url_decoded(contains(("audience", "test-aud".to_string())))),
                request::query(url_decoded(contains(("format", "full".to_string())))),
                request::query(url_decoded(contains(("licenses", "TRUE".to_string())))),
            ])
            .respond_with(status_code(200).body("test-id-token")),
        );

        let token = client
            .id_token(
                "test-aud",
                Some("full".to_string()),
                Some("TRUE".to_string()),
            )
            .send()
            .await?;
        assert_eq!(token, "test-id-token");

        Ok(())
    }

    #[tokio::test]
    #[parallel]
    #[cfg(feature = "idtoken")]
    async fn test_id_token_failure() {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(format!("{}/identity", MDS_DEFAULT_URI)),
            ])
            .respond_with(status_code(404).body("Not Found")),
        );

        let err = client
            .id_token("test-aud", None, None)
            .send()
            .await
            .unwrap_err();
        assert!(err.to_string().contains("failed to fetch id token"));
    }

    #[tokio::test]
    #[parallel]
    async fn test_email_success() -> TestResult {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(format!("{}/email", MDS_DEFAULT_URI)),
            ])
            .respond_with(status_code(200).body("test@example.com")),
        );

        let email = client.email().send().await?;
        assert_eq!(email, "test@example.com");

        Ok(())
    }

    #[tokio::test]
    #[parallel]
    async fn test_email_failure() {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(format!("{}/email", MDS_DEFAULT_URI)),
            ])
            .respond_with(status_code(404).body("Not Found")),
        );

        let err = client.email().send().await.unwrap_err();
        assert!(err.to_string().contains("failed to fetch email"));
    }

    #[tokio::test]
    #[parallel]
    async fn test_universe_domain_success() -> TestResult {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(MDS_UNIVERSE_DOMAIN_URI),
            ])
            .respond_with(status_code(200).body("my-universe-domain.com")),
        );

        let domain = client.universe_domain().send().await?;
        assert_eq!(domain, "my-universe-domain.com");

        Ok(())
    }

    #[tokio::test]
    #[parallel]
    async fn test_universe_domain_failure() {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(MDS_UNIVERSE_DOMAIN_URI),
            ])
            .respond_with(status_code(404).body("Not Found")),
        );

        let err = client.universe_domain().send().await.unwrap_err();
        assert!(err.to_string().contains("failed to fetch universe domain"));
    }

    #[test]
    #[parallel]
    fn test_resolve_endpoint_default() {
        let client = Client::new(None);
        assert_eq!(client.endpoint, "http://metadata.google.internal");
    }

    #[test]
    #[parallel]
    fn test_resolve_endpoint_override() {
        let client = Client::new(Some("http://custom.endpoint".to_string()));
        assert_eq!(client.endpoint, "http://custom.endpoint");
    }

    #[test]
    #[serial]
    fn test_resolve_endpoint_env_var() {
        let _s = ScopedEnv::set(super::super::GCE_METADATA_HOST_ENV_VAR, "env.var.host");
        let client = Client::new(None);
        assert_eq!(client.endpoint, "http://env.var.host");
    }

    #[test]
    #[serial]
    fn test_resolve_endpoint_priority() {
        let _s = ScopedEnv::set(super::super::GCE_METADATA_HOST_ENV_VAR, "env.priority.host");
        // Env var should take precedence over constructor argument
        let client = Client::new(Some("http://custom.endpoint".to_string()));
        assert_eq!(client.endpoint, "http://env.priority.host");
    }

    #[tokio::test]
    #[parallel]
    async fn test_universe_domain_retry_success() -> TestResult {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        // First request fails, second succeeds
        let responses: Vec<Box<dyn Responder>> = vec![
            Box::new(status_code(500)),
            Box::new(status_code(200).body("my-universe-domain.com")),
        ];
        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(MDS_UNIVERSE_DOMAIN_URI),
            ])
            .times(2)
            .respond_with(cycle(responses)),
        );

        let domain = client
            .universe_domain()
            .with_retry_policy(get_mock_auth_retry_policy(2).into())
            .with_backoff_policy(get_mock_backoff_policy().into())
            .with_retry_throttler(get_mock_retry_throttler().into())
            .send()
            .await?;

        assert_eq!(domain, "my-universe-domain.com");

        Ok(())
    }

    #[tokio::test]
    #[parallel]
    async fn test_universe_domain_retry_failure() -> TestResult {
        let server = Server::run();
        let client = Client::new(Some(format!("http://{}", server.addr())));

        // All requests fail
        server.expect(
            Expectation::matching(all_of![
                request::method("GET"),
                request::path(MDS_UNIVERSE_DOMAIN_URI),
            ])
            .times(2)
            .respond_with(status_code(500)),
        );

        let err = client
            .universe_domain()
            .with_retry_policy(get_mock_auth_retry_policy(2).into())
            .with_backoff_policy(get_mock_backoff_policy().into())
            .with_retry_throttler(get_mock_retry_throttler().into())
            .send()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("failed to fetch universe domain"));

        Ok(())
    }
}