alibi_plugins/oauth/providers/
paybin.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use base64::Engine;
8use serde_json::Map;
9use serde_json::Value;
10
11#[derive(Clone)]
14pub struct PaybinOptions {
15 pub client_id: String,
16 pub client_secret: Option<String>,
17 pub client_key: Option<String>,
19 pub scope: Vec<String>,
20 pub disable_default_scope: bool,
21 pub authorization_endpoint: Option<String>,
22 pub redirect_uri: Option<String>,
23 pub issuer: Option<String>,
25 pub prompt: Option<String>,
26 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
28}
29impl PaybinOptions {
30 #[must_use]
31 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
32 Self {
33 client_id: client_id.into(),
34 client_secret,
35 client_key: None,
36 scope: Vec::new(),
37 disable_default_scope: false,
38 authorization_endpoint: None,
39 redirect_uri: None,
40 issuer: None,
41 prompt: None,
42 map_profile_to_user: None,
43 }
44 }
45}
46impl std::fmt::Debug for PaybinOptions {
47 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 formatter
49 .debug_struct("PaybinOptions")
50 .field("client_id", &self.client_id)
51 .field("scope", &self.scope)
52 .field("disable_default_scope", &self.disable_default_scope)
53 .field("authorization_endpoint", &self.authorization_endpoint)
54 .field("redirect_uri", &self.redirect_uri)
55 .finish_non_exhaustive()
56 }
57}
58impl OAuthProvider {
59 #[must_use]
60 pub fn paybin(client_id: &str, client_secret: Option<&str>) -> Self {
61 Self::paybin_with_options(PaybinOptions::new(
62 client_id,
63 client_secret.map(str::to_owned),
64 ))
65 }
66 #[must_use]
67 pub fn paybin_with_options(options: PaybinOptions) -> Self {
68 let secret = options.client_secret.unwrap_or_default();
69 let authentication = if secret.is_empty() {
70 OAuthTokenEndpointAuth::None
71 } else {
72 OAuthTokenEndpointAuth::ClientSecretPost
73 };
74 let issuer = options
75 .issuer
76 .filter(|value| !value.is_empty())
77 .unwrap_or_else(|| "https://idp.paybin.io".into());
78 Self {
79 client_id: options.client_id,
80 client_secret: secret,
81 additional_client_ids: Vec::new(),
82 hosted_domain: None,
83 require_email_verification: false,
84 auth_url: options
85 .authorization_endpoint
86 .filter(|value| !value.is_empty())
87 .unwrap_or_else(|| format!("{issuer}/oauth2/authorize")),
88 token_url: format!("{issuer}/oauth2/token"),
89 user_info_url: None,
90 scopes: vec!["openid".into(), "email".into(), "profile".into()],
91 authorization: Some(OAuthAuthorizationPolicy {
92 preserve_raw_profile_scalars: true,
93 source_profile_exceptions: true,
94 allow_missing_access_token: true,
95 configured_scopes: options.scope,
96 disable_default_scopes: options.disable_default_scope,
97 require_client_id: true,
98 require_client_secret: true,
99 default_prompt: options.prompt,
100 token_endpoint_auth: Some(authentication),
101 authorization_code_client_key: options.client_key,
102 redirect_uri: options.redirect_uri,
103 login_hint: true,
104 propagate_grant_profile_errors: true,
105 preserve_raw_email_errors: true,
106 ..OAuthAuthorizationPolicy::default()
107 }),
108 authorization_params: Vec::new(),
109 account_subject: Some(subject),
110 map_user_info: None,
111 get_user_info: Some(std::sync::Arc::new(PaybinUserInfo {
112 application_mapper: None,
113 mapper: options.map_profile_to_user,
114 })),
115 refresh_access_token: None,
116 verify_id_token: None,
117 id_token: None,
118 disable_id_token_sign_in: false,
119 disable_implicit_sign_up: false,
120 disable_sign_up: false,
121 allow_idp_initiated: false,
122 override_user_info_on_sign_in: false,
123 }
124 }
125}
126#[derive(Clone)]
127struct PaybinUserInfo {
128 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
129 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
130}
131#[async_trait]
132impl OAuthUserInfoHandler for PaybinUserInfo {
133 fn errors_are_exceptions(&self) -> bool {
134 false
135 }
136
137 fn mapped_handler(
138 &self,
139 mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
140 ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
141 let mut handler = self.clone();
142 handler.mapper = None;
143 handler.application_mapper = Some(mapper);
144 Some(std::sync::Arc::new(handler))
145 }
146
147 async fn get_user_info(
148 &self,
149 request: OAuthUserInfoRequest,
150 ) -> Result<OAuthUserInfoResponse, String> {
151 let profile = super::remaining_profile::grant_id_token(&request)?
154 .as_deref()
155 .and_then(decode_profile)
156 .ok_or("Missing or invalid Paybin ID token")?;
157 let application_output = if let Some(mapper) = &self.application_mapper {
158 Some(
159 mapper
160 .map_profile(profile.clone())
161 .await
162 .map_err(super::remaining_profile::profile_exception)?,
163 )
164 } else {
165 None
166 };
167 let mapped = self
168 .mapper
169 .map(|mapper| mapper(profile.clone()))
170 .transpose()
171 .map_err(super::remaining_profile::profile_exception)?;
172 let mut output = serde_json::Map::new();
174 for (source, target) in [("email", "email"), ("picture", "image")] {
175 if let Some(value) = profile.get(source) {
176 _ = output.insert(target.into(), value.clone());
177 }
178 }
179 let name = profile
180 .get("name")
181 .filter(|v| truthy(v))
182 .or_else(|| profile.get("preferred_username").filter(|v| truthy(v)))
183 .cloned()
184 .unwrap_or_else(|| Value::String(String::new()));
185 _ = output.insert("name".into(), name.clone());
186 _ = output.insert(
187 "emailVerified".into(),
188 profile
189 .get("email_verified")
190 .filter(|v| truthy(v))
191 .cloned()
192 .unwrap_or(Value::Bool(false)),
193 );
194 if let Some(user) = &mapped {
195 output.extend(user.public_profile(true));
196 }
197 let user_output = Some(output);
198 let user = match mapped {
199 Some(user) => user,
200 None => OAuthUserInfo {
201 additional_fields: Map::default(),
202 id: profile
203 .get("sub")
204 .map(super::remaining_profile::js_string)
205 .transpose()?
206 .unwrap_or_default(),
207 name: scalar(Some(&name))?,
208 email: profile
209 .get("email")
210 .and_then(Value::as_str)
211 .unwrap_or_default()
212 .into(),
213 image: scalar(profile.get("picture"))?,
214 email_verified: profile.get("email_verified").is_some_and(truthy),
215 },
216 };
217 let mut response = OAuthUserInfoResponse {
218 user_output,
219 user,
220 data: profile,
221 };
222 if let Some(mapped) = application_output {
223 super::apply_application_mapping(&mut response, mapped)?;
224 }
225 Ok(response)
226 }
227}
228fn truthy(value: &Value) -> bool {
229 match value {
230 Value::Null | Value::Bool(false) => false,
231 Value::Number(value) => value.as_f64() != Some(0.0),
232 Value::String(value) => !value.is_empty(),
233 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
234 }
235}
236fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
237 match value {
238 Some(Value::String(value)) => Ok(Some(value.clone())),
239 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
240 .map(Some)
241 .map_err(|error| error.to_string()),
242 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
243 None | Some(Value::Null | Value::Array(_) | Value::Object(_)) => Ok(None),
244 }
245}
246fn subject(profile: &Value) -> Result<String, String> {
247 super::remaining_profile::raw_subject(profile.get("sub"))
248}
249
250fn decode_profile(token: &str) -> Option<Value> {
251 let mut parts = token.split('.');
252 _ = parts.next()?;
253 let payload = parts.next()?;
254 _ = parts.next()?;
255 if payload.is_empty() || parts.next().is_some() {
256 return None;
257 }
258 let encoded = payload.replace('-', "+").replace('_', "/");
259 let decoder = base64::engine::GeneralPurpose::new(
260 &base64::alphabet::STANDARD,
261 base64::engine::GeneralPurposeConfig::new()
262 .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
263 );
264 let bytes = decoder.decode(encoded).ok()?;
265 let profile: Value = alibi_core::utils::json::from_slice(&bytes).ok()?;
266 profile.is_object().then_some(profile)
267}