Skip to main content

alibi_plugins/oauth/providers/
line.rs

1//! LINE scopes, delegated direct proof and decoded/fallback profile identity.
2use 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/// Application-owned Line configuration. Generic signup and asynchronous
12/// user-info/refresh callbacks remain configurable on the returned provider.
13#[derive(Clone)]
14pub struct LineOptions {
15    pub client_id: String,
16    pub client_secret: Option<String>,
17    /// Sent only during authorization-code exchange.
18    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    /// Trusted transport override retaining LINE's actual GET and mapping.
24    pub user_info_endpoint: Option<String>,
25    /// Trusted transport override retaining LINE's actual delegated POST proof.
26    pub verification_endpoint: Option<String>,
27    /// Receives the original profile before its raw account identity is resolved.
28    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            allowed_request_params: Vec::new(),
108            authorization_params: Vec::new(),
109            account_subject: Some(subject),
110            map_user_info: None,
111            get_user_info: Some(std::sync::Arc::new(LineUserInfo {
112                endpoint,
113                mapper: options.map_profile_to_user,
114            })),
115            refresh_access_token: None,
116            verify_id_token: Some(std::sync::Arc::new(verifier)),
117            id_token: None,
118            disable_id_token_sign_in: false,
119            disable_implicit_sign_up: false,
120            disable_sign_up: false,
121            allow_idp_initiated: false,
122            override_user_info_on_sign_in: false,
123        }
124    }
125}
126struct LineUserInfo {
127    endpoint: String,
128    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
129}
130#[async_trait]
131impl OAuthUserInfoHandler for LineUserInfo {
132    async fn get_user_info(
133        &self,
134        request: OAuthUserInfoRequest,
135    ) -> Result<OAuthUserInfoResponse, String> {
136        let decoded = request.id_token.as_deref().and_then(decode_profile);
137        let profile = if let Some(profile) = decoded {
138            profile
139        } else {
140            // The pinned factory tries userinfo even when the caller has no
141            // access token. The remote endpoint owns that credential decision.
142            reqwest::Client::new()
143                .get(&self.endpoint)
144                .header(
145                    reqwest::header::AUTHORIZATION,
146                    format!(
147                        "Bearer {}",
148                        request.access_token.as_deref().unwrap_or("undefined")
149                    ),
150                )
151                .send()
152                .await
153                .map_err(|error| error.to_string())?
154                .error_for_status()
155                .map_err(|error| error.to_string())?
156                .json::<Value>()
157                .await
158                .map_err(|error| error.to_string())?
159        };
160        let mapped = self
161            .mapper
162            .map(|mapper| mapper(profile.clone()))
163            .transpose()?;
164        // The published profile preserves JSON types and explicit nulls; its
165        // typed persistence values remain separate from this public output.
166        let user_output = Some(mapped.as_ref().map_or_else(
167            || {
168                let mut output = serde_json::Map::new();
169                _ = output.insert(
170                    "name".into(),
171                    profile
172                        .get("name")
173                        .filter(|value| truthy(value))
174                        .cloned()
175                        .unwrap_or_else(|| Value::String(String::new())),
176                );
177                for (source, target) in [("email", "email"), ("picture", "image")] {
178                    if let Some(value) = profile.get(source) {
179                        _ = output.insert(target.into(), value.clone());
180                    }
181                }
182                _ = output.insert("emailVerified".into(), Value::Bool(false));
183                output
184            },
185            |user| user.public_profile(true),
186        ));
187        let user = match mapped {
188            Some(user) => user,
189            None => OAuthUserInfo {
190                additional_fields: Map::default(),
191                id: scalar(profile.get("sub"))?.unwrap_or_default(),
192                name: Some(
193                    scalar(profile.get("name").filter(|value| truthy(value)))?.unwrap_or_default(),
194                ),
195                email: profile
196                    .get("email")
197                    .and_then(Value::as_str)
198                    .unwrap_or_default()
199                    .into(),
200                image: scalar(profile.get("picture"))?,
201                email_verified: false,
202            },
203        };
204        Ok(OAuthUserInfoResponse {
205            user_output,
206            user,
207            data: profile,
208        })
209    }
210}
211fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
212    match value {
213        None | Some(Value::Null) => Ok(None),
214        Some(Value::String(value)) => Ok(Some(value.clone())),
215        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
216            .map(Some)
217            .map_err(|error| error.to_string()),
218        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
219        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid LINE profile field".into()),
220    }
221}
222fn subject(profile: &Value) -> Result<String, String> {
223    let id = scalar(profile.get("sub"))?.ok_or("Missing LINE sub")?;
224    if id
225        .trim_matches(|character: char| {
226            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
227        })
228        .is_empty()
229        || id == "null"
230        || id == "undefined"
231    {
232        return Err("Invalid LINE sub".into());
233    }
234    Ok(id)
235}
236
237fn truthy(value: &Value) -> bool {
238    match value {
239        Value::Null => false,
240        Value::Bool(value) => *value,
241        Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
242        Value::String(value) => !value.is_empty(),
243        Value::Array(_) | Value::Object(_) => true,
244    }
245}
246
247struct LineVerifier {
248    client_id: String,
249    endpoint: String,
250}
251#[async_trait]
252impl OAuthIdTokenVerifier for LineVerifier {
253    async fn verify_id_token(&self, token: &str, nonce: Option<&str>) -> Result<bool, String> {
254        let mut body = vec![("id_token", token), ("client_id", self.client_id.as_str())];
255        if let Some(nonce) = nonce.filter(|value| !value.is_empty()) {
256            body.push(("nonce", nonce));
257        }
258        let response: Value = reqwest::Client::new()
259            .post(&self.endpoint)
260            .form(&body)
261            .send()
262            .await
263            .map_err(|error| error.to_string())?
264            .error_for_status()
265            .map_err(|error| error.to_string())?
266            .json()
267            .await
268            .map_err(|error| error.to_string())?;
269        if response.get("aud").and_then(Value::as_str) != Some(self.client_id.as_str()) {
270            return Ok(false);
271        }
272        if response
273            .get("nonce")
274            .filter(|value| truthy(value))
275            .is_some_and(|returned_nonce| {
276                returned_nonce
277                    .as_str()
278                    .is_none_or(|returned_nonce| Some(returned_nonce) != nonce)
279            })
280        {
281            return Ok(false);
282        }
283        Ok(true)
284    }
285}
286fn decode_profile(token: &str) -> Option<Value> {
287    let mut parts = token.split('.');
288    _ = parts.next()?;
289    let payload = parts.next()?;
290    _ = parts.next()?;
291    if payload.is_empty() || parts.next().is_some() {
292        return None;
293    }
294    let encoded = payload.replace('-', "+").replace('_', "/");
295    let decoder = base64::engine::GeneralPurpose::new(
296        &base64::alphabet::STANDARD,
297        base64::engine::GeneralPurposeConfig::new()
298            .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
299    );
300    let bytes = decoder.decode(encoded).ok()?;
301    let profile: Value = alibi_core::utils::json::from_slice(&bytes).ok()?;
302    profile.is_object().then_some(profile)
303}