Skip to main content

alibi_plugins/oauth/providers/
paypal.rs

1//! `PayPal`'s sandbox/live endpoints, PKCE grants and original user-info subject.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use serde_json::Map;
7use serde_json::Value;
8
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10pub enum PayPalEnvironment {
11    #[default]
12    Sandbox,
13    Live,
14}
15
16/// Application-owned `PayPal` configuration. The published factory ignores scopes,
17/// requestShippingAddress, clientKey and responseMode.
18/// Generic signup and asynchronous callbacks remain available on the provider.
19#[derive(Clone)]
20pub struct PayPalOptions {
21    pub client_id: String,
22    pub client_secret: String,
23    pub environment: PayPalEnvironment,
24    pub prompt: Option<String>,
25    pub authorization_endpoint: Option<String>,
26    pub redirect_uri: Option<String>,
27    /// Trusted transport override retaining the `PayPal` query and mapping.
28    pub user_info_endpoint: Option<String>,
29    /// Receives the original profile; its ID cannot replace the account subject.
30    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
31}
32impl PayPalOptions {
33    #[must_use]
34    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
35        Self {
36            client_id: client_id.into(),
37            client_secret: client_secret.into(),
38            environment: PayPalEnvironment::Sandbox,
39            prompt: None,
40            authorization_endpoint: None,
41            redirect_uri: None,
42            user_info_endpoint: None,
43            map_profile_to_user: None,
44        }
45    }
46}
47impl std::fmt::Debug for PayPalOptions {
48    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        formatter
50            .debug_struct("PayPalOptions")
51            .field("client_id", &self.client_id)
52            .field("environment", &self.environment)
53            .field("prompt", &self.prompt)
54            .field("authorization_endpoint", &self.authorization_endpoint)
55            .field("redirect_uri", &self.redirect_uri)
56            .finish_non_exhaustive()
57    }
58}
59impl OAuthProvider {
60    #[must_use]
61    pub fn paypal(client_id: &str, client_secret: &str) -> Self {
62        Self::paypal_with_options(PayPalOptions::new(client_id, client_secret))
63    }
64    #[must_use]
65    pub fn paypal_with_options(options: PayPalOptions) -> Self {
66        let sandbox = options.environment == PayPalEnvironment::Sandbox;
67        let web = if sandbox {
68            "www.sandbox.paypal.com"
69        } else {
70            "www.paypal.com"
71        };
72        let api = if sandbox {
73            "api-m.sandbox.paypal.com"
74        } else {
75            "api-m.paypal.com"
76        };
77        let endpoint = options
78            .user_info_endpoint
79            .unwrap_or_else(|| format!("https://{api}/v1/identity/oauth2/userinfo"));
80        Self {
81            client_id: options.client_id,
82            client_secret: options.client_secret,
83            additional_client_ids: Vec::new(),
84            hosted_domain: None,
85            require_email_verification: false,
86            auth_url: options
87                .authorization_endpoint
88                .filter(|value| !value.is_empty())
89                .unwrap_or_else(|| format!("https://{web}/signin/authorize")),
90            token_url: format!("https://{api}/v1/oauth2/token"),
91            user_info_url: Some(endpoint.clone()),
92            scopes: Vec::new(),
93            authorization: Some(OAuthAuthorizationPolicy {
94                preserve_raw_profile_scalars: true,
95                source_profile_exceptions: true,
96                allow_missing_access_token: true,
97                preserve_raw_email_errors: true,
98                omit_scopes: true,
99                require_client_id: true,
100                require_client_secret: true,
101                token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
102                redirect_uri: options.redirect_uri,
103                login_hint: false,
104                prompt: options.prompt,
105                ..OAuthAuthorizationPolicy::default()
106            }),
107            allowed_request_params: Vec::new(),
108            authorization_params: Vec::new(),
109            account_subject: Some(subject),
110            map_user_info: None,
111            get_user_info: Some(std::sync::Arc::new(PayPalUserInfo {
112                application_mapper: None,
113                endpoint,
114                mapper: options.map_profile_to_user,
115            })),
116            refresh_access_token: None,
117            verify_id_token: None,
118            id_token: None,
119            disable_id_token_sign_in: false,
120            disable_implicit_sign_up: false,
121            disable_sign_up: false,
122            allow_idp_initiated: false,
123            override_user_info_on_sign_in: false,
124        }
125    }
126}
127#[derive(Clone)]
128struct PayPalUserInfo {
129    application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
130    endpoint: String,
131    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
132}
133#[async_trait::async_trait]
134impl OAuthUserInfoHandler for PayPalUserInfo {
135    fn errors_are_exceptions(&self) -> bool {
136        false
137    }
138
139    fn mapped_handler(
140        &self,
141        mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
142    ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
143        let mut handler = self.clone();
144        handler.mapper = None;
145        handler.application_mapper = Some(mapper);
146        Some(std::sync::Arc::new(handler))
147    }
148
149    async fn get_user_info(
150        &self,
151        request: OAuthUserInfoRequest,
152    ) -> Result<OAuthUserInfoResponse, String> {
153        if !super::remaining_profile::has_access_token(&request) {
154            return Err("Missing PayPal access token".into());
155        }
156        let access_token = super::remaining_profile::bearer_access_token(&request)?;
157        let profile: Value = reqwest::Client::new()
158            .get(&self.endpoint)
159            .query(&[("schema", "paypalv1.1")])
160            .bearer_auth(access_token)
161            .header("Accept", "application/json")
162            .send()
163            .await
164            .map_err(|error| error.to_string())?
165            .error_for_status()
166            .map_err(|error| error.to_string())?
167            .json()
168            .await
169            .map_err(|error| error.to_string())?;
170        if !profile.is_object() {
171            return Err("Missing PayPal profile".into());
172        }
173        if request.id_token.is_none()
174            && request
175                .raw
176                .as_ref()
177                .and_then(|raw| raw.get("id_token"))
178                .is_some_and(truthy)
179        {
180            return Err("Invalid PayPal ID token type".into());
181        }
182        if let Some(token) = super::remaining_profile::grant_id_token(&request)? {
183            // The published factory decodes, it does not verify JWT signatures.
184            // This token comes from the trusted code exchange; direct ID-token
185            // sign-in remains unsupported because no verifier is configured.
186            let claims = super::remaining_profile::decode_grant_jwt(&token)?;
187            let token_subject = claims
188                .get("sub")
189                .filter(|value| truthy(value))
190                .ok_or("Missing PayPal ID-token subject")?;
191            let profile_subject = profile
192                .get("sub")
193                .filter(|value| !value.is_null())
194                .or_else(|| profile.get("user_id"));
195            if !profile_subject.is_some_and(|subject| {
196                super::remaining_profile::strict_primitive_equal(subject, token_subject)
197            }) {
198                return Err("PayPal ID-token subject mismatch".into());
199            }
200        }
201        let application_output = if let Some(mapper) = &self.application_mapper {
202            Some(mapper.map_profile(profile.clone()).await?)
203        } else {
204            None
205        };
206        let mapped = self
207            .mapper
208            .map(|mapper| mapper(profile.clone()))
209            .transpose()?;
210        let mut output = serde_json::Map::new();
211        for (source, target) in [
212            ("name", "name"),
213            ("email", "email"),
214            ("picture", "image"),
215            ("email_verified", "emailVerified"),
216        ] {
217            if let Some(value) = profile.get(source) {
218                _ = output.insert(target.into(), value.clone());
219            }
220        }
221        if let Some(user) = &mapped {
222            output.extend(user.public_profile(true));
223        }
224        let user = match mapped {
225            Some(user) => user,
226            None => OAuthUserInfo {
227                additional_fields: Map::default(),
228                id: profile
229                    .get("user_id")
230                    .map(super::remaining_profile::js_string)
231                    .transpose()?
232                    .unwrap_or_default(),
233                name: scalar(profile.get("name").filter(|value| truthy(value)))?,
234                email: profile
235                    .get("email")
236                    .and_then(Value::as_str)
237                    .unwrap_or_default()
238                    .into(),
239                image: scalar(profile.get("picture"))?,
240                email_verified: profile.get("email_verified").is_some_and(truthy),
241            },
242        };
243        let mut response = OAuthUserInfoResponse {
244            user_output: Some(output),
245            user,
246            data: profile,
247        };
248        if let Some(mapped) = application_output {
249            super::apply_application_mapping(&mut response, mapped)?;
250        }
251        Ok(response)
252    }
253}
254fn truthy(value: &Value) -> bool {
255    match value {
256        Value::Null | Value::Bool(false) => false,
257        Value::Number(value) => value.as_f64() != Some(0.0),
258        Value::String(value) => !value.is_empty(),
259        _ => true,
260    }
261}
262fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
263    match value {
264        None | Some(Value::Null) => Ok(None),
265        Some(Value::String(value)) => Ok(Some(value.clone())),
266        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
267            .map(Some)
268            .map_err(|error| error.to_string()),
269        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
270        _ => Err("Invalid PayPal profile field".into()),
271    }
272}
273fn subject(profile: &Value) -> Result<String, String> {
274    super::remaining_profile::raw_subject(profile.get("user_id"))
275}