1#![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
63pub const ARM_SCOPE: &str = "https://management.azure.com/.default";
65
66pub const LOGS_SCOPE: &str = "https://api.loganalytics.io/.default";
72
73pub const GRAPH_SCOPE: &str = "https://graph.microsoft.com/.default";
75
76pub const IDENTITY_API_VERSION: &str = "2019-08-01";
78
79pub const IDENTITY_ENDPOINT_VARIABLE: &str = "IDENTITY_ENDPOINT";
81
82pub const IDENTITY_HEADER_VARIABLE: &str = "IDENTITY_HEADER";
84
85pub const DEFAULT_EXPIRY_MARGIN: Duration = Duration::from_secs(300);
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Error {
95 NoAmbientCredential {
98 variable: &'static str,
100 },
101 NotJson,
103 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#[derive(Clone)]
126pub enum Credential {
127 ClientSecret {
129 tenant_id: String,
131 client_id: String,
133 client_secret: String,
135 },
136 ManagedIdentity {
151 client_id: Option<String>,
154 },
155}
156
157impl fmt::Debug for Credential {
158 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159 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 #[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 #[must_use]
196 pub const fn managed_identity() -> Self {
197 Self::ManagedIdentity { client_id: None }
198 }
199
200 #[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 #[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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306pub enum Method {
307 Get,
309 Post,
311}
312
313impl Method {
314 #[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#[derive(Clone, PartialEq, Eq)]
334pub struct TokenRequest {
335 pub method: Method,
337 pub url: String,
339 pub headers: Vec<(String, String)>,
341 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 .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
365pub const CONTENT_TYPE: &str = "application/x-www-form-urlencoded";
367
368#[derive(Clone, PartialEq, Eq)]
370pub struct Token {
371 pub access_token: String,
373 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
387pub 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#[must_use]
454pub fn resource_of(scope: &str) -> &str {
455 scope.strip_suffix(".default").unwrap_or(scope)
456}
457
458#[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
488fn 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#[derive(Debug, Clone)]
498struct Held {
499 value: String,
501 usable_until: Instant,
503}
504
505pub struct TokenSource {
520 credential: Credential,
522 held: Mutex<BTreeMap<String, Held>>,
525 margin: Duration,
527}
528
529impl fmt::Debug for TokenSource {
530 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
531 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 #[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 #[must_use]
553 pub fn with_expiry_margin(mut self, margin: Duration) -> Self {
554 self.margin = margin;
555 self
556 }
557
558 #[must_use]
560 pub const fn credential(&self) -> &Credential {
561 &self.credential
562 }
563
564 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 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 pub async fn invalidate(&self) {
633 self.held.lock().await.clear();
634 }
635
636 pub async fn invalidate_scope(&self, scope: &str) {
638 self.held.lock().await.remove(scope);
639 }
640}
641
642#[derive(Debug, Clone, PartialEq, Eq)]
644pub enum TokenError<E> {
645 Token(Error),
647 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 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 #[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 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 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 let credential = Credential::managed_identity();
713
714 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 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 #[test]
736 fn expires_in_is_accepted_as_a_number_or_a_string() {
737 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 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 #[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 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 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 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 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 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 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 #[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}