alibi_api/plugins/oauth/providers/
line.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthIdTokenVerifier, OAuthProvider, OAuthTokenEndpointAuth,
4 OAuthUserInfo, OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use base64::Engine;
8use serde_json::Value;
9
10#[derive(Clone)]
13pub struct LineOptions {
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 verification_endpoint: Option<String>,
26 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
28}
29impl LineOptions {
30 #[must_use]
31 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
32 Self {
33 client_id: client_id.into(),
34 client_secret,
35 client_key: None,
36 scope: Vec::new(),
37 disable_default_scope: false,
38 authorization_endpoint: None,
39 redirect_uri: None,
40 user_info_endpoint: None,
41 verification_endpoint: None,
42 map_profile_to_user: None,
43 }
44 }
45}
46impl std::fmt::Debug for LineOptions {
47 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 formatter
49 .debug_struct("LineOptions")
50 .field("client_id", &self.client_id)
51 .field("scope", &self.scope)
52 .field("disable_default_scope", &self.disable_default_scope)
53 .field("authorization_endpoint", &self.authorization_endpoint)
54 .field("redirect_uri", &self.redirect_uri)
55 .finish_non_exhaustive()
56 }
57}
58impl OAuthProvider {
59 #[must_use]
60 pub fn line(client_id: &str, client_secret: Option<&str>) -> Self {
61 Self::line_with_options(LineOptions::new(
62 client_id,
63 client_secret.map(str::to_owned),
64 ))
65 }
66 #[must_use]
67 pub fn line_with_options(options: LineOptions) -> Self {
68 let secret = options.client_secret.unwrap_or_default();
69 let authentication = if secret.is_empty() {
70 OAuthTokenEndpointAuth::None
71 } else {
72 OAuthTokenEndpointAuth::ClientSecretPost
73 };
74 let endpoint = options
75 .user_info_endpoint
76 .unwrap_or_else(|| "https://api.line.me/oauth2/v2.1/userinfo".into());
77 let verifier = LineVerifier {
78 client_id: options.client_id.clone(),
79 endpoint: options
80 .verification_endpoint
81 .unwrap_or_else(|| "https://api.line.me/oauth2/v2.1/verify".into()),
82 };
83 Self {
84 client_id: options.client_id,
85 client_secret: secret,
86 additional_client_ids: Vec::new(),
87 hosted_domain: None,
88 require_email_verification: false,
89 auth_url: options
90 .authorization_endpoint
91 .filter(|value| !value.is_empty())
92 .unwrap_or_else(|| "https://access.line.me/oauth2/v2.1/authorize".into()),
93 token_url: "https://api.line.me/oauth2/v2.1/token".into(),
94 user_info_url: Some(endpoint.clone()),
95 scopes: vec!["openid".into(), "profile".into(), "email".into()],
96 authorization: Some(OAuthAuthorizationPolicy {
97 configured_scopes: options.scope,
98 disable_default_scopes: options.disable_default_scope,
99 require_client_id: true,
100 token_endpoint_auth: Some(authentication),
101 authorization_code_client_key: options.client_key,
102 redirect_uri: options.redirect_uri,
103 login_hint: true,
104 ..OAuthAuthorizationPolicy::default()
105 }),
106 authorization_params: Vec::new(),
107 account_subject: Some(subject),
108 map_user_info: None,
109 get_user_info: Some(std::sync::Arc::new(LineUserInfo {
110 endpoint,
111 mapper: options.map_profile_to_user,
112 })),
113 refresh_access_token: None,
114 verify_id_token: Some(std::sync::Arc::new(verifier)),
115 id_token: None,
116 disable_id_token_sign_in: false,
117 disable_implicit_sign_up: false,
118 disable_sign_up: false,
119 override_user_info_on_sign_in: false,
120 }
121 }
122}
123struct LineUserInfo {
124 endpoint: String,
125 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
126}
127#[async_trait]
128impl OAuthUserInfoHandler for LineUserInfo {
129 async fn get_user_info(
130 &self,
131 request: OAuthUserInfoRequest,
132 ) -> Result<OAuthUserInfoResponse, String> {
133 let decoded = request.id_token.as_deref().and_then(decode_profile);
134 let profile = if let Some(profile) = decoded {
135 profile
136 } else {
137 reqwest::Client::new()
140 .get(&self.endpoint)
141 .header(
142 reqwest::header::AUTHORIZATION,
143 format!(
144 "Bearer {}",
145 request.access_token.as_deref().unwrap_or("undefined")
146 ),
147 )
148 .send()
149 .await
150 .map_err(|error| error.to_string())?
151 .error_for_status()
152 .map_err(|error| error.to_string())?
153 .json::<Value>()
154 .await
155 .map_err(|error| error.to_string())?
156 };
157 let mapped = self
158 .mapper
159 .map(|mapper| mapper(profile.clone()))
160 .transpose()?;
161 let user_output = Some(mapped.as_ref().map_or_else(
164 || {
165 let mut output = serde_json::Map::new();
166 drop(
167 output.insert(
168 "name".into(),
169 profile
170 .get("name")
171 .filter(|value| truthy(value))
172 .cloned()
173 .unwrap_or_else(|| Value::String(String::new())),
174 ),
175 );
176 for (source, target) in [("email", "email"), ("picture", "image")] {
177 if let Some(value) = profile.get(source) {
178 drop(output.insert(target.into(), value.clone()));
179 }
180 }
181 drop(output.insert("emailVerified".into(), Value::Bool(false)));
182 output
183 },
184 |user| user.public_profile(true),
185 ));
186 let user = match mapped {
187 Some(user) => user,
188 None => OAuthUserInfo {
189 additional_fields: Default::default(),
190 id: scalar(profile.get("sub"))?.unwrap_or_default(),
191 name: Some(
192 scalar(profile.get("name").filter(|value| truthy(value)))?.unwrap_or_default(),
193 ),
194 email: profile
195 .get("email")
196 .and_then(Value::as_str)
197 .unwrap_or_default()
198 .into(),
199 image: scalar(profile.get("picture"))?,
200 email_verified: false,
201 },
202 };
203 Ok(OAuthUserInfoResponse {
204 user_output,
205 user,
206 data: profile,
207 })
208 }
209}
210fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
211 match value {
212 None | Some(Value::Null) => Ok(None),
213 Some(Value::String(value)) => Ok(Some(value.clone())),
214 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
215 .map(Some)
216 .map_err(|error| error.to_string()),
217 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
218 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid LINE profile field".into()),
219 }
220}
221fn subject(profile: &Value) -> Result<String, String> {
222 let id = scalar(profile.get("sub"))?.ok_or("Missing LINE sub")?;
223 if id
224 .trim_matches(|character: char| {
225 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
226 })
227 .is_empty()
228 || id == "null"
229 || id == "undefined"
230 {
231 return Err("Invalid LINE sub".into());
232 }
233 Ok(id)
234}
235
236fn truthy(value: &Value) -> bool {
237 match value {
238 Value::Null => false,
239 Value::Bool(value) => *value,
240 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
241 Value::String(value) => !value.is_empty(),
242 Value::Array(_) | Value::Object(_) => true,
243 }
244}
245
246struct LineVerifier {
247 client_id: String,
248 endpoint: String,
249}
250#[async_trait]
251impl OAuthIdTokenVerifier for LineVerifier {
252 async fn verify_id_token(&self, token: &str, nonce: Option<&str>) -> Result<bool, String> {
253 let mut body = vec![("id_token", token), ("client_id", self.client_id.as_str())];
254 if let Some(nonce) = nonce.filter(|value| !value.is_empty()) {
255 body.push(("nonce", nonce));
256 }
257 let response: Value = reqwest::Client::new()
258 .post(&self.endpoint)
259 .form(&body)
260 .send()
261 .await
262 .map_err(|error| error.to_string())?
263 .error_for_status()
264 .map_err(|error| error.to_string())?
265 .json()
266 .await
267 .map_err(|error| error.to_string())?;
268 if response.get("aud").and_then(Value::as_str) != Some(self.client_id.as_str()) {
269 return Ok(false);
270 }
271 if response
272 .get("nonce")
273 .filter(|value| truthy(value))
274 .is_some_and(|returned_nonce| {
275 returned_nonce
276 .as_str()
277 .is_none_or(|returned_nonce| Some(returned_nonce) != nonce)
278 })
279 {
280 return Ok(false);
281 }
282 Ok(true)
283 }
284}
285fn decode_profile(token: &str) -> Option<Value> {
286 let mut parts = token.split('.');
287 let _header = parts.next()?;
288 let payload = parts.next()?;
289 let _signature = parts.next()?;
290 if payload.is_empty() || parts.next().is_some() {
291 return None;
292 }
293 let encoded = payload.replace('-', "+").replace('_', "/");
294 let decoder = base64::engine::GeneralPurpose::new(
295 &base64::alphabet::STANDARD,
296 base64::engine::GeneralPurposeConfig::new()
297 .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
298 );
299 let bytes = decoder.decode(encoded).ok()?;
300 let profile: Value = alibi_core::utils::json::from_slice(&bytes).ok()?;
301 profile.is_object().then_some(profile)
302}