Skip to main content

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