Skip to main content

posemesh_compute_node/auth/
token_manager.rs

1use std::{
2    sync::{
3        atomic::{AtomicBool, Ordering},
4        Arc,
5    },
6    time::{Duration, Instant},
7};
8
9use async_trait::async_trait;
10use chrono::{DateTime, Utc};
11use rand::{rngs::StdRng, Rng, SeedableRng};
12use tokio::{
13    sync::{Mutex, Notify},
14    task::JoinHandle,
15    time::sleep,
16};
17use tracing::{info, warn};
18
19use super::siwe::{AccessBundle, SiweError};
20
21const DEFAULT_RATIO: f64 = 0.75;
22const MIN_DURATION: Duration = Duration::from_millis(1);
23pub(crate) const AUTH_FAILURE_BACKOFF: Duration = Duration::from_secs(30);
24
25#[async_trait]
26pub trait AccessAuthenticator: Send + Sync {
27    async fn login(&self) -> Result<AccessBundle, SiweError>;
28}
29
30pub trait Clock: Send + Sync {
31    fn now_instant(&self) -> Instant;
32    fn now_utc(&self) -> DateTime<Utc>;
33}
34
35#[derive(Clone)]
36pub struct SystemClock;
37
38impl Clock for SystemClock {
39    fn now_instant(&self) -> Instant {
40        Instant::now()
41    }
42
43    fn now_utc(&self) -> DateTime<Utc> {
44        Utc::now()
45    }
46}
47
48#[derive(Debug, Clone)]
49pub struct TokenManagerConfig {
50    pub safety_ratio: f64,
51    pub max_retries: u32,
52    pub jitter: Duration,
53}
54
55impl Default for TokenManagerConfig {
56    fn default() -> Self {
57        Self {
58            safety_ratio: DEFAULT_RATIO,
59            max_retries: 3,
60            jitter: Duration::from_millis(500),
61        }
62    }
63}
64
65impl TokenManagerConfig {
66    fn clamped_ratio(&self) -> f64 {
67        self.safety_ratio.clamp(0.0, 1.0)
68    }
69}
70
71#[derive(Debug, thiserror::Error)]
72pub enum TokenManagerError {
73    #[error("token manager stopped")]
74    Stopped,
75    #[error("token response already expired")]
76    Expired,
77    #[error("authentication failed after {attempts} attempts: {last_error}")]
78    Authentication {
79        attempts: u32,
80        #[source]
81        last_error: SiweError,
82    },
83    #[error("authentication retry is backing off")]
84    AuthenticationBackoff,
85}
86
87#[derive(Debug, thiserror::Error)]
88pub enum TokenProviderError {
89    #[error(transparent)]
90    TokenManager(#[from] TokenManagerError),
91    #[error("{0}")]
92    Message(String),
93}
94
95pub type TokenProviderResult<T> = std::result::Result<T, TokenProviderError>;
96
97#[async_trait]
98pub trait TokenProvider: Send + Sync {
99    async fn bearer(&self) -> TokenProviderResult<String>;
100    async fn on_unauthorized(&self);
101}
102
103pub struct TokenManager<A: AccessAuthenticator, C: Clock> {
104    auth: Arc<A>,
105    clock: Arc<C>,
106    config: TokenManagerConfig,
107    rng: Arc<Mutex<StdRng>>,
108    state: Arc<Mutex<State>>,
109    stopped: Arc<AtomicBool>,
110    stop_notify: Arc<Notify>,
111    state_notify: Arc<Notify>,
112    bg_task: Arc<Mutex<Option<JoinHandle<()>>>>,
113}
114
115impl<A: AccessAuthenticator, C: Clock> Clone for TokenManager<A, C> {
116    fn clone(&self) -> Self {
117        Self {
118            auth: Arc::clone(&self.auth),
119            clock: Arc::clone(&self.clock),
120            config: self.config.clone(),
121            rng: Arc::clone(&self.rng),
122            state: Arc::clone(&self.state),
123            stopped: Arc::clone(&self.stopped),
124            stop_notify: Arc::clone(&self.stop_notify),
125            state_notify: Arc::clone(&self.state_notify),
126            bg_task: Arc::clone(&self.bg_task),
127        }
128    }
129}
130
131#[async_trait]
132impl<A, C> TokenProvider for TokenManager<A, C>
133where
134    A: AccessAuthenticator + 'static,
135    C: Clock + 'static,
136{
137    async fn bearer(&self) -> TokenProviderResult<String> {
138        let now = self.clock.now_instant();
139        self.get_access(now)
140            .await
141            .map_err(TokenProviderError::TokenManager)
142    }
143
144    async fn on_unauthorized(&self) {
145        self.on_unauthorized_retry().await;
146    }
147}
148
149struct State {
150    token: Option<TokenEntry>,
151    inflight: Option<Arc<Notify>>,
152    retry_not_before: Option<Instant>,
153}
154
155#[derive(Clone)]
156struct TokenEntry {
157    value: String,
158    refresh_at: Instant,
159}
160
161impl TokenEntry {
162    fn is_valid(&self, now: Instant) -> bool {
163        now <= self.refresh_at
164    }
165}
166
167impl<A, C> TokenManager<A, C>
168where
169    A: AccessAuthenticator + 'static,
170    C: Clock + 'static,
171{
172    pub fn new(auth: Arc<A>, clock: Arc<C>, config: TokenManagerConfig) -> Self {
173        let rng = StdRng::from_entropy();
174        Self::with_rng(auth, clock, config, rng)
175    }
176
177    pub fn with_rng(auth: Arc<A>, clock: Arc<C>, config: TokenManagerConfig, rng: StdRng) -> Self {
178        Self {
179            auth,
180            clock,
181            config,
182            rng: Arc::new(Mutex::new(rng)),
183            state: Arc::new(Mutex::new(State {
184                token: None,
185                inflight: None,
186                retry_not_before: None,
187            })),
188            stopped: Arc::new(AtomicBool::new(false)),
189            stop_notify: Arc::new(Notify::new()),
190            state_notify: Arc::new(Notify::new()),
191            bg_task: Arc::new(Mutex::new(None)),
192        }
193    }
194
195    pub async fn get_access(&self, now: Instant) -> Result<String, TokenManagerError> {
196        loop {
197            let (notify, is_owner) = {
198                let mut state = self.state.lock().await;
199                if self.stopped.load(Ordering::SeqCst) {
200                    return Err(TokenManagerError::Stopped);
201                }
202                if let Some(entry) = &state.token {
203                    if entry.is_valid(now) {
204                        return Ok(entry.value.clone());
205                    }
206                }
207                if let Some(retry_not_before) = state.retry_not_before {
208                    if now < retry_not_before {
209                        return Err(TokenManagerError::AuthenticationBackoff);
210                    }
211                    state.retry_not_before = None;
212                }
213                match state.inflight.clone() {
214                    Some(existing) => (existing, false),
215                    None => {
216                        let notify = Arc::new(Notify::new());
217                        state.inflight = Some(notify.clone());
218                        (notify, true)
219                    }
220                }
221            };
222
223            if is_owner {
224                let result = self.reauth(now).await;
225                let mut refreshed = false;
226                let (notify_to_signal, outcome) = {
227                    let mut state = self.state.lock().await;
228                    let notify_opt = state.inflight.take();
229                    let outcome = match result {
230                        Ok(entry) => {
231                            let token = entry.value.clone();
232                            state.token = Some(entry);
233                            state.retry_not_before = None;
234                            refreshed = true;
235                            Ok(token)
236                        }
237                        Err(err) => {
238                            state.retry_not_before = Some(now + AUTH_FAILURE_BACKOFF);
239                            Err(err)
240                        }
241                    };
242                    (notify_opt, outcome)
243                };
244                if let Some(n) = notify_to_signal {
245                    n.notify_waiters();
246                }
247                if refreshed {
248                    self.state_notify.notify_waiters();
249                }
250                return outcome;
251            } else {
252                notify.notified().await;
253            }
254        }
255    }
256
257    pub async fn clear(&self) {
258        let mut state = self.state.lock().await;
259        state.token = None;
260        state.retry_not_before = None;
261        drop(state);
262        self.state_notify.notify_waiters();
263    }
264
265    pub async fn on_unauthorized_retry(&self) {
266        let mut state = self.state.lock().await;
267        state.retry_not_before = None;
268        if let Some(entry) = &mut state.token {
269            let now = self.clock.now_instant();
270            entry.refresh_at = now.checked_sub(MIN_DURATION).unwrap_or(now);
271        }
272        drop(state);
273        self.state_notify.notify_waiters();
274    }
275
276    pub async fn stop(&self) {
277        self.stopped.store(true, Ordering::SeqCst);
278        self.stop_notify.notify_waiters();
279        let notify = {
280            let mut state = self.state.lock().await;
281            state.token = None;
282            state.retry_not_before = None;
283            let inflight = state.inflight.take();
284            drop(state);
285            self.state_notify.notify_waiters();
286            inflight
287        };
288        if let Some(waiters) = notify {
289            waiters.notify_waiters();
290        }
291        if let Some(handle) = self.take_bg_handle().await {
292            let _ = handle.await;
293        }
294    }
295
296    pub async fn start_bg(&self) {
297        let mut guard = self.bg_task.lock().await;
298        if guard.is_some() {
299            return;
300        }
301        if self.stopped.load(Ordering::SeqCst) {
302            self.stopped.store(false, Ordering::SeqCst);
303        }
304        let manager = self.clone();
305        let handle = tokio::spawn(async move {
306            manager.background_loop().await;
307        });
308        *guard = Some(handle);
309    }
310
311    pub async fn stop_bg(&self) {
312        self.stop().await;
313    }
314
315    async fn reauth(&self, now: Instant) -> Result<TokenEntry, TokenManagerError> {
316        if self.stopped.load(Ordering::SeqCst) {
317            return Err(TokenManagerError::Stopped);
318        }
319
320        let attempts = self.config.max_retries.saturating_add(1);
321        let mut last_error: Option<SiweError> = None;
322
323        for attempt in 1..=attempts {
324            if self.stopped.load(Ordering::SeqCst) {
325                return Err(TokenManagerError::Stopped);
326            }
327
328            let login_fut = self.auth.login();
329            tokio::pin!(login_fut);
330            let stop_fut = self.stop_notify.notified();
331            tokio::pin!(stop_fut);
332
333            let bundle = tokio::select! {
334                res = &mut login_fut => res,
335                _ = &mut stop_fut => return Err(TokenManagerError::Stopped),
336            };
337
338            match bundle {
339                Ok(bundle) => match self.bundle_to_entry(&bundle, now).await {
340                    Ok(entry) => {
341                        let ttl = entry.refresh_at.saturating_duration_since(now);
342                        info!(
343                            expires_in_ms = ttl.as_millis(),
344                            "Refreshed DDS access token"
345                        );
346                        return Ok(entry);
347                    }
348                    Err(err) => {
349                        warn!(attempt, error = %err, "DDS authentication response invalid");
350                        last_error = Some(err);
351                    }
352                },
353                Err(err) => {
354                    warn!(attempt, error = %err, "DDS authentication failed");
355                    last_error = Some(err);
356                }
357            }
358
359            if attempt < attempts {
360                let delay = self.next_delay().await;
361                if !delay.is_zero() {
362                    tokio::time::sleep(delay).await;
363                }
364            }
365        }
366
367        Err(TokenManagerError::Authentication {
368            attempts,
369            last_error: last_error.unwrap_or_else(|| SiweError::MissingField("access_token")),
370        })
371    }
372
373    async fn bundle_to_entry(
374        &self,
375        bundle: &AccessBundle,
376        now: Instant,
377    ) -> Result<TokenEntry, SiweError> {
378        let now_utc = self.clock.now_utc();
379        let expires_at = bundle.expires_at();
380        let ttl = expires_at
381            .signed_duration_since(now_utc)
382            .to_std()
383            .map_err(|_| SiweError::MissingField("expires_at"))?;
384        if ttl.is_zero() {
385            return Err(SiweError::MissingField("expires_at"));
386        }
387
388        let ratio = self.config.clamped_ratio();
389        let safe_secs = ttl.as_secs_f64() * ratio;
390        let safe_duration = if safe_secs <= 0.0 {
391            MIN_DURATION.min(ttl)
392        } else {
393            Duration::from_secs_f64(safe_secs).min(ttl)
394        };
395
396        let actual_expiry = now + ttl;
397        let base_refresh = now + safe_duration;
398
399        let jitter_ms = self.sample_jitter_ms().await;
400        let refresh_at = if jitter_ms >= 0 {
401            let add = Duration::from_millis(jitter_ms as u64);
402            base_refresh + add
403        } else {
404            let sub = Duration::from_millis((-jitter_ms) as u64);
405            base_refresh.checked_sub(sub).unwrap_or(now)
406        };
407
408        let min_refresh = now + MIN_DURATION.min(ttl);
409        let mut refresh_at = refresh_at.max(min_refresh);
410        refresh_at = refresh_at.min(actual_expiry);
411
412        Ok(TokenEntry {
413            value: bundle.token().to_string(),
414            refresh_at,
415        })
416    }
417
418    async fn next_delay(&self) -> Duration {
419        if self.config.jitter.is_zero() {
420            return Duration::ZERO;
421        }
422        let mut rng = self.rng.lock().await;
423        let max_ms = self.config.jitter.as_millis() as u64;
424        if max_ms == 0 {
425            Duration::ZERO
426        } else {
427            let jitter_ms = rng.gen_range(0..=max_ms);
428            Duration::from_millis(jitter_ms)
429        }
430    }
431
432    async fn sample_jitter_ms(&self) -> i64 {
433        if self.config.jitter.is_zero() {
434            return 0;
435        }
436        let max_ms_u128 = self.config.jitter.as_millis();
437        let max_ms = max_ms_u128.min(i64::MAX as u128) as i64;
438        if max_ms == 0 {
439            return 0;
440        }
441        let mut rng = self.rng.lock().await;
442        rng.gen_range(-max_ms..=max_ms)
443    }
444
445    async fn take_bg_handle(&self) -> Option<JoinHandle<()>> {
446        let mut guard = self.bg_task.lock().await;
447        guard.take()
448    }
449
450    async fn background_loop(self) {
451        loop {
452            if self.stopped.load(Ordering::SeqCst) {
453                break;
454            }
455
456            match self.next_refresh_target().await {
457                Some(target) => {
458                    let now = self.clock.now_instant();
459                    if target <= now {
460                        if let Err(err) = self.get_access(now).await {
461                            warn!(
462                                error = %err,
463                                retry_in_ms = AUTH_FAILURE_BACKOFF.as_millis(),
464                                "Background DDS authentication attempt failed"
465                            );
466                            if !self.wait_after_background_failure().await {
467                                break;
468                            }
469                        }
470                        continue;
471                    }
472
473                    let delay = target.saturating_duration_since(now);
474
475                    tokio::select! {
476                        _ = self.stop_notify.notified() => break,
477                        _ = self.state_notify.notified() => continue,
478                        _ = sleep(delay) => {}
479                    }
480
481                    if self.stopped.load(Ordering::SeqCst) {
482                        break;
483                    }
484
485                    let now = self.clock.now_instant();
486                    if let Err(err) = self.get_access(now).await {
487                        warn!(
488                            error = %err,
489                            retry_in_ms = AUTH_FAILURE_BACKOFF.as_millis(),
490                            "Background DDS authentication attempt failed"
491                        );
492                        if !self.wait_after_background_failure().await {
493                            break;
494                        }
495                    }
496                }
497                None => {
498                    tokio::select! {
499                        _ = self.stop_notify.notified() => break,
500                        _ = self.state_notify.notified() => {}
501                    }
502                }
503            }
504        }
505    }
506
507    async fn wait_after_background_failure(&self) -> bool {
508        if self.stopped.load(Ordering::SeqCst) {
509            return false;
510        }
511
512        tokio::select! {
513            _ = self.stop_notify.notified() => false,
514            _ = self.state_notify.notified() => true,
515            _ = sleep(AUTH_FAILURE_BACKOFF) => true,
516        }
517    }
518
519    async fn next_refresh_target(&self) -> Option<Instant> {
520        let state = self.state.lock().await;
521        state.token.as_ref().map(|entry| entry.refresh_at)
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528    use std::{
529        collections::VecDeque,
530        sync::{
531            atomic::{AtomicUsize, Ordering as AtomicOrdering},
532            Arc,
533        },
534    };
535    use tokio::task::yield_now;
536    use tokio::time::advance;
537
538    struct TestClock {
539        start_instant: Instant,
540        instant_offset: std::sync::Mutex<Duration>,
541        start_utc: DateTime<Utc>,
542        utc_offset: std::sync::Mutex<chrono::Duration>,
543    }
544
545    impl TestClock {
546        fn new() -> Self {
547            Self {
548                start_instant: Instant::now(),
549                instant_offset: std::sync::Mutex::new(Duration::ZERO),
550                start_utc: Utc::now(),
551                utc_offset: std::sync::Mutex::new(chrono::Duration::zero()),
552            }
553        }
554    }
555
556    impl Clock for TestClock {
557        fn now_instant(&self) -> Instant {
558            let offset = self.instant_offset.lock().unwrap();
559            self.start_instant + *offset
560        }
561
562        fn now_utc(&self) -> DateTime<Utc> {
563            let offset = self.utc_offset.lock().unwrap();
564            self.start_utc + *offset
565        }
566    }
567
568    struct QueueAuthenticator {
569        calls: AtomicUsize,
570        responses: Mutex<VecDeque<Result<AccessBundle, SiweError>>>,
571    }
572
573    impl QueueAuthenticator {
574        fn new(responses: VecDeque<Result<AccessBundle, SiweError>>) -> Self {
575            Self {
576                calls: AtomicUsize::new(0),
577                responses: Mutex::new(responses),
578            }
579        }
580
581        fn calls(&self) -> usize {
582            self.calls.load(AtomicOrdering::SeqCst)
583        }
584    }
585
586    #[async_trait]
587    impl AccessAuthenticator for QueueAuthenticator {
588        async fn login(&self) -> Result<AccessBundle, SiweError> {
589            self.calls.fetch_add(1, AtomicOrdering::SeqCst);
590            let mut guard = self.responses.lock().await;
591            guard
592                .pop_front()
593                .unwrap_or_else(|| Err(SiweError::MissingField("access_token")))
594        }
595    }
596
597    fn access_bundle(token: &str, ttl_secs: i64) -> AccessBundle {
598        let expires_at = Utc::now() + chrono::Duration::seconds(ttl_secs);
599        AccessBundle::new(token.to_string(), expires_at)
600    }
601
602    struct TokioTestClock {
603        start_tokio: tokio::time::Instant,
604        start_std: Instant,
605        start_utc: DateTime<Utc>,
606    }
607
608    impl TokioTestClock {
609        fn new() -> Self {
610            let start_tokio = tokio::time::Instant::now();
611            Self {
612                start_std: start_tokio.into_std(),
613                start_utc: Utc::now(),
614                start_tokio,
615            }
616        }
617    }
618
619    impl Clock for TokioTestClock {
620        fn now_instant(&self) -> Instant {
621            let now_tokio = tokio::time::Instant::now();
622            let offset = now_tokio.duration_since(self.start_tokio);
623            self.start_std + offset
624        }
625
626        fn now_utc(&self) -> DateTime<Utc> {
627            let now_tokio = tokio::time::Instant::now();
628            let offset = now_tokio.duration_since(self.start_tokio);
629            self.start_utc + chrono::Duration::from_std(offset).unwrap()
630        }
631    }
632
633    struct RecordingAuthenticator {
634        clock: Arc<TokioTestClock>,
635        ttl: chrono::Duration,
636        calls: Mutex<Vec<tokio::time::Instant>>,
637        counter: AtomicUsize,
638    }
639
640    struct SuccessThenFailAuthenticator {
641        clock: Arc<TokioTestClock>,
642        calls: AtomicUsize,
643    }
644
645    impl SuccessThenFailAuthenticator {
646        fn new(clock: Arc<TokioTestClock>) -> Self {
647            Self {
648                clock,
649                calls: AtomicUsize::new(0),
650            }
651        }
652
653        fn calls(&self) -> usize {
654            self.calls.load(AtomicOrdering::SeqCst)
655        }
656    }
657
658    #[async_trait]
659    impl AccessAuthenticator for SuccessThenFailAuthenticator {
660        async fn login(&self) -> Result<AccessBundle, SiweError> {
661            let call = self.calls.fetch_add(1, AtomicOrdering::SeqCst);
662            if call == 0 {
663                return Ok(AccessBundle::new(
664                    "initial-token",
665                    self.clock.now_utc() + chrono::Duration::seconds(10),
666                ));
667            }
668
669            Err(SiweError::MissingField("access_token"))
670        }
671    }
672
673    impl RecordingAuthenticator {
674        fn new(clock: Arc<TokioTestClock>, ttl: chrono::Duration) -> Self {
675            Self {
676                clock,
677                ttl,
678                calls: Mutex::new(Vec::new()),
679                counter: AtomicUsize::new(0),
680            }
681        }
682
683        fn call_count(&self) -> usize {
684            self.counter.load(AtomicOrdering::SeqCst)
685        }
686
687        async fn call_history(&self) -> Vec<tokio::time::Instant> {
688            self.calls.lock().await.clone()
689        }
690    }
691
692    #[async_trait]
693    impl AccessAuthenticator for RecordingAuthenticator {
694        async fn login(&self) -> Result<AccessBundle, SiweError> {
695            let order = self.counter.fetch_add(1, AtomicOrdering::SeqCst) + 1;
696            self.calls.lock().await.push(tokio::time::Instant::now());
697            let expires_at = self.clock.now_utc() + self.ttl;
698            Ok(AccessBundle::new(format!("token-{order}"), expires_at))
699        }
700    }
701
702    #[tokio::test]
703    async fn concurrent_access_triggers_single_login() {
704        let responses = VecDeque::from([Ok(access_bundle("token-1", 3600))]);
705        let auth = Arc::new(QueueAuthenticator::new(responses));
706        let clock = Arc::new(TestClock::new());
707        let manager = TokenManager::with_rng(
708            auth.clone(),
709            clock.clone(),
710            TokenManagerConfig {
711                safety_ratio: 1.0,
712                max_retries: 0,
713                jitter: Duration::ZERO,
714            },
715            StdRng::seed_from_u64(42),
716        );
717
718        let now = clock.now_instant();
719        let tasks = (0..5).map(|_| {
720            let manager = manager.clone();
721            async move { manager.get_access(now).await.unwrap() }
722        });
723
724        let tokens: Vec<_> = futures::future::join_all(tasks).await;
725        assert!(tokens.iter().all(|t| t == "token-1"));
726        assert_eq!(auth.calls(), 1);
727    }
728
729    #[tokio::test]
730    async fn concurrent_failed_access_shares_backoff_without_reauthenticating() {
731        let responses = VecDeque::from([
732            Err(SiweError::MissingField("access_token")),
733            Ok(access_bundle("recovered-token", 3600)),
734        ]);
735        let auth = Arc::new(QueueAuthenticator::new(responses));
736        let clock = Arc::new(TestClock::new());
737        let manager = TokenManager::with_rng(
738            auth.clone(),
739            clock.clone(),
740            TokenManagerConfig {
741                safety_ratio: 1.0,
742                max_retries: 0,
743                jitter: Duration::ZERO,
744            },
745            StdRng::seed_from_u64(43),
746        );
747
748        let now = clock.now_instant();
749        let tasks = (0..5).map(|_| {
750            let manager = manager.clone();
751            async move { manager.get_access(now).await }
752        });
753        let results: Vec<_> = futures::future::join_all(tasks).await;
754
755        assert!(results.iter().all(Result::is_err));
756        assert_eq!(auth.calls(), 1);
757        assert!(matches!(
758            manager.get_access(now).await,
759            Err(TokenManagerError::AuthenticationBackoff)
760        ));
761        assert_eq!(auth.calls(), 1);
762
763        *clock.instant_offset.lock().unwrap() += AUTH_FAILURE_BACKOFF;
764        assert_eq!(
765            manager.get_access(clock.now_instant()).await.unwrap(),
766            "recovered-token"
767        );
768        assert_eq!(auth.calls(), 2);
769    }
770
771    #[tokio::test]
772    async fn unauthorized_forces_refresh_on_next_access() {
773        let responses = VecDeque::from([
774            Ok(access_bundle("token-1", 3600)),
775            Ok(access_bundle("token-2", 3600)),
776        ]);
777        let auth = Arc::new(QueueAuthenticator::new(responses));
778        let clock = Arc::new(TestClock::new());
779        let manager = TokenManager::with_rng(
780            auth.clone(),
781            clock.clone(),
782            TokenManagerConfig {
783                safety_ratio: 1.0,
784                max_retries: 0,
785                jitter: Duration::ZERO,
786            },
787            StdRng::seed_from_u64(1),
788        );
789
790        let now = clock.now_instant();
791        assert_eq!(manager.get_access(now).await.unwrap(), "token-1");
792        manager.on_unauthorized_retry().await;
793        let later = clock.now_instant();
794        assert_eq!(manager.get_access(later).await.unwrap(), "token-2");
795        assert_eq!(auth.calls(), 2);
796    }
797
798    #[tokio::test]
799    async fn retries_until_success() {
800        let responses = VecDeque::from([
801            Err(SiweError::MissingField("nonce")),
802            Ok(access_bundle("token-3", 3600)),
803        ]);
804        let auth = Arc::new(QueueAuthenticator::new(responses));
805        let clock = Arc::new(TestClock::new());
806        let manager = TokenManager::with_rng(
807            auth.clone(),
808            clock.clone(),
809            TokenManagerConfig {
810                safety_ratio: 1.0,
811                max_retries: 1,
812                jitter: Duration::ZERO,
813            },
814            StdRng::seed_from_u64(7),
815        );
816
817        let now = clock.now_instant();
818        assert_eq!(manager.get_access(now).await.unwrap(), "token-3");
819        assert_eq!(auth.calls(), 2);
820    }
821
822    struct HangingAuthenticator {
823        calls: AtomicUsize,
824        notify: Notify,
825    }
826
827    impl HangingAuthenticator {
828        fn new() -> Self {
829            Self {
830                calls: AtomicUsize::new(0),
831                notify: Notify::new(),
832            }
833        }
834
835        fn calls(&self) -> usize {
836            self.calls.load(AtomicOrdering::SeqCst)
837        }
838
839        fn release(&self) {
840            self.notify.notify_waiters();
841        }
842    }
843
844    #[async_trait]
845    impl AccessAuthenticator for HangingAuthenticator {
846        async fn login(&self) -> Result<AccessBundle, SiweError> {
847            self.calls.fetch_add(1, AtomicOrdering::SeqCst);
848            self.notify.notified().await;
849            Ok(access_bundle("never", 60))
850        }
851    }
852
853    #[tokio::test]
854    async fn stop_cancels_inflight_refresh() {
855        let auth = Arc::new(HangingAuthenticator::new());
856        let clock = Arc::new(TestClock::new());
857        let manager = TokenManager::with_rng(
858            auth.clone(),
859            clock.clone(),
860            TokenManagerConfig {
861                safety_ratio: 1.0,
862                max_retries: 0,
863                jitter: Duration::ZERO,
864            },
865            StdRng::seed_from_u64(99),
866        );
867
868        let now = clock.now_instant();
869        let mgr_clone = manager.clone();
870        let handle = tokio::spawn(async move { mgr_clone.get_access(now).await });
871
872        tokio::time::sleep(Duration::from_millis(50)).await;
873        assert_eq!(auth.calls(), 1);
874
875        manager.stop().await;
876        let result = handle.await.unwrap();
877        assert!(matches!(result, Err(TokenManagerError::Stopped)));
878
879        auth.release();
880    }
881
882    #[tokio::test(start_paused = true)]
883    async fn background_refresh_occurs_within_jitter() {
884        let clock = Arc::new(TokioTestClock::new());
885        let ttl = chrono::Duration::seconds(100);
886        let auth = Arc::new(RecordingAuthenticator::new(clock.clone(), ttl));
887        let config = TokenManagerConfig {
888            safety_ratio: 0.5,
889            max_retries: 0,
890            jitter: Duration::from_secs(10),
891        };
892
893        let seed = 123_u64;
894        let manager = TokenManager::with_rng(
895            auth.clone(),
896            clock.clone(),
897            config.clone(),
898            StdRng::seed_from_u64(seed),
899        );
900
901        manager.start_bg().await;
902        yield_now().await;
903
904        let now = clock.now_instant();
905        assert_eq!(manager.get_access(now).await.unwrap(), "token-1");
906
907        yield_now().await;
908
909        // Compute expected refresh timing based on deterministic RNG
910        let ttl_std = Duration::from_secs(100);
911        let safe_duration = Duration::from_secs(50);
912        let mut rng = StdRng::seed_from_u64(seed);
913        let jitter_ms_range = config.jitter.as_millis() as i64;
914        let jitter_ms = if jitter_ms_range == 0 {
915            0
916        } else {
917            rng.gen_range(-jitter_ms_range..=jitter_ms_range)
918        };
919
920        let mut expected = if jitter_ms >= 0 {
921            safe_duration + Duration::from_millis(jitter_ms as u64)
922        } else {
923            safe_duration
924                .checked_sub(Duration::from_millis((-jitter_ms) as u64))
925                .unwrap_or(Duration::ZERO)
926        };
927        let min_refresh = MIN_DURATION.min(ttl_std);
928        if expected < min_refresh {
929            expected = min_refresh;
930        }
931        if expected > ttl_std {
932            expected = ttl_std;
933        }
934
935        let before = expected.saturating_sub(Duration::from_millis(1));
936        advance(before).await;
937        yield_now().await;
938        assert_eq!(auth.call_count(), 1);
939
940        advance(Duration::from_millis(1)).await;
941        yield_now().await;
942
943        for _ in 0..5 {
944            if auth.call_count() >= 2 {
945                break;
946            }
947            advance(Duration::from_millis(1)).await;
948            yield_now().await;
949        }
950
951        assert_eq!(auth.call_count(), 2);
952        let calls = auth.call_history().await;
953        let elapsed = calls[1].duration_since(calls[0]);
954        let elapsed_std = Duration::from_secs_f64(elapsed.as_secs_f64());
955        assert!(elapsed_std >= expected);
956        assert!(elapsed_std <= expected + Duration::from_millis(10));
957    }
958
959    #[tokio::test(start_paused = true)]
960    async fn background_refresh_failure_waits_before_retrying() {
961        let clock = Arc::new(TokioTestClock::new());
962        let auth = Arc::new(SuccessThenFailAuthenticator::new(clock.clone()));
963        let manager = TokenManager::with_rng(
964            auth.clone(),
965            clock.clone(),
966            TokenManagerConfig {
967                safety_ratio: 0.5,
968                max_retries: 0,
969                jitter: Duration::ZERO,
970            },
971            StdRng::seed_from_u64(456),
972        );
973
974        manager.start_bg().await;
975        for _ in 0..3 {
976            yield_now().await;
977        }
978        assert_eq!(
979            manager.get_access(clock.now_instant()).await.unwrap(),
980            "initial-token"
981        );
982        for _ in 0..3 {
983            yield_now().await;
984        }
985
986        manager.on_unauthorized_retry().await;
987        for _ in 0..5 {
988            yield_now().await;
989            if auth.calls() >= 2 {
990                break;
991            }
992        }
993        assert_eq!(auth.calls(), 2);
994
995        advance(AUTH_FAILURE_BACKOFF - Duration::from_millis(1)).await;
996        yield_now().await;
997        assert_eq!(auth.calls(), 2);
998
999        advance(Duration::from_millis(1)).await;
1000        for _ in 0..5 {
1001            yield_now().await;
1002            if auth.calls() >= 3 {
1003                break;
1004            }
1005        }
1006        assert_eq!(auth.calls(), 3);
1007
1008        manager.stop_bg().await;
1009    }
1010
1011    #[tokio::test(start_paused = true)]
1012    async fn background_stop_prevents_refresh() {
1013        let clock = Arc::new(TokioTestClock::new());
1014        let ttl = chrono::Duration::seconds(100);
1015        let auth = Arc::new(RecordingAuthenticator::new(clock.clone(), ttl));
1016        let config = TokenManagerConfig {
1017            safety_ratio: 0.5,
1018            max_retries: 0,
1019            jitter: Duration::from_secs(5),
1020        };
1021
1022        let manager = TokenManager::with_rng(
1023            auth.clone(),
1024            clock.clone(),
1025            config,
1026            StdRng::seed_from_u64(321),
1027        );
1028
1029        manager.start_bg().await;
1030        yield_now().await;
1031
1032        let now = clock.now_instant();
1033        assert_eq!(manager.get_access(now).await.unwrap(), "token-1");
1034
1035        manager.stop_bg().await;
1036
1037        advance(Duration::from_secs(200)).await;
1038        yield_now().await;
1039
1040        assert_eq!(auth.call_count(), 1);
1041    }
1042}