Skip to main content

alibi_api/plugins/oauth/providers/
cloudflare.rs

1//! Cloudflare's API profile, scope ordering and OAuth credential transport.
2use super::{OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo};
3use serde_json::Value;
4
5/// Cloudflare configuration. Generic callback/signup policies remain available
6/// on the returned provider.
7#[derive(Clone)]
8pub struct CloudflareOptions {
9    pub client_id: String,
10    pub client_secret: Option<String>,
11    pub scope: Vec<String>,
12    pub disable_default_scope: bool,
13    pub authorization_endpoint: Option<String>,
14    pub redirect_uri: Option<String>,
15    pub token_endpoint_auth_method: Option<OAuthTokenEndpointAuth>,
16    /// Trusted transport override, retaining Cloudflare's API envelope mapping.
17    pub user_info_endpoint: Option<String>,
18    /// Receives the original API result. Its ID cannot replace the raw subject.
19    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
20}
21impl CloudflareOptions {
22    #[must_use]
23    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
24        Self {
25            client_id: client_id.into(),
26            client_secret,
27            scope: Vec::new(),
28            disable_default_scope: false,
29            authorization_endpoint: None,
30            redirect_uri: None,
31            token_endpoint_auth_method: None,
32            user_info_endpoint: None,
33            map_profile_to_user: None,
34        }
35    }
36}
37impl std::fmt::Debug for CloudflareOptions {
38    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        formatter
40            .debug_struct("CloudflareOptions")
41            .field("client_id", &self.client_id)
42            .field("scope", &self.scope)
43            .field("disable_default_scope", &self.disable_default_scope)
44            .field(
45                "token_endpoint_auth_method",
46                &self.token_endpoint_auth_method,
47            )
48            .finish_non_exhaustive()
49    }
50}
51impl OAuthProvider {
52    #[must_use]
53    pub fn cloudflare(client_id: &str, client_secret: Option<&str>) -> Self {
54        Self::cloudflare_with_options(CloudflareOptions::new(
55            client_id,
56            client_secret.map(str::to_owned),
57        ))
58    }
59    #[must_use]
60    pub fn cloudflare_with_options(options: CloudflareOptions) -> Self {
61        let client_secret = options.client_secret.unwrap_or_default();
62        let authentication = options.token_endpoint_auth_method.unwrap_or({
63            if client_secret.is_empty() {
64                OAuthTokenEndpointAuth::None
65            } else {
66                OAuthTokenEndpointAuth::ClientSecretBasic
67            }
68        });
69        let user_info_url = options
70            .user_info_endpoint
71            .unwrap_or_else(|| "https://api.cloudflare.com/client/v4/user".into());
72        Self {
73            client_id: options.client_id,
74            client_secret,
75            additional_client_ids: Vec::new(),
76            hosted_domain: None,
77            require_email_verification: false,
78            auth_url: options
79                .authorization_endpoint
80                .filter(|value| !value.is_empty())
81                .unwrap_or_else(|| "https://dash.cloudflare.com/oauth2/auth".into()),
82            token_url: "https://dash.cloudflare.com/oauth2/token".into(),
83            user_info_url: Some(user_info_url.clone()),
84            scopes: vec!["user-details.read".into()],
85            authorization: Some(OAuthAuthorizationPolicy {
86                configured_scopes: options.scope,
87                disable_default_scopes: options.disable_default_scope,
88                deduplicate_scopes: true,
89                require_client_id: true,
90                token_endpoint_auth: Some(authentication),
91                redirect_uri: options.redirect_uri,
92                login_hint: false,
93                ..OAuthAuthorizationPolicy::default()
94            }),
95            authorization_params: Vec::new(),
96            account_subject: None,
97            map_user_info: None,
98            get_user_info: Some(std::sync::Arc::new(CloudflareUserInfo {
99                url: user_info_url,
100                mapper: options.map_profile_to_user,
101            })),
102            refresh_access_token: None,
103            verify_id_token: None,
104            id_token: None,
105            disable_id_token_sign_in: false,
106            disable_implicit_sign_up: false,
107            disable_sign_up: false,
108            override_user_info_on_sign_in: false,
109        }
110    }
111}
112fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
113    match value {
114        Some(Value::String(value)) => Ok(Some(value.clone())),
115        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
116            .map(Some)
117            .map_err(|error| error.to_string()),
118        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
119        None | Some(Value::Null) => Ok(None),
120        _ => Err("Invalid Cloudflare profile field".into()),
121    }
122}
123fn truthy(value: &Value) -> bool {
124    match value {
125        Value::Null | Value::Bool(false) => false,
126        Value::Number(value) => value.as_f64() != Some(0.0),
127        Value::String(value) => !value.is_empty(),
128        _ => true,
129    }
130}
131fn subject(profile: &Value) -> Result<String, String> {
132    let id = scalar(profile.get("id"))?.ok_or("Missing Cloudflare ID")?;
133    if id
134        .trim_matches(|character: char| {
135            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
136        })
137        .is_empty()
138        || id == "null"
139        || id == "undefined"
140    {
141        return Err("Invalid Cloudflare ID".into());
142    }
143    Ok(id)
144}
145struct CloudflareUserInfo {
146    url: String,
147    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
148}
149#[async_trait::async_trait]
150impl super::OAuthUserInfoHandler for CloudflareUserInfo {
151    async fn get_user_info(
152        &self,
153        request: super::OAuthUserInfoRequest,
154    ) -> Result<super::OAuthUserInfoResponse, String> {
155        let access_token = request
156            .access_token
157            .ok_or("Missing Cloudflare access token")?;
158        let response = reqwest::Client::new()
159            .get(&self.url)
160            .bearer_auth(access_token)
161            .send()
162            .await
163            .map_err(|error| error.to_string())?
164            .error_for_status()
165            .map_err(|error| error.to_string())?;
166        let envelope: Value = response.json().await.map_err(|error| error.to_string())?;
167        if !envelope.get("success").is_some_and(truthy)
168            || !envelope.get("result").is_some_and(truthy)
169        {
170            return Err("Cloudflare API rejected user info".into());
171        }
172        let profile = envelope
173            .get("result")
174            .ok_or("Missing Cloudflare API result")?;
175        let email = profile
176            .get("email")
177            .and_then(Value::as_str)
178            .unwrap_or_default()
179            .to_owned();
180        let names = ["first_name", "last_name"]
181            .into_iter()
182            .filter_map(|key| profile.get(key))
183            .filter(|value| truthy(value))
184            .map(|value| scalar(Some(value)).map(Option::unwrap_or_default))
185            .collect::<Result<Vec<_>, _>>()?;
186        let name = names.join(" ");
187        let mapped = self
188            .mapper
189            .map(|mapper| mapper(profile.clone()))
190            .transpose()?;
191        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
192        let id = subject(profile)?;
193        let mut user = mapped.unwrap_or_else(|| OAuthUserInfo {
194            additional_fields: Default::default(),
195            id: id.clone(),
196            email: email.clone(),
197            name: Some(if name.is_empty() { email } else { name }),
198            image: None,
199            email_verified: false,
200        });
201        user.id = id;
202        Ok(super::OAuthUserInfoResponse {
203            user_output,
204            user,
205            data: profile.clone(),
206        })
207    }
208}