Skip to main content

duroxide_pg/
entra.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Microsoft Entra ID (formerly Azure Active Directory) authentication support
5//! for [`PostgresProvider`](crate::PostgresProvider).
6//!
7//! This module exposes [`EntraAuthOptions`] — the configuration type passed to
8//! [`ProviderConfig::entra`](crate::ProviderConfig::entra) — plus the internal
9//! credential abstractions used to fetch and rotate Entra access tokens.
10//!
11//! Azure SDK types (`azure_core::credentials::TokenCredential`,
12//! `azure_identity::ManagedIdentityCredential`, etc.) are intentionally **not
13//! re-exported**. The public surface is just [`EntraAuthOptions`]; everything
14//! else stays internal so we can adapt to upstream churn without a breaking
15//! change.
16
17use std::sync::Arc;
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use anyhow::{Context, Result};
21use async_trait::async_trait;
22use azure_core::credentials::TokenCredential;
23use azure_identity::{
24    DeveloperToolsCredential, ManagedIdentityCredential, WorkloadIdentityCredential,
25};
26
27/// The default audience/scope used when requesting Entra ID access tokens for
28/// Azure Database for PostgreSQL Flexible Server in the Azure public cloud.
29///
30/// Sovereign clouds (Azure US Government, Azure China, etc.) require a
31/// different audience; override via [`EntraAuthOptions::audience`].
32pub const DEFAULT_AUDIENCE: &str = "https://ossrdbms-aad.database.windows.net/.default";
33
34/// Default `max_connections` for the pool. Matches the password-path default
35/// in [`PostgresProvider::new_with_schema`](crate::PostgresProvider::new_with_schema)
36/// when `DUROXIDE_PG_POOL_MAX` is not set.
37const DEFAULT_MAX_CONNECTIONS: u32 = 10;
38
39/// Default acquire timeout for the pool. Matches the password path.
40const DEFAULT_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(30);
41
42/// Default refresh-interval ceiling. Treated as a *ceiling* — the actual
43/// refresh schedule is driven by each token's `expires_at` minus a safety
44/// margin (see Phase 2 of the implementation plan / refresh task in
45/// `provider.rs`).
46///
47/// Entra access tokens for Azure Database for PostgreSQL typically expire
48/// after one hour; refreshing every twenty minutes keeps connect options
49/// fresh well before expiry under normal conditions while keeping background
50/// chatter minimal.
51const DEFAULT_REFRESH_INTERVAL: Duration = Duration::from_secs(20 * 60);
52
53/// Configuration for connecting to Azure Database for PostgreSQL using
54/// Microsoft Entra ID authentication.
55///
56/// Construct with [`EntraAuthOptions::new`] (sensible Azure-public-cloud
57/// defaults) and customize via the chainable mutators below.
58///
59/// # Example
60///
61/// ```rust,no_run
62/// use duroxide_pg::entra::EntraAuthOptions;
63/// use std::time::Duration;
64///
65/// let opts = EntraAuthOptions::new()
66///     .max_connections(20)
67///     .acquire_timeout(Duration::from_secs(45));
68/// # let _ = opts;
69/// ```
70#[derive(Clone, Debug)]
71pub struct EntraAuthOptions {
72    audience: String,
73    max_connections: u32,
74    acquire_timeout: Duration,
75    refresh_interval: Duration,
76}
77
78impl Default for EntraAuthOptions {
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84impl EntraAuthOptions {
85    /// Create options with Azure public cloud defaults.
86    pub fn new() -> Self {
87        let max_connections = std::env::var("DUROXIDE_PG_POOL_MAX")
88            .ok()
89            .and_then(|s| s.parse::<u32>().ok())
90            .unwrap_or(DEFAULT_MAX_CONNECTIONS);
91        Self {
92            audience: DEFAULT_AUDIENCE.to_string(),
93            max_connections,
94            acquire_timeout: DEFAULT_ACQUIRE_TIMEOUT,
95            refresh_interval: DEFAULT_REFRESH_INTERVAL,
96        }
97    }
98
99    /// Override the token audience/scope. Required for sovereign clouds
100    /// (e.g., Azure US Government uses
101    /// `https://ossrdbms-aad.database.usgovcloudapi.net/.default`).
102    pub fn audience(mut self, audience: impl Into<String>) -> Self {
103        self.audience = audience.into();
104        self
105    }
106
107    /// Override the pool's maximum connection count.
108    ///
109    /// A value of `0` is silently clamped to `1` because the pool's
110    /// hardcoded `min_connections(1)` would otherwise reject the
111    /// configuration at runtime (SF-G).
112    pub fn max_connections(mut self, max: u32) -> Self {
113        self.max_connections = max.max(1);
114        self
115    }
116
117    /// Override the pool's connection acquisition timeout.
118    pub fn acquire_timeout(mut self, timeout: Duration) -> Self {
119        self.acquire_timeout = timeout;
120        self
121    }
122
123    /// Override the upper bound on time between refresh attempts. The
124    /// background refresh task may refresh sooner than this interval if a
125    /// token's `expires_at` is approaching.
126    pub fn refresh_interval(mut self, interval: Duration) -> Self {
127        self.refresh_interval = interval;
128        self
129    }
130
131    /// Internal: read accessor for the audience.
132    pub(crate) fn audience_str(&self) -> &str {
133        &self.audience
134    }
135
136    /// Internal: read accessor for max pool connections.
137    pub(crate) fn max_connections_value(&self) -> u32 {
138        self.max_connections
139    }
140
141    /// Internal: read accessor for acquire timeout.
142    pub(crate) fn acquire_timeout_value(&self) -> Duration {
143        self.acquire_timeout
144    }
145
146    /// Internal: read accessor for refresh-interval ceiling.
147    pub(crate) fn refresh_interval_value(&self) -> Duration {
148        self.refresh_interval
149    }
150
151    /// Construct the default [`TokenSource`] (the [`AzureIdentityTokenSource`]
152    /// wrapping the chained credential).
153    ///
154    /// Surfaces a descriptive error if the underlying Azure SDK fails to build
155    /// any credential in the chain.
156    pub(crate) fn default_token_source(&self) -> Result<Arc<dyn TokenSource>> {
157        let credential =
158            build_default_chained_credential().context("Entra credential resolution failed")?;
159        Ok(Arc::new(AzureIdentityTokenSource::new(credential)))
160    }
161}
162
163/// An Entra access token plus the wall-clock time at which it expires.
164///
165/// `Debug` is hand-written to redact the token secret. The struct is
166/// `pub(crate)` so it never leaves the crate, but a panic backtrace or
167/// `?token` formatter inside the crate could otherwise leak the bearer
168/// string into logs.
169#[derive(Clone)]
170pub(crate) struct EntraToken {
171    pub(crate) secret: String,
172    pub(crate) expires_at: SystemTime,
173}
174
175impl std::fmt::Debug for EntraToken {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        f.debug_struct("EntraToken")
178            .field("secret", &"<redacted>")
179            .field("expires_at", &self.expires_at)
180            .finish()
181    }
182}
183
184impl EntraToken {
185    pub(crate) fn new(secret: String, expires_at: SystemTime) -> Self {
186        Self { secret, expires_at }
187    }
188}
189
190/// Internal seam for fetching Entra tokens. Kept `pub(crate)` so the public
191/// surface of `duroxide-pg` does not bind callers to a specific `azure_*`
192/// version (mitigation for spec Risk #2). Tests in this crate inject fake
193/// implementations via this trait.
194#[async_trait]
195pub(crate) trait TokenSource: Send + Sync {
196    async fn fetch_token(&self, scopes: &[&str]) -> Result<EntraToken>;
197}
198
199/// Production [`TokenSource`] that delegates to an
200/// [`azure_core::credentials::TokenCredential`].
201pub(crate) struct AzureIdentityTokenSource {
202    credential: Arc<dyn TokenCredential>,
203}
204
205impl AzureIdentityTokenSource {
206    pub(crate) fn new(credential: Arc<dyn TokenCredential>) -> Self {
207        Self { credential }
208    }
209}
210
211#[async_trait]
212impl TokenSource for AzureIdentityTokenSource {
213    async fn fetch_token(&self, scopes: &[&str]) -> Result<EntraToken> {
214        let access = self
215            .credential
216            .get_token(scopes, None)
217            .await
218            .map_err(|e| anyhow::anyhow!("Entra token acquisition failed: {e}"))?;
219
220        let expires_at = offset_datetime_to_system_time(access.expires_on);
221        validate_token_freshness(
222            SystemTime::now(),
223            expires_at,
224            crate::provider::ENTRA_REFRESH_SAFETY_MARGIN,
225        )?;
226        Ok(EntraToken::new(
227            access.token.secret().to_string(),
228            expires_at,
229        ))
230    }
231}
232
233/// Convert an `azure_core::time::OffsetDateTime` (from `time` crate) into a
234/// `SystemTime`. Treats pre-epoch values as `UNIX_EPOCH` (effectively immediate
235/// expiry).
236fn offset_datetime_to_system_time(t: azure_core::time::OffsetDateTime) -> SystemTime {
237    let seconds = t.unix_timestamp();
238    if seconds < 0 {
239        return UNIX_EPOCH;
240    }
241    UNIX_EPOCH
242        .checked_add(Duration::from_secs(seconds as u64))
243        .unwrap_or(UNIX_EPOCH)
244}
245
246/// Pure helper: validate that a freshly-issued token's `expires_at` leaves
247/// at least `margin` of useful lifetime relative to `now`. Defends against
248/// upstream returning an already-expired (or near-expired) token, which
249/// would otherwise produce an immediate connection-storm of 28xxx errors
250/// at the pool boundary (SF-D).
251///
252/// Returns `Ok(())` if the token is fresh enough, or an error explaining
253/// the skew/staleness on rejection.
254pub(crate) fn validate_token_freshness(
255    now: SystemTime,
256    expires_at: SystemTime,
257    margin: Duration,
258) -> Result<()> {
259    let cutoff = now
260        .checked_add(margin)
261        .ok_or_else(|| anyhow::anyhow!("clock arithmetic overflow validating token freshness"))?;
262    if expires_at <= cutoff {
263        let secs_remaining = expires_at
264            .duration_since(now)
265            .map(|d| d.as_secs() as i64)
266            .unwrap_or_else(|e| -(e.duration().as_secs() as i64));
267        anyhow::bail!(
268            "Entra token rejected: expires_at is too close to now \
269             (remaining={}s, required margin={}s). Possible upstream SDK \
270             bug, clock skew on the credential issuer, or stale cached \
271             token.",
272            secs_remaining,
273            margin.as_secs(),
274        );
275    }
276    Ok(())
277}
278
279/// Build the default chained credential used when the caller does not provide
280/// an explicit token source. The chain mimics the spirit of upstream
281/// `DefaultAzureCredential` (which is not present in `azure_identity = 0.35`):
282///
283/// 1. `WorkloadIdentityCredential` — federated tokens for AKS Workload
284///    Identity, GitHub OIDC, etc. (only succeeds when the corresponding env
285///    vars are set).
286/// 2. `ManagedIdentityCredential` — IMDS for Azure VMs, App Service,
287///    Container Apps, Container Instances, Functions.
288/// 3. `DeveloperToolsCredential` — Azure CLI (`az login`) and Azure Developer
289///    CLI (`azd auth login`) for local development.
290///
291/// Returns an `azure_core::Error` from any failed inner constructor; the
292/// caller wraps it into an `anyhow::Error`.
293fn build_default_chained_credential() -> azure_core::Result<Arc<dyn TokenCredential>> {
294    let mut sources: Vec<(&'static str, Arc<dyn TokenCredential>)> = Vec::new();
295    // WorkloadIdentityCredential::new only succeeds when AZURE_FEDERATED_TOKEN_FILE
296    // (and friends) are set. Skip silently otherwise so the chain still works
297    // on a developer laptop. Note: leaving these env vars set on a NON-AKS host
298    // can cause the chain to spend per-refresh latency budget here before
299    // falling through; see Docs.md "Troubleshooting" for details.
300    if let Ok(workload) = WorkloadIdentityCredential::new(None) {
301        sources.push(("WorkloadIdentityCredential", workload));
302    }
303    sources.push((
304        "ManagedIdentityCredential",
305        ManagedIdentityCredential::new(None)?,
306    ));
307    sources.push((
308        "DeveloperToolsCredential",
309        DeveloperToolsCredential::new(None)?,
310    ));
311    Ok(Arc::new(ChainedCredential::new(sources)))
312}
313
314/// Tiny `TokenCredential` chain — tries each source in order, returns the
315/// first that succeeds, aggregates errors otherwise. Modeled after upstream
316/// [`DeveloperToolsCredential`]'s chaining behavior.
317///
318/// Sources are stored alongside a static class-name so the first successful
319/// source can be logged at INFO — useful in production to confirm the
320/// expected principal class is being used (e.g. AKS pods should show
321/// `WorkloadIdentityCredential`, not `DeveloperToolsCredential`).
322///
323/// The INFO log fires **once per `ChainedCredential` instance** (gated via
324/// `OnceLock`) so a long-running process emits exactly one credential-class
325/// disclosure per provider, regardless of how many refreshes occur (SF-A).
326struct ChainedCredential {
327    sources: Vec<(&'static str, Arc<dyn TokenCredential>)>,
328    logged_first_success: std::sync::OnceLock<()>,
329}
330
331impl ChainedCredential {
332    fn new(sources: Vec<(&'static str, Arc<dyn TokenCredential>)>) -> Self {
333        Self {
334            sources,
335            logged_first_success: std::sync::OnceLock::new(),
336        }
337    }
338}
339
340impl std::fmt::Debug for ChainedCredential {
341    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342        f.write_str("ChainedCredential")
343    }
344}
345
346#[async_trait]
347impl TokenCredential for ChainedCredential {
348    async fn get_token(
349        &self,
350        scopes: &[&str],
351        options: Option<azure_core::credentials::TokenRequestOptions<'_>>,
352    ) -> azure_core::Result<azure_core::credentials::AccessToken> {
353        let mut errors: Vec<String> = Vec::new();
354        for (name, source) in &self.sources {
355            match source.get_token(scopes, options.clone()).await {
356                Ok(token) => {
357                    if self.logged_first_success.set(()).is_ok() {
358                        tracing::info!(
359                            target: "duroxide::providers::postgres",
360                            credential = %name,
361                            "Entra credential chain: token acquired (first success on this instance)",
362                        );
363                    }
364                    return Ok(token);
365                }
366                Err(e) => errors.push(format!("{name}: {e}")),
367            }
368        }
369        Err(azure_core::Error::with_message_fn(
370            azure_core::error::ErrorKind::Credential,
371            move || {
372                format!(
373                    "All chained Entra credentials failed to acquire a token:\n  - {}",
374                    errors.join("\n  - ")
375                )
376            },
377        ))
378    }
379}
380
381#[cfg(test)]
382pub(crate) mod test_support {
383    //! Test fixtures shared across crate unit tests (entra and provider).
384    use super::*;
385    use std::sync::atomic::{AtomicUsize, Ordering};
386    use std::sync::Mutex;
387
388    /// `TokenSource` fixture used across `entra` and `provider` unit tests.
389    /// Returns successive tokens from a script and records the scopes passed
390    /// to each call.
391    pub(crate) struct RecordingFakeTokenSource {
392        scripted: Mutex<Vec<EntraToken>>,
393        recorded_scopes: Mutex<Vec<Vec<String>>>,
394        call_count: AtomicUsize,
395        fail_with: Option<String>,
396    }
397
398    impl RecordingFakeTokenSource {
399        pub(crate) fn with_tokens(tokens: Vec<EntraToken>) -> Arc<Self> {
400            Arc::new(Self {
401                scripted: Mutex::new(tokens),
402                recorded_scopes: Mutex::new(Vec::new()),
403                call_count: AtomicUsize::new(0),
404                fail_with: None,
405            })
406        }
407
408        pub(crate) fn always_failing(message: impl Into<String>) -> Arc<Self> {
409            Arc::new(Self {
410                scripted: Mutex::new(Vec::new()),
411                recorded_scopes: Mutex::new(Vec::new()),
412                call_count: AtomicUsize::new(0),
413                fail_with: Some(message.into()),
414            })
415        }
416
417        pub(crate) fn call_count(&self) -> usize {
418            self.call_count.load(Ordering::SeqCst)
419        }
420
421        pub(crate) fn recorded_scopes(&self) -> Vec<Vec<String>> {
422            self.recorded_scopes.lock().unwrap().clone()
423        }
424    }
425
426    #[async_trait]
427    impl TokenSource for RecordingFakeTokenSource {
428        async fn fetch_token(&self, scopes: &[&str]) -> Result<EntraToken> {
429            self.call_count.fetch_add(1, Ordering::SeqCst);
430            self.recorded_scopes
431                .lock()
432                .unwrap()
433                .push(scopes.iter().map(|s| s.to_string()).collect());
434            if let Some(msg) = &self.fail_with {
435                return Err(anyhow::anyhow!("{msg}"));
436            }
437            let mut scripted = self.scripted.lock().unwrap();
438            if scripted.is_empty() {
439                return Err(anyhow::anyhow!(
440                    "RecordingFakeTokenSource: script exhausted"
441                ));
442            }
443            Ok(scripted.remove(0))
444        }
445    }
446
447    pub(crate) fn token(secret: &str, expires_in_secs: u64) -> EntraToken {
448        EntraToken::new(
449            secret.to_string(),
450            SystemTime::now() + Duration::from_secs(expires_in_secs),
451        )
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::test_support::*;
458    use super::*;
459
460    #[test]
461    fn defaults_match_password_path() {
462        let opts = EntraAuthOptions::new();
463        assert_eq!(opts.audience_str(), DEFAULT_AUDIENCE);
464        assert_eq!(opts.max_connections_value(), 10);
465        assert_eq!(opts.acquire_timeout_value(), Duration::from_secs(30));
466        assert_eq!(opts.refresh_interval_value(), DEFAULT_REFRESH_INTERVAL);
467    }
468
469    #[test]
470    fn audience_override_round_trips() {
471        let opts = EntraAuthOptions::new()
472            .audience("https://ossrdbms-aad.database.usgovcloudapi.net/.default");
473        assert_eq!(
474            opts.audience_str(),
475            "https://ossrdbms-aad.database.usgovcloudapi.net/.default"
476        );
477    }
478
479    #[test]
480    fn pool_tunables_round_trip() {
481        let opts = EntraAuthOptions::new()
482            .max_connections(5)
483            .acquire_timeout(Duration::from_secs(45))
484            .refresh_interval(Duration::from_secs(120));
485        assert_eq!(opts.max_connections_value(), 5);
486        assert_eq!(opts.acquire_timeout_value(), Duration::from_secs(45));
487        assert_eq!(opts.refresh_interval_value(), Duration::from_secs(120));
488    }
489
490    #[tokio::test]
491    async fn fake_token_source_returns_scripted_tokens() {
492        let source = RecordingFakeTokenSource::with_tokens(vec![
493            token("first", 3600),
494            token("second", 3600),
495        ]);
496        let t1 = source.fetch_token(&[DEFAULT_AUDIENCE]).await.unwrap();
497        let t2 = source.fetch_token(&[DEFAULT_AUDIENCE]).await.unwrap();
498        assert_eq!(t1.secret, "first");
499        assert_eq!(t2.secret, "second");
500        assert_eq!(source.call_count(), 2);
501        assert_eq!(
502            source.recorded_scopes(),
503            vec![
504                vec![DEFAULT_AUDIENCE.to_string()],
505                vec![DEFAULT_AUDIENCE.to_string()]
506            ]
507        );
508    }
509
510    #[tokio::test]
511    async fn fake_token_source_propagates_failures() {
512        let source = RecordingFakeTokenSource::always_failing("simulated");
513        let err = source
514            .fetch_token(&[DEFAULT_AUDIENCE])
515            .await
516            .expect_err("must fail");
517        assert!(err.to_string().contains("simulated"));
518        assert_eq!(source.call_count(), 1);
519    }
520
521    #[test]
522    fn offset_datetime_conversion_handles_negative() {
523        // OffsetDateTime::UNIX_EPOCH is the canonical zero; pre-epoch values
524        // should clamp to UNIX_EPOCH rather than panic / underflow.
525        let pre_epoch =
526            azure_core::time::OffsetDateTime::UNIX_EPOCH - azure_core::time::Duration::seconds(60);
527        assert_eq!(offset_datetime_to_system_time(pre_epoch), UNIX_EPOCH);
528
529        let post_epoch =
530            azure_core::time::OffsetDateTime::UNIX_EPOCH + azure_core::time::Duration::seconds(120);
531        let converted = offset_datetime_to_system_time(post_epoch);
532        assert_eq!(converted, UNIX_EPOCH + Duration::from_secs(120));
533    }
534
535    /// Minimal `TokenCredential` stub for chain ordering tests.
536    #[derive(Debug)]
537    struct StubCred {
538        ok: bool,
539        label: &'static str,
540    }
541
542    #[async_trait]
543    impl TokenCredential for StubCred {
544        async fn get_token(
545            &self,
546            _scopes: &[&str],
547            _options: Option<azure_core::credentials::TokenRequestOptions<'_>>,
548        ) -> azure_core::Result<azure_core::credentials::AccessToken> {
549            if self.ok {
550                Ok(azure_core::credentials::AccessToken::new(
551                    azure_core::credentials::Secret::new(format!("token-from-{}", self.label)),
552                    azure_core::time::OffsetDateTime::UNIX_EPOCH
553                        + azure_core::time::Duration::seconds(3_700_000_000),
554                ))
555            } else {
556                Err(azure_core::Error::with_message(
557                    azure_core::error::ErrorKind::Credential,
558                    format!("{} failed", self.label),
559                ))
560            }
561        }
562    }
563
564    #[tokio::test]
565    async fn chained_credential_returns_first_success_in_chain_order() {
566        let chain = ChainedCredential::new(vec![
567            (
568                "Failing",
569                Arc::new(StubCred {
570                    ok: false,
571                    label: "Failing",
572                }),
573            ),
574            (
575                "Winner",
576                Arc::new(StubCred {
577                    ok: true,
578                    label: "Winner",
579                }),
580            ),
581            (
582                "ShouldNotBeCalled",
583                Arc::new(StubCred {
584                    ok: true,
585                    label: "ShouldNotBeCalled",
586                }),
587            ),
588        ]);
589        let token = chain.get_token(&["aud"], None).await.unwrap();
590        assert_eq!(token.token.secret(), "token-from-Winner");
591    }
592
593    #[tokio::test]
594    async fn chained_credential_aggregates_class_names_in_failure_message() {
595        let chain = ChainedCredential::new(vec![
596            (
597                "Workload",
598                Arc::new(StubCred {
599                    ok: false,
600                    label: "WorkloadIdentity",
601                }),
602            ),
603            (
604                "Managed",
605                Arc::new(StubCred {
606                    ok: false,
607                    label: "ManagedIdentity",
608                }),
609            ),
610            (
611                "Dev",
612                Arc::new(StubCred {
613                    ok: false,
614                    label: "DeveloperTools",
615                }),
616            ),
617        ]);
618        let err = chain.get_token(&["aud"], None).await.expect_err("all fail");
619        let msg = format!("{err}");
620        assert!(msg.contains("Workload"), "{msg}");
621        assert!(msg.contains("Managed"), "{msg}");
622        assert!(msg.contains("Dev"), "{msg}");
623    }
624
625    /// SF-A: INFO log fires only on the first successful chain call per
626    /// instance, not on every refresh. We can't easily intercept `tracing`
627    /// output from a unit test without pulling in a subscriber crate, so
628    /// we instead pin the *gating mechanism* directly: the OnceLock must
629    /// be empty before the first call and populated after, and stay
630    /// populated after subsequent calls.
631    #[tokio::test]
632    async fn chained_credential_logs_first_success_only_once() {
633        let chain = ChainedCredential::new(vec![(
634            "Winner",
635            Arc::new(StubCred {
636                ok: true,
637                label: "Winner",
638            }),
639        )]);
640        assert!(
641            chain.logged_first_success.get().is_none(),
642            "should start unset"
643        );
644        let _ = chain.get_token(&["aud"], None).await.unwrap();
645        assert!(
646            chain.logged_first_success.get().is_some(),
647            "OnceLock must be populated after first success",
648        );
649        // Subsequent calls re-succeed but must NOT re-arm or re-log. The
650        // observable signal here is that `set` would have returned `Err`
651        // had we tried again — but get_token already swallows that. We
652        // verify by checking the OnceLock is still populated and the
653        // call still succeeds.
654        let _ = chain.get_token(&["aud"], None).await.unwrap();
655        assert!(chain.logged_first_success.get().is_some());
656    }
657
658    // SF-D: validate_token_freshness rejects stale/expired tokens.
659    #[test]
660    fn validate_token_freshness_rejects_already_expired_token() {
661        let now = SystemTime::now();
662        let expires_at = now - Duration::from_secs(10); // 10s in the past
663        let err = validate_token_freshness(now, expires_at, Duration::from_secs(60))
664            .expect_err("must reject");
665        let msg = format!("{err}");
666        assert!(msg.contains("too close to now"), "{msg}");
667        assert!(msg.contains("clock skew"), "{msg}");
668    }
669
670    #[test]
671    fn validate_token_freshness_rejects_token_within_safety_margin() {
672        let now = SystemTime::now();
673        // Token expires in 60s but margin requires 5min — must reject.
674        let expires_at = now + Duration::from_secs(60);
675        let err = validate_token_freshness(now, expires_at, Duration::from_secs(5 * 60))
676            .expect_err("must reject");
677        assert!(format!("{err}").contains("too close to now"));
678    }
679
680    #[test]
681    fn validate_token_freshness_accepts_fresh_token() {
682        let now = SystemTime::now();
683        let expires_at = now + Duration::from_secs(3600);
684        validate_token_freshness(now, expires_at, Duration::from_secs(5 * 60))
685            .expect("must accept fresh token");
686    }
687
688    #[test]
689    fn validate_token_freshness_rejects_at_exact_cutoff() {
690        // Boundary: token expiring exactly at now+margin should be rejected
691        // (we use strict `>`, not `>=`, because a token whose lifetime is
692        // exactly the margin has no useful working window).
693        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
694        let margin = Duration::from_secs(60);
695        let expires_at = now + margin;
696        validate_token_freshness(now, expires_at, margin).expect_err("must reject at exact cutoff");
697    }
698
699    // SF-G: max_connections(0) clamps to 1 to satisfy the
700    // hardcoded min_connections(1) invariant on the pool builder.
701    #[test]
702    fn max_connections_zero_is_clamped_to_one() {
703        let opts = EntraAuthOptions::new().max_connections(0);
704        assert_eq!(opts.max_connections_value(), 1);
705    }
706
707    #[test]
708    fn max_connections_one_is_preserved() {
709        let opts = EntraAuthOptions::new().max_connections(1);
710        assert_eq!(opts.max_connections_value(), 1);
711    }
712}