libhimmelblau 0.8.37

Samba Library for Azure Entra ID Authentication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
/*
   Unix Azure Entra ID implementation
   Copyright (C) David Mulder <dmulder@samba.org> 2024

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use crate::error::MsalError;
#[cfg(feature = "proxyable")]
use reqwest::Proxy;
use reqwest::{header, Client, StatusCode, Url};
use serde::de::{DeserializeOwned, Error};
use serde::Deserialize;
use serde_json::{json, to_string_pretty};
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::time::sleep;
use tracing::debug;

#[cfg(feature = "ipvers")]
use crate::auth::IpVersion;
#[cfg(feature = "set_timeout")]
use std::cmp::min;

#[derive(Debug, Deserialize)]
struct FederationProvider {
    #[serde(rename = "tenantId")]
    tenant_id: String,
    authority_host: String,
    graph: String,
}

#[derive(Debug)]
pub struct DirectoryObject {
    pub data_type: String,
    pub id: String,
    pub description: Option<String>,
    pub display_name: Option<String>,
    pub security_identifier: Option<String>,
    pub extension_attrs: HashMap<String, String>,
}

impl<'de> Deserialize<'de> for DirectoryObject {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let mut map = Map::<String, Value>::deserialize(deserializer)?;

        let data_type = map
            .remove("@odata.type")
            .ok_or_else(|| D::Error::missing_field("@odata.type"))?;
        let data_type: String = serde_json::from_value(data_type).map_err(D::Error::custom)?;

        let id = map
            .remove("id")
            .ok_or_else(|| D::Error::missing_field("id"))?;
        let id: String = serde_json::from_value(id).map_err(D::Error::custom)?;

        let description: Option<String> = map.remove("description").map_or(Ok(None), |v| {
            serde_json::from_value(v).map_err(D::Error::custom)
        })?;
        let display_name: Option<String> = map.remove("displayName").map_or(Ok(None), |v| {
            serde_json::from_value(v).map_err(D::Error::custom)
        })?;
        let security_identifier: Option<String> =
            map.remove("securityIdentifier").map_or(Ok(None), |v| {
                serde_json::from_value(v).map_err(D::Error::custom)
            })?;

        let mut extension_attrs = HashMap::new();
        for (key, value) in map {
            if key.starts_with("extension_") {
                let s = if let Value::String(s) = value {
                    s
                } else {
                    value.to_string()
                };
                let short_key = key.splitn(3, '_').nth(2).unwrap_or(&key).to_string();
                extension_attrs.insert(short_key, s);
            }
        }

        Ok(DirectoryObject {
            data_type,
            id,
            description,
            display_name,
            security_identifier,
            extension_attrs,
        })
    }
}

#[derive(Deserialize)]
struct GraphPage<T> {
    value: Vec<T>,
    #[serde(rename = "@odata.nextLink")]
    next_link: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct UserObject {
    #[serde(rename = "displayName")]
    pub displayname: String,
    #[serde(rename = "userPrincipalName")]
    pub upn: String,
    #[serde(rename = "onPremisesSamAccountName")]
    pub on_premises_sam_account_name: Option<String>,
    pub id: String,
    pub uid: Option<u32>,
    pub gid: Option<u32>,
}

#[derive(Debug, Deserialize)]
pub struct GroupObject {
    #[serde(rename = "displayName")]
    pub displayname: String,
    pub id: String,
    pub gid: Option<u32>,
}

#[derive(Deserialize)]
struct IntuneServiceEndpoint {
    #[serde(rename = "providerName")]
    provider_name: String,
    uri: String,
}

#[derive(Deserialize)]
pub struct IntuneServiceEndpoints {
    value: Vec<IntuneServiceEndpoint>,
}

impl IntuneServiceEndpoints {
    pub fn get(&self, provider_name: &str) -> Result<&str, MsalError> {
        self.value
            .iter()
            .find(|ep| ep.provider_name == provider_name)
            .map(|ep| ep.uri.as_str())
            .ok_or_else(|| MsalError::Missing(provider_name.to_string()))
    }
}

pub struct Graph {
    client: Client,
    odc_provider: String,
    domain: String,
    federation_provider: RwLock<Option<FederationProvider>>,
}

async fn request_federation_provider(
    client: &Client,
    odc_provider: &str,
    domain: &str,
) -> Result<FederationProvider, MsalError> {
    let url = Url::parse_with_params(
        &format!("https://{}/odc/v2.1/federationProvider", odc_provider),
        &[("domain", domain)],
    )
    .map_err(|e| MsalError::GeneralFailure(format!("{:?}", e)))?;

    let resp = client
        .get(url)
        .send()
        .await
        .map_err(|e| MsalError::request_failed(&e))?;
    if resp.status().is_success() {
        let json_resp: FederationProvider = resp
            .json()
            .await
            .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;
        debug!("Discovered: {:?}", json_resp);
        Ok(json_resp)
    } else {
        Err(MsalError::GeneralFailure(format!(
            "Federation Provider request failed: {}",
            resp.status(),
        )))
    }
}

macro_rules! federation_provider_or_none {
    ($client:expr, $odc_provider:expr, $domain:expr) => {{
        match request_federation_provider(&$client, $odc_provider, $domain).await {
            Ok(resp) => Some(resp),
            Err(e) => {
                debug!("{:?}", e);
                None
            }
        }
    }};
}

macro_rules! federation_provider_fetch {
    ($graph:ident, $val:ident) => {{
        {
            let mut federation_provider = $graph.federation_provider.write().await;
            if federation_provider.is_none() {
                *federation_provider = federation_provider_or_none!(
                    $graph.client,
                    &$graph.odc_provider,
                    &$graph.domain
                );
            }
        }
        // This nested scope forces the drop of the federation_provider write
        // lock, otherwise we deadlock when we request a read lock next.

        match &*$graph.federation_provider.read().await {
            Some(federation_provider) => Ok(federation_provider.$val.clone()),
            None => Err(MsalError::GeneralFailure(
                "federation provider not set".to_string(),
            )),
        }
    }};
}

impl Graph {
    pub async fn new(
        odc_provider: &str,
        domain: &str,
        authority_host: Option<&str>,
        tenant_id: Option<&str>,
        graph_url: Option<&str>,
        #[cfg(feature = "set_timeout")] timeout: Duration,
        #[cfg(feature = "ipvers")] ip_version: &[IpVersion],
    ) -> Result<Self, MsalError> {
        #[cfg(feature = "set_timeout")]
        let (timeout, connect_timeout) = { (timeout, min(timeout / 2, Duration::from_secs(3))) };
        #[cfg(not(feature = "set_timeout"))]
        let (timeout, connect_timeout) = (Duration::from_secs(3), Duration::from_secs(1));

        #[allow(unused_mut)]
        let mut builder = reqwest::Client::builder()
            .connect_timeout(connect_timeout)
            .timeout(timeout)
            .cookie_store(true);

        #[cfg(feature = "proxyable")]
        {
            if let Some(proxy_var) = std::env::var("HTTPS_PROXY")
                .ok()
                .or_else(|| std::env::var("ALL_PROXY").ok())
            {
                let proxy = Proxy::https(proxy_var)
                    .map_err(|e| MsalError::GeneralFailure(format!("{:?}", e)))?;
                builder = builder.proxy(proxy).danger_accept_invalid_certs(true);
            }
        }

        #[cfg(feature = "ipvers")]
        {
            let has_v4 = ip_version.contains(&IpVersion::V4);
            let has_v6 = ip_version.contains(&IpVersion::V6);
            if has_v4 && !has_v6 {
                builder =
                    builder.local_address(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED))
            } else if !has_v4 && has_v6 {
                builder =
                    builder.local_address(std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED))
            }
        }

        let client = builder
            .build()
            .map_err(|e| MsalError::RequestFailed(format!("{:?}", e)))?;

        let federation_provider = if let Some(authority_host) = authority_host {
            if let Some(tenant_id) = tenant_id {
                if let Some(graph_url) = graph_url {
                    Some(FederationProvider {
                        authority_host: authority_host.to_string(),
                        tenant_id: tenant_id.to_string(),
                        graph: graph_url.to_string(),
                    })
                } else {
                    federation_provider_or_none!(client, odc_provider, domain)
                }
            } else {
                federation_provider_or_none!(client, odc_provider, domain)
            }
        } else {
            federation_provider_or_none!(client, odc_provider, domain)
        };

        Ok(Graph {
            client,
            odc_provider: odc_provider.to_string(),
            domain: domain.to_string(),
            federation_provider: RwLock::new(federation_provider),
        })
    }

    pub async fn authority_host(&self) -> Result<String, MsalError> {
        federation_provider_fetch!(self, authority_host)
    }

    pub async fn tenant_id(&self) -> Result<String, MsalError> {
        federation_provider_fetch!(self, tenant_id)
    }

    pub async fn graph_url(&self) -> Result<String, MsalError> {
        federation_provider_fetch!(self, graph)
    }

    pub async fn request_user(
        &self,
        access_token: &str,
        upn: &str,
    ) -> Result<UserObject, MsalError> {
        let url = &format!("{}/v1.0/users/{}", self.graph_url().await?, upn);
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let json_resp: UserObject = resp
                .json()
                .await
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;
            Ok(json_resp)
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn request_all_users_with_extension_attributes(
        &self,
        access_token: &str,
    ) -> Result<Vec<UserObject>, MsalError> {
        let url = Url::parse(&format!("{}/beta/users?$top=999", self.graph_url().await?))
            .map_err(|e| MsalError::URLFormatFailed(format!("{}", e)))?;

        let objs = self
            .fetch_all_pages(url.as_str(), access_token)
            .await
            .map(|objs: Vec<Value>| objs)?;

        let mut res: Vec<UserObject> = vec![];
        for user in &objs {
            let mut userobj: UserObject = serde_json::from_value(user.clone())
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;

            if let Value::Object(obj) = &user {
                for (key, value) in obj.iter() {
                    if key.starts_with("extension_") {
                        if key.ends_with("uidNumber") {
                            if let Value::Number(num) = value {
                                userobj.uid = num.as_u64().map(|uid| uid as u32);
                            }
                        } else if key.ends_with("gidNumber") {
                            if let Value::Number(num) = value {
                                userobj.gid = num.as_u64().map(|gid| gid as u32);
                            }
                        }
                    }
                }
            }

            if userobj.uid.is_some() || userobj.gid.is_some() {
                res.push(userobj);
            }
        }

        Ok(res)
    }

    pub async fn request_all_groups_with_extension_attributes(
        &self,
        access_token: &str,
    ) -> Result<Vec<GroupObject>, MsalError> {
        let url = Url::parse(&format!("{}/beta/groups?$top=999", self.graph_url().await?))
            .map_err(|e| MsalError::URLFormatFailed(format!("{}", e)))?;

        let objs = self
            .fetch_all_pages(url.as_str(), access_token)
            .await
            .map(|objs: Vec<Value>| objs)?;

        let mut res: Vec<GroupObject> = vec![];
        for user in &objs {
            let mut groupobj: GroupObject = serde_json::from_value(user.clone())
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;

            if let Value::Object(obj) = &user {
                for (key, value) in obj.iter() {
                    if key.starts_with("extension_") && key.ends_with("gidNumber") {
                        if let Value::Number(num) = value {
                            groupobj.gid = num.as_u64().map(|gid| gid as u32);
                        }
                    }
                }
            }

            if groupobj.gid.is_some() {
                res.push(groupobj);
            }
        }

        Ok(res)
    }

    pub async fn request_user_groups(
        &self,
        access_token: &str,
    ) -> Result<Vec<DirectoryObject>, MsalError> {
        let url = &format!("{}/v1.0/me/memberOf?$top=999", self.graph_url().await?);
        self.fetch_all_pages(url, access_token)
            .await
            .map(|objs: Vec<DirectoryObject>| objs)
    }

    pub async fn request_user_groups_by_user_id(
        &self,
        access_token: &str,
        object_id: &str,
    ) -> Result<Vec<DirectoryObject>, MsalError> {
        let url = &format!(
            "{}/v1.0/users/{}/memberOf?$top=999",
            self.graph_url().await?,
            object_id
        );
        self.fetch_all_pages(url, access_token)
            .await
            .map(|objs: Vec<DirectoryObject>| objs)
    }

    pub async fn assign_device_to_user(
        &self,
        access_token: &str,
        device_id: &str,
        upn: &str,
    ) -> Result<(), MsalError> {
        let url = &format!(
            "{}/v1.0/devices/{}/registeredOwners/$ref",
            self.graph_url().await?,
            device_id
        );
        let user_obj = self.request_user(access_token, upn).await?;
        let payload = json!({
            "@odata.id": format!("{}/v1.0/directoryObjects/{}", self.graph_url().await?, user_obj.id),
        });
        if let Ok(pretty) = to_string_pretty(&payload) {
            debug!("POST {}: {}", url, pretty);
        }
        let resp = self
            .client
            .post(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .header(header::CONTENT_TYPE, "application/json")
            .json(&payload)
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            Ok(())
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn request_group(
        &self,
        access_token: &str,
        displayname: &str,
    ) -> Result<GroupObject, MsalError> {
        let url = Url::parse_with_params(
            &format!("{}/v1.0/groups", self.graph_url().await?),
            &[("$filter", format!("displayName eq '{}'", displayname))],
        )
        .map_err(|e| MsalError::GeneralFailure(format!("{:?}", e)))?;
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let json_resp: GroupObject = resp
                .json()
                .await
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;
            Ok(json_resp)
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn fetch_user_profile_photo(
        &self,
        access_token: &str,
        mut file: File,
    ) -> Result<(), MsalError> {
        let url = format!("{}/v1.0/me/photo/$value", self.graph_url().await?);
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let content = resp
                .bytes()
                .await
                .map_err(|e| MsalError::GeneralFailure(format!("Failed to read bytes: {:?}", e)))?;
            file.write_all(&content)
                .map_err(|e| MsalError::GeneralFailure(format!("Failed to write file: {:?}", e)))?;

            Ok(())
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn fetch_user_extension_attributes(
        &self,
        access_token: &str,
        extension_attributes: Vec<&str>,
    ) -> Result<HashMap<String, String>, MsalError> {
        let url = format!("{}/beta/me", self.graph_url().await?);
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let json_resp: Value = resp
                .json()
                .await
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;

            let mut result_map = HashMap::new();
            if let Value::Object(obj) = json_resp {
                for (key, value) in obj.iter() {
                    if key.starts_with("extension_") {
                        for &attr in &extension_attributes {
                            if key.ends_with(&format!("_{}", attr)) {
                                if let Value::String(val) = value {
                                    result_map.insert(attr.to_string(), val.clone());
                                } else if let Value::Number(num) = value {
                                    result_map.insert(attr.to_string(), num.to_string());
                                }
                            }
                        }
                    }
                }
            }

            Ok(result_map)
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn fetch_user_extension_attributes_by_user_id(
        &self,
        access_token: &str,
        object_id: &str,
        extension_attributes: Vec<&str>,
    ) -> Result<HashMap<String, String>, MsalError> {
        let url = &format!("{}/beta/users/{}", self.graph_url().await?, object_id);
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let json_resp: Value = resp
                .json()
                .await
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;

            let mut result_map = HashMap::new();
            if let Value::Object(obj) = json_resp {
                for (key, value) in obj.iter() {
                    if key.starts_with("extension_") {
                        for &attr in &extension_attributes {
                            if key.ends_with(&format!("_{}", attr)) {
                                if let Value::String(val) = value {
                                    result_map.insert(attr.to_string(), val.clone());
                                } else if let Value::Number(num) = value {
                                    result_map.insert(attr.to_string(), num.to_string());
                                }
                            }
                        }
                    }
                }
            }

            Ok(result_map)
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn fetch_group_extension_attributes(
        &self,
        groupname: &str,
        access_token: &str,
        extension_attributes: Vec<&str>,
    ) -> Result<HashMap<String, String>, MsalError> {
        let url = format!("{}/beta/groups/{}", self.graph_url().await?, groupname);
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let json_resp: Value = resp
                .json()
                .await
                .map_err(|e| MsalError::InvalidJson(format!("{:?}", e)))?;

            let mut result_map = HashMap::new();
            if let Value::Object(obj) = json_resp {
                for (key, value) in obj.iter() {
                    if key.starts_with("extension_") {
                        for &attr in &extension_attributes {
                            if key.ends_with(&format!("_{}", attr)) {
                                if let Value::String(val) = value {
                                    result_map.insert(attr.to_string(), val.clone());
                                } else if let Value::Number(num) = value {
                                    result_map.insert(attr.to_string(), num.to_string());
                                }
                            }
                        }
                    }
                }
            }

            Ok(result_map)
        } else {
            Err(MsalError::GeneralFailure(format!("{}", resp.status())))
        }
    }

    pub async fn intune_service_endpoints(
        &self,
        access_token: &str,
    ) -> Result<IntuneServiceEndpoints, MsalError> {
        let url = format!(
            "{}/v1.0/servicePrincipals/appId=0000000a-0000-0000-c000-000000000000/endpoints",
            self.graph_url().await?
        );
        let resp = self
            .client
            .get(url)
            .header(header::AUTHORIZATION, format!("Bearer {}", access_token))
            .header(header::ACCEPT, "application/json")
            .send()
            .await
            .map_err(|e| MsalError::request_failed(&e))?;
        if resp.status().is_success() {
            let json_resp: IntuneServiceEndpoints = resp
                .json()
                .await
                .map_err(|e| MsalError::RequestFailed(format!("{:?}", e)))?;
            Ok(json_resp)
        } else {
            Err(MsalError::RequestFailed(format!("{}", resp.status())))
        }
    }

    async fn fetch_with_retry(
        &self,
        url: &str,
        token: &str,
    ) -> Result<reqwest::Response, MsalError> {
        let mut attempt = 0;
        let max_attempts = 6;

        loop {
            let resp = self
                .client
                .get(url)
                .bearer_auth(token)
                .header("ConsistencyLevel", "eventual")
                .send()
                .await
                .map_err(|e| MsalError::request_failed(&e))?;

            match resp.status() {
                StatusCode::OK => return Ok(resp),
                StatusCode::TOO_MANY_REQUESTS
                | StatusCode::SERVICE_UNAVAILABLE
                | StatusCode::BAD_GATEWAY
                | StatusCode::GATEWAY_TIMEOUT => {
                    attempt += 1;
                    if attempt >= max_attempts {
                        return Err(MsalError::RequestFailed(format!(
                            "HTTP {} after {} attempts",
                            resp.status(),
                            attempt
                        )));
                    }
                    let wait = resp
                        .headers()
                        .get("Retry-After")
                        .and_then(|h| h.to_str().ok())
                        .and_then(|s| s.parse::<u64>().ok())
                        .map(Duration::from_secs)
                        .unwrap_or_else(|| {
                            Duration::from_millis(200u64.saturating_mul(2u64.pow(attempt.min(5))))
                        });
                    sleep(wait).await;
                }
                s => {
                    let body = resp.text().await.unwrap_or_default();
                    return Err(MsalError::GeneralFailure(format!(
                        "Graph error {}: {}",
                        s, body
                    )));
                }
            }
        }
    }

    async fn fetch_all_pages<T: DeserializeOwned>(
        &self,
        first_url: &str,
        token: &str,
    ) -> Result<Vec<T>, MsalError> {
        let mut url = first_url.to_string();
        let mut all = Vec::<T>::new();

        loop {
            let resp = self.fetch_with_retry(&url, token).await?;
            let text = resp.text().await.map_err(|e| {
                MsalError::GeneralFailure(format!("Failed getting text from response: {:?}", e))
            })?;
            let page: GraphPage<T> = serde_json::from_str(&text).or_else(
                |_| -> std::result::Result<GraphPage<T>, MsalError> {
                    let v: Value = serde_json::from_str(&text).map_err(|e| {
                        MsalError::InvalidJson(format!("Failed parsing page: {:?}", e))
                    })?;
                    let value = v
                        .get("value")
                        .cloned()
                        .ok_or_else(|| MsalError::GeneralFailure("missing 'value'".to_string()))?;
                    let next = v
                        .get("@odata.nextLink")
                        .and_then(|n| n.as_str())
                        .map(|s| s.to_string());
                    let items: Vec<T> = serde_json::from_value(value).map_err(|e| {
                        MsalError::InvalidJson(format!("Failed parsing page: {:?}", e))
                    })?;
                    Ok(GraphPage {
                        value: items,
                        next_link: next,
                    })
                },
            )?;

            all.extend(page.value);
            if let Some(next) = page.next_link {
                url = next;
            } else {
                break;
            }
        }

        Ok(all)
    }
}