1use 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#[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#[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 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 pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
71 pub profile_photo_endpoint: Option<String>,
73 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 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 selection: OAuthJwksSelection::ExactKid,
159 nonce_comparison: OAuthNonceComparison::Exact,
160 verify_claims: Some(Arc::new(MicrosoftClaims {
161 authority: authority.clone(),
162 tenant: tenant.clone(),
163 })),
164 };
165 let scopes: Vec<_> = DEFAULT_SCOPES.map(String::from).to_vec();
166 let mut refresh_scopes = if options.disable_default_scope {
167 Vec::new()
168 } else {
169 scopes.clone()
170 };
171 refresh_scopes.extend(options.scope.clone());
172 let token_endpoint_auth = if options.client_assertion.is_some() {
173 OAuthTokenEndpointAuth::PrivateKeyJwt
174 } else if options
175 .client_secret
176 .as_ref()
177 .is_some_and(|secret| !secret.is_empty())
178 {
179 OAuthTokenEndpointAuth::ClientSecretPost
180 } else {
181 OAuthTokenEndpointAuth::None
182 };
183 let size = options.profile_photo_size.pixels();
184 let photo_endpoint = options.profile_photo_endpoint.unwrap_or_else(|| {
185 format!("https://graph.microsoft.com/v1.0/me/photos/{size}x{size}/$value")
186 });
187 let mut clients = options.client_ids.into_iter();
188 Ok(Self {
189 client_id: clients.next().unwrap_or_default(),
190 additional_client_ids: clients.collect(),
191 client_secret: options.client_secret.unwrap_or_default(),
192 hosted_domain: None,
193 require_email_verification: false,
194 auth_url: options
195 .authorization_endpoint
196 .filter(|value| !value.is_empty())
197 .unwrap_or_else(|| format!("{authority}/{tenant}/oauth2/v2.0/authorize")),
198 token_url: format!("{authority}/{tenant}/oauth2/v2.0/token"),
199 user_info_url: None,
200 scopes,
201 authorization: Some(OAuthAuthorizationPolicy {
202 configured_scopes: options.scope,
203 scope_encoding: OAuthScopeEncoding::UriComponent,
204 disable_default_scopes: options.disable_default_scope,
205 disable_sign_up_option: options.disable_sign_up.then_some(true),
206 require_client_id: true,
207 token_endpoint_auth: Some(token_endpoint_auth),
208 authorization_code_client_key: options.client_key,
209 client_assertion: options.client_assertion,
210 refresh_scope: Some(refresh_scopes.join(" ")),
211 prompt: options.prompt,
212 redirect_uri: options.redirect_uri,
213 ..OAuthAuthorizationPolicy::default()
214 }),
215 allowed_request_params: Vec::new(),
216 authorization_params: Vec::new(),
217 account_subject: Some(subject),
218 map_user_info: None,
219 get_user_info: Some(Arc::new(MicrosoftUserInfo {
220 photo_endpoint,
221 disable_photo: options.disable_profile_photo,
222 mapper: options.map_profile_to_user,
223 })),
224 refresh_access_token: None,
225 verify_id_token: None,
226 id_token: Some(verification),
227 disable_id_token_sign_in: false,
228 disable_implicit_sign_up: false,
229 disable_sign_up: false,
230 allow_idp_initiated: false,
231 override_user_info_on_sign_in: false,
232 })
233 }
234}
235struct MicrosoftClaims {
236 authority: String,
237 tenant: String,
238}
239impl OAuthIdTokenClaimsVerifier for MicrosoftClaims {
240 fn verify_claims(&self, claims: &JsValue) -> bool {
241 let Some(tid) = claims.get("tid").and_then(JsValue::as_str) else {
242 return false;
243 };
244 claims.get("iss").and_then(JsValue::as_str)
245 == Some(format!("{}/{tid}/v2.0", self.authority).as_str())
246 && !(self.tenant == "organizations" && tid == CONSUMER_TENANT)
247 && !(self.tenant == "consumers" && tid != CONSUMER_TENANT)
248 }
249}
250struct MicrosoftUserInfo {
251 photo_endpoint: String,
252 disable_photo: bool,
253 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
254}
255#[async_trait]
256impl OAuthUserInfoHandler for MicrosoftUserInfo {
257 async fn get_user_info(
258 &self,
259 request: OAuthUserInfoRequest,
260 ) -> Result<OAuthUserInfoResponse, String> {
261 let token = request
262 .id_token
263 .filter(|value| !value.is_empty())
264 .ok_or("Missing Microsoft ID token")?;
265 let parts: Vec<_> = token.split('.').collect();
266 let [_, payload, _] = parts.as_slice() else {
267 return Err("Invalid Microsoft ID token".into());
268 };
269 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
270 .decode(payload)
271 .map_err(|error| error.to_string())?;
272 let mut profile: Value =
273 alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
274 if !profile.is_object() {
275 return Err("Invalid Microsoft ID-token claims set".into());
276 }
277 let id = subject(&profile)?;
278 if !self.disable_photo
279 && let Some(access) = request.access_token.filter(|value| !value.is_empty())
280 {
281 if let Ok(response) = reqwest::Client::new()
283 .get(&self.photo_endpoint)
284 .bearer_auth(access)
285 .send()
286 .await
287 && response.status().is_success()
288 && let Ok(bytes) = response.bytes().await
289 && let Some(object) = profile.as_object_mut()
290 {
291 _ = object.insert(
292 "picture".into(),
293 Value::String(format!(
294 "data:image/jpeg;base64, {}",
295 base64::engine::general_purpose::STANDARD.encode(bytes)
296 )),
297 );
298 }
299 }
300 let mapped = self
301 .mapper
302 .map(|mapper| mapper(profile.clone()))
303 .transpose()?;
304 let email = profile
305 .get("email")
306 .and_then(Value::as_str)
307 .unwrap_or_default()
308 .to_owned();
309 let verified = match profile.get("email_verified") {
310 Some(value) => truthy(value),
311 None => {
312 !email.is_empty()
313 && (email_list_includes(profile.get("verified_primary_email"), &email)?
314 || email_list_includes(profile.get("verified_secondary_email"), &email)?)
315 }
316 };
317 let user_output = Some(mapped.as_ref().map_or_else(
320 || {
321 let mut output = serde_json::Map::new();
322 for (source, target) in [("name", "name"), ("email", "email"), ("picture", "image")]
323 {
324 if let Some(value) = profile.get(source) {
325 _ = output.insert(target.into(), value.clone());
326 }
327 }
328 _ = output.insert(
329 "emailVerified".into(),
330 profile
331 .get("email_verified")
332 .cloned()
333 .unwrap_or(Value::Bool(verified)),
334 );
335 output
336 },
337 |user| user.public_profile(true),
338 ));
339 let user = match mapped {
340 Some(user) => user,
341 None => OAuthUserInfo {
342 additional_fields: Map::default(),
343 id,
344 email,
345 name: scalar(profile.get("name"))?,
346 image: scalar(profile.get("picture"))?,
347 email_verified: verified,
348 },
349 };
350 Ok(OAuthUserInfoResponse {
351 user_output,
352 user,
353 data: profile,
354 })
355 }
356}
357fn subject(profile: &Value) -> Result<String, String> {
358 let id = profile
359 .get("oid")
360 .and_then(Value::as_str)
361 .ok_or("Missing Microsoft oid")?;
362 if id
363 .trim_matches(|character: char| {
364 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
365 })
366 .is_empty()
367 {
368 return Err("Invalid Microsoft oid".into());
369 }
370 Ok(id.into())
371}
372fn email_list_includes(value: Option<&Value>, email: &str) -> Result<bool, String> {
373 match value {
374 None | Some(Value::Null) => Ok(false),
375 Some(Value::Array(values)) => Ok(values.iter().any(|value| value.as_str() == Some(email))),
376 Some(Value::String(value)) => Ok(value.contains(email)),
377 _ => Err("Invalid Microsoft verified email list".into()),
378 }
379}
380fn truthy(value: &Value) -> bool {
381 match value {
382 Value::Null => false,
383 Value::Bool(value) => *value,
384 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
385 Value::String(value) => !value.is_empty(),
386 Value::Array(_) | Value::Object(_) => true,
387 }
388}
389fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
390 match value {
391 None | Some(Value::Null) => Ok(None),
392 Some(Value::String(value)) => Ok(Some(value.clone())),
393 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
394 .map(Some)
395 .map_err(|error| error.to_string()),
396 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
397 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Microsoft profile field".into()),
398 }
399}