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