alibi_plugins/oauth/providers/
linear.rs1use 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#[derive(Clone)]
13pub struct LinearOptions {
14 pub client_id: String,
15 pub client_secret: Option<String>,
16 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 pub user_info_endpoint: Option<String>,
24 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 authorization_params: Vec::new(),
99 account_subject: Some(subject),
100 map_user_info: None,
101 get_user_info: Some(std::sync::Arc::new(LinearUserInfo {
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 LinearUserInfo {
117 endpoint: String,
118 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
119}
120#[async_trait]
121impl OAuthUserInfoHandler for LinearUserInfo {
122 async fn get_user_info(
123 &self,
124 request: OAuthUserInfoRequest,
125 ) -> Result<OAuthUserInfoResponse, String> {
126 let access_token = request.access_token.ok_or("Missing Linear access token")?;
127 let response: Value = reqwest::Client::new()
128 .post(&self.endpoint)
129 .json(&serde_json::json!({"query": USER_INFO_QUERY}))
130 .bearer_auth(access_token)
131 .send()
132 .await
133 .map_err(|error| error.to_string())?
134 .error_for_status()
135 .map_err(|error| error.to_string())?
136 .json()
137 .await
138 .map_err(|error| error.to_string())?;
139 let profile = response
140 .get("data")
141 .and_then(|data| data.get("viewer"))
142 .filter(|viewer| truthy(viewer))
143 .cloned()
144 .ok_or("Missing Linear profile")?;
145 let mapped = self
146 .mapper
147 .map(|mapper| mapper(profile.clone()))
148 .transpose()?;
149 let mut output = serde_json::Map::new();
151 for (source, target) in [("name", "name"), ("email", "email"), ("avatarUrl", "image")] {
152 if let Some(value) = profile.get(source) {
153 _ = output.insert(target.into(), value.clone());
154 }
155 }
156 _ = output.insert("emailVerified".into(), Value::Bool(false));
157 if let Some(user) = &mapped {
158 output.extend(user.public_profile(true));
159 }
160 let user_output = Some(output);
161 let user = match mapped {
162 Some(user) => user,
163 None => OAuthUserInfo {
164 additional_fields: Map::default(),
165 id: scalar(profile.get("id"))?.unwrap_or_default(),
166 name: scalar(profile.get("name"))?,
167 email: profile
168 .get("email")
169 .and_then(Value::as_str)
170 .unwrap_or_default()
171 .into(),
172 image: scalar(profile.get("avatarUrl"))?,
173 email_verified: false,
174 },
175 };
176 Ok(OAuthUserInfoResponse {
177 user_output,
178 user,
179 data: profile,
180 })
181 }
182}
183fn truthy(value: &Value) -> bool {
184 match value {
185 Value::Null | Value::Bool(false) => false,
186 Value::Number(value) => value.as_f64() != Some(0.0),
187 Value::String(value) => !value.is_empty(),
188 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
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 Linear profile field".into()),
200 }
201}
202fn subject(profile: &Value) -> Result<String, String> {
203 let id = scalar(profile.get("id"))?.ok_or("Missing Linear id")?;
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 Linear id".into());
213 }
214 Ok(id)
215}
216
217const USER_INFO_QUERY: &str = r"
219 query {
220 viewer {
221 id
222 name
223 email
224 avatarUrl
225 active
226 createdAt
227 updatedAt
228 }
229 }
230 ";