alibi_plugins/oauth/providers/
apple.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthUserInfo, OAuthUserInfoHandler,
4 OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use crate::oauth::{OAuthIdTokenConfig, OAuthJwksSource};
7use alibi_core::utils::json::{JsValue, parse_value};
8use async_trait::async_trait;
9use base64::Engine;
10use serde_json::Map;
11use std::sync::Arc;
12
13#[derive(Clone)]
16pub struct AppleOptions {
17 pub client_ids: Vec<String>,
18 pub client_secret: String,
19 pub audience: Option<Vec<String>>,
20 pub app_bundle_identifier: Option<String>,
21 pub scope: Vec<String>,
22 pub disable_default_scope: bool,
23 pub disable_id_token_sign_in: bool,
24 pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
25 pub map_profile_to_user: Option<fn(serde_json::Value) -> Result<OAuthUserInfo, String>>,
27}
28impl AppleOptions {
29 #[must_use]
30 pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
31 Self {
32 client_ids: vec![client_id.into()],
33 client_secret: client_secret.into(),
34 audience: None,
35 app_bundle_identifier: None,
36 scope: Vec::new(),
37 disable_default_scope: false,
38 disable_id_token_sign_in: false,
39 jwks_source: None,
40 map_profile_to_user: None,
41 }
42 }
43}
44impl std::fmt::Debug for AppleOptions {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 f.debug_struct("AppleOptions")
47 .field("client_ids", &self.client_ids)
48 .field("audience", &self.audience)
49 .field("app_bundle_identifier", &self.app_bundle_identifier)
50 .field("scope", &self.scope)
51 .field("disable_default_scope", &self.disable_default_scope)
52 .field("disable_id_token_sign_in", &self.disable_id_token_sign_in)
53 .finish_non_exhaustive()
54 }
55}
56impl OAuthProvider {
57 #[must_use]
58 pub fn apple(client_id: &str, client_secret: &str) -> Self {
59 Self::apple_with_options(AppleOptions::new(client_id, client_secret))
60 }
61 #[must_use]
62 pub fn apple_with_options(options: AppleOptions) -> Self {
63 let client_ids = options.client_ids.clone();
64 let mut clients = options.client_ids.into_iter();
65 let mut verification = OAuthIdTokenConfig::apple();
66 verification.client_ids = Some(client_ids);
67 verification.audience = options
68 .audience
69 .filter(|values| !values.is_empty())
70 .or_else(|| {
71 options
72 .app_bundle_identifier
73 .filter(|value| !value.is_empty())
74 .map(|value| vec![value])
75 });
76 if let Some(source) = options.jwks_source {
77 verification.jwks_source = source;
78 }
79 Self {
80 client_id: clients.next().unwrap_or_default(),
81 additional_client_ids: clients.collect(),
82 hosted_domain: None,
83 require_email_verification: false,
84 client_secret: options.client_secret,
85 auth_url: "https://appleid.apple.com/auth/authorize".into(),
86 token_url: "https://appleid.apple.com/auth/token".into(),
87 user_info_url: None,
88 scopes: vec!["email".into(), "name".into()],
89 authorization: Some(OAuthAuthorizationPolicy {
90 configured_scopes: options.scope,
91 disable_default_scopes: options.disable_default_scope,
92 response_type: "code id_token".into(),
93 response_mode: Some("form_post".into()),
94 require_client_secret: true,
95 login_hint: false,
96 ..OAuthAuthorizationPolicy::default()
97 }),
98 allowed_request_params: Vec::new(),
99 authorization_params: Vec::new(),
100 account_subject: None,
101 map_user_info: None,
102 get_user_info: Some(Arc::new(AppleUserInfo {
103 map_profile_to_user: options.map_profile_to_user,
104 })),
105 refresh_access_token: None,
106 verify_id_token: None,
107 id_token: Some(verification),
108 disable_id_token_sign_in: options.disable_id_token_sign_in,
109 disable_implicit_sign_up: false,
110 disable_sign_up: false,
111 allow_idp_initiated: false,
112 override_user_info_on_sign_in: false,
113 }
114 }
115}
116struct AppleUserInfo {
117 map_profile_to_user: Option<fn(serde_json::Value) -> Result<OAuthUserInfo, String>>,
118}
119#[async_trait]
120impl OAuthUserInfoHandler for AppleUserInfo {
121 async fn get_user_info(
122 &self,
123 request: OAuthUserInfoRequest,
124 ) -> Result<OAuthUserInfoResponse, String> {
125 let token = request.id_token.ok_or("Missing Apple ID token")?;
126 let parts: Vec<_> = token.split('.').collect();
127 let [_, payload, _] = parts.as_slice() else {
128 return Err("Invalid Apple ID token".into());
129 };
130 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
131 .decode(payload)
132 .map_err(|error| error.to_string())?;
133 let mut profile =
134 parse_value(std::str::from_utf8(&bytes).map_err(|error| error.to_string())?)
135 .map_err(|error| error.to_string())?;
136 _ = profile.as_object().ok_or("Invalid Apple profile")?;
137 let name_value = if let Some(name) = request.user.and_then(|user| user.name) {
138 JsValue::String(
139 format!(
140 "{} {}",
141 name.first_name.unwrap_or_default(),
142 name.last_name.unwrap_or_default()
143 )
144 .trim_matches(js_whitespace)
145 .to_owned(),
146 )
147 } else {
148 match profile.get("name") {
149 Some(JsValue::Number(value)) if *value != 0.0 && value.is_finite() => {
150 JsValue::Number(*value)
151 }
152 Some(JsValue::String(value)) => JsValue::String(value.clone()),
153 Some(JsValue::Bool(true)) => JsValue::Bool(true),
154 _ => JsValue::String(String::new()),
155 }
156 };
157 let name = match &name_value {
158 JsValue::String(value) => value.clone(),
159 JsValue::Number(value) => alibi_core::utils::json::number_to_string(
160 &serde_json::Number::from_f64(*value).ok_or("Invalid Apple name")?,
161 )
162 .map_err(|error| error.to_string())?,
163 JsValue::Bool(value) => value.to_string(),
164 _ => return Err("Invalid Apple name".into()),
165 };
166 let id = match profile.get("sub") {
167 Some(JsValue::String(value))
168 if !value.trim_matches(js_whitespace).is_empty()
169 && value != "null"
170 && value != "undefined" =>
171 {
172 value.clone()
173 }
174 Some(JsValue::Number(value)) if value.is_finite() => {
175 alibi_core::utils::json::number_to_string(
176 &serde_json::Number::from_f64(*value).ok_or("Invalid Apple subject")?,
177 )
178 .map_err(|error| error.to_string())?
179 }
180 _ => return Err("Invalid Apple subject".into()),
181 };
182 let email = profile
183 .get("email")
184 .and_then(JsValue::as_str)
185 .unwrap_or_default()
186 .to_owned();
187 let email_verified = match profile.get("email_verified") {
188 Some(JsValue::Bool(value)) => *value,
189 Some(JsValue::String(value)) => value == "true",
190 _ => false,
191 };
192 let JsValue::Object(object) = &mut profile else {
193 return Err("Invalid Apple profile".into());
194 };
195 _ = object.insert("name".into(), name_value);
196 let data = profile.to_json_value().map_err(|error| error.to_string())?;
197 let mut user_output = None;
198 let user = if let Some(mapper) = self.map_profile_to_user {
199 let mut mapped = mapper(data.clone())?;
200 user_output = Some(mapped.public_profile(true));
201 mapped.id = id;
202 mapped
203 } else {
204 OAuthUserInfo {
205 additional_fields: Map::default(),
206 id,
207 email,
208 name: Some(name),
209 image: None,
210 email_verified,
211 }
212 };
213 Ok(OAuthUserInfoResponse {
214 user_output,
215 user,
216 data,
217 })
218 }
219}
220
221fn js_whitespace(character: char) -> bool {
222 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
223}