Skip to main content

alibi_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::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/// Apple-specific immutable configuration. Generic provider policy and trusted
14/// application callback overrides remain available on the returned provider.
15#[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    /// Receives the enriched original profile. Its mapped ID cannot replace `sub`.
26    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            authorization_params: Vec::new(),
99            account_subject: None,
100            map_user_info: None,
101            get_user_info: Some(Arc::new(AppleUserInfo {
102                map_profile_to_user: options.map_profile_to_user,
103            })),
104            refresh_access_token: None,
105            verify_id_token: None,
106            id_token: Some(verification),
107            disable_id_token_sign_in: options.disable_id_token_sign_in,
108            disable_implicit_sign_up: false,
109            disable_sign_up: false,
110            allow_idp_initiated: false,
111            override_user_info_on_sign_in: false,
112        }
113    }
114}
115struct AppleUserInfo {
116    map_profile_to_user: Option<fn(serde_json::Value) -> Result<OAuthUserInfo, String>>,
117}
118#[async_trait]
119impl OAuthUserInfoHandler for AppleUserInfo {
120    async fn get_user_info(
121        &self,
122        request: OAuthUserInfoRequest,
123    ) -> Result<OAuthUserInfoResponse, String> {
124        let token = request.id_token.ok_or("Missing Apple ID token")?;
125        let parts: Vec<_> = token.split('.').collect();
126        let [_, payload, _] = parts.as_slice() else {
127            return Err("Invalid Apple ID token".into());
128        };
129        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
130            .decode(payload)
131            .map_err(|error| error.to_string())?;
132        let mut profile =
133            parse_value(std::str::from_utf8(&bytes).map_err(|error| error.to_string())?)
134                .map_err(|error| error.to_string())?;
135        _ = profile.as_object().ok_or("Invalid Apple profile")?;
136        let name_value = if let Some(name) = request.user.and_then(|user| user.name) {
137            JsValue::String(
138                format!(
139                    "{} {}",
140                    name.first_name.unwrap_or_default(),
141                    name.last_name.unwrap_or_default()
142                )
143                .trim_matches(js_whitespace)
144                .to_owned(),
145            )
146        } else {
147            match profile.get("name") {
148                Some(JsValue::Number(value)) if *value != 0.0 && value.is_finite() => {
149                    JsValue::Number(*value)
150                }
151                Some(JsValue::String(value)) => JsValue::String(value.clone()),
152                Some(JsValue::Bool(true)) => JsValue::Bool(true),
153                _ => JsValue::String(String::new()),
154            }
155        };
156        let name = match &name_value {
157            JsValue::String(value) => value.clone(),
158            JsValue::Number(value) => alibi_core::utils::json::number_to_string(
159                &serde_json::Number::from_f64(*value).ok_or("Invalid Apple name")?,
160            )
161            .map_err(|error| error.to_string())?,
162            JsValue::Bool(value) => value.to_string(),
163            _ => return Err("Invalid Apple name".into()),
164        };
165        let id = match profile.get("sub") {
166            Some(JsValue::String(value))
167                if !value.trim_matches(js_whitespace).is_empty()
168                    && value != "null"
169                    && value != "undefined" =>
170            {
171                value.clone()
172            }
173            Some(JsValue::Number(value)) if value.is_finite() => {
174                alibi_core::utils::json::number_to_string(
175                    &serde_json::Number::from_f64(*value).ok_or("Invalid Apple subject")?,
176                )
177                .map_err(|error| error.to_string())?
178            }
179            _ => return Err("Invalid Apple subject".into()),
180        };
181        let email = profile
182            .get("email")
183            .and_then(JsValue::as_str)
184            .unwrap_or_default()
185            .to_owned();
186        let email_verified = match profile.get("email_verified") {
187            Some(JsValue::Bool(value)) => *value,
188            Some(JsValue::String(value)) => value == "true",
189            _ => false,
190        };
191        let JsValue::Object(object) = &mut profile else {
192            return Err("Invalid Apple profile".into());
193        };
194        _ = object.insert("name".into(), name_value);
195        let data = profile.to_json_value().map_err(|error| error.to_string())?;
196        let mut user_output = None;
197        let user = if let Some(mapper) = self.map_profile_to_user {
198            let mut mapped = mapper(data.clone())?;
199            user_output = Some(mapped.public_profile(true));
200            mapped.id = id;
201            mapped
202        } else {
203            OAuthUserInfo {
204                additional_fields: Map::default(),
205                id,
206                email,
207                name: Some(name),
208                image: None,
209                email_verified,
210            }
211        };
212        Ok(OAuthUserInfoResponse {
213            user_output,
214            user,
215            data,
216        })
217    }
218}
219
220fn js_whitespace(character: char) -> bool {
221    (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
222}