1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright (c) 2020-2021 Dropbox, Inc.

//! The default HTTP client.
//!
//! Use this client if you're not particularly picky about implementation details, as the specific
//! implementation is not exposed, and may be changed in the future.
//!
//! If you have a need for a specific HTTP client implementation, or your program is already using
//! some HTTP client crate, you probably want to have this Dropbox SDK crate use it as well. To do
//! that, you should implement the traits in `crate::client_trait` for it and use it instead.
//!
//! This code (and its dependencies) are only built if you use the `default_client` Cargo feature.

use crate::Error;
use crate::auth::AuthError;
use crate::client_trait::*;
use crate::oauth2::{Authorization, TokenCache};
use std::borrow::Cow;
use std::sync::Arc;

const USER_AGENT: &str = concat!("Dropbox-APIv2-Rust/", env!("CARGO_PKG_VERSION"));

macro_rules! forward_noauth_request {
    ($self:ident, $inner:expr, $path_root:expr) => {
        fn request(
            &$self,
            endpoint: Endpoint,
            style: Style,
            function: &str,
            params: String,
            params_type: ParamsType,
            body: Option<&[u8]>,
            range_start: Option<u64>,
            range_end: Option<u64>,
        ) -> crate::Result<HttpRequestResultRaw> {
            $inner.request(endpoint, style, function, &params, params_type, body, range_start,
                range_end, None, $path_root, None)
        }
    }
}

macro_rules! forward_authed_request {
    ($self:ident, $tokens:expr, $inner:expr, $path_root:expr, $team_select:expr) => {
        fn request(
            &$self,
            endpoint: Endpoint,
            style: Style,
            function: &str,
            params: String,
            params_type: ParamsType,
            body: Option<&[u8]>,
            range_start: Option<u64>,
            range_end: Option<u64>,
        ) -> crate::Result<HttpRequestResultRaw> {
            let mut token = $tokens.get_token(TokenUpdateClient { inner: &$inner })?;

            let mut retried = false;
            loop {
                let result = $inner.request(endpoint, style, function, &params, params_type, body,
                    range_start, range_end, Some(&token), $path_root, $team_select);

                if retried {
                    break result;
                }

                if let Err(crate::Error::Authentication(AuthError::ExpiredAccessToken)) = &result {
                    info!("refreshing auth token");
                    let old_token = token;
                    token = $tokens.update_token(
                        TokenUpdateClient { inner: &$inner },
                        old_token,
                    )?;
                    retried = true;
                    continue;
                }

                break result;
            }
        }
    }
}

macro_rules! impl_set_path_root {
    ($self:ident) => {
        /// Set a root which all subsequent paths are evaluated relative to.
        ///
        /// The default, if this function is not called, is to behave as if it was called with
        /// [`PathRoot::Home`](crate::common::PathRoot::Home).
        ///
        /// See <https://www.dropbox.com/developers/reference/path-root-header-modes> for more
        /// information.
        #[cfg(feature = "dbx_common")]
        pub fn set_path_root(&mut $self, path_root: &crate::common::PathRoot) {
            // Only way this can fail is if PathRoot::Other was specified, which is a programmer
            // error, so panic if that happens.
            $self.path_root = Some(serde_json::to_string(path_root).expect("invalid path root"));
        }
    }
}

/// Default HTTP client using User authorization.
pub struct UserAuthDefaultClient {
    inner: UreqClient,
    tokens: Arc<TokenCache>,
    path_root: Option<String>, // a serialized PathRoot enum
}

impl UserAuthDefaultClient {
    /// Create a new client using the given OAuth2 authorization.
    pub fn new(auth: Authorization) -> Self {
        Self::from_token_cache(Arc::new(TokenCache::new(auth)))
    }

    /// Create a new client from a [`TokenCache`], which lets you share the same tokens between
    /// multiple clients.
    pub fn from_token_cache(tokens: Arc<TokenCache>) -> Self {
        Self {
            inner: UreqClient::default(),
            tokens,
            path_root: None,
        }
    }

    impl_set_path_root!(self);
}

impl HttpClient for UserAuthDefaultClient {
    forward_authed_request! { self, self.tokens, self.inner, self.path_root.as_deref(), None }
}

impl UserAuthClient for UserAuthDefaultClient {}

/// Default HTTP client using Team authorization.
pub struct TeamAuthDefaultClient {
    inner: UreqClient,
    tokens: Arc<TokenCache>,
    path_root: Option<String>, // a serialized PathRoot enum
    team_select: Option<TeamSelect>,
}

impl TeamAuthDefaultClient {
    /// Create a new client using the given OAuth2 token, with no user/admin context selected.
    pub fn new(tokens: impl Into<Arc<TokenCache>>) -> Self {
        Self {
            inner: UreqClient::default(),
            tokens: tokens.into(),
            path_root: None,
            team_select: None,
        }
    }

    /// Select a user or team context to operate in.
    pub fn select(&mut self, team_select: Option<TeamSelect>) {
        self.team_select = team_select;
    }

    impl_set_path_root!(self);
}

impl HttpClient for TeamAuthDefaultClient {
    forward_authed_request! { self, self.tokens, self.inner, self.path_root.as_deref(), self.team_select.as_ref() }
}

impl TeamAuthClient for TeamAuthDefaultClient {}

/// Default HTTP client for unauthenticated API calls.
#[derive(Debug, Default)]
pub struct NoauthDefaultClient {
    inner: UreqClient,
    path_root: Option<String>,
}

impl NoauthDefaultClient {
    impl_set_path_root!(self);
}

impl HttpClient for NoauthDefaultClient {
    forward_noauth_request! { self, self.inner, self.path_root.as_deref() }
}

impl NoauthClient for NoauthDefaultClient {}

/// Same as NoauthDefaultClient but with inner by reference and no path_root.
/// Only used for updating authorization tokens.
struct TokenUpdateClient<'a> {
    inner: &'a UreqClient,
}

impl<'a> HttpClient for TokenUpdateClient<'a> {
    forward_noauth_request! { self, self.inner, None }
}

impl<'a> NoauthClient for TokenUpdateClient<'a> {}

#[derive(Debug, Default)]
struct UreqClient {}

impl UreqClient {
    #[allow(clippy::too_many_arguments)]
    fn request(
        &self,
        endpoint: Endpoint,
        style: Style,
        function: &str,
        params: &str,
        params_type: ParamsType,
        body: Option<&[u8]>,
        range_start: Option<u64>,
        range_end: Option<u64>,
        token: Option<&str>,
        path_root: Option<&str>,
        team_select: Option<&TeamSelect>,
    ) -> crate::Result<HttpRequestResultRaw> {

        let url = endpoint.url().to_owned() + function;
        debug!("request for {:?}", url);

        let mut req = ureq::post(&url)
            .set("User-Agent", USER_AGENT);

        if let Some(token) = token {
            req = req.set("Authorization", &format!("Bearer {}", token));
        }

        if let Some(path_root) = path_root {
            req = req.set("Dropbox-API-Path-Root", path_root);
        }

        if let Some(team_select) = team_select {
            req = match team_select {
                TeamSelect::User(id) => req.set("Dropbox-API-Select-User", id),
                TeamSelect::Admin(id) => req.set("Dropbox-API-Select-Admin", id),
            };
        }

        req = match (range_start, range_end) {
            (Some(start), Some(end)) => req.set("Range", &format!("bytes={}-{}", start, end)),
            (Some(start), None) => req.set("Range", &format!("bytes={}-", start)),
            (None, Some(end)) => req.set("Range", &format!("bytes=-{}", end)),
            (None, None) => req,
        };

        // If the params are totally empty, don't send any arg header or body.
        let result = if params.is_empty() {
            req.call()
        } else {
            match style {
                Style::Rpc => {
                    // Send params in the body.
                    req = req.set("Content-Type", params_type.content_type());
                    req.send_string(params)
                }
                Style::Upload | Style::Download => {
                    // Send params in a header. Note that non-ASCII and 0x7F in a header need to be
                    // escaped per the HTTP spec.
                    req = req.set(
                        "Dropbox-API-Arg",
                        json_escape_header(params).as_ref());
                    if style == Style::Upload {
                        req = req.set("Content-Type", "application/octet-stream");
                        if let Some(body) = body {
                            req.send_bytes(body)
                        } else {
                            req.send_bytes(&[])
                        }
                    } else {
                        assert!(body.is_none(), "body can only be set for Style::Upload request");
                        req.call()
                    }
                }
            }
        };

        let resp = match result {
            Ok(resp) => resp,
            Err(e @ ureq::Error::Transport(_)) => {
                error!("request failed: {}", e);
                return Err(RequestError { inner: e }.into());
            }
            Err(ureq::Error::Status(code, resp)) => {
                let status = resp.status_text().to_owned();
                let json = resp.into_string()?;
                return Err(Error::UnexpectedHttpError {
                    code,
                    status,
                    json,
                });
            }
        };

        match style {
            Style::Rpc | Style::Upload => {
                // Get the response from the body; return no body stream.
                let result_json = resp.into_string()?;
                Ok(HttpRequestResultRaw {
                    result_json,
                    content_length: None,
                    body: None,
                })
            }
            Style::Download => {
                // Get the response from a header; return the body stream.
                let result_json = resp.header("Dropbox-API-Result")
                    .ok_or(Error::UnexpectedResponse("missing Dropbox-API-Result header"))?
                    .to_owned();

                let content_length = match resp.header("Content-Length") {
                    Some(s) => Some(s.parse()
                        .map_err(|_| Error::UnexpectedResponse("invalid Content-Length header"))?),
                    None => None,
                };

                Ok(HttpRequestResultRaw {
                    result_json,
                    content_length,
                    body: Some(Box::new(resp.into_reader())),
                })
            }
        }
    }
}

/// Errors from the HTTP client encountered in the course of making a request.
#[derive(thiserror::Error, Debug)]
#[allow(clippy::large_enum_variant)] // it's always boxed
pub enum DefaultClientError {
    /// The HTTP client encountered invalid UTF-8 data.
    #[error("invalid UTF-8 string")]
    Utf8(#[from] std::string::FromUtf8Error),

    /// The HTTP client encountered some I/O error.
    #[error("I/O error: {0}")]
    #[allow(clippy::upper_case_acronyms)]
    IO(#[from] std::io::Error),

    /// Some other error from the HTTP client implementation.
    #[error(transparent)]
    Request(#[from] RequestError),
}

macro_rules! wrap_error {
    ($e:ty) => {
        impl From<$e> for crate::Error {
            fn from(e: $e) -> Self {
                Self::HttpClient(Box::new(DefaultClientError::from(e)))
            }
        }
    }
}

wrap_error!(std::io::Error);
wrap_error!(std::string::FromUtf8Error);
wrap_error!(RequestError);

/// Something went wrong making the request, or the server returned a response we didn't expect.
/// Use the `Display` or `Debug` impls to see more details.
/// Note that this type is intentionally vague about the details beyond these string
/// representations, to allow implementation changes in the future.
pub struct RequestError {
    inner: ureq::Error,
}

impl std::fmt::Display for RequestError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <ureq::Error as std::fmt::Display>::fmt(&self.inner, f)
    }
}

impl std::fmt::Debug for RequestError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <ureq::Error as std::fmt::Debug>::fmt(&self.inner, f)
    }
}

impl std::error::Error for RequestError {
    fn cause(&self) -> Option<&dyn std::error::Error> {
        Some(&self.inner)
    }
}

/// Replaces any non-ASCII characters (and 0x7f) with JSON-style '\uXXXX' sequence. Otherwise,
/// returns it unmodified without any additional allocation or copying.
fn json_escape_header(s: &str) -> Cow<'_, str> {
    // Unfortunately, the HTTP spec requires escaping ASCII DEL (0x7F), so we can't use the quicker
    // bit pattern check done in str::is_ascii() to skip this for the common case of all ASCII. :(

    let mut out = Cow::Borrowed(s);
    for (i, c) in s.char_indices() {
        if !c.is_ascii() || c == '\x7f' {
            let mstr = match out {
                Cow::Borrowed(_) => {
                    // If we're still borrowed, we must have had ascii up until this point.
                    // Clone the string up until here, and from now on we'll be pushing chars to it.
                    out = Cow::Owned(s[0..i].to_owned());
                    out.to_mut()
                }
                Cow::Owned(ref mut m) => m,
            };
            mstr.push_str(&format!("\\u{:04x}", c as u32));
        } else if let Cow::Owned(ref mut o) = out {
            o.push(c);
        }
    }
    out
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_json_escape() {
        assert_eq!(Cow::Borrowed("foobar"), json_escape_header("foobar"));
        assert_eq!(
            Cow::<'_, str>::Owned("tro\\u0161kovi".to_owned()),
            json_escape_header("troškovi"));
        assert_eq!(
            Cow::<'_, str>::Owned(
                r#"{"field": "some_\u00fc\u00f1\u00eec\u00f8d\u00e9_and_\u007f"}"#.to_owned()),
            json_escape_header("{\"field\": \"some_üñîcødé_and_\x7f\"}"));
        assert_eq!(
            Cow::<'_, str>::Owned("almost,\\u007f but not quite".to_owned()),
            json_escape_header("almost,\x7f but not quite"));
    }
}