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}
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 allowed_request_params: Vec::new(),
124 authorization_params: options
125 .config_id
126 .filter(|value| !value.is_empty())
127 .map(|value| vec![("config_id".into(), value)])
128 .unwrap_or_default(),
129 account_subject: Some(subject),
130 map_user_info: None,
131 get_user_info: Some(Arc::new(FacebookUserInfo {
132 client_id,
133 client_ids: options.client_ids,
134 client_secret: secret,
135 inspection_endpoint: options
136 .token_inspection_endpoint
137 .unwrap_or_else(|| "https://graph.facebook.com/debug_token".into()),
138 endpoint,
139 fields: options.fields,
140 mapper: options.map_profile_to_user,
141 })),
142 refresh_access_token: None,
143 verify_id_token: None,
144 id_token: Some(verification),
145 disable_id_token_sign_in: false,
146 disable_implicit_sign_up: false,
147 disable_sign_up: false,
148 allow_idp_initiated: false,
149 override_user_info_on_sign_in: false,
150 }
151 }
152}
153struct FacebookUserInfo {
154 client_id: String,
155 client_ids: Vec<String>,
156 client_secret: String,
157 inspection_endpoint: String,
158 endpoint: String,
159 fields: Vec<String>,
160 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
161}
162#[async_trait]
163impl OAuthUserInfoHandler for FacebookUserInfo {
164 async fn get_user_info(
165 &self,
166 request: OAuthUserInfoRequest,
167 ) -> Result<OAuthUserInfoResponse, String> {
168 let limited_login = request
169 .id_token
170 .as_deref()
171 .is_some_and(|token| token.split('.').count() == 3);
172 let profile = if limited_login {
173 let token = request
174 .id_token
175 .as_deref()
176 .ok_or("Missing Facebook ID token")?;
177 let payload = token.split('.').nth(1).ok_or("Invalid Facebook ID token")?;
178 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
179 .decode(payload)
180 .map_err(|error| error.to_string())?;
181 let data: Value =
182 alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
183 if !data.is_object() {
184 return Err("Invalid Facebook ID profile".into());
185 }
186 data
187 } else {
188 self.graph_profile(request.access_token.as_deref()).await?
189 };
190 let mapped = self
191 .mapper
192 .map(|mapper| mapper(profile.clone()))
193 .transpose()?;
194 let user_output = mapped.as_ref().map(|user| user.public_profile(true));
195 let user = match mapped {
196 Some(user) => user,
197 None => OAuthUserInfo {
198 additional_fields: Map::default(),
199 id: scalar(profile.get("sub").or_else(|| profile.get("id")))?.unwrap_or_default(),
200 name: scalar(profile.get("name"))?,
201 email: profile
202 .get("email")
203 .and_then(Value::as_str)
204 .unwrap_or_default()
205 .into(),
206 image: scalar(if limited_login {
207 profile.get("picture")
208 } else {
209 profile
210 .get("picture")
211 .and_then(|picture| picture.get("data"))
212 .and_then(|data| data.get("url"))
213 })?,
214 email_verified: !limited_login
215 && profile
216 .get("email_verified")
217 .and_then(Value::as_bool)
218 .unwrap_or(false),
219 },
220 };
221 Ok(OAuthUserInfoResponse {
222 user_output,
223 user,
224 data: profile,
225 })
226 }
227}
228impl FacebookUserInfo {
229 async fn graph_profile(&self, access_token: Option<&str>) -> Result<Value, String> {
230 let access_token = access_token
231 .filter(|token| !token.is_empty())
232 .ok_or("Missing Facebook access token")?;
233 if self.client_id.is_empty() || self.client_secret.is_empty() {
234 return Err("Facebook client ID and secret are required".into());
235 }
236 let client = reqwest::Client::new();
237 let app_access_token = format!("{}|{}", self.client_id, self.client_secret);
238 let inspected: Value = client
239 .get(&self.inspection_endpoint)
240 .query(&[
241 ("input_token", access_token),
242 ("access_token", app_access_token.as_str()),
243 ])
244 .send()
245 .await
246 .map_err(http_error)?
247 .error_for_status()
248 .map_err(http_error)?
249 .json()
250 .await
251 .map_err(http_error)?;
252 let data = inspected
253 .get("data")
254 .ok_or("Facebook inspection returned no data")?;
255 let app_valid = data
256 .get("app_id")
257 .and_then(Value::as_str)
258 .is_some_and(|id| {
259 !id.is_empty() && self.client_ids.iter().any(|configured| configured == id)
260 });
261 if data.get("is_valid").and_then(Value::as_bool) != Some(true) || !app_valid {
262 return Err("Invalid Facebook token or configured app binding".into());
263 }
264 let user_id = data
265 .get("user_id")
266 .filter(|value| {
267 matches!(value, Value::String(_) | Value::Number(_) | Value::Bool(_))
268 && truthy(value)
269 })
270 .ok_or("Facebook inspection returned no user")?;
271 let mut fields = vec!["id", "name", "email", "picture"];
272 fields.extend(self.fields.iter().map(String::as_str));
273 let profile: Value = client
274 .get(&self.endpoint)
275 .query(&[("fields", fields.join(","))])
276 .bearer_auth(access_token)
277 .send()
278 .await
279 .map_err(http_error)?
280 .error_for_status()
281 .map_err(http_error)?
282 .json()
283 .await
284 .map_err(http_error)?;
285 if profile.get("id") != Some(user_id) {
286 return Err("Facebook profile does not match inspected identity".into());
287 }
288 Ok(profile)
289 }
290}
291fn http_error(error: reqwest::Error) -> String {
292 error.without_url().to_string()
293}
294fn truthy(value: &Value) -> bool {
295 match value {
296 Value::Null => false,
297 Value::Bool(value) => *value,
298 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
299 Value::String(value) => !value.is_empty(),
300 Value::Array(_) | Value::Object(_) => true,
301 }
302}
303fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
304 match value {
305 None | Some(Value::Null) => Ok(None),
306 Some(Value::String(value)) => Ok(Some(value.clone())),
307 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
308 .map(Some)
309 .map_err(|error| error.to_string()),
310 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
311 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Facebook profile field".into()),
312 }
313}
314fn subject(profile: &Value) -> Result<String, String> {
315 let id = scalar(profile.get("sub").or_else(|| profile.get("id")))?
316 .ok_or("Missing Facebook account subject")?;
317 if id
318 .trim_matches(|character: char| {
319 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
320 })
321 .is_empty()
322 || id == "null"
323 || id == "undefined"
324 {
325 return Err("Invalid Facebook account subject".into());
326 }
327 Ok(id)
328}