Skip to main content

alibi_api/plugins/oauth/providers/
facebook.rs

1//! Facebook Graph app-bound access tokens and signed Limited Login profiles.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use crate::plugins::oauth::{
7    HttpOAuthJwksSource, OAuthIdTokenConfig, OAuthJwksSelection, OAuthJwksSource,
8    id_token::OAuthNonceComparison,
9};
10use async_trait::async_trait;
11use base64::Engine;
12use serde_json::Value;
13use std::sync::Arc;
14
15/// Application-owned Facebook configuration. User-info/refresh callbacks and
16/// signup policies remain configurable on the returned provider.
17#[derive(Clone)]
18pub struct FacebookOptions {
19    pub client_ids: Vec<String>,
20    pub client_secret: Option<String>,
21    /// Sent during authorization-code exchange only.
22    pub client_key: Option<String>,
23    pub scope: Vec<String>,
24    pub disable_default_scope: bool,
25    pub fields: Vec<String>,
26    pub config_id: Option<String>,
27    pub authorization_endpoint: Option<String>,
28    pub redirect_uri: Option<String>,
29    /// Trusted key authority for Limited Login signature verification.
30    pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
31    /// Trusted transport overrides retain the actual inspection and mapping.
32    pub token_inspection_endpoint: Option<String>,
33    pub user_info_endpoint: Option<String>,
34    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
35}
36impl FacebookOptions {
37    #[must_use]
38    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
39        Self {
40            client_ids: vec![client_id.into()],
41            client_secret,
42            client_key: None,
43            scope: Vec::new(),
44            disable_default_scope: false,
45            fields: Vec::new(),
46            config_id: None,
47            authorization_endpoint: None,
48            redirect_uri: None,
49            jwks_source: None,
50            token_inspection_endpoint: None,
51            user_info_endpoint: None,
52            map_profile_to_user: None,
53        }
54    }
55}
56impl std::fmt::Debug for FacebookOptions {
57    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        formatter
59            .debug_struct("FacebookOptions")
60            .field("client_ids", &self.client_ids)
61            .field("scope", &self.scope)
62            .field("disable_default_scope", &self.disable_default_scope)
63            .field("fields", &self.fields)
64            .field("config_id", &self.config_id)
65            .field("authorization_endpoint", &self.authorization_endpoint)
66            .field("redirect_uri", &self.redirect_uri)
67            .finish_non_exhaustive()
68    }
69}
70impl OAuthProvider {
71    #[must_use]
72    pub fn facebook(client_id: &str, client_secret: &str) -> Self {
73        Self::facebook_with_options(FacebookOptions::new(client_id, Some(client_secret.into())))
74    }
75    #[must_use]
76    pub fn facebook_with_options(options: FacebookOptions) -> Self {
77        let client_id = options.client_ids.first().cloned().unwrap_or_default();
78        let secret = options.client_secret.unwrap_or_default();
79        let endpoint = options
80            .user_info_endpoint
81            .unwrap_or_else(|| "https://graph.facebook.com/me".into());
82        let verification = OAuthIdTokenConfig {
83            issuers: vec!["https://www.facebook.com".into()],
84            audience: None,
85            client_ids: Some(options.client_ids.clone()),
86            jwks_source: options.jwks_source.unwrap_or_else(|| {
87                Arc::new(HttpOAuthJwksSource::new(
88                    "https://limited.facebook.com/.well-known/oauth/openid/jwks/",
89                ))
90            }),
91            max_age_secs: None,
92            allow_opaque_token: true,
93            algorithm: Some(jsonwebtoken::Algorithm::RS256),
94            selection: OAuthJwksSelection::RemoteRs256,
95            nonce_comparison: OAuthNonceComparison::Exact,
96            verify_claims: None,
97        };
98        Self {
99            client_id: client_id.clone(),
100            client_secret: secret.clone(),
101            additional_client_ids: options.client_ids.iter().skip(1).cloned().collect(),
102            hosted_domain: None,
103            require_email_verification: false,
104            auth_url: options
105                .authorization_endpoint
106                .filter(|value| !value.is_empty())
107                .unwrap_or_else(|| "https://www.facebook.com/v24.0/dialog/oauth".into()),
108            token_url: "https://graph.facebook.com/v24.0/oauth/access_token".into(),
109            user_info_url: Some(endpoint.clone()),
110            scopes: vec!["email".into(), "public_profile".into()],
111            authorization: Some(OAuthAuthorizationPolicy {
112                configured_scopes: options.scope,
113                disable_default_scopes: options.disable_default_scope,
114                require_client_id: true,
115                require_client_secret: true,
116                token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretPost),
117                authorization_code_client_key: options.client_key,
118                redirect_uri: options.redirect_uri,
119                pkce: false,
120                ..OAuthAuthorizationPolicy::default()
121            }),
122            authorization_params: options
123                .config_id
124                .filter(|value| !value.is_empty())
125                .map(|value| vec![("config_id".into(), value)])
126                .unwrap_or_default(),
127            account_subject: Some(subject),
128            map_user_info: None,
129            get_user_info: Some(Arc::new(FacebookUserInfo {
130                client_id,
131                client_ids: options.client_ids,
132                client_secret: secret,
133                inspection_endpoint: options
134                    .token_inspection_endpoint
135                    .unwrap_or_else(|| "https://graph.facebook.com/debug_token".into()),
136                endpoint,
137                fields: options.fields,
138                mapper: options.map_profile_to_user,
139            })),
140            refresh_access_token: None,
141            verify_id_token: None,
142            id_token: Some(verification),
143            disable_id_token_sign_in: false,
144            disable_implicit_sign_up: false,
145            disable_sign_up: false,
146            override_user_info_on_sign_in: false,
147        }
148    }
149}
150struct FacebookUserInfo {
151    client_id: String,
152    client_ids: Vec<String>,
153    client_secret: String,
154    inspection_endpoint: String,
155    endpoint: String,
156    fields: Vec<String>,
157    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
158}
159#[async_trait]
160impl OAuthUserInfoHandler for FacebookUserInfo {
161    async fn get_user_info(
162        &self,
163        request: OAuthUserInfoRequest,
164    ) -> Result<OAuthUserInfoResponse, String> {
165        let limited_login = request
166            .id_token
167            .as_deref()
168            .is_some_and(|token| token.split('.').count() == 3);
169        let profile = if limited_login {
170            let token = request
171                .id_token
172                .as_deref()
173                .ok_or("Missing Facebook ID token")?;
174            let payload = token.split('.').nth(1).ok_or("Invalid Facebook ID token")?;
175            let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
176                .decode(payload)
177                .map_err(|error| error.to_string())?;
178            let data: Value =
179                alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
180            if !data.is_object() {
181                return Err("Invalid Facebook ID profile".into());
182            }
183            data
184        } else {
185            self.graph_profile(request.access_token.as_deref()).await?
186        };
187        let mapped = self
188            .mapper
189            .map(|mapper| mapper(profile.clone()))
190            .transpose()?;
191        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
192        let user = match mapped {
193            Some(user) => user,
194            None => OAuthUserInfo {
195                additional_fields: Default::default(),
196                id: scalar(profile.get("sub").or_else(|| profile.get("id")))?.unwrap_or_default(),
197                name: scalar(profile.get("name"))?,
198                email: profile
199                    .get("email")
200                    .and_then(Value::as_str)
201                    .unwrap_or_default()
202                    .into(),
203                image: scalar(if limited_login {
204                    profile.get("picture")
205                } else {
206                    profile
207                        .get("picture")
208                        .and_then(|picture| picture.get("data"))
209                        .and_then(|data| data.get("url"))
210                })?,
211                email_verified: !limited_login
212                    && profile
213                        .get("email_verified")
214                        .and_then(Value::as_bool)
215                        .unwrap_or(false),
216            },
217        };
218        Ok(OAuthUserInfoResponse {
219            user_output,
220            user,
221            data: profile,
222        })
223    }
224}
225impl FacebookUserInfo {
226    async fn graph_profile(&self, access_token: Option<&str>) -> Result<Value, String> {
227        let access_token = access_token
228            .filter(|token| !token.is_empty())
229            .ok_or("Missing Facebook access token")?;
230        if self.client_id.is_empty() || self.client_secret.is_empty() {
231            return Err("Facebook client ID and secret are required".into());
232        }
233        let client = reqwest::Client::new();
234        let app_access_token = format!("{}|{}", self.client_id, self.client_secret);
235        let inspected: Value = client
236            .get(&self.inspection_endpoint)
237            .query(&[
238                ("input_token", access_token),
239                ("access_token", app_access_token.as_str()),
240            ])
241            .send()
242            .await
243            .map_err(http_error)?
244            .error_for_status()
245            .map_err(http_error)?
246            .json()
247            .await
248            .map_err(http_error)?;
249        let data = inspected
250            .get("data")
251            .ok_or("Facebook inspection returned no data")?;
252        let app_valid = data
253            .get("app_id")
254            .and_then(Value::as_str)
255            .is_some_and(|id| {
256                !id.is_empty() && self.client_ids.iter().any(|configured| configured == id)
257            });
258        if data.get("is_valid").and_then(Value::as_bool) != Some(true) || !app_valid {
259            return Err("Invalid Facebook token or configured app binding".into());
260        }
261        let user_id = data
262            .get("user_id")
263            .filter(|value| {
264                matches!(value, Value::String(_) | Value::Number(_) | Value::Bool(_))
265                    && truthy(value)
266            })
267            .ok_or("Facebook inspection returned no user")?;
268        let mut fields = vec!["id", "name", "email", "picture"];
269        fields.extend(self.fields.iter().map(String::as_str));
270        let profile: Value = client
271            .get(&self.endpoint)
272            .query(&[("fields", fields.join(","))])
273            .bearer_auth(access_token)
274            .send()
275            .await
276            .map_err(http_error)?
277            .error_for_status()
278            .map_err(http_error)?
279            .json()
280            .await
281            .map_err(http_error)?;
282        if profile.get("id") != Some(user_id) {
283            return Err("Facebook profile does not match inspected identity".into());
284        }
285        Ok(profile)
286    }
287}
288fn http_error(error: reqwest::Error) -> String {
289    error.without_url().to_string()
290}
291fn truthy(value: &Value) -> bool {
292    match value {
293        Value::Null => false,
294        Value::Bool(value) => *value,
295        Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
296        Value::String(value) => !value.is_empty(),
297        Value::Array(_) | Value::Object(_) => true,
298    }
299}
300fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
301    match value {
302        None | Some(Value::Null) => Ok(None),
303        Some(Value::String(value)) => Ok(Some(value.clone())),
304        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
305            .map(Some)
306            .map_err(|error| error.to_string()),
307        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
308        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Facebook profile field".into()),
309    }
310}
311fn subject(profile: &Value) -> Result<String, String> {
312    let id = scalar(profile.get("sub").or_else(|| profile.get("id")))?
313        .ok_or("Missing Facebook account subject")?;
314    if id
315        .trim_matches(|character: char| {
316            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
317        })
318        .is_empty()
319        || id == "null"
320        || id == "undefined"
321    {
322        return Err("Invalid Facebook account subject".into());
323    }
324    Ok(id)
325}