Skip to main content

alibi_plugins/oauth/providers/
linkedin.rs

1//! `LinkedIn`'s non-PKCE grants and original subject with nullish email verification.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Map;
8use serde_json::Value;
9
10/// Application-owned `LinkedIn` configuration. Generic signup and asynchronous
11/// user-info/refresh callbacks remain configurable on the returned provider.
12#[derive(Clone)]
13pub struct LinkedInOptions {
14    pub client_id: String,
15    pub client_secret: Option<String>,
16    /// Sent only during authorization-code exchange.
17    pub client_key: Option<String>,
18    pub scope: Vec<String>,
19    pub disable_default_scope: bool,
20    pub authorization_endpoint: Option<String>,
21    pub redirect_uri: Option<String>,
22    /// Trusted transport override retaining `LinkedIn`'s actual GET and mapping.
23    pub user_info_endpoint: Option<String>,
24    /// Receives the original profile before its raw account identity is resolved.
25    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
26}
27impl LinkedInOptions {
28    #[must_use]
29    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
30        Self {
31            client_id: client_id.into(),
32            client_secret,
33            client_key: None,
34            scope: Vec::new(),
35            disable_default_scope: false,
36            authorization_endpoint: None,
37            redirect_uri: None,
38            user_info_endpoint: None,
39            map_profile_to_user: None,
40        }
41    }
42}
43impl std::fmt::Debug for LinkedInOptions {
44    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        formatter
46            .debug_struct("LinkedInOptions")
47            .field("client_id", &self.client_id)
48            .field("scope", &self.scope)
49            .field("disable_default_scope", &self.disable_default_scope)
50            .field("authorization_endpoint", &self.authorization_endpoint)
51            .field("redirect_uri", &self.redirect_uri)
52            .finish_non_exhaustive()
53    }
54}
55impl OAuthProvider {
56    #[must_use]
57    pub fn linkedin(client_id: &str, client_secret: Option<&str>) -> Self {
58        Self::linkedin_with_options(LinkedInOptions::new(
59            client_id,
60            client_secret.map(str::to_owned),
61        ))
62    }
63    #[must_use]
64    pub fn linkedin_with_options(options: LinkedInOptions) -> Self {
65        let secret = options.client_secret.unwrap_or_default();
66        let authentication = if secret.is_empty() {
67            OAuthTokenEndpointAuth::None
68        } else {
69            OAuthTokenEndpointAuth::ClientSecretPost
70        };
71        let endpoint = options
72            .user_info_endpoint
73            .unwrap_or_else(|| "https://api.linkedin.com/v2/userinfo".into());
74        Self {
75            client_id: options.client_id,
76            client_secret: secret,
77            additional_client_ids: Vec::new(),
78            hosted_domain: None,
79            require_email_verification: false,
80            auth_url: options
81                .authorization_endpoint
82                .filter(|value| !value.is_empty())
83                .unwrap_or_else(|| "https://www.linkedin.com/oauth/v2/authorization".into()),
84            token_url: "https://www.linkedin.com/oauth/v2/accessToken".into(),
85            user_info_url: Some(endpoint.clone()),
86            scopes: ["profile", "email", "openid"].map(String::from).to_vec(),
87            authorization: Some(OAuthAuthorizationPolicy {
88                configured_scopes: options.scope,
89                disable_default_scopes: options.disable_default_scope,
90                require_client_id: true,
91                token_endpoint_auth: Some(authentication),
92                authorization_code_client_key: options.client_key,
93                redirect_uri: options.redirect_uri,
94                login_hint: true,
95                pkce: false,
96                ..OAuthAuthorizationPolicy::default()
97            }),
98            allowed_request_params: Vec::new(),
99            authorization_params: Vec::new(),
100            account_subject: Some(subject),
101            map_user_info: None,
102            get_user_info: Some(std::sync::Arc::new(LinkedInUserInfo {
103                endpoint,
104                mapper: options.map_profile_to_user,
105            })),
106            refresh_access_token: None,
107            verify_id_token: None,
108            id_token: None,
109            disable_id_token_sign_in: false,
110            disable_implicit_sign_up: false,
111            disable_sign_up: false,
112            allow_idp_initiated: false,
113            override_user_info_on_sign_in: false,
114        }
115    }
116}
117struct LinkedInUserInfo {
118    endpoint: String,
119    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
120}
121#[async_trait]
122impl OAuthUserInfoHandler for LinkedInUserInfo {
123    async fn get_user_info(
124        &self,
125        request: OAuthUserInfoRequest,
126    ) -> Result<OAuthUserInfoResponse, String> {
127        let access_token = request
128            .access_token
129            .ok_or("Missing LinkedIn access token")?;
130        let response: Value = reqwest::Client::new()
131            .get(&self.endpoint)
132            .bearer_auth(access_token)
133            .send()
134            .await
135            .map_err(|error| error.to_string())?
136            .error_for_status()
137            .map_err(|error| error.to_string())?
138            .json()
139            .await
140            .map_err(|error| error.to_string())?;
141        let profile = response;
142        let mapped = self
143            .mapper
144            .map(|mapper| mapper(profile.clone()))
145            .transpose()?;
146        // Keep the factory's original JSON publication separate from typed
147        // persistence and raw account-subject admission.
148        let mut output = serde_json::Map::new();
149        for (source, target) in [("name", "name"), ("email", "email"), ("picture", "image")] {
150            if let Some(value) = profile.get(source) {
151                _ = output.insert(target.into(), value.clone());
152            }
153        }
154        _ = output.insert(
155            "emailVerified".into(),
156            profile
157                .get("email_verified")
158                .filter(|value| !value.is_null())
159                .cloned()
160                .unwrap_or(Value::Bool(false)),
161        );
162        if let Some(user) = &mapped {
163            output.extend(user.public_profile(true));
164        }
165        let user_output = Some(output);
166        let user = match mapped {
167            Some(user) => user,
168            None => OAuthUserInfo {
169                additional_fields: Map::default(),
170                id: scalar(profile.get("sub"))?.unwrap_or_default(),
171                name: scalar(profile.get("name"))?,
172                email: profile
173                    .get("email")
174                    .and_then(Value::as_str)
175                    .unwrap_or_default()
176                    .into(),
177                image: scalar(profile.get("picture"))?,
178                email_verified: profile
179                    .get("email_verified")
180                    .and_then(Value::as_bool)
181                    .unwrap_or(false),
182            },
183        };
184        Ok(OAuthUserInfoResponse {
185            user_output,
186            user,
187            data: profile,
188        })
189    }
190}
191fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
192    match value {
193        None | Some(Value::Null) => Ok(None),
194        Some(Value::String(value)) => Ok(Some(value.clone())),
195        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
196            .map(Some)
197            .map_err(|error| error.to_string()),
198        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
199        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid LinkedIn profile field".into()),
200    }
201}
202fn subject(profile: &Value) -> Result<String, String> {
203    let id = scalar(profile.get("sub"))?.ok_or("Missing LinkedIn subject")?;
204    if id
205        .trim_matches(|character: char| {
206            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
207        })
208        .is_empty()
209        || id == "null"
210        || id == "undefined"
211    {
212        return Err("Invalid LinkedIn subject".into());
213    }
214    Ok(id)
215}