alibi_api/plugins/oauth/providers/
linear.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Value;
8
9#[derive(Clone)]
12pub struct LinearOptions {
13 pub client_id: String,
14 pub client_secret: Option<String>,
15 pub client_key: Option<String>,
17 pub scope: Vec<String>,
18 pub disable_default_scope: bool,
19 pub authorization_endpoint: Option<String>,
20 pub redirect_uri: Option<String>,
21 pub user_info_endpoint: Option<String>,
23 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
25}
26impl LinearOptions {
27 #[must_use]
28 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
29 Self {
30 client_id: client_id.into(),
31 client_secret,
32 client_key: None,
33 scope: Vec::new(),
34 disable_default_scope: false,
35 authorization_endpoint: None,
36 redirect_uri: None,
37 user_info_endpoint: None,
38 map_profile_to_user: None,
39 }
40 }
41}
42impl std::fmt::Debug for LinearOptions {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 formatter
45 .debug_struct("LinearOptions")
46 .field("client_id", &self.client_id)
47 .field("scope", &self.scope)
48 .field("disable_default_scope", &self.disable_default_scope)
49 .field("authorization_endpoint", &self.authorization_endpoint)
50 .field("redirect_uri", &self.redirect_uri)
51 .finish_non_exhaustive()
52 }
53}
54impl OAuthProvider {
55 #[must_use]
56 pub fn linear(client_id: &str, client_secret: Option<&str>) -> Self {
57 Self::linear_with_options(LinearOptions::new(
58 client_id,
59 client_secret.map(str::to_owned),
60 ))
61 }
62 #[must_use]
63 pub fn linear_with_options(options: LinearOptions) -> Self {
64 let secret = options.client_secret.unwrap_or_default();
65 let authentication = if secret.is_empty() {
66 OAuthTokenEndpointAuth::None
67 } else {
68 OAuthTokenEndpointAuth::ClientSecretPost
69 };
70 let endpoint = options
71 .user_info_endpoint
72 .unwrap_or_else(|| "https://api.linear.app/graphql".into());
73 Self {
74 client_id: options.client_id,
75 client_secret: secret,
76 additional_client_ids: Vec::new(),
77 hosted_domain: None,
78 require_email_verification: false,
79 auth_url: options
80 .authorization_endpoint
81 .filter(|value| !value.is_empty())
82 .unwrap_or_else(|| "https://linear.app/oauth/authorize".into()),
83 token_url: "https://api.linear.app/oauth/token".into(),
84 user_info_url: Some(endpoint.clone()),
85 scopes: vec!["read".into()],
86 authorization: Some(OAuthAuthorizationPolicy {
87 configured_scopes: options.scope,
88 disable_default_scopes: options.disable_default_scope,
89 require_client_id: true,
90 token_endpoint_auth: Some(authentication),
91 authorization_code_client_key: options.client_key,
92 redirect_uri: options.redirect_uri,
93 login_hint: true,
94 pkce: false,
95 ..OAuthAuthorizationPolicy::default()
96 }),
97 authorization_params: Vec::new(),
98 account_subject: Some(subject),
99 map_user_info: None,
100 get_user_info: Some(std::sync::Arc::new(LinearUserInfo {
101 endpoint,
102 mapper: options.map_profile_to_user,
103 })),
104 refresh_access_token: None,
105 verify_id_token: None,
106 id_token: None,
107 disable_id_token_sign_in: false,
108 disable_implicit_sign_up: false,
109 disable_sign_up: false,
110 override_user_info_on_sign_in: false,
111 }
112 }
113}
114struct LinearUserInfo {
115 endpoint: String,
116 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
117}
118#[async_trait]
119impl OAuthUserInfoHandler for LinearUserInfo {
120 async fn get_user_info(
121 &self,
122 request: OAuthUserInfoRequest,
123 ) -> Result<OAuthUserInfoResponse, String> {
124 let access_token = request.access_token.ok_or("Missing Linear access token")?;
125 let response: Value = reqwest::Client::new()
126 .post(&self.endpoint)
127 .json(&serde_json::json!({"query": USER_INFO_QUERY}))
128 .bearer_auth(access_token)
129 .send()
130 .await
131 .map_err(|error| error.to_string())?
132 .error_for_status()
133 .map_err(|error| error.to_string())?
134 .json()
135 .await
136 .map_err(|error| error.to_string())?;
137 let profile = response
138 .get("data")
139 .and_then(|data| data.get("viewer"))
140 .filter(|viewer| truthy(viewer))
141 .cloned()
142 .ok_or("Missing Linear profile")?;
143 let mapped = self
144 .mapper
145 .map(|mapper| mapper(profile.clone()))
146 .transpose()?;
147 let mut output = serde_json::Map::new();
149 for (source, target) in [("name", "name"), ("email", "email"), ("avatarUrl", "image")] {
150 if let Some(value) = profile.get(source) {
151 drop(output.insert(target.into(), value.clone()));
152 }
153 }
154 drop(output.insert("emailVerified".into(), Value::Bool(false)));
155 if let Some(user) = &mapped {
156 output.extend(user.public_profile(true));
157 }
158 let user_output = Some(output);
159 let user = match mapped {
160 Some(user) => user,
161 None => OAuthUserInfo {
162 additional_fields: Default::default(),
163 id: scalar(profile.get("id"))?.unwrap_or_default(),
164 name: scalar(profile.get("name"))?,
165 email: profile
166 .get("email")
167 .and_then(Value::as_str)
168 .unwrap_or_default()
169 .into(),
170 image: scalar(profile.get("avatarUrl"))?,
171 email_verified: false,
172 },
173 };
174 Ok(OAuthUserInfoResponse {
175 user_output,
176 user,
177 data: profile,
178 })
179 }
180}
181fn truthy(value: &Value) -> bool {
182 match value {
183 Value::Null | Value::Bool(false) => false,
184 Value::Number(value) => value.as_f64() != Some(0.0),
185 Value::String(value) => !value.is_empty(),
186 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
187 }
188}
189fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
190 match value {
191 None | Some(Value::Null) => Ok(None),
192 Some(Value::String(value)) => Ok(Some(value.clone())),
193 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
194 .map(Some)
195 .map_err(|error| error.to_string()),
196 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
197 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Linear profile field".into()),
198 }
199}
200fn subject(profile: &Value) -> Result<String, String> {
201 let id = scalar(profile.get("id"))?.ok_or("Missing Linear id")?;
202 if id
203 .trim_matches(|character: char| {
204 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
205 })
206 .is_empty()
207 || id == "null"
208 || id == "undefined"
209 {
210 return Err("Invalid Linear id".into());
211 }
212 Ok(id)
213}
214
215const USER_INFO_QUERY: &str = r#"
217 query {
218 viewer {
219 id
220 name
221 email
222 avatarUrl
223 active
224 createdAt
225 updatedAt
226 }
227 }
228 "#;