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            authorization_params: Vec::new(),
99            account_subject: Some(subject),
100            map_user_info: None,
101            get_user_info: Some(std::sync::Arc::new(LinkedInUserInfo {
102                endpoint,
103                mapper: options.map_profile_to_user,
104            })),
105            refresh_access_token: None,
106            verify_id_token: None,
107            id_token: None,
108            disable_id_token_sign_in: false,
109            disable_implicit_sign_up: false,
110            disable_sign_up: false,
111            allow_idp_initiated: false,
112            override_user_info_on_sign_in: false,
113        }
114    }
115}
116struct LinkedInUserInfo {
117    endpoint: String,
118    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
119}
120#[async_trait]
121impl OAuthUserInfoHandler for LinkedInUserInfo {
122    async fn get_user_info(
123        &self,
124        request: OAuthUserInfoRequest,
125    ) -> Result<OAuthUserInfoResponse, String> {
126        let access_token = request
127            .access_token
128            .ok_or("Missing LinkedIn access token")?;
129        let response: Value = reqwest::Client::new()
130            .get(&self.endpoint)
131            .bearer_auth(access_token)
132            .send()
133            .await
134            .map_err(|error| error.to_string())?
135            .error_for_status()
136            .map_err(|error| error.to_string())?
137            .json()
138            .await
139            .map_err(|error| error.to_string())?;
140        let profile = response;
141        let mapped = self
142            .mapper
143            .map(|mapper| mapper(profile.clone()))
144            .transpose()?;
145        // Keep the factory's original JSON publication separate from typed
146        // persistence and raw account-subject admission.
147        let mut output = serde_json::Map::new();
148        for (source, target) in [("name", "name"), ("email", "email"), ("picture", "image")] {
149            if let Some(value) = profile.get(source) {
150                _ = output.insert(target.into(), value.clone());
151            }
152        }
153        _ = output.insert(
154            "emailVerified".into(),
155            profile
156                .get("email_verified")
157                .filter(|value| !value.is_null())
158                .cloned()
159                .unwrap_or(Value::Bool(false)),
160        );
161        if let Some(user) = &mapped {
162            output.extend(user.public_profile(true));
163        }
164        let user_output = Some(output);
165        let user = match mapped {
166            Some(user) => user,
167            None => OAuthUserInfo {
168                additional_fields: Map::default(),
169                id: scalar(profile.get("sub"))?.unwrap_or_default(),
170                name: scalar(profile.get("name"))?,
171                email: profile
172                    .get("email")
173                    .and_then(Value::as_str)
174                    .unwrap_or_default()
175                    .into(),
176                image: scalar(profile.get("picture"))?,
177                email_verified: profile
178                    .get("email_verified")
179                    .and_then(Value::as_bool)
180                    .unwrap_or(false),
181            },
182        };
183        Ok(OAuthUserInfoResponse {
184            user_output,
185            user,
186            data: profile,
187        })
188    }
189}
190fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
191    match value {
192        None | Some(Value::Null) => Ok(None),
193        Some(Value::String(value)) => Ok(Some(value.clone())),
194        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
195            .map(Some)
196            .map_err(|error| error.to_string()),
197        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
198        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid LinkedIn profile field".into()),
199    }
200}
201fn subject(profile: &Value) -> Result<String, String> {
202    let id = scalar(profile.get("sub"))?.ok_or("Missing LinkedIn subject")?;
203    if id
204        .trim_matches(|character: char| {
205            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
206        })
207        .is_empty()
208        || id == "null"
209        || id == "undefined"
210    {
211        return Err("Invalid LinkedIn subject".into());
212    }
213    Ok(id)
214}