Skip to main content

alibi_plugins/oauth/providers/
notion.rs

1//! Notion's bot owner identity, versioned lookup and grant-specific credentials.
2use 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/// Application-owned Notion configuration. Generic signup and asynchronous
11/// user-info/refresh callbacks remain configurable on the returned provider.
12#[derive(Clone)]
13pub struct NotionOptions {
14    pub client_id: String,
15    pub client_secret: Option<String>,
16    /// Sent only during authorization-code exchange.
17    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    /// Trusted transport override retaining Notion's versioned GET and mapping.
23    pub user_info_endpoint: Option<String>,
24    /// Receives the original profile before its raw account identity is resolved.
25    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
26}
27impl NotionOptions {
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 NotionOptions {
44    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        formatter
46            .debug_struct("NotionOptions")
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 notion(client_id: &str, client_secret: Option<&str>) -> Self {
58        Self::notion_with_options(NotionOptions::new(
59            client_id,
60            client_secret.map(str::to_owned),
61        ))
62    }
63    #[must_use]
64    pub fn notion_with_options(options: NotionOptions) -> Self {
65        let secret = options.client_secret.unwrap_or_default();
66        let refresh_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.notion.com/v1/users/me".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://api.notion.com/v1/oauth/authorize".into()),
84            token_url: "https://api.notion.com/v1/oauth/token".into(),
85            user_info_url: Some(endpoint.clone()),
86            scopes: Vec::new(),
87            authorization: Some(OAuthAuthorizationPolicy {
88                preserve_raw_profile_scalars: true,
89                source_profile_exceptions: true,
90                allow_missing_access_token: true,
91                preserve_raw_email_errors: true,
92                configured_scopes: options.scope,
93                disable_default_scopes: options.disable_default_scope,
94                require_client_id: true,
95                token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
96                refresh_token_endpoint_auth: Some(refresh_authentication),
97                fixed_authorization_params: vec![("owner".into(), "user".into())],
98                authorization_code_client_key: options.client_key,
99                redirect_uri: options.redirect_uri,
100                login_hint: true,
101                pkce: false,
102                ..OAuthAuthorizationPolicy::default()
103            }),
104            allowed_request_params: Vec::new(),
105            authorization_params: Vec::new(),
106            account_subject: Some(subject),
107            map_user_info: None,
108            get_user_info: Some(std::sync::Arc::new(NotionUserInfo {
109                application_mapper: None,
110                endpoint,
111                mapper: options.map_profile_to_user,
112            })),
113            refresh_access_token: None,
114            verify_id_token: None,
115            id_token: None,
116            disable_id_token_sign_in: false,
117            disable_implicit_sign_up: false,
118            disable_sign_up: false,
119            allow_idp_initiated: false,
120            override_user_info_on_sign_in: false,
121        }
122    }
123}
124#[derive(Clone)]
125struct NotionUserInfo {
126    application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
127    endpoint: String,
128    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
129}
130#[async_trait]
131impl OAuthUserInfoHandler for NotionUserInfo {
132    fn errors_are_exceptions(&self) -> bool {
133        false
134    }
135
136    fn mapped_handler(
137        &self,
138        mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
139    ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
140        let mut handler = self.clone();
141        handler.mapper = None;
142        handler.application_mapper = Some(mapper);
143        Some(std::sync::Arc::new(handler))
144    }
145
146    async fn get_user_info(
147        &self,
148        request: OAuthUserInfoRequest,
149    ) -> Result<OAuthUserInfoResponse, String> {
150        let access_token = super::remaining_profile::bearer_access_token(&request)?;
151        let response: Value = reqwest::Client::new()
152            .get(&self.endpoint)
153            .header("Notion-Version", "2022-06-28")
154            .bearer_auth(access_token)
155            .send()
156            .await
157            .map_err(|error| error.to_string())?
158            .error_for_status()
159            .map_err(|error| error.to_string())?
160            .json()
161            .await
162            .map_err(|error| error.to_string())?;
163        let profile = response
164            .get("bot")
165            .and_then(|bot| bot.get("owner"))
166            .and_then(|owner| owner.get("user"))
167            .filter(|user| truthy(user))
168            .cloned()
169            .ok_or("Missing Notion profile")?;
170        let application_output = if let Some(mapper) = &self.application_mapper {
171            Some(
172                mapper
173                    .map_profile(profile.clone())
174                    .await
175                    .map_err(super::remaining_profile::profile_exception)?,
176            )
177        } else {
178            None
179        };
180        let mapped = self
181            .mapper
182            .map(|mapper| mapper(profile.clone()))
183            .transpose()
184            .map_err(super::remaining_profile::profile_exception)?;
185        // Keep the published raw JSON independently from typed persistence.
186        let mut output = serde_json::Map::new();
187        _ = output.insert(
188            "name".into(),
189            profile
190                .get("name")
191                .filter(|v| truthy(v))
192                .cloned()
193                .unwrap_or_else(|| Value::String(String::new())),
194        );
195        let email = profile
196            .get("person")
197            .and_then(|person| person.get("email"))
198            .filter(|v| truthy(v));
199        _ = output.insert("email".into(), email.cloned().unwrap_or(Value::Null));
200        if let Some(image) = profile.get("avatar_url") {
201            _ = output.insert("image".into(), image.clone());
202        }
203        _ = output.insert("emailVerified".into(), Value::Bool(false));
204        if let Some(user) = &mapped {
205            output.extend(user.public_profile(true));
206        }
207        let user_output = Some(output);
208        let user = match mapped {
209            Some(user) => user,
210            None => OAuthUserInfo {
211                additional_fields: Map::default(),
212                id: profile
213                    .get("id")
214                    .map(super::remaining_profile::js_string)
215                    .transpose()?
216                    .unwrap_or_default(),
217                name: scalar(profile.get("name").filter(|v| truthy(v)))?
218                    .or_else(|| Some(String::new())),
219                email: email.and_then(Value::as_str).unwrap_or_default().into(),
220                image: scalar(profile.get("avatar_url"))?,
221                email_verified: false,
222            },
223        };
224        let mut response = OAuthUserInfoResponse {
225            user_output,
226            user,
227            data: profile,
228        };
229        if let Some(mapped) = application_output {
230            super::apply_application_mapping(&mut response, mapped)?;
231        }
232        Ok(response)
233    }
234}
235fn truthy(value: &Value) -> bool {
236    match value {
237        Value::Null | Value::Bool(false) => false,
238        Value::Number(value) => value.as_f64() != Some(0.0),
239        Value::String(value) => !value.is_empty(),
240        Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
241    }
242}
243fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
244    match value {
245        Some(Value::String(value)) => Ok(Some(value.clone())),
246        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
247            .map(Some)
248            .map_err(|error| error.to_string()),
249        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
250        None | Some(Value::Null | Value::Array(_) | Value::Object(_)) => Ok(None),
251    }
252}
253fn subject(profile: &Value) -> Result<String, String> {
254    super::remaining_profile::raw_subject(profile.get("id"))
255}