Skip to main content

azure_token_lite/
lib.rs

1//! Microsoft Entra ID (Azure AD) access tokens, using **your** HTTP client.
2//!
3//! This crate builds the token request, parses the response, and caches the
4//! result per scope. It performs no I/O: you hand it a closure that runs
5//! one HTTP request with whatever client your process already has.
6//!
7//! That is the whole design. `azure_identity` brings a transport, and a
8//! process that already has `hyper` or `reqwest` and a TLS stack does not
9//! want a second one to fetch a bearer token.
10//!
11//! # Examples
12//!
13//! ```
14//! # #[tokio::main(flavor = "current_thread")]
15//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
16//! use azure_token_lite::{Credential, TokenSource, ARM_SCOPE};
17//!
18//! let credential = Credential::client_secret("tenant", "client", "secret");
19//! let source = TokenSource::new(credential);
20//!
21//! let token = source
22//!     .token(ARM_SCOPE, |request| async move {
23//!         // Perform `request` with your own client and return the body.
24//!         # let _ = request;
25//!         Ok::<_, std::io::Error>(
26//!             r#"{"access_token":"eyJ...","expires_in":3600}"#.to_string(),
27//!         )
28//!     })
29//!     .await?;
30//!
31//! assert!(token.starts_with("eyJ"));
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! # Four things that are easy to get wrong
37//!
38//! **A scope and a resource are spelled differently.** The Entra v2
39//! endpoint takes a *scope* ending in `/.default`; a managed identity
40//! endpoint takes a *resource* without it. Sending one form to the other is
41//! a `400` that says nothing useful. [`resource_of`] converts.
42//!
43//! **`expires_in` is a number from Entra and a *string* from the identity
44//! endpoint.** Accepting both is one line here and an hour of confusion
45//! otherwise.
46//!
47//! **Different scopes are different tokens.** A token for Resource Manager
48//! sent to Log Analytics returns a `401` that looks exactly like a missing
49//! role assignment. The cache is keyed by scope for that reason.
50//!
51//! **IMDS is not the same as `IDENTITY_ENDPOINT`.** This crate implements
52//! the latter only — see [`Credential::ManagedIdentity`] for why.
53
54#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
55
56use std::collections::BTreeMap;
57use std::fmt;
58use std::time::Duration;
59
60use tokio::sync::Mutex;
61use tokio::time::Instant;
62
63/// The Azure Resource Manager scope.
64pub const ARM_SCOPE: &str = "https://management.azure.com/.default";
65
66/// The Log Analytics scope.
67///
68/// A **different** token from [`ARM_SCOPE`]. Sending the ARM one here
69/// returns a `401` that looks exactly like a missing role assignment, which
70/// is a long afternoon.
71pub const LOGS_SCOPE: &str = "https://api.loganalytics.io/.default";
72
73/// The Microsoft Graph scope.
74pub const GRAPH_SCOPE: &str = "https://graph.microsoft.com/.default";
75
76/// The managed-identity API version this crate requests.
77pub const IDENTITY_API_VERSION: &str = "2019-08-01";
78
79/// The environment variable naming the managed-identity endpoint.
80pub const IDENTITY_ENDPOINT_VARIABLE: &str = "IDENTITY_ENDPOINT";
81
82/// The environment variable carrying the managed-identity header secret.
83pub const IDENTITY_HEADER_VARIABLE: &str = "IDENTITY_HEADER";
84
85/// How long before a token's stated expiry it is treated as expired.
86///
87/// Five minutes: long enough that a token is never used in the last moments
88/// of its life, short enough that the cache still does its job across an
89/// hour-long token.
90pub const DEFAULT_EXPIRY_MARGIN: Duration = Duration::from_secs(300);
91
92/// What went wrong.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Error {
95    /// A managed-identity credential was selected but the environment does
96    /// not provide one.
97    NoAmbientCredential {
98        /// Which variable is missing.
99        variable: &'static str,
100    },
101    /// The response was not JSON.
102    NotJson,
103    /// The response carried no `access_token`.
104    NoAccessToken,
105}
106
107impl fmt::Display for Error {
108    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Self::NoAmbientCredential { variable } => write!(
111                formatter,
112                "{variable} is not set, so there is no ambient managed identity here"
113            ),
114            Self::NotJson => formatter.write_str("the token response is not JSON"),
115            Self::NoAccessToken => {
116                formatter.write_str("the token response carries no access_token")
117            }
118        }
119    }
120}
121
122impl std::error::Error for Error {}
123
124/// How to authenticate.
125#[derive(Clone)]
126pub enum Credential {
127    /// A service principal, with a client secret.
128    ClientSecret {
129        /// The directory (tenant) id.
130        tenant_id: String,
131        /// The application (client) id.
132        client_id: String,
133        /// The client secret.
134        client_secret: String,
135    },
136    /// The ambient managed identity, via `IDENTITY_ENDPOINT`.
137    ///
138    /// # Why not IMDS
139    ///
140    /// This crate deliberately does **not** fall back to the instance
141    /// metadata service at `169.254.169.254`. A request to that address
142    /// from a machine that is not in Azure does not fail fast; it hangs
143    /// until the socket times out, once per call. On a developer's laptop
144    /// that turns "works without Azure" into "works without Azure, after a
145    /// minute" — and the failure looks like a hung program rather than an
146    /// absent credential.
147    ///
148    /// App Service, Functions and Container Apps all set
149    /// `IDENTITY_ENDPOINT`. If you need IMDS, build the request yourself.
150    ManagedIdentity {
151        /// A user-assigned identity's client id, or [`None`] for the
152        /// system-assigned one.
153        client_id: Option<String>,
154    },
155}
156
157impl fmt::Debug for Credential {
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        // Never the secret.
160        match self {
161            Self::ClientSecret {
162                tenant_id,
163                client_id,
164                ..
165            } => formatter
166                .debug_struct("ClientSecret")
167                .field("tenant_id", tenant_id)
168                .field("client_id", client_id)
169                .field("client_secret", &"<redacted>")
170                .finish(),
171            Self::ManagedIdentity { client_id } => formatter
172                .debug_struct("ManagedIdentity")
173                .field("client_id", client_id)
174                .finish(),
175        }
176    }
177}
178
179impl Credential {
180    /// A service principal credential.
181    #[must_use]
182    pub fn client_secret(
183        tenant_id: impl Into<String>,
184        client_id: impl Into<String>,
185        client_secret: impl Into<String>,
186    ) -> Self {
187        Self::ClientSecret {
188            tenant_id: tenant_id.into(),
189            client_id: client_id.into(),
190            client_secret: client_secret.into(),
191        }
192    }
193
194    /// The system-assigned managed identity.
195    #[must_use]
196    pub const fn managed_identity() -> Self {
197        Self::ManagedIdentity { client_id: None }
198    }
199
200    /// A user-assigned managed identity.
201    #[must_use]
202    pub fn user_assigned_identity(client_id: impl Into<String>) -> Self {
203        Self::ManagedIdentity {
204            client_id: Some(client_id.into()),
205        }
206    }
207
208    /// A short description, safe to log.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use azure_token_lite::Credential;
214    ///
215    /// assert_eq!(
216    ///     Credential::client_secret("t", "c", "s").describe(),
217    ///     "service principal c in tenant t"
218    /// );
219    /// assert_eq!(
220    ///     Credential::managed_identity().describe(),
221    ///     "the system-assigned managed identity"
222    /// );
223    /// ```
224    #[must_use]
225    pub fn describe(&self) -> String {
226        match self {
227            Self::ClientSecret {
228                tenant_id,
229                client_id,
230                ..
231            } => format!("service principal {client_id} in tenant {tenant_id}"),
232            Self::ManagedIdentity { client_id: None } => {
233                "the system-assigned managed identity".to_string()
234            }
235            Self::ManagedIdentity {
236                client_id: Some(id),
237            } => format!("the user-assigned managed identity {id}"),
238        }
239    }
240
241    /// Build the HTTP request that obtains a token for `scope`.
242    ///
243    /// For [`Credential::ManagedIdentity`] this reads
244    /// [`IDENTITY_ENDPOINT_VARIABLE`] and [`IDENTITY_HEADER_VARIABLE`] from
245    /// the environment.
246    ///
247    /// # Errors
248    ///
249    /// [`Error::NoAmbientCredential`] when a managed identity was selected
250    /// and the environment does not provide one.
251    pub fn request(&self, scope: &str) -> Result<TokenRequest, Error> {
252        match self {
253            Self::ClientSecret {
254                tenant_id,
255                client_id,
256                client_secret,
257            } => Ok(TokenRequest {
258                method: Method::Post,
259                url: format!("https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"),
260                headers: Vec::new(),
261                body: Some(format!(
262                    "grant_type=client_credentials&client_id={}&client_secret={}&scope={}",
263                    form_encode(client_id),
264                    form_encode(client_secret),
265                    form_encode(scope),
266                )),
267            }),
268
269            Self::ManagedIdentity { client_id } => {
270                let endpoint = env_value(IDENTITY_ENDPOINT_VARIABLE).ok_or(
271                    Error::NoAmbientCredential {
272                        variable: IDENTITY_ENDPOINT_VARIABLE,
273                    },
274                )?;
275                let header = env_value(IDENTITY_HEADER_VARIABLE).ok_or(
276                    Error::NoAmbientCredential {
277                        variable: IDENTITY_HEADER_VARIABLE,
278                    },
279                )?;
280
281                // A *resource*, not a scope: the two endpoints disagree
282                // about the spelling.
283                let mut url = format!(
284                    "{endpoint}?api-version={IDENTITY_API_VERSION}&resource={}",
285                    form_encode(resource_of(scope)),
286                );
287                if let Some(client_id) = client_id {
288                    use fmt::Write as _;
289                    // Cannot fail: writing into a String.
290                    let _ = write!(url, "&client_id={}", form_encode(client_id));
291                }
292
293                Ok(TokenRequest {
294                    method: Method::Get,
295                    url,
296                    headers: vec![("X-IDENTITY-HEADER".to_string(), header)],
297                    body: None,
298                })
299            }
300        }
301    }
302}
303
304/// Which HTTP method a [`TokenRequest`] needs.
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306pub enum Method {
307    /// `GET`, for the managed-identity endpoint.
308    Get,
309    /// `POST`, for the Entra token endpoint.
310    Post,
311}
312
313impl Method {
314    /// The method name.
315    #[must_use]
316    pub const fn as_str(self) -> &'static str {
317        match self {
318            Self::Get => "GET",
319            Self::Post => "POST",
320        }
321    }
322}
323
324/// One HTTP request for the caller to perform.
325///
326/// A `body` of [`Some`] is already form-encoded and should be sent with
327/// `Content-Type: application/x-www-form-urlencoded`; [`CONTENT_TYPE`] is
328/// that string.
329///
330/// # This type does not print its body
331///
332/// The body of a client-credentials request contains the client secret.
333#[derive(Clone, PartialEq, Eq)]
334pub struct TokenRequest {
335    /// The method to use.
336    pub method: Method,
337    /// The absolute URL.
338    pub url: String,
339    /// Headers to add.
340    pub headers: Vec<(String, String)>,
341    /// The form-encoded body, when there is one.
342    pub body: Option<String>,
343}
344
345impl fmt::Debug for TokenRequest {
346    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
347        formatter
348            .debug_struct("TokenRequest")
349            .field("method", &self.method)
350            .field("url", &self.url)
351            // Header values carry the identity-endpoint secret.
352            .field(
353                "headers",
354                &self
355                    .headers
356                    .iter()
357                    .map(|(name, _)| name.as_str())
358                    .collect::<Vec<_>>(),
359            )
360            .field("body", &self.body.as_ref().map(|_| "<redacted>"))
361            .finish()
362    }
363}
364
365/// The `Content-Type` a [`TokenRequest`] with a body needs.
366pub const CONTENT_TYPE: &str = "application/x-www-form-urlencoded";
367
368/// A parsed token response.
369#[derive(Clone, PartialEq, Eq)]
370pub struct Token {
371    /// The bearer token.
372    pub access_token: String,
373    /// How long it is valid for, from when the response was produced.
374    pub expires_in: Duration,
375}
376
377impl fmt::Debug for Token {
378    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
379        formatter
380            .debug_struct("Token")
381            .field("access_token", &"<redacted>")
382            .field("expires_in", &self.expires_in)
383            .finish()
384    }
385}
386
387/// Parse a token response body.
388///
389/// # `expires_in` arrives in two shapes
390///
391/// A number from the Entra endpoint, a **string** from the managed-identity
392/// endpoint. Both are accepted. A response with neither is treated as
393/// already expired rather than as valid forever — the safe direction, since
394/// the cost is one extra request and the alternative is a token that is
395/// never refreshed.
396///
397/// # Errors
398///
399/// [`Error::NotJson`] or [`Error::NoAccessToken`].
400///
401/// # Examples
402///
403/// ```
404/// use azure_token_lite::parse_response;
405///
406/// # fn main() -> Result<(), azure_token_lite::Error> {
407/// let entra = parse_response(r#"{"access_token":"a","expires_in":3600}"#)?;
408/// let identity = parse_response(r#"{"access_token":"a","expires_in":"3600"}"#)?;
409///
410/// assert_eq!(entra.expires_in, identity.expires_in);
411/// # Ok(())
412/// # }
413/// ```
414pub fn parse_response(body: &str) -> Result<Token, Error> {
415    let document: serde_json::Value = serde_json::from_str(body).map_err(|_| Error::NotJson)?;
416
417    let access_token = document
418        .get("access_token")
419        .and_then(serde_json::Value::as_str)
420        .ok_or(Error::NoAccessToken)?
421        .to_string();
422
423    let seconds = document
424        .get("expires_in")
425        .and_then(|value| {
426            value
427                .as_u64()
428                .or_else(|| value.as_str().and_then(|text| text.parse::<u64>().ok()))
429        })
430        .unwrap_or(0);
431
432    Ok(Token {
433        access_token,
434        expires_in: Duration::from_secs(seconds),
435    })
436}
437
438/// The `resource` an identity endpoint wants, from a `.default` scope.
439///
440/// The two token endpoints disagree about spelling: Entra v2 takes a
441/// **scope** ending in `/.default`, the identity endpoint takes a
442/// **resource** without it. Sending one form to the other is a `400` that
443/// says nothing useful.
444///
445/// # Examples
446///
447/// ```
448/// use azure_token_lite::{resource_of, ARM_SCOPE};
449///
450/// assert_eq!(resource_of(ARM_SCOPE), "https://management.azure.com/");
451/// assert_eq!(resource_of("https://x/"), "https://x/", "already a resource");
452/// ```
453#[must_use]
454pub fn resource_of(scope: &str) -> &str {
455    scope.strip_suffix(".default").unwrap_or(scope)
456}
457
458/// Percent-encode a form value.
459///
460/// A client secret can contain any of `+ / = &`, and every one of them
461/// changes the meaning of a form body.
462///
463/// # Examples
464///
465/// ```
466/// use azure_token_lite::form_encode;
467///
468/// assert_eq!(form_encode("a+b/c=d&e"), "a%2Bb%2Fc%3Dd%26e");
469/// assert_eq!(form_encode("plain-value_1.0~x"), "plain-value_1.0~x");
470/// ```
471#[must_use]
472pub fn form_encode(value: &str) -> String {
473    let mut out = String::with_capacity(value.len());
474    for byte in value.bytes() {
475        match byte {
476            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
477                out.push(byte as char);
478            }
479            _ => {
480                use fmt::Write as _;
481                let _ = write!(out, "%{byte:02X}");
482            }
483        }
484    }
485    out
486}
487
488/// A variable's value, treating blank as absent.
489fn env_value(name: &str) -> Option<String> {
490    std::env::var(name)
491        .ok()
492        .map(|value| value.trim().to_string())
493        .filter(|value| !value.is_empty())
494}
495
496/// A token and when it stops being usable.
497#[derive(Debug, Clone)]
498struct Held {
499    /// The bearer token.
500    value: String,
501    /// When it may no longer be used — already reduced by the margin.
502    usable_until: Instant,
503}
504
505/// Where tokens come from: one per process, shared by everything.
506///
507/// # Why cache at all
508///
509/// An Entra token lasts about an hour. A process that fetches one per call
510/// turns one page load into a dozen token requests and meets Entra's own
511/// throttle.
512///
513/// # Why the lock is held across the fetch
514///
515/// Deliberately. A caller fanning out to four APIs at once makes **one**
516/// token request rather than four; the other three wait for it and then
517/// find it cached. Releasing the lock during the fetch would restore the
518/// stampede the cache exists to prevent.
519pub struct TokenSource {
520    /// How to authenticate.
521    credential: Credential,
522    /// Held tokens, by scope. Different scopes are different tokens, so
523    /// this cannot be a single slot.
524    held: Mutex<BTreeMap<String, Held>>,
525    /// How long before stated expiry a token is treated as expired.
526    margin: Duration,
527}
528
529impl fmt::Debug for TokenSource {
530    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
531        // Never the tokens, and never the secret.
532        formatter
533            .debug_struct("TokenSource")
534            .field("credential", &self.credential.describe())
535            .field("margin", &self.margin)
536            .finish_non_exhaustive()
537    }
538}
539
540impl TokenSource {
541    /// A source using this credential and [`DEFAULT_EXPIRY_MARGIN`].
542    #[must_use]
543    pub fn new(credential: Credential) -> Self {
544        Self {
545            credential,
546            held: Mutex::new(BTreeMap::new()),
547            margin: DEFAULT_EXPIRY_MARGIN,
548        }
549    }
550
551    /// Use a different expiry margin.
552    #[must_use]
553    pub fn with_expiry_margin(mut self, margin: Duration) -> Self {
554        self.margin = margin;
555        self
556    }
557
558    /// The credential this source uses.
559    #[must_use]
560    pub const fn credential(&self) -> &Credential {
561        &self.credential
562    }
563
564    /// A usable token for `scope`, from the cache when there is one.
565    ///
566    /// `perform` is given a [`TokenRequest`] and must return the response
567    /// body. It is only called on a cache miss.
568    ///
569    /// # Errors
570    ///
571    /// [`TokenError::Token`] for a problem building the request or reading
572    /// the response, or [`TokenError::Transport`] for whatever `perform`
573    /// returned.
574    ///
575    /// # Examples
576    ///
577    /// ```
578    /// # #[tokio::main(flavor = "current_thread")]
579    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
580    /// use azure_token_lite::{Credential, TokenSource, LOGS_SCOPE};
581    ///
582    /// let source = TokenSource::new(Credential::client_secret("t", "c", "s"));
583    ///
584    /// let token = source
585    ///     .token(LOGS_SCOPE, |request| async move {
586    ///         # let _ = request;
587    ///         Ok::<_, std::io::Error>(r#"{"access_token":"abc","expires_in":3600}"#.to_string())
588    ///     })
589    ///     .await?;
590    ///
591    /// assert_eq!(token, "abc");
592    /// # Ok(())
593    /// # }
594    /// ```
595    pub async fn token<F, Fut, E>(&self, scope: &str, perform: F) -> Result<String, TokenError<E>>
596    where
597        F: FnOnce(TokenRequest) -> Fut,
598        Fut: Future<Output = Result<String, E>>,
599    {
600        let mut held = self.held.lock().await;
601
602        if let Some(token) = held.get(scope)
603            && Instant::now() < token.usable_until
604        {
605            return Ok(token.value.clone());
606        }
607
608        let request = self.credential.request(scope).map_err(TokenError::Token)?;
609        let body = perform(request).await.map_err(TokenError::Transport)?;
610        let parsed = parse_response(&body).map_err(TokenError::Token)?;
611
612        // `saturating_sub` because a token shorter than the margin is
613        // simply not cached, rather than cached with a time in the past.
614        let usable_for = parsed.expires_in.saturating_sub(self.margin);
615        let value = parsed.access_token;
616
617        held.insert(
618            scope.to_string(),
619            Held {
620                value: value.clone(),
621                usable_until: Instant::now() + usable_for,
622            },
623        );
624
625        Ok(value)
626    }
627
628    /// Forget every cached token.
629    ///
630    /// For a caller that has seen a `401` and wants the next call to fetch
631    /// afresh rather than re-present a token the service has rejected.
632    pub async fn invalidate(&self) {
633        self.held.lock().await.clear();
634    }
635
636    /// Forget the cached token for one scope.
637    pub async fn invalidate_scope(&self, scope: &str) {
638        self.held.lock().await.remove(scope);
639    }
640}
641
642/// Why [`TokenSource::token`] failed.
643#[derive(Debug, Clone, PartialEq, Eq)]
644pub enum TokenError<E> {
645    /// Building the request, or reading the response.
646    Token(Error),
647    /// Whatever the caller's transport returned.
648    Transport(E),
649}
650
651impl<E: fmt::Display> fmt::Display for TokenError<E> {
652    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
653        match self {
654            Self::Token(error) => write!(formatter, "{error}"),
655            Self::Transport(error) => write!(formatter, "the token request failed: {error}"),
656        }
657    }
658}
659
660impl<E: fmt::Display + fmt::Debug> std::error::Error for TokenError<E> {}
661
662#[cfg(test)]
663mod tests {
664    use std::sync::Arc;
665    use std::sync::atomic::{AtomicUsize, Ordering};
666
667    use super::*;
668
669    /// A response body with a given lifetime.
670    fn response(seconds: u64) -> String {
671        format!(r#"{{"access_token":"token-{seconds}","expires_in":{seconds}}}"#)
672    }
673
674    fn principal() -> Credential {
675        Credential::client_secret("tenant-1", "client-1", "secret-1")
676    }
677
678    // -- request building --------------------------------------------------
679
680    #[test]
681    fn a_client_secret_request_posts_a_form_to_the_v2_endpoint() {
682        let request = principal().request(ARM_SCOPE).unwrap();
683
684        assert_eq!(request.method, Method::Post);
685        assert_eq!(
686            request.url,
687            "https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token"
688        );
689
690        let body = request.body.unwrap();
691        assert!(body.contains("grant_type=client_credentials"));
692        assert!(body.contains("client_id=client-1"));
693        // The scope keeps its `.default`, unlike the identity endpoint's.
694        assert!(body.contains("scope=https%3A%2F%2Fmanagement.azure.com%2F.default"));
695    }
696
697    #[test]
698    fn a_secret_with_awkward_characters_is_form_encoded() {
699        // A client secret can contain any of `+ / = &`, and every one of
700        // them changes the meaning of a form body.
701        let credential = Credential::client_secret("t", "c", "a+b/c=d&e");
702        let body = credential.request(ARM_SCOPE).unwrap().body.unwrap();
703
704        assert!(body.contains("client_secret=a%2Bb%2Fc%3Dd%26e"), "{body}");
705        assert_eq!(body.matches('&').count(), 3, "only the separators: {body}");
706    }
707
708    #[test]
709    fn a_managed_identity_request_needs_both_variables() {
710        // Reading process-global state, so this asserts the absent path
711        // without setting anything.
712        let credential = Credential::managed_identity();
713
714        // In a test process neither variable is set.
715        assert_eq!(
716            credential.request(ARM_SCOPE).unwrap_err(),
717            Error::NoAmbientCredential {
718                variable: IDENTITY_ENDPOINT_VARIABLE
719            }
720        );
721    }
722
723    #[test]
724    fn a_scope_becomes_a_resource_for_the_identity_endpoint() {
725        // The two endpoints disagree about the spelling, and sending one
726        // form to the other is a 400 that says nothing useful.
727        assert_eq!(resource_of(ARM_SCOPE), "https://management.azure.com/");
728        assert_eq!(resource_of(LOGS_SCOPE), "https://api.loganalytics.io/");
729        assert_eq!(resource_of("https://x/"), "https://x/");
730        assert_eq!(resource_of(""), "");
731    }
732
733    // -- response parsing --------------------------------------------------
734
735    #[test]
736    fn expires_in_is_accepted_as_a_number_or_a_string() {
737        // A number from Entra, a string from the identity endpoint.
738        let entra = parse_response(r#"{"access_token":"a","expires_in":3600}"#).unwrap();
739        let identity = parse_response(r#"{"access_token":"a","expires_in":"3600"}"#).unwrap();
740
741        assert_eq!(entra.expires_in, Duration::from_secs(3600));
742        assert_eq!(entra.expires_in, identity.expires_in);
743    }
744
745    #[test]
746    fn a_response_with_no_expiry_is_treated_as_already_expired() {
747        // The safe direction: the cost is one extra request, and the
748        // alternative is a token that is never refreshed.
749        let parsed = parse_response(r#"{"access_token":"a"}"#).unwrap();
750        assert_eq!(parsed.expires_in, Duration::ZERO);
751    }
752
753    #[test]
754    fn a_response_without_a_token_is_an_error() {
755        assert_eq!(
756            parse_response(r#"{"error":"invalid_client"}"#).unwrap_err(),
757            Error::NoAccessToken
758        );
759        assert_eq!(parse_response("not json").unwrap_err(), Error::NotJson);
760    }
761
762    #[test]
763    fn an_unparseable_expires_in_string_is_treated_as_expired() {
764        let parsed = parse_response(r#"{"access_token":"a","expires_in":"soon"}"#).unwrap();
765        assert_eq!(parsed.expires_in, Duration::ZERO);
766    }
767
768    // -- the cache ---------------------------------------------------------
769
770    #[tokio::test]
771    async fn a_second_call_for_the_same_scope_is_served_from_the_cache() {
772        let source = TokenSource::new(principal());
773        let calls = Arc::new(AtomicUsize::new(0));
774
775        for _ in 0..3 {
776            let calls = Arc::clone(&calls);
777            let token = source
778                .token(ARM_SCOPE, |_| async move {
779                    calls.fetch_add(1, Ordering::SeqCst);
780                    Ok::<_, String>(response(3600))
781                })
782                .await
783                .unwrap();
784            assert_eq!(token, "token-3600");
785        }
786
787        assert_eq!(calls.load(Ordering::SeqCst), 1, "one fetch, three calls");
788    }
789
790    #[tokio::test]
791    async fn different_scopes_are_different_tokens() {
792        // An ARM token sent to Log Analytics is a 401 that looks exactly
793        // like a missing role assignment.
794        let source = TokenSource::new(principal());
795        let calls = Arc::new(AtomicUsize::new(0));
796
797        for scope in [ARM_SCOPE, LOGS_SCOPE, ARM_SCOPE] {
798            let calls = Arc::clone(&calls);
799            source
800                .token(scope, |_| async move {
801                    calls.fetch_add(1, Ordering::SeqCst);
802                    Ok::<_, String>(response(3600))
803                })
804                .await
805                .unwrap();
806        }
807
808        assert_eq!(calls.load(Ordering::SeqCst), 2, "one per scope, then cached");
809    }
810
811    #[tokio::test(start_paused = true)]
812    async fn a_token_is_refreshed_before_its_stated_expiry() {
813        // The margin: a token is never used in the last moments of its
814        // life.
815        let source = TokenSource::new(principal()).with_expiry_margin(Duration::from_secs(300));
816        let calls = Arc::new(AtomicUsize::new(0));
817
818        let fetch = || {
819            let calls = Arc::clone(&calls);
820            async move {
821                calls.fetch_add(1, Ordering::SeqCst);
822                Ok::<_, String>(response(3600))
823            }
824        };
825
826        source.token(ARM_SCOPE, |_| fetch()).await.unwrap();
827
828        // Just inside the usable window: 3600 - 300 = 3300 seconds.
829        tokio::time::advance(Duration::from_secs(3299)).await;
830        source.token(ARM_SCOPE, |_| fetch()).await.unwrap();
831        assert_eq!(calls.load(Ordering::SeqCst), 1, "still cached");
832
833        // Past it, but well before the token's stated hour.
834        tokio::time::advance(Duration::from_secs(2)).await;
835        source.token(ARM_SCOPE, |_| fetch()).await.unwrap();
836        assert_eq!(calls.load(Ordering::SeqCst), 2, "refreshed early");
837    }
838
839    #[tokio::test]
840    async fn a_token_shorter_than_the_margin_is_not_cached() {
841        // `saturating_sub`, rather than a usable-until time in the past.
842        let source = TokenSource::new(principal()).with_expiry_margin(Duration::from_secs(300));
843        let calls = Arc::new(AtomicUsize::new(0));
844
845        for _ in 0..2 {
846            let calls = Arc::clone(&calls);
847            source
848                .token(ARM_SCOPE, |_| async move {
849                    calls.fetch_add(1, Ordering::SeqCst);
850                    Ok::<_, String>(response(60))
851                })
852                .await
853                .unwrap();
854        }
855
856        assert_eq!(calls.load(Ordering::SeqCst), 2);
857    }
858
859    #[tokio::test]
860    async fn invalidating_forces_a_fresh_fetch() {
861        let source = TokenSource::new(principal());
862        let calls = Arc::new(AtomicUsize::new(0));
863
864        let fetch = || {
865            let calls = Arc::clone(&calls);
866            async move {
867                calls.fetch_add(1, Ordering::SeqCst);
868                Ok::<_, String>(response(3600))
869            }
870        };
871
872        source.token(ARM_SCOPE, |_| fetch()).await.unwrap();
873        source.invalidate().await;
874        source.token(ARM_SCOPE, |_| fetch()).await.unwrap();
875        assert_eq!(calls.load(Ordering::SeqCst), 2);
876
877        source.invalidate_scope(ARM_SCOPE).await;
878        source.token(ARM_SCOPE, |_| fetch()).await.unwrap();
879        assert_eq!(calls.load(Ordering::SeqCst), 3);
880    }
881
882    #[tokio::test]
883    async fn a_transport_failure_is_returned_unchanged_and_not_cached() {
884        let source = TokenSource::new(principal());
885
886        let error = source
887            .token(ARM_SCOPE, |_| async { Err::<String, _>("no route to host") })
888            .await
889            .unwrap_err();
890
891        assert_eq!(error, TokenError::Transport("no route to host"));
892
893        // And the next call still tries.
894        let token = source
895            .token(ARM_SCOPE, |_| async { Ok::<_, &str>(response(3600)) })
896            .await
897            .unwrap();
898        assert_eq!(token, "token-3600");
899    }
900
901    // -- secrecy -----------------------------------------------------------
902
903    #[test]
904    fn nothing_prints_a_secret() {
905        let printed = format!("{:?}", principal());
906        assert!(printed.contains("tenant-1"));
907        assert!(printed.contains("client-1"));
908        assert!(!printed.contains("secret-1"), "{printed}");
909
910        let request = format!("{:?}", principal().request(ARM_SCOPE).unwrap());
911        assert!(!request.contains("secret-1"), "{request}");
912        assert!(request.contains("<redacted>"));
913
914        let source = format!("{:?}", TokenSource::new(principal()));
915        assert!(!source.contains("secret-1"), "{source}");
916
917        let token = format!(
918            "{:?}",
919            parse_response(r#"{"access_token":"eyJsecret","expires_in":1}"#).unwrap()
920        );
921        assert!(!token.contains("eyJsecret"), "{token}");
922    }
923
924    #[test]
925    fn a_credential_describes_itself_safely() {
926        assert_eq!(
927            principal().describe(),
928            "service principal client-1 in tenant tenant-1"
929        );
930        assert_eq!(
931            Credential::managed_identity().describe(),
932            "the system-assigned managed identity"
933        );
934        assert_eq!(
935            Credential::user_assigned_identity("abc").describe(),
936            "the user-assigned managed identity abc"
937        );
938        assert!(!principal().describe().contains("secret-1"));
939    }
940}