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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
// Copyright 2025 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.

//! The token cache

use crate::Result;
use crate::credentials::{CacheableResource, EntityTag};
use crate::token::{CachedTokenProvider, Token, TokenProvider};
use http::Extensions;
use std::sync::Arc;
use tokio::sync::watch;
use tokio::time::{Duration, Instant, sleep};

// Different MDS(Metadata Service) backends have different policies to
// determine when to refresh a token. Most MDS' refresh token 5 mins before
// expiry, except for Serverless which refresh tokens 4 mins before
// expiry. So we are using 4 mins as the staleness limit for our refresh logic.
const NORMAL_REFRESH_SLACK: Duration = Duration::from_secs(240);
const SHORT_REFRESH_SLACK: Duration = Duration::from_secs(10);

#[derive(Debug, Clone)]
pub(crate) struct TokenCache {
    rx_token: watch::Receiver<Option<Result<(Token, EntityTag)>>>,
}

impl TokenCache {
    pub(crate) fn new<T>(inner: T) -> Self
    where
        T: TokenProvider + Send + Sync + 'static,
    {
        let (tx_token, rx_token) = watch::channel::<Option<Result<(Token, EntityTag)>>>(None);
        let token_provider = Arc::new(inner);

        tokio::spawn(refresh_task(token_provider, tx_token));

        Self { rx_token }
    }

    async fn latest_token_and_entity_tag(&self) -> Result<(Token, EntityTag)> {
        let mut rx = self.rx_token.clone();
        let token_result = rx.borrow_and_update().clone();
        if let Some(token_result) = token_result {
            match token_result {
                Ok((token, tag)) => match token.expires_at {
                    None => Ok((token, tag)),
                    Some(e) => {
                        if e < Instant::now() {
                            // Expired token, wait for refresh
                            wait_for_next_token(rx).await
                        } else {
                            // valid token
                            Ok((token, tag))
                        }
                    }
                },
                // An error in the result is still a valid result to propagate to the client library
                Err(e) => Err(e),
            }
        } else {
            wait_for_next_token(rx).await
        }
    }
}

#[async_trait::async_trait]
impl CachedTokenProvider for TokenCache {
    async fn token(&self, extensions: Extensions) -> Result<CacheableResource<Token>> {
        let (data, entity_tag) = self.latest_token_and_entity_tag().await?;
        match extensions.get::<EntityTag>() {
            Some(tag) if entity_tag.eq(tag) => Ok(CacheableResource::NotModified),
            _ => Ok(CacheableResource::New { entity_tag, data }),
        }
    }
}

async fn wait_for_next_token(
    mut rx_token: watch::Receiver<Option<Result<(Token, EntityTag)>>>,
) -> Result<(Token, EntityTag)> {
    rx_token.changed().await.unwrap();
    let token_result = rx_token.borrow().clone();

    token_result.expect("There should always be a token or error in the channel after changed()")
}

async fn refresh_task<T>(
    token_provider: Arc<T>,
    tx_token: watch::Sender<Option<Result<(Token, EntityTag)>>>,
) where
    T: TokenProvider + Send + Sync + 'static,
{
    loop {
        let token_result = token_provider.token().await;
        let expiry = token_result.as_ref().map(|t| t.expires_at);
        let tagged = token_result.clone().map(|token| {
            let entity_tag = EntityTag::new();
            (token, entity_tag)
        });

        let _ = tx_token.send(Some(tagged));

        match expiry {
            Ok(Some(expiry)) => {
                let time_until_expiry = expiry.checked_duration_since(Instant::now());

                match time_until_expiry {
                    None => {
                        // We were given a token that is expired, or expires in less than 10 seconds.
                        // We will immediately restart the loop, and fetch a new token.
                    }
                    Some(time_until_expiry) => {
                        if time_until_expiry > NORMAL_REFRESH_SLACK {
                            sleep(time_until_expiry - NORMAL_REFRESH_SLACK).await;
                        } else if time_until_expiry > SHORT_REFRESH_SLACK {
                            // If expiry is less than 4 mins, try to refresh every 10 seconds
                            // This is to handle cases where MDS **repeatedly** returns about to expire tokens.
                            sleep(SHORT_REFRESH_SLACK).await;
                        }
                    }
                }
            }
            Ok(None) => {
                // If there is no expiry, the token is valid forever, so no need to refresh
                // TODO(#1553): Validate that all auth backends provide expiry and make expiry not optional.
                break;
            }
            Err(err) => {
                // On transient errors, even if the retry policy is exhausted,
                // we want to continue running this retry loop.
                // This loop cannot stop because that may leave the
                // credentials in an unrecoverable state (see #4541).
                // We considered using a notification to wake up the next time
                // a caller wants to retrieve a token, but that seemed prone to
                // deadlocks. We may implement this as an improvement (#4593).
                // On permanent errors, then there is really no point in trying
                // again, by definition of "permanent". If the error was misclassified
                // as permanent, that is a bug in the retry policy and better fixed
                // there than implemented as a workaround here.
                if !err.is_transient() {
                    break;
                }
                sleep(SHORT_REFRESH_SLACK).await;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors;
    use crate::token::tests::MockTokenProvider;
    use google_cloud_gax::error::CredentialsError;
    use std::ops::{Add, Sub};
    use std::sync::{Arc, Mutex};
    use tokio::time::{Duration, Instant};

    static TOKEN_VALID_DURATION: Duration = Duration::from_secs(3600);
    type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;

    fn get_cached_token(cache: CacheableResource<Token>) -> Result<Token> {
        match cache {
            CacheableResource::New { data, .. } => Ok(data),
            CacheableResource::NotModified => Err(CredentialsError::from_msg(
                false,
                "Expecting token to be present.",
            )),
        }
    }

    #[tokio::test]
    async fn initial_token_success() -> TestResult {
        let expected = Token {
            token: "test-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: None,
            metadata: None,
        };
        let expected_clone = expected.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(expected_clone));

        let cache = TokenCache::new(mock);

        let mut extensions = Extensions::new();
        let cached_token = cache.token(extensions.clone()).await.unwrap();
        let (actual, entity_tag) = match cached_token {
            CacheableResource::New { entity_tag, data } => (data, entity_tag),
            CacheableResource::NotModified => unreachable!("expecting new headers"),
        };

        assert_eq!(actual, expected);

        // Verify that we use the cached token instead of making a new request
        // to the mock token provider.
        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual, expected);

        // Verify that we return no token if extension is provided.
        extensions.insert(entity_tag);

        let cached_token = cache.token(extensions).await?;

        match cached_token {
            CacheableResource::New { .. } => unreachable!("expecting new headers"),
            CacheableResource::NotModified => CacheableResource::<Token>::NotModified,
        };
        Ok(())
    }

    #[tokio::test]
    async fn initial_token_failure() {
        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .returning(|| Err(errors::non_retryable_from_str("fail")));

        let cache = TokenCache::new(mock);
        let result = cache.token(Extensions::new()).await;
        assert!(result.is_err(), "{result:?}");

        // Verify that a new request is made to the mock token provider when we
        // don't have a valid token.
        let result = cache.token(Extensions::new()).await;
        assert!(result.is_err(), "{result:?}");
    }

    #[tokio::test(start_paused = true)]
    async fn expired_token_success() -> TestResult {
        let now = Instant::now();

        let initial = Token {
            token: "initial-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + TOKEN_VALID_DURATION),
            metadata: None,
        };
        let initial_clone = initial.clone();

        let refresh = Token {
            token: "refreshed-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 2 * TOKEN_VALID_DURATION),
            metadata: None,
        };
        let refresh_clone = refresh.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(initial_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(refresh_clone));

        // fetch an initial token
        let cache = TokenCache::new(mock);
        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual, initial);

        // wait long enough for the token to be expired
        // token should be waiting until the new token is available
        let sleep = TOKEN_VALID_DURATION.add(Duration::from_secs(100));
        tokio::time::advance(sleep).await;

        // make sure this is the new token
        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual, refresh);
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn expired_token_failure() -> TestResult {
        let now = Instant::now();

        let initial = Token {
            token: "initial-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + TOKEN_VALID_DURATION),
            metadata: None,
        };
        let initial_clone = initial.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(initial_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Err(errors::non_retryable_from_str("fail")));

        // fetch an initial token
        let cache = TokenCache::new(mock);
        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual, initial);

        // wait long enough for the token to be expired
        let sleep = TOKEN_VALID_DURATION.add(Duration::from_secs(100));
        tokio::time::advance(sleep).await;

        // make sure we return the error, not the expired token
        let result = cache.token(Extensions::new()).await;
        assert!(result.is_err(), "{result:?}");
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
    async fn token_cache_multiple_requests_existing_valid_token() -> TestResult {
        let now = Instant::now();

        let token = Token {
            token: "initial-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token_clone = token.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token().times(1).return_once(|| Ok(token_clone));

        // fetch an initial token
        let cache = TokenCache::new(mock);
        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual, token);

        // Spawn N tasks, all asking for a token at once.
        let tasks = (0..1000)
            .map(|_| {
                let cache_clone = cache.clone();
                tokio::spawn(async move { cache_clone.token(Extensions::new()).await })
            })
            .collect::<Vec<_>>();

        // Wait for the N token requests to complete, verifying the returned token.
        for task in tasks {
            let actual = task.await??;
            assert_eq!(get_cached_token(actual)?, token);
        }
        Ok(())
    }

    #[tokio::test]
    async fn refresh_task_expired_token_loop() {
        let now = Instant::now();

        let token1 = Token {
            token: "token1".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now),
            metadata: None,
        };
        let token1_clone = token1.clone();

        let token2 = Token {
            token: "token2".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token2_clone = token2.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token1_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token2_clone));

        let (tx, mut rx) = watch::channel::<Option<Result<(Token, EntityTag)>>>(None);

        tokio::spawn(async move {
            refresh_task(Arc::new(mock), tx).await;
        });

        // Give the refresh task a chance to run
        sleep(Duration::from_millis(100)).await;

        rx.changed().await.unwrap();

        // Validate that the refresh loop tried getting new token almost immediately
        assert!(Instant::now() <= now + Duration::from_millis(500));

        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token2.clone());
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_task_loop() {
        let now = Instant::now();

        let token1 = Token {
            token: "token1".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token1_clone = token1.clone();

        let token2 = Token {
            token: "token2".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 2 * TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token2_clone = token2.clone();

        let token3 = Token {
            token: "token3".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 3 * TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token3_clone = token3.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token1_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token2_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token3_clone));

        let (tx, mut rx) = watch::channel::<Option<Result<(Token, EntityTag)>>>(None);

        // check that channel has None before refresh task starts
        let actual = rx.borrow().clone();
        assert!(actual.is_none(), "{actual:?}");

        tokio::spawn(async move {
            refresh_task(Arc::new(mock), tx).await;
        });

        rx.changed().await.unwrap();
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token1.clone());

        // Validate that it is the same token before it is stale
        let sleep = Duration::from_secs(120);
        tokio::time::advance(sleep).await;
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token1.clone());

        // time machine takes execution to 3 minutes before expiry
        tokio::time::advance(TOKEN_VALID_DURATION.sub(Duration::from_secs(300))).await;

        rx.changed().await.unwrap();

        // validate that the token changed less than 4 mins before expiry
        assert!(Instant::now() < now + TOKEN_VALID_DURATION);
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token2);

        // wait long enough for the token to be expired
        // Adding 500 secs to account for the time manipulation above
        let sleep = TOKEN_VALID_DURATION.add(Duration::from_secs(500));
        tokio::time::advance(sleep).await;

        rx.changed().await.unwrap();
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token3);
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_task_loop_less_expiry() {
        let now = Instant::now();

        let token1 = Token {
            token: "token1".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + Duration::from_secs(120)),
            metadata: None,
        };
        let token1_clone = token1.clone();
        let token1_clone2 = token1.clone();

        let token2 = Token {
            token: "token2".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 2 * TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token2_clone = token2.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token1_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token1_clone2));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token2_clone));

        let (tx, mut rx) = watch::channel::<Option<Result<(Token, EntityTag)>>>(None);

        // check that channel has None before refresh task starts
        let actual = rx.borrow().clone();
        assert!(actual.is_none(), "{actual:?}");

        tokio::spawn(async move {
            refresh_task(Arc::new(mock), tx).await;
        });

        rx.changed().await.unwrap();
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token1);

        // time machine forwards time by 10 secs
        tokio::time::advance(Duration::from_secs(10)).await;

        // validate that the same token is obtained and it was
        // attempted to be refreshed within 10ish seconds
        assert!(Instant::now() < now + Duration::from_secs(11));
        rx.changed().await.unwrap();
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token1);

        // time machine forwards time by 100 secs
        tokio::time::advance(Duration::from_secs(100)).await;

        rx.changed().await.unwrap();

        // validate that the token was refreshed within 10ish seconds
        // before expiry
        assert!(Instant::now() < now + Duration::from_secs(111));
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token2);
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_task_loop_long_expiry_waits_long_time_before_refresh() {
        let now = Instant::now();

        let token1 = Token {
            token: "token1".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 3 * NORMAL_REFRESH_SLACK),
            metadata: None,
        };
        let token1_clone = token1.clone();

        let token2 = Token {
            token: "token2".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 2 * TOKEN_VALID_DURATION),
            metadata: None,
        };
        let token2_clone = token2.clone();

        let mut mock = MockTokenProvider::new();
        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token1_clone));

        mock.expect_token()
            .times(1)
            .return_once(|| Ok(token2_clone));

        let (tx, mut rx) = watch::channel::<Option<Result<(Token, EntityTag)>>>(None);

        // check that channel has None before refresh task starts
        let actual = rx.borrow().clone();
        assert!(actual.is_none(), "{actual:?}");

        tokio::spawn(async move {
            refresh_task(Arc::new(mock), tx).await;
        });

        rx.changed().await.unwrap();

        tokio::time::advance(NORMAL_REFRESH_SLACK).await;

        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token1);

        tokio::time::advance(NORMAL_REFRESH_SLACK).await;
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token1);

        tokio::time::advance(2 * NORMAL_REFRESH_SLACK).await;
        let (actual, ..) = rx.borrow().clone().unwrap().unwrap();
        assert_eq!(actual, token2);
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_task_sleeps_on_transient_error_and_recovers_on_next_loop() -> TestResult {
        let now = Instant::now();

        let token = Token {
            token: "token-1".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + TOKEN_VALID_DURATION),
            metadata: None,
        };

        let mut mock = MockTokenProvider::new();
        // 1st request succeeds
        mock.expect_token()
            .times(1)
            .return_once(move || Ok(token.clone()));

        // 2nd request (triggered by refresh loop) fails with transient error
        mock.expect_token()
            .times(1)
            .return_once(|| Err(CredentialsError::from_msg(true, "transient error")));

        let token = Token {
            token: "token-2".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(now + 2 * TOKEN_VALID_DURATION),
            metadata: None,
        };

        // 3rd request (triggered by next loop) succeeds
        mock.expect_token()
            .times(1)
            .return_once(move || Ok(token.clone()));

        let cache = TokenCache::new(mock);

        // fetch an initial token
        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual.token, "token-1");

        // advance time to force expiration, which wakes up the background task.
        let sleep = TOKEN_VALID_DURATION.add(Duration::from_secs(10));
        tokio::time::advance(sleep).await;

        let result = cache.token(Extensions::new()).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("transient error"));

        // Wait another SHORT_REFRESH_SLACK + buffer for the background loop to try again and recover
        tokio::time::advance(SHORT_REFRESH_SLACK.add(Duration::from_secs(10))).await;
        tokio::task::yield_now().await;

        let actual = get_cached_token(cache.token(Extensions::new()).await.unwrap())?;
        assert_eq!(actual.token, "token-2");

        Ok(())
    }

    #[derive(Clone, Debug)]
    struct FakeTokenProvider {
        result: Result<Token>,
        calls: Arc<Mutex<i32>>,
    }

    impl FakeTokenProvider {
        pub fn new(result: Result<Token>) -> Self {
            FakeTokenProvider {
                result,
                calls: Arc::new(Mutex::new(0)),
            }
        }

        pub fn calls(&self) -> i32 {
            *self.calls.lock().unwrap()
        }
    }

    #[async_trait::async_trait]
    impl TokenProvider for FakeTokenProvider {
        async fn token(&self) -> Result<Token> {
            // We give enough time for a thundering herd to pile up, while
            // waiting for a change notification from the watch channel.
            sleep(Duration::from_millis(50)).await;

            // Track how many calls were made to the inner token provider.
            *self.calls.lock().unwrap() += 1;

            // Return the result.
            self.result.clone()
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
    async fn no_initial_token_thundering_herd_success() -> TestResult {
        let token = Token {
            token: "delayed-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: Some(Instant::now()),
            metadata: None,
        };

        let tp = FakeTokenProvider::new(Ok(token.clone()));

        let cache = TokenCache::new(tp.clone());

        // Spawn N tasks, all asking for a token at once.
        let tasks = (0..100)
            .map(|_| {
                let cache_clone = cache.clone();
                tokio::spawn(async move { cache_clone.token(Extensions::new()).await })
            })
            .collect::<Vec<_>>();

        // Wait for the N token requests to complete, verifying the returned token.
        for task in tasks {
            let actual = task.await??;
            assert_eq!(get_cached_token(actual)?, token);
        }

        let calls = tp.calls();
        // We expect one call to be made to the inner token provider. But if the
        // 100 tasks take longer than 50ms to launch, we may see multiple.
        assert!(calls < 10, "calls to inner token provider: {calls}");
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
    async fn no_initial_token_thundering_herd_failure_shares_error() -> TestResult {
        let err = Err(errors::non_retryable_from_str("epic fail"));

        let tp = FakeTokenProvider::new(err);

        let cache = TokenCache::new(tp.clone());

        // Spawn N tasks, all asking for a token at once.
        let tasks = (0..100)
            .map(|_| {
                let cache_clone = cache.clone();
                tokio::spawn(async move { cache_clone.token(Extensions::new()).await })
            })
            .collect::<Vec<_>>();

        // Wait for the N token requests to complete, verifying the returned error.
        for task in tasks {
            let actual = task.await?;
            assert!(actual.is_err(), "{actual:?}");
            let e = format!("{}", actual.unwrap_err());
            assert!(e.contains("epic fail"), "{e}");
        }

        let calls = tp.calls();
        // We expect one call to be made to the inner token provider. But if the
        // 100 tasks take longer than 50ms to launch, we may see multiple.
        assert!(calls < 10, "calls to inner token provider: {calls}");
        Ok(())
    }

    #[tokio::test]
    async fn debug_token_cache() {
        let mut mock_provider = MockTokenProvider::new();
        mock_provider.expect_token().return_const(Ok(Token {
            token: "test-token".to_string(),
            token_type: "Bearer".to_string(),
            expires_at: None,
            metadata: None,
        }));

        let cache = TokenCache::new(mock_provider);
        let debug_output = format!("{cache:?}");

        assert!(debug_output.contains("TokenCache"));
        assert!(debug_output.contains("rx_token"));
    }
}