Skip to main content

alibi_plugins/oauth/providers/
linear.rs

1//! Linear's non-PKCE grants and GraphQL viewer bound by its original ID.
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 Linear configuration. Generic signup and asynchronous
11/// user-info/refresh callbacks remain configurable on the returned provider.
12#[derive(Clone)]
13pub struct LinearOptions {
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 Linear's actual GraphQL POST 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 LinearOptions {
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 LinearOptions {
44    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        formatter
46            .debug_struct("LinearOptions")
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 linear(client_id: &str, client_secret: Option<&str>) -> Self {
58        Self::linear_with_options(LinearOptions::new(
59            client_id,
60            client_secret.map(str::to_owned),
61        ))
62    }
63    #[must_use]
64    pub fn linear_with_options(options: LinearOptions) -> 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.linear.app/graphql".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://linear.app/oauth/authorize".into()),
84            token_url: "https://api.linear.app/oauth/token".into(),
85            user_info_url: Some(endpoint.clone()),
86            scopes: vec!["read".into()],
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(LinearUserInfo {
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 LinearUserInfo {
118    endpoint: String,
119    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
120}
121#[async_trait]
122impl OAuthUserInfoHandler for LinearUserInfo {
123    async fn get_user_info(
124        &self,
125        request: OAuthUserInfoRequest,
126    ) -> Result<OAuthUserInfoResponse, String> {
127        let access_token = request.access_token.ok_or("Missing Linear access token")?;
128        let response: Value = reqwest::Client::new()
129            .post(&self.endpoint)
130            .json(&serde_json::json!({"query": USER_INFO_QUERY}))
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            .get("data")
142            .and_then(|data| data.get("viewer"))
143            .filter(|viewer| truthy(viewer))
144            .cloned()
145            .ok_or("Missing Linear profile")?;
146        let mapped = self
147            .mapper
148            .map(|mapper| mapper(profile.clone()))
149            .transpose()?;
150        // Keep the published raw JSON independently from typed persistence.
151        let mut output = serde_json::Map::new();
152        for (source, target) in [("name", "name"), ("email", "email"), ("avatarUrl", "image")] {
153            if let Some(value) = profile.get(source) {
154                _ = output.insert(target.into(), value.clone());
155            }
156        }
157        _ = output.insert("emailVerified".into(), Value::Bool(false));
158        if let Some(user) = &mapped {
159            output.extend(user.public_profile(true));
160        }
161        let user_output = Some(output);
162        let user = match mapped {
163            Some(user) => user,
164            None => OAuthUserInfo {
165                additional_fields: Map::default(),
166                id: scalar(profile.get("id"))?.unwrap_or_default(),
167                name: scalar(profile.get("name"))?,
168                email: profile
169                    .get("email")
170                    .and_then(Value::as_str)
171                    .unwrap_or_default()
172                    .into(),
173                image: scalar(profile.get("avatarUrl"))?,
174                email_verified: false,
175            },
176        };
177        Ok(OAuthUserInfoResponse {
178            user_output,
179            user,
180            data: profile,
181        })
182    }
183}
184fn truthy(value: &Value) -> bool {
185    match value {
186        Value::Null | Value::Bool(false) => false,
187        Value::Number(value) => value.as_f64() != Some(0.0),
188        Value::String(value) => !value.is_empty(),
189        Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
190    }
191}
192fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
193    match value {
194        None | Some(Value::Null) => Ok(None),
195        Some(Value::String(value)) => Ok(Some(value.clone())),
196        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
197            .map(Some)
198            .map_err(|error| error.to_string()),
199        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
200        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Linear profile field".into()),
201    }
202}
203fn subject(profile: &Value) -> Result<String, String> {
204    let id = scalar(profile.get("id"))?.ok_or("Missing Linear id")?;
205    if id
206        .trim_matches(|character: char| {
207            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
208        })
209        .is_empty()
210        || id == "null"
211        || id == "undefined"
212    {
213        return Err("Invalid Linear id".into());
214    }
215    Ok(id)
216}
217
218// Public factory field selection, including its actual transport whitespace.
219const USER_INFO_QUERY: &str = r"
220							query {
221								viewer {
222									id
223									name
224									email
225									avatarUrl
226									active
227									createdAt
228									updatedAt
229								}
230							}
231						";