Skip to main content

alibi_plugins/oauth/providers/
microsoft.rs

1//! Microsoft Entra ID's configured authority, tenant and original object ID.
2use super::{
3    OAuthAuthorizationPolicy, OAuthClientAssertion, OAuthProvider, OAuthScopeEncoding,
4    OAuthTokenEndpointAuth, OAuthUserInfo, OAuthUserInfoHandler, OAuthUserInfoRequest,
5    OAuthUserInfoResponse,
6};
7use crate::oauth::{
8    HttpOAuthJwksSource, OAuthIdTokenClaimsVerifier, OAuthIdTokenConfig, OAuthJwksSelection,
9    OAuthJwksSource, OAuthNonceComparison,
10};
11use alibi_core::utils::json::JsValue;
12use async_trait::async_trait;
13use base64::Engine;
14use serde_json::Map;
15use serde_json::Value;
16use std::sync::Arc;
17
18const CONSUMER_TENANT: &str = "9188040d-6c67-4c5b-b112-36a304b66dad";
19const DEFAULT_SCOPES: [&str; 5] = ["openid", "profile", "email", "User.Read", "offline_access"];
20
21/// Supported Graph profile-photo sizes in pixels.
22#[derive(Debug, Clone, Copy, Default)]
23pub enum MicrosoftProfilePhotoSize {
24    #[default]
25    Size48,
26    Size64,
27    Size96,
28    Size120,
29    Size240,
30    Size360,
31    Size432,
32    Size504,
33    Size648,
34}
35impl MicrosoftProfilePhotoSize {
36    const fn pixels(self) -> u16 {
37        match self {
38            Self::Size48 => 48,
39            Self::Size64 => 64,
40            Self::Size96 => 96,
41            Self::Size120 => 120,
42            Self::Size240 => 240,
43            Self::Size360 => 360,
44            Self::Size432 => 432,
45            Self::Size504 => 504,
46            Self::Size648 => 648,
47        }
48    }
49}
50
51/// Immutable application configuration for the published Microsoft factory.
52#[derive(Clone)]
53pub struct MicrosoftOptions {
54    pub client_ids: Vec<String>,
55    pub client_secret: Option<String>,
56    pub client_key: Option<String>,
57    pub client_assertion: Option<OAuthClientAssertion>,
58    pub tenant_id: Option<String>,
59    pub authority: Option<String>,
60    pub scope: Vec<String>,
61    pub disable_default_scope: bool,
62    /// Reject new identities, including an explicit signup request.
63    pub disable_sign_up: bool,
64    pub prompt: Option<String>,
65    pub authorization_endpoint: Option<String>,
66    pub redirect_uri: Option<String>,
67    pub disable_profile_photo: bool,
68    pub profile_photo_size: MicrosoftProfilePhotoSize,
69    /// Trusted application transport override. Claims never select this source.
70    pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
71    /// Trusted application Graph transport override, retaining byte/photo mapping.
72    pub profile_photo_endpoint: Option<String>,
73    /// Receives the original claims with any successfully fetched photo applied.
74    /// Its mapped ID cannot replace the raw oid account identity.
75    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
76}
77impl MicrosoftOptions {
78    #[must_use]
79    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
80        Self {
81            client_ids: vec![client_id.into()],
82            client_secret,
83            client_key: None,
84            client_assertion: None,
85            tenant_id: None,
86            authority: None,
87            scope: Vec::new(),
88            disable_default_scope: false,
89            disable_sign_up: false,
90            prompt: None,
91            authorization_endpoint: None,
92            redirect_uri: None,
93            disable_profile_photo: false,
94            profile_photo_size: MicrosoftProfilePhotoSize::default(),
95            jwks_source: None,
96            profile_photo_endpoint: None,
97            map_profile_to_user: None,
98        }
99    }
100}
101impl std::fmt::Debug for MicrosoftOptions {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("MicrosoftOptions")
104            .field("client_ids", &self.client_ids)
105            .field("tenant_id", &self.tenant_id)
106            .field("authority", &self.authority)
107            .field("scope", &self.scope)
108            .field("disable_default_scope", &self.disable_default_scope)
109            .field("disable_sign_up", &self.disable_sign_up)
110            .field("disable_profile_photo", &self.disable_profile_photo)
111            .field("profile_photo_size", &self.profile_photo_size)
112            .finish_non_exhaustive()
113    }
114}
115impl OAuthProvider {
116    /// Builds Microsoft's actual authorization, grant and tenant-verification policy.
117    ///
118    /// # Errors
119    /// Returns an error when a secret is combined with a client assertion.
120    pub fn microsoft(options: MicrosoftOptions) -> Result<Self, String> {
121        if options.client_assertion.is_some()
122            && options
123                .client_secret
124                .as_ref()
125                .is_some_and(|secret| !secret.is_empty())
126        {
127            return Err(
128                "Microsoft Entra ID clientAssertion cannot be combined with clientSecret".into(),
129            );
130        }
131        let tenant = options
132            .tenant_id
133            .filter(|value| !value.is_empty())
134            .unwrap_or_else(|| "common".into());
135        let authority = options
136            .authority
137            .filter(|value| !value.is_empty())
138            .unwrap_or_else(|| "https://login.microsoftonline.com".into())
139            .trim_end_matches('/')
140            .to_owned();
141        let multi_tenant = ["common", "organizations", "consumers"].contains(&tenant.as_str());
142        let verification = OAuthIdTokenConfig {
143            issuers: if multi_tenant {
144                Vec::new()
145            } else {
146                vec![format!("{authority}/{tenant}/v2.0")]
147            },
148            audience: None,
149            client_ids: Some(options.client_ids.clone()),
150            jwks_source: options.jwks_source.unwrap_or_else(|| {
151                Arc::new(HttpOAuthJwksSource::new(format!(
152                    "{authority}/{tenant}/discovery/v2.0/keys"
153                )))
154            }),
155            max_age_secs: Some(3600),
156            allow_opaque_token: false,
157            algorithm: None,
158            algorithms: Some(vec![jsonwebtoken::Algorithm::RS256]),
159            // Microsoft's key set omits `alg`; Entra ID signs ID tokens with RS256.
160            default_key_algorithm: Some(jsonwebtoken::Algorithm::RS256),
161            selection: OAuthJwksSelection::ExactKid,
162            nonce_comparison: OAuthNonceComparison::Exact,
163            verify_claims: Some(Arc::new(MicrosoftClaims {
164                authority: authority.clone(),
165                tenant: tenant.clone(),
166            })),
167        };
168        let scopes: Vec<_> = DEFAULT_SCOPES.map(String::from).to_vec();
169        let mut refresh_scopes = if options.disable_default_scope {
170            Vec::new()
171        } else {
172            scopes.clone()
173        };
174        refresh_scopes.extend(options.scope.clone());
175        let token_endpoint_auth = if options.client_assertion.is_some() {
176            OAuthTokenEndpointAuth::PrivateKeyJwt
177        } else if options
178            .client_secret
179            .as_ref()
180            .is_some_and(|secret| !secret.is_empty())
181        {
182            OAuthTokenEndpointAuth::ClientSecretPost
183        } else {
184            OAuthTokenEndpointAuth::None
185        };
186        let size = options.profile_photo_size.pixels();
187        let photo_endpoint = options.profile_photo_endpoint.unwrap_or_else(|| {
188            format!("https://graph.microsoft.com/v1.0/me/photos/{size}x{size}/$value")
189        });
190        let mut clients = options.client_ids.into_iter();
191        Ok(Self {
192            client_id: clients.next().unwrap_or_default(),
193            additional_client_ids: clients.collect(),
194            client_secret: options.client_secret.unwrap_or_default(),
195            hosted_domain: None,
196            require_email_verification: false,
197            auth_url: options
198                .authorization_endpoint
199                .filter(|value| !value.is_empty())
200                .unwrap_or_else(|| format!("{authority}/{tenant}/oauth2/v2.0/authorize")),
201            token_url: format!("{authority}/{tenant}/oauth2/v2.0/token"),
202            user_info_url: None,
203            scopes,
204            authorization: Some(OAuthAuthorizationPolicy {
205                configured_scopes: options.scope,
206                scope_encoding: OAuthScopeEncoding::UriComponent,
207                disable_default_scopes: options.disable_default_scope,
208                disable_sign_up_option: options.disable_sign_up.then_some(true),
209                require_client_id: true,
210                token_endpoint_auth: Some(token_endpoint_auth),
211                authorization_code_client_key: options.client_key,
212                client_assertion: options.client_assertion,
213                refresh_scope: Some(refresh_scopes.join(" ")),
214                prompt: options.prompt,
215                redirect_uri: options.redirect_uri,
216                ..OAuthAuthorizationPolicy::default()
217            }),
218            allowed_request_params: Vec::new(),
219            authorization_params: Vec::new(),
220            account_subject: Some(subject),
221            map_user_info: None,
222            get_user_info: Some(Arc::new(MicrosoftUserInfo {
223                photo_endpoint,
224                disable_photo: options.disable_profile_photo,
225                mapper: options.map_profile_to_user,
226            })),
227            refresh_access_token: None,
228            verify_id_token: None,
229            id_token: Some(verification),
230            disable_id_token_sign_in: false,
231            disable_implicit_sign_up: false,
232            disable_sign_up: false,
233            allow_idp_initiated: false,
234            override_user_info_on_sign_in: false,
235        })
236    }
237}
238struct MicrosoftClaims {
239    authority: String,
240    tenant: String,
241}
242impl OAuthIdTokenClaimsVerifier for MicrosoftClaims {
243    fn verify_claims(&self, claims: &JsValue) -> bool {
244        let Some(tid) = claims.get("tid").and_then(JsValue::as_str) else {
245            return false;
246        };
247        claims.get("iss").and_then(JsValue::as_str)
248            == Some(format!("{}/{tid}/v2.0", self.authority).as_str())
249            && !(self.tenant == "organizations" && tid == CONSUMER_TENANT)
250            && !(self.tenant == "consumers" && tid != CONSUMER_TENANT)
251    }
252}
253struct MicrosoftUserInfo {
254    photo_endpoint: String,
255    disable_photo: bool,
256    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
257}
258#[async_trait]
259impl OAuthUserInfoHandler for MicrosoftUserInfo {
260    async fn get_user_info(
261        &self,
262        request: OAuthUserInfoRequest,
263    ) -> Result<OAuthUserInfoResponse, String> {
264        let token = request
265            .id_token
266            .filter(|value| !value.is_empty())
267            .ok_or("Missing Microsoft ID token")?;
268        let parts: Vec<_> = token.split('.').collect();
269        let [_, payload, _] = parts.as_slice() else {
270            return Err("Invalid Microsoft ID token".into());
271        };
272        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
273            .decode(payload)
274            .map_err(|error| error.to_string())?;
275        let mut profile: Value =
276            alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
277        if !profile.is_object() {
278            return Err("Invalid Microsoft ID-token claims set".into());
279        }
280        let id = subject(&profile)?;
281        if !self.disable_photo
282            && let Some(access) = request.access_token.filter(|value| !value.is_empty())
283        {
284            // A failed optional photo operation does not deny the authenticated profile.
285            if let Ok(response) = reqwest::Client::new()
286                .get(&self.photo_endpoint)
287                .bearer_auth(access)
288                .send()
289                .await
290                && response.status().is_success()
291                && let Ok(bytes) = response.bytes().await
292                && let Some(object) = profile.as_object_mut()
293            {
294                _ = object.insert(
295                    "picture".into(),
296                    Value::String(format!(
297                        "data:image/jpeg;base64, {}",
298                        base64::engine::general_purpose::STANDARD.encode(bytes)
299                    )),
300                );
301            }
302        }
303        let mapped = self
304            .mapper
305            .map(|mapper| mapper(profile.clone()))
306            .transpose()?;
307        let email = profile
308            .get("email")
309            .and_then(Value::as_str)
310            .unwrap_or_default()
311            .to_owned();
312        let verified = match profile.get("email_verified") {
313            Some(value) => truthy(value),
314            None => {
315                !email.is_empty()
316                    && (email_list_includes(profile.get("verified_primary_email"), &email)?
317                        || email_list_includes(profile.get("verified_secondary_email"), &email)?)
318            }
319        };
320        // Public provider output keeps the original JSON shape independently
321        // from the typed values used by account admission and persistence.
322        let user_output = Some(mapped.as_ref().map_or_else(
323            || {
324                let mut output = serde_json::Map::new();
325                for (source, target) in [("name", "name"), ("email", "email"), ("picture", "image")]
326                {
327                    if let Some(value) = profile.get(source) {
328                        _ = output.insert(target.into(), value.clone());
329                    }
330                }
331                _ = output.insert(
332                    "emailVerified".into(),
333                    profile
334                        .get("email_verified")
335                        .cloned()
336                        .unwrap_or(Value::Bool(verified)),
337                );
338                output
339            },
340            |user| user.public_profile(true),
341        ));
342        let user = match mapped {
343            Some(user) => user,
344            None => OAuthUserInfo {
345                additional_fields: Map::default(),
346                id,
347                email,
348                name: scalar(profile.get("name"))?,
349                image: scalar(profile.get("picture"))?,
350                email_verified: verified,
351            },
352        };
353        Ok(OAuthUserInfoResponse {
354            user_output,
355            user,
356            data: profile,
357        })
358    }
359}
360fn subject(profile: &Value) -> Result<String, String> {
361    let id = profile
362        .get("oid")
363        .and_then(Value::as_str)
364        .ok_or("Missing Microsoft oid")?;
365    if id
366        .trim_matches(|character: char| {
367            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
368        })
369        .is_empty()
370    {
371        return Err("Invalid Microsoft oid".into());
372    }
373    Ok(id.into())
374}
375fn email_list_includes(value: Option<&Value>, email: &str) -> Result<bool, String> {
376    match value {
377        None | Some(Value::Null) => Ok(false),
378        Some(Value::Array(values)) => Ok(values.iter().any(|value| value.as_str() == Some(email))),
379        Some(Value::String(value)) => Ok(value.contains(email)),
380        _ => Err("Invalid Microsoft verified email list".into()),
381    }
382}
383fn truthy(value: &Value) -> bool {
384    match value {
385        Value::Null => false,
386        Value::Bool(value) => *value,
387        Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
388        Value::String(value) => !value.is_empty(),
389        Value::Array(_) | Value::Object(_) => true,
390    }
391}
392fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
393    match value {
394        None | Some(Value::Null) => Ok(None),
395        Some(Value::String(value)) => Ok(Some(value.clone())),
396        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
397            .map(Some)
398            .map_err(|error| error.to_string()),
399        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
400        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Microsoft profile field".into()),
401    }
402}