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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::fmt;
use serde::{Deserialize, Serialize};
use reqwest::{Url, blocking::Client};

use crate::{Error, ErrorKind, LocalServer, ClientSecrets};

const TOKEN_INFO_URI: &str = "https://oauth2.googleapis.com/tokeninfo";

/// An opaque (proprietary format) token that conforms to the
/// [OAuth 2.0 framework](https://datatracker.ietf.org/doc/html/rfc6749#section-1.4). They contain authorization information, but
/// not identity information. They are used to authenticate and provide authorization information to Google APIs.
///
/// # Examples:
///
/// ```no_run
/// use drive_v3::AccessToken;
/// use drive_v3::ClientSecrets;
/// # use drive_v3::Error;
///
/// // Load your client_secrets file
/// let secrets_path = "my_client_secrets.json";
/// # let secrets_path = ".secure-files/google_drive_secrets.json";
/// let my_client_secrets = ClientSecrets::from_file(secrets_path)?;
///
/// // Request an access token, this will prompt you to authorize via the browser
/// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
/// let my_access_token = AccessToken::request(&my_client_secrets, &scopes)?;
///
/// // After getting your token you can make a request (with reqwest for example) using it for authorization
/// let client = reqwest::blocking::Client::new();
/// let body = client.get("google-api-endpoint")
///     .bearer_auth(&my_access_token.access_token)
///     .send()?
///     .text()?;
///
/// println!("response: {:?}", body);
/// # Ok::<(), Error>(())
/// ```
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccessToken {
    /// The value used for for authentication or authorization.
    pub access_token: String,

    /// The number of seconds until the token expires.
    pub expires_in: i128,

    /// A special token used to request a new token after this one expires or is revoked.
    pub refresh_token: String,

    /// The [Drive API scopes](https://developers.google.com/drive/api/guides/api-specific-auth) added to this access token as a
    /// string separated by spaces.
    pub scope: String,

    /// Type of the token, an access token should always be of the
    /// [Bearer](https://cloud.google.com/docs/authentication/token-types#bearer) type.
    pub token_type: String,
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for AccessToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AccessToken")
            .field("access_token", &format_args!("[hidden for security]"))
            .field("expires_in", &self.expires_in)
            .field("refresh_token", &format_args!("[hidden for security]"))
            .field("scope", &self.scope)
            .field("token_type", &self.token_type)
            .finish()
    }
}

impl AccessToken {
    /// Updates an [`AccessToken`] with the values of a [`RefreshToken`].
    fn update_with( &mut self, refresh_token: &RefreshToken ) {
        self.access_token = refresh_token.access_token.clone();
        self.expires_in   = refresh_token.expires_in;
        self.scope        = refresh_token.scope.clone();
        self.token_type   = refresh_token.token_type.clone();
    }

    /// Checks if an [`AccessToken`] is valid by making a request to the
    /// [tokeninfo](https://developers.google.com/identity/sign-in/web/backend-auth#calling-the-tokeninfo-endpoint)
    /// endpoint of the Google Drive API.
    ///
    /// # Note
    ///
    /// [`is_valid`](AccessToken::is_valid) will return false if the token has expired or has been revoked, but it will also
    /// return false if the tokeninfo endpoint cannot be reached or if the request returns an error response of any kind.
    ///
    /// # Examples:
    ///
    /// ```no_run
    /// use drive_v3::ClientSecrets;
    ///
    /// # use drive_v3::{Credentials, Error};
    /// # use drive_v3::AccessToken;
    /// #
    /// # let credentials_path = ".secure-files/google_drive_credentials.json";
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// #
    /// # let credentials = Credentials::from_file(&credentials_path, &scopes)?;
    /// #
    /// # let mut access_token = credentials.access_token;
    /// # let my_client_secrets = credentials.client_secrets;
    /// #
    /// let secrets_path = "my_client_secrets.json";
    /// # let secrets_path = ".secure-files/google_drive_secrets.json";
    /// let my_client_secrets = ClientSecrets::from_file(secrets_path)?;
    ///
    /// if access_token.is_valid() {
    ///     // Do something with your valid token
    /// } else {
    ///     access_token.refresh(&my_client_secrets)?;
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn is_valid( &self ) -> bool {
        let parameters = [ ("access_token", &self.access_token) ];

        let request_url = match Url::parse_with_params(TOKEN_INFO_URI, &parameters) {
            Ok(url) => url,
            Err(_) => return false,
        };

        let response = match reqwest::blocking::get(request_url) {
            Ok(response) => response,
            Err(_) => return false,
        };

        response.status() == 200
    }

    /// Checks if an [`AccessToken`] has all of the specified `scopes`.
    ///
    /// See [Choose scopes](https://developers.google.com/drive/api/guides/api-specific-auth) documentation, for information on
    /// the scopes supported by the Google Drive API.
    ///
    /// # Note
    ///
    /// [`has_scopes`](AccessToken::has_scopes) does not check if the present `scopes` are equal to the specified ones, it
    /// only checks that all specified `scopes` are present in the [`AccessToken`]'s scopes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use drive_v3::{Credentials, Error};
    /// # use drive_v3::AccessToken;
    /// #
    /// # let credentials_path = ".secure-files/google_drive_credentials.json";
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// #
    /// # let credentials = Credentials::from_file(&credentials_path, &scopes)?;
    /// # let access_token = credentials.access_token;
    /// #
    /// let required_scopes = [
    ///     "https://www.googleapis.com/auth/drive.metadata.readonly",
    ///     "https://www.googleapis.com/auth/drive.file",
    /// ];
    ///
    /// assert!( access_token.has_scopes(&required_scopes) );
    /// # Ok::<(), Error>(())
    /// ```
    pub fn has_scopes<T: AsRef<str>> ( &self, scopes: &[T] ) -> bool {
        let token_scopes: Vec<&str> = self.scope.split(' ').collect();

        scopes.iter().all( |s| token_scopes.contains(&s.as_ref()) )
    }

    /// Requests an [`AccessToken`] with the specified `scopes` from the Google Drive API using
    /// [OAuth2](https://developers.google.com/identity/protocols/oauth2/native-app#obtainingaccesstokens).
    ///
    /// See [Choose scopes](https://developers.google.com/drive/api/guides/api-specific-auth), for information on the scopes
    /// supported by the Google Drive API.
    ///
    /// # Examples:
    ///
    /// ```no_run
    /// use drive_v3::AccessToken;
    /// use drive_v3::ClientSecrets;
    /// # use drive_v3::Error;
    ///
    /// // Load your client_secrets file
    /// let secrets_path = "my_client_secrets.json";
    /// # let secrets_path = ".secure-files/google_drive_secrets.json";
    /// let my_client_secrets = ClientSecrets::from_file(secrets_path)?;
    ///
    /// // Request an access token, this will prompt you to authorize via the browser
    /// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// let my_access_token = AccessToken::request(&my_client_secrets, &scopes)?;
    ///
    /// // After getting your token you can make a request (with reqwest for example) using it for authorization
    /// let client = reqwest::blocking::Client::new();
    /// let body = client.get("google-api-endpoint")
    ///     .bearer_auth(&my_access_token.access_token)
    ///     .send()?
    ///     .text()?;
    ///
    /// println!("response: {:?}", body);
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - a [`HexDecoding`](crate::ErrorKind::HexDecoding) or [`UrlParsing`](crate::ErrorKind::UrlParsing) error, if the
    /// creation of the `code verifier` failed.
    /// - a [`Request`](crate::ErrorKind::Request) error, if unable to send the request or get a body from the response.
    /// - a [`Response`](crate::ErrorKind::Response) error, if the token request returned an error response.
    /// - a [`Json`](crate::ErrorKind::Json) error, if unable to parse the response's body to an [`AccessToken`].
    /// - a [`MismatchedScopes`](crate::ErrorKind::MismatchedScopes) error, if the scopes in the created [`AccessToken`] are
    /// different to the `scopes` passed to the function.
    #[cfg(not(tarpaulin_include))]
    pub fn request<T: AsRef<str>> ( client_secrets: &ClientSecrets, scopes: &[T], ) -> Result<Self, Error> {
        let (authorization_code, code_verifier) = client_secrets.get_authorization_code(scopes, true)?;
        let redirect_uri = &LocalServer::default().uri;

        let parameters = [
            ( "client_id",     &client_secrets.client_id           ),
            ( "client_secret", &client_secrets.client_secret       ),
            ( "code",          &authorization_code.to_string()     ),
            ( "code_verifier", &code_verifier.to_string()          ),
            ( "grant_type",    &String::from("authorization_code") ),
            ( "redirect_uri",  &redirect_uri                       ),
        ];

        let request = Client::new()
            .post(&client_secrets.token_uri)
            .form(&parameters);

        let response = request.send()?;

        if response.status() != 200 {
            return Err( response.into() );
        }

        let access_token: AccessToken = serde_json::from_str( &response.text()? )?;

        if !access_token.has_scopes(scopes) {
            return Err(Error {
                kind: ErrorKind::MismatchedScopes,
                message: String::from("created access token does not contain the requested scopes"),
            })
        }

        Ok(access_token)
    }

    /// Refreshes an [`AccessToken`] by requesting a new token from
    /// [OAuth2](https://developers.google.com/identity/protocols/oauth2/native-app#offline) using its
    /// [`refresh_token`](AccessToken::refresh_token).
    ///
    /// # Note
    ///
    /// There are limits on the number of refresh tokens that your application will be issued:
    ///
    /// - A limit per client/user combination.
    /// - A limit per user across all clients.
    ///
    /// It is your responsibility save refreshed tokens in long-term storage and continue to use them for as long as they remain
    /// valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh
    /// tokens will stop working.
    ///
    /// # Examples:
    ///
    /// ```no_run
    /// use drive_v3::ClientSecrets;
    /// #
    /// # use drive_v3::{Credentials, Error};
    /// #
    /// # let credentials_path = ".secure-files/google_drive_credentials.json";
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// # let credentials = Credentials::from_file(credentials_path, &scopes)?;
    /// #
    /// # let mut access_token = credentials.access_token;
    ///
    /// let secrets_path = "my_client_secrets.json";
    /// # let secrets_path = ".secure-files/google_drive_secrets.json";
    /// let my_client_secrets = ClientSecrets::from_file(secrets_path)?;
    ///
    /// if !access_token.is_valid() {
    ///     access_token.refresh(&my_client_secrets)?;
    /// }
    ///
    /// assert!( access_token.is_valid() );
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - a [`Request`](crate::ErrorKind::Request) error, if unable to send the refresh request or get a body from the response.
    /// - a [`Json`](crate::ErrorKind::Json) error, if unable to parse the received token from JSON.
    pub fn refresh( &mut self, client_secrets: &ClientSecrets ) -> Result<(), Error> {
        let body: [(&str, &str); 4] = [
            ( "client_id",     &client_secrets.client_id     ),
            ( "client_secret", &client_secrets.client_secret ),
            ( "grant_type",    "refresh_token"               ),
            ( "refresh_token", &self.refresh_token           ),
        ];

        let request = Client::new().post(&client_secrets.token_uri).form(&body);
        let response = request.send()?;

        if response.status() != 200 {
            return Err( response.into() );
        }

        let refresh_token: RefreshToken = serde_json::from_str( &response.text()? )?;
        self.update_with(&refresh_token);

        Ok(())
    }
}

/// A special token used to
/// [update](https://cloud.google.com/docs/authentication/token-types#refresh) expired or invalid [`AccessTokens`](AccessToken)
/// without having to prompt the user for authorization.
#[derive(Clone, Serialize, Deserialize)]
pub struct RefreshToken {
    /// The value used for for authentication or authorization.
    pub access_token: String,

    /// The number of seconds until the new token expires.
    pub expires_in: i128,

    /// The [Drive API scopes](https://developers.google.com/drive/api/guides/api-specific-auth) added to this access token as a
    /// string separated by spaces.
    pub scope: String,

    /// Type of this token.
    pub token_type: String,
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for RefreshToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RefreshToken")
            .field("access_token", &format_args!("[hidden for security]"))
            .field("expires_in", &self.expires_in)
            .field("scope", &self.scope)
            .field("token_type", &self.token_type)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use crate::ErrorKind;
    use super::{AccessToken, RefreshToken};
    use crate::utils::test::{VALID_CREDENTIALS, INVALID_CREDENTIALS};

    fn get_test_access_token() -> AccessToken {
        AccessToken {
            access_token:  String::from("test_access_token"),
            expires_in:    1984,
            refresh_token: String::from("test_refresh_token"),
            scope:         String::from("test_scope_one test_scope_two"),
            token_type:    String::from("Bearer"),
        }
    }

    fn get_test_refresh_token() -> RefreshToken {
        RefreshToken {
            access_token:  String::from("updated_test_access_token"),
            expires_in:    9999,
            scope:         String::from("test_scope_one test_scope_two"),
            token_type:    String::from("Bearer"),
        }
    }

    #[test]
    fn update_with_test() {
        let mut access_token = get_test_access_token();
        let refresh_token_value = access_token.refresh_token.clone();

        let refresh_token = get_test_refresh_token();
        access_token.update_with(&refresh_token);

        assert_eq!(access_token.access_token,  refresh_token.access_token);
        assert_eq!(access_token.expires_in,    refresh_token.expires_in);
        assert_eq!(access_token.refresh_token, refresh_token_value);
        assert_eq!(access_token.scope,         refresh_token.scope);
        assert_eq!(access_token.token_type,    refresh_token.token_type);
    }

    #[test]
    fn is_valid_test() {
        let invalid_access_token = get_test_access_token();

        assert!( !invalid_access_token.is_valid() );
        assert!( VALID_CREDENTIALS.access_token.is_valid() );
    }

    #[test]
    fn has_scopes_test() {
        let access_token = get_test_access_token();

        let scopes = ["test_scope_one", "test_scope_two"];
        assert!( access_token.has_scopes(&scopes) );

        let scopes = ["test_scope_one"];
        assert!( access_token.has_scopes(&scopes) );

        let scopes= ["test_scope_two"];
        assert!( access_token.has_scopes(&scopes) );
    }

    #[test]
    fn has_scopes_mismatch_test() {
        let access_token = get_test_access_token();

        let scopes = ["invalid_test_scope"];
        assert!( !access_token.has_scopes(&scopes) );

        let scopes = ["test_scope_one", "test_scope_one", "test_scope_three"];
        assert!( !access_token.has_scopes(&scopes) );

        let scopes = ["test_scope_one", "invalid_test_scope_two"];
        assert!( !access_token.has_scopes(&scopes) );
    }

    #[test]
    fn has_scopes_empty_test() {
        let access_token = get_test_access_token();

        let scopes: [&str; 0]  = [];
        assert!( access_token.has_scopes(&scopes) );
    }

    #[test]
    #[ignore = "requires user input (CI/CD)"]
    fn request_test() {
        let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
        let access_token = AccessToken::request(&VALID_CREDENTIALS.client_secrets, &scopes);

        assert!( access_token.is_ok() )
    }

    #[test]
    #[ignore = "requires user input (CI/CD)"]
    fn request_invalid_secrets_uri_test() {
        let mut client_secrets = VALID_CREDENTIALS.client_secrets.clone();

        client_secrets.token_uri = String::from("invalid-token-uri");

        let scopes: [&str; 1] = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
        let result = AccessToken::request(&client_secrets, &scopes);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::Request );
    }

    #[test]
    #[ignore = "requires user input (CI/CD)"]
    fn request_mismatched_scopes_test() {
        // MAKE SURE TO ONLY GIVE PERMISSION FOR ONE OF THE REQUESTED SCOPES

        let client_secrets = VALID_CREDENTIALS.client_secrets.clone();

        let scopes = [
            "https://www.googleapis.com/auth/drive.metadata.readonly",
            "https://www.googleapis.com/auth/drive.file",
        ];

        let access_token = AccessToken::request(&client_secrets, &scopes);

        assert!( access_token.is_err() );
        assert_eq!( access_token.unwrap_err().kind, ErrorKind::MismatchedScopes );
    }

    #[test]
    fn refresh_test() {
        let mut invalid_credentials = INVALID_CREDENTIALS.clone();

        let result = invalid_credentials.access_token.refresh(&invalid_credentials.client_secrets);

        assert!( result.is_ok() );
        assert!( invalid_credentials.access_token.is_valid() );
    }

    #[test]
    fn refresh_invalid_refresh_token_test() {
        let mut credentials = VALID_CREDENTIALS.clone();

        credentials.access_token.refresh_token = String::from("invalid-token");

        let result = credentials.access_token.refresh(&credentials.client_secrets);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::Response );
    }

    #[test]
    fn refresh_invalid_secrets_test() {
        let mut credentials = VALID_CREDENTIALS.clone();

        credentials.client_secrets.client_id = String::from("invalid-client-id");
        credentials.client_secrets.client_secret = String::from("invalid-client-secret");

        let result = credentials.access_token.refresh(&credentials.client_secrets);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::Response );
    }

    #[test]
    fn refresh_invalid_secrets_uri_test() {
        let mut credentials = VALID_CREDENTIALS.clone();

        credentials.client_secrets.token_uri = String::from("invalid-token-uri");

        let result = credentials.access_token.refresh(&credentials.client_secrets);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::Request );
    }
}