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 authorization_params: Vec::new(),
216 account_subject: Some(subject),
217 map_user_info: None,
218 get_user_info: Some(Arc::new(MicrosoftUserInfo {
219 photo_endpoint,
220 disable_photo: options.disable_profile_photo,
221 mapper: options.map_profile_to_user,
222 })),
223 refresh_access_token: None,
224 verify_id_token: None,
225 id_token: Some(verification),
226 disable_id_token_sign_in: false,
227 disable_implicit_sign_up: false,
228 disable_sign_up: false,
229 allow_idp_initiated: false,
230 override_user_info_on_sign_in: false,
231 })
232 }
233}
234struct MicrosoftClaims {
235 authority: String,
236 tenant: String,
237}
238impl OAuthIdTokenClaimsVerifier for MicrosoftClaims {
239 fn verify_claims(&self, claims: &JsValue) -> bool {
240 let Some(tid) = claims.get("tid").and_then(JsValue::as_str) else {
241 return false;
242 };
243 claims.get("iss").and_then(JsValue::as_str)
244 == Some(format!("{}/{tid}/v2.0", self.authority).as_str())
245 && !(self.tenant == "organizations" && tid == CONSUMER_TENANT)
246 && !(self.tenant == "consumers" && tid != CONSUMER_TENANT)
247 }
248}
249struct MicrosoftUserInfo {
250 photo_endpoint: String,
251 disable_photo: bool,
252 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
253}
254#[async_trait]
255impl OAuthUserInfoHandler for MicrosoftUserInfo {
256 async fn get_user_info(
257 &self,
258 request: OAuthUserInfoRequest,
259 ) -> Result<OAuthUserInfoResponse, String> {
260 let token = request
261 .id_token
262 .filter(|value| !value.is_empty())
263 .ok_or("Missing Microsoft ID token")?;
264 let parts: Vec<_> = token.split('.').collect();
265 let [_, payload, _] = parts.as_slice() else {
266 return Err("Invalid Microsoft ID token".into());
267 };
268 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
269 .decode(payload)
270 .map_err(|error| error.to_string())?;
271 let mut profile: Value =
272 alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
273 if !profile.is_object() {
274 return Err("Invalid Microsoft ID-token claims set".into());
275 }
276 let id = subject(&profile)?;
277 if !self.disable_photo
278 && let Some(access) = request.access_token.filter(|value| !value.is_empty())
279 {
280 if let Ok(response) = reqwest::Client::new()
282 .get(&self.photo_endpoint)
283 .bearer_auth(access)
284 .send()
285 .await
286 && response.status().is_success()
287 && let Ok(bytes) = response.bytes().await
288 && let Some(object) = profile.as_object_mut()
289 {
290 _ = object.insert(
291 "picture".into(),
292 Value::String(format!(
293 "data:image/jpeg;base64, {}",
294 base64::engine::general_purpose::STANDARD.encode(bytes)
295 )),
296 );
297 }
298 }
299 let mapped = self
300 .mapper
301 .map(|mapper| mapper(profile.clone()))
302 .transpose()?;
303 let email = profile
304 .get("email")
305 .and_then(Value::as_str)
306 .unwrap_or_default()
307 .to_owned();
308 let verified = match profile.get("email_verified") {
309 Some(value) => truthy(value),
310 None => {
311 !email.is_empty()
312 && (email_list_includes(profile.get("verified_primary_email"), &email)?
313 || email_list_includes(profile.get("verified_secondary_email"), &email)?)
314 }
315 };
316 let user_output = Some(mapped.as_ref().map_or_else(
319 || {
320 let mut output = serde_json::Map::new();
321 for (source, target) in [("name", "name"), ("email", "email"), ("picture", "image")]
322 {
323 if let Some(value) = profile.get(source) {
324 _ = output.insert(target.into(), value.clone());
325 }
326 }
327 _ = output.insert(
328 "emailVerified".into(),
329 profile
330 .get("email_verified")
331 .cloned()
332 .unwrap_or(Value::Bool(verified)),
333 );
334 output
335 },
336 |user| user.public_profile(true),
337 ));
338 let user = match mapped {
339 Some(user) => user,
340 None => OAuthUserInfo {
341 additional_fields: Map::default(),
342 id,
343 email,
344 name: scalar(profile.get("name"))?,
345 image: scalar(profile.get("picture"))?,
346 email_verified: verified,
347 },
348 };
349 Ok(OAuthUserInfoResponse {
350 user_output,
351 user,
352 data: profile,
353 })
354 }
355}
356fn subject(profile: &Value) -> Result<String, String> {
357 let id = profile
358 .get("oid")
359 .and_then(Value::as_str)
360 .ok_or("Missing Microsoft oid")?;
361 if id
362 .trim_matches(|character: char| {
363 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
364 })
365 .is_empty()
366 {
367 return Err("Invalid Microsoft oid".into());
368 }
369 Ok(id.into())
370}
371fn email_list_includes(value: Option<&Value>, email: &str) -> Result<bool, String> {
372 match value {
373 None | Some(Value::Null) => Ok(false),
374 Some(Value::Array(values)) => Ok(values.iter().any(|value| value.as_str() == Some(email))),
375 Some(Value::String(value)) => Ok(value.contains(email)),
376 _ => Err("Invalid Microsoft verified email list".into()),
377 }
378}
379fn truthy(value: &Value) -> bool {
380 match value {
381 Value::Null => false,
382 Value::Bool(value) => *value,
383 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
384 Value::String(value) => !value.is_empty(),
385 Value::Array(_) | Value::Object(_) => true,
386 }
387}
388fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
389 match value {
390 None | Some(Value::Null) => Ok(None),
391 Some(Value::String(value)) => Ok(Some(value.clone())),
392 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
393 .map(Some)
394 .map_err(|error| error.to_string()),
395 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
396 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Microsoft profile field".into()),
397 }
398}