Skip to main content

alibi_plugins/oauth/providers/
dropbox.rs

1//! Dropbox's ordered scopes, POST profile lookup and stable raw account identity.
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/// Dropbox's declared token access modes.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum DropboxAccessType {
13    Offline,
14    Online,
15    Legacy,
16}
17impl DropboxAccessType {
18    const fn as_str(self) -> &'static str {
19        match self {
20            Self::Offline => "offline",
21            Self::Online => "online",
22            Self::Legacy => "legacy",
23        }
24    }
25}
26
27/// Application-owned Dropbox configuration. Generic signup and asynchronous
28/// user-info/refresh callbacks remain configurable on the returned provider.
29#[derive(Clone)]
30pub struct DropboxOptions {
31    pub client_id: String,
32    pub client_secret: Option<String>,
33    /// Sent only during authorization-code exchange.
34    pub client_key: Option<String>,
35    pub scope: Vec<String>,
36    pub disable_default_scope: bool,
37    pub access_type: Option<DropboxAccessType>,
38    pub authorization_endpoint: Option<String>,
39    pub redirect_uri: Option<String>,
40    /// Trusted transport override retaining Dropbox's actual POST and mapping.
41    pub user_info_endpoint: Option<String>,
42    /// Receives the original profile before its raw account identity is resolved.
43    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
44}
45impl DropboxOptions {
46    #[must_use]
47    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
48        Self {
49            client_id: client_id.into(),
50            client_secret,
51            client_key: None,
52            scope: Vec::new(),
53            disable_default_scope: false,
54            access_type: None,
55            authorization_endpoint: None,
56            redirect_uri: None,
57            user_info_endpoint: None,
58            map_profile_to_user: None,
59        }
60    }
61}
62impl std::fmt::Debug for DropboxOptions {
63    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        formatter
65            .debug_struct("DropboxOptions")
66            .field("client_id", &self.client_id)
67            .field("scope", &self.scope)
68            .field("disable_default_scope", &self.disable_default_scope)
69            .field("access_type", &self.access_type)
70            .field("authorization_endpoint", &self.authorization_endpoint)
71            .field("redirect_uri", &self.redirect_uri)
72            .finish_non_exhaustive()
73    }
74}
75impl OAuthProvider {
76    #[must_use]
77    pub fn dropbox(client_id: &str, client_secret: Option<&str>) -> Self {
78        Self::dropbox_with_options(DropboxOptions::new(
79            client_id,
80            client_secret.map(str::to_owned),
81        ))
82    }
83    #[must_use]
84    pub fn dropbox_with_options(options: DropboxOptions) -> Self {
85        let secret = options.client_secret.unwrap_or_default();
86        let authentication = if secret.is_empty() {
87            OAuthTokenEndpointAuth::None
88        } else {
89            OAuthTokenEndpointAuth::ClientSecretPost
90        };
91        let endpoint = options
92            .user_info_endpoint
93            .unwrap_or_else(|| "https://api.dropboxapi.com/2/users/get_current_account".into());
94        Self {
95            client_id: options.client_id,
96            client_secret: secret,
97            additional_client_ids: Vec::new(),
98            hosted_domain: None,
99            require_email_verification: false,
100            auth_url: options
101                .authorization_endpoint
102                .filter(|value| !value.is_empty())
103                .unwrap_or_else(|| "https://www.dropbox.com/oauth2/authorize".into()),
104            token_url: "https://api.dropboxapi.com/oauth2/token".into(),
105            user_info_url: Some(endpoint.clone()),
106            scopes: vec!["account_info.read".into()],
107            authorization: Some(OAuthAuthorizationPolicy {
108                configured_scopes: options.scope,
109                disable_default_scopes: options.disable_default_scope,
110                require_client_id: true,
111                token_endpoint_auth: Some(authentication),
112                authorization_code_client_key: options.client_key,
113                redirect_uri: options.redirect_uri,
114                login_hint: false,
115                ..OAuthAuthorizationPolicy::default()
116            }),
117            authorization_params: options
118                .access_type
119                .map(|value| vec![("token_access_type".into(), value.as_str().into())])
120                .unwrap_or_default(),
121            account_subject: Some(subject),
122            map_user_info: None,
123            get_user_info: Some(std::sync::Arc::new(DropboxUserInfo {
124                endpoint,
125                mapper: options.map_profile_to_user,
126            })),
127            refresh_access_token: None,
128            verify_id_token: None,
129            id_token: None,
130            disable_id_token_sign_in: false,
131            disable_implicit_sign_up: false,
132            disable_sign_up: false,
133            allow_idp_initiated: false,
134            override_user_info_on_sign_in: false,
135        }
136    }
137}
138struct DropboxUserInfo {
139    endpoint: String,
140    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
141}
142#[async_trait]
143impl OAuthUserInfoHandler for DropboxUserInfo {
144    async fn get_user_info(
145        &self,
146        request: OAuthUserInfoRequest,
147    ) -> Result<OAuthUserInfoResponse, String> {
148        let access_token = request.access_token.ok_or("Missing Dropbox access token")?;
149        let profile: Value = reqwest::Client::new()
150            .post(&self.endpoint)
151            .bearer_auth(access_token)
152            .send()
153            .await
154            .map_err(|error| error.to_string())?
155            .error_for_status()
156            .map_err(|error| error.to_string())?
157            .json()
158            .await
159            .map_err(|error| error.to_string())?;
160        let mapped = self
161            .mapper
162            .map(|mapper| mapper(profile.clone()))
163            .transpose()?;
164        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
165        let user = match mapped {
166            Some(user) => user,
167            None => OAuthUserInfo {
168                additional_fields: Map::default(),
169                id: scalar(profile.get("account_id"))?.unwrap_or_default(),
170                name: scalar(
171                    profile
172                        .get("name")
173                        .and_then(|name| name.get("display_name")),
174                )?,
175                email: profile
176                    .get("email")
177                    .and_then(Value::as_str)
178                    .unwrap_or_default()
179                    .into(),
180                image: scalar(profile.get("profile_photo_url"))?,
181                email_verified: profile
182                    .get("email_verified")
183                    .and_then(Value::as_bool)
184                    .unwrap_or(false),
185            },
186        };
187        Ok(OAuthUserInfoResponse {
188            user_output,
189            user,
190            data: profile,
191        })
192    }
193}
194fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
195    match value {
196        None | Some(Value::Null) => Ok(None),
197        Some(Value::String(value)) => Ok(Some(value.clone())),
198        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
199            .map(Some)
200            .map_err(|error| error.to_string()),
201        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
202        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Dropbox profile field".into()),
203    }
204}
205fn subject(profile: &Value) -> Result<String, String> {
206    let id = scalar(profile.get("account_id"))?.ok_or("Missing Dropbox account_id")?;
207    if id
208        .trim_matches(|character: char| {
209            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
210        })
211        .is_empty()
212        || id == "null"
213        || id == "undefined"
214    {
215        return Err("Invalid Dropbox account_id".into());
216    }
217    Ok(id)
218}