alibi_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::Map;
9use serde_json::Value;
10
11#[derive(Clone)]
14pub struct LineOptions {
15 pub client_id: String,
16 pub client_secret: Option<String>,
17 pub client_key: Option<String>,
19 pub scope: Vec<String>,
20 pub disable_default_scope: bool,
21 pub authorization_endpoint: Option<String>,
22 pub redirect_uri: Option<String>,
23 pub user_info_endpoint: Option<String>,
25 pub verification_endpoint: Option<String>,
27 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
29}
30impl LineOptions {
31 #[must_use]
32 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
33 Self {
34 client_id: client_id.into(),
35 client_secret,
36 client_key: None,
37 scope: Vec::new(),
38 disable_default_scope: false,
39 authorization_endpoint: None,
40 redirect_uri: None,
41 user_info_endpoint: None,
42 verification_endpoint: None,
43 map_profile_to_user: None,
44 }
45 }
46}
47impl std::fmt::Debug for LineOptions {
48 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 formatter
50 .debug_struct("LineOptions")
51 .field("client_id", &self.client_id)
52 .field("scope", &self.scope)
53 .field("disable_default_scope", &self.disable_default_scope)
54 .field("authorization_endpoint", &self.authorization_endpoint)
55 .field("redirect_uri", &self.redirect_uri)
56 .finish_non_exhaustive()
57 }
58}
59impl OAuthProvider {
60 #[must_use]
61 pub fn line(client_id: &str, client_secret: Option<&str>) -> Self {
62 Self::line_with_options(LineOptions::new(
63 client_id,
64 client_secret.map(str::to_owned),
65 ))
66 }
67 #[must_use]
68 pub fn line_with_options(options: LineOptions) -> Self {
69 let secret = options.client_secret.unwrap_or_default();
70 let authentication = if secret.is_empty() {
71 OAuthTokenEndpointAuth::None
72 } else {
73 OAuthTokenEndpointAuth::ClientSecretPost
74 };
75 let endpoint = options
76 .user_info_endpoint
77 .unwrap_or_else(|| "https://api.line.me/oauth2/v2.1/userinfo".into());
78 let verifier = LineVerifier {
79 client_id: options.client_id.clone(),
80 endpoint: options
81 .verification_endpoint
82 .unwrap_or_else(|| "https://api.line.me/oauth2/v2.1/verify".into()),
83 };
84 Self {
85 client_id: options.client_id,
86 client_secret: secret,
87 additional_client_ids: Vec::new(),
88 hosted_domain: None,
89 require_email_verification: false,
90 auth_url: options
91 .authorization_endpoint
92 .filter(|value| !value.is_empty())
93 .unwrap_or_else(|| "https://access.line.me/oauth2/v2.1/authorize".into()),
94 token_url: "https://api.line.me/oauth2/v2.1/token".into(),
95 user_info_url: Some(endpoint.clone()),
96 scopes: vec!["openid".into(), "profile".into(), "email".into()],
97 authorization: Some(OAuthAuthorizationPolicy {
98 configured_scopes: options.scope,
99 disable_default_scopes: options.disable_default_scope,
100 require_client_id: true,
101 token_endpoint_auth: Some(authentication),
102 authorization_code_client_key: options.client_key,
103 redirect_uri: options.redirect_uri,
104 login_hint: true,
105 ..OAuthAuthorizationPolicy::default()
106 }),
107 authorization_params: Vec::new(),
108 account_subject: Some(subject),
109 map_user_info: None,
110 get_user_info: Some(std::sync::Arc::new(LineUserInfo {
111 endpoint,
112 mapper: options.map_profile_to_user,
113 })),
114 refresh_access_token: None,
115 verify_id_token: Some(std::sync::Arc::new(verifier)),
116 id_token: None,
117 disable_id_token_sign_in: false,
118 disable_implicit_sign_up: false,
119 disable_sign_up: false,
120 allow_idp_initiated: false,
121 override_user_info_on_sign_in: false,
122 }
123 }
124}
125struct LineUserInfo {
126 endpoint: String,
127 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
128}
129#[async_trait]
130impl OAuthUserInfoHandler for LineUserInfo {
131 async fn get_user_info(
132 &self,
133 request: OAuthUserInfoRequest,
134 ) -> Result<OAuthUserInfoResponse, String> {
135 let decoded = request.id_token.as_deref().and_then(decode_profile);
136 let profile = if let Some(profile) = decoded {
137 profile
138 } else {
139 reqwest::Client::new()
142 .get(&self.endpoint)
143 .header(
144 reqwest::header::AUTHORIZATION,
145 format!(
146 "Bearer {}",
147 request.access_token.as_deref().unwrap_or("undefined")
148 ),
149 )
150 .send()
151 .await
152 .map_err(|error| error.to_string())?
153 .error_for_status()
154 .map_err(|error| error.to_string())?
155 .json::<Value>()
156 .await
157 .map_err(|error| error.to_string())?
158 };
159 let mapped = self
160 .mapper
161 .map(|mapper| mapper(profile.clone()))
162 .transpose()?;
163 let user_output = Some(mapped.as_ref().map_or_else(
166 || {
167 let mut output = serde_json::Map::new();
168 _ = output.insert(
169 "name".into(),
170 profile
171 .get("name")
172 .filter(|value| truthy(value))
173 .cloned()
174 .unwrap_or_else(|| Value::String(String::new())),
175 );
176 for (source, target) in [("email", "email"), ("picture", "image")] {
177 if let Some(value) = profile.get(source) {
178 _ = output.insert(target.into(), value.clone());
179 }
180 }
181 _ = 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: Map::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 _ = parts.next()?;
288 let payload = parts.next()?;
289 _ = 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}