Skip to main content

alibi_api/plugins/oauth/providers/
apple.rs

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