tiny_google_oidc 0.6.0

Tiny library for Google's OpenID Connect
Documentation
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! This module handles the process of requesting and verifying an authorization code
//! in the OpenID Connect authentication flow.   
//!
//! It provides the following key functionalities:
//! - Generating an authorization request URL (`CodeRequest`).
//! - Parsing and verifying the authorization code received from Google's callback (`RawCodeResponse`).
//!
//! # Key Structures and Features
//!
//! ## `CodeRequest`
//! A structure used to generate the authorization request URL.  
//! - Includes parameters like CSRF token, scope, redirect URI, and nonce.
//!
//! ## `RawCodeResponse`
//! Represents the authorization code response received from Google.  
//! - This response must be validated using a CSRF token before it can be used.
//!
//! ## `Code`
//! Represents a verified authorization code that can be exchanged for tokens.  
//! - This is obtained after validating the `RawCodeResponse` with a CSRF token.
//!
//! # Examples
//! ## Generating an Authorization Request URL
//! ```rust,no_run
//! let config = Config::builder()
//!     .client_id("your_client_id")
//!     .redirect_uri("your_redirect_uri")
//!     .build();
//!
//! let csrf_token = CSRFToken::new().unwrap();
//! let nonce = Nonce::new();
//! let scope = AdditionalScope::Email;
//!
//! let request = CodeRequest::new(true, &config, scope, &csrf_token, &nonce);
//! let url = request.try_into_url().unwrap();
//! println!("Auth URL: {}", url);
//! ```
//!
//! ## Handling the Callback and Verifying the Authorization Code
//! ```rust,no_run
//! let response = RawCodeResponse::new(req).unwrap();
//! // get stored CSRF token From DB(Redis, in memory ...)
//! let csrf_token = store.get("csrf_token_key")?;
//!
//! let code = response.exchange_with_code(csrf_token).expect("CSRF token mismatch!");
//! ```
//!
//! # Flow
//! 1. Generate a CSRF token (`CSRFToken`) and include it in the authorization request.
//! 2. Redirect the user to Google's authentication page.
//! 3. After authentication, Google redirects back with an authorization code (`RawCodeResponse`).
//! 4. Validate the CSRF token in the `RawCodeResponse` using `Code::new_with_verify_csrf()` or `RawCodeResponse::exchange_with_code()`.
//! 5. If validation succeeds, a `Code` is obtained, which can be exchanged for tokens.
//!
//! # Notes
//! - Always validate the CSRF token to ensure the integrity of the authentication flow.
//! - Do not use `RawCodeResponse` directly without verification.
use url::Url;

use crate::{
    config::{AuthEndPoint, ClientID, Config, RedirectURI},
    csrf_token::{CSRFToken, RawCSRFToken},
    error::Error,
    nonce::Nonce,
};
use std::{collections::HashMap, iter::Iterator};

/// Represents the value of the `code` query parameter sent by Google during the OpenID Connect flow.  
/// This structure ensures that the `code` can only be obtained after validating the associated `CSRFToken`.
///
/// # Purpose
/// The `Code` is used to construct an `IDTokenRequest`, which is required to retrieve an ID token from Google.
/// ```rust,no_run
/// let code: Code = Code::new_with_verify_csrf(res, stored_csrf_token)?;
/// let id_token_req = IDTokenRequest::new(&config, code);
/// ```
///
/// # How to Create
/// A `Code` can only be created after validating the `CSRFToken`.  
/// Use either `Code::new_with_verify_csrf` or `RawCodeResponse::exchange_with_code` to validate and create a `Code`.
///
/// # Example
/// ```rust,no_run
/// let response = RawCodeResponse::new(req).unwrap();
/// let csrf_token = store.get("csrf_token_key")?;
///
/// let code = response.exchange_with_code(csrf_token).expect("CSRF token mismatch!");
/// ```
///
/// # Notes
/// - Always validate the `CSRFToken` before using the `Code`.
/// - The `Code` is essential for constructing an `IDTokenRequest` to retrieve an ID token.
#[derive(Debug, Clone, PartialEq)]
pub struct Code(pub(crate) String);

impl Code {
    /// Checks if `res.state` (CSRF token from Google) matches `csrf_token` (generated by user).
    /// If valid, returns a `Code`; otherwise, returns `Error::CSRFNotMatch`.
    pub fn new_with_verify_csrf(res: RawCodeResponse, csrf_token_val: &str) -> Result<Self, Error> {
        if res.state.0 == csrf_token_val {
            Ok(res.code)
        } else {
            Err(Error::CSRFNotMatch)
        }
    }
}

/// Generates a URL to initiate the authorization request.
/// # Example
/// ```rust,no_run
/// let config = Config::builder()
///     .client_id("your_client_id")
///     .redirect_uri("your_redirect_uri")
///     .build();
///
/// let csrf_token = CSRFToken::new().unwrap();
/// let nonce = Nonce::new();
/// let scope = AdditionalScope::Email;
///
/// let request = CodeRequest::new(AccessType::Online, &config, scope, &csrf_token, &nonce);
/// let url = request.try_into_url().unwrap();
/// println!("Auth URL: {}", url);
/// ```
#[derive(Debug, Clone)]
pub struct CodeRequest<'a> {
    auth_endpoint: &'a AuthEndPoint,
    client_id: &'a ClientID,
    response_type: &'a str,
    scope: AdditionalScope,
    redirect_uri: &'a RedirectURI,
    access_type: AccessType,
    state: &'a CSRFToken,
    nonce: &'a Nonce,
}

impl<'a> CodeRequest<'a> {
    /// # **Parameters**
    ///
    /// - `access_type`:
    ///   - Offline → Requests an **offline** access token (includes a refresh token).
    ///   - Online → Requests an **online** access token (no refresh token).
    ///
    /// - `config`:
    ///   - Contains necessary settings such as `client_id`, `auth_endpoint`, and `redirect_uri`.
    ///
    /// - `scope`:
    ///   - Specifies additional scopes (`email`, `profile`) in addition to the required `openid` scope.
    ///   - If `None`, only `openid` will be requested.
    ///
    /// - `state`:
    ///   - A **CSRF protection token** to prevent cross-site request forgery attacks.
    ///
    /// - `nonce`:
    ///   - A **nonce value** used to mitigate replay attacks.
    pub fn new(
        access_type: AccessType,
        config: &'a Config,
        scope: AdditionalScope,
        state: &'a CSRFToken,
        nonce: &'a Nonce,
    ) -> Self {
        Self {
            auth_endpoint: &config.auth_endpoint,
            client_id: &config.client_id,
            response_type: "code",
            scope,
            redirect_uri: &config.redirect_uri,
            access_type,
            state,
            nonce,
        }
    }

    /// Constructs a URL with the required parameters for Google authentication.
    pub fn try_into_url(self) -> Result<Url, Error> {
        let access_type = match self.access_type {
            AccessType::Online => "online",
            AccessType::Offline => "offline",
        };

        let scope = match self.scope {
            AdditionalScope::Email => "openid email",
            AdditionalScope::Profile => "openid profile",
            AdditionalScope::Both => "openid email profile",
            AdditionalScope::None => "openid",
        };

        let url = format!(
            "{}?response_type={}&client_id={}&scope={}&access_type={}&redirect_uri={}&state={}&nonce={}",
            self.auth_endpoint.0,
            self.response_type,
            self.client_id.0,
            scope,
            access_type,
            self.redirect_uri.0,
            self.state.0,
            self.nonce.0,
        );
        let url = Url::parse(&url).map_err(|_| Error::ParseURL)?;
        Ok(url)
    }
}

/// A response from Google containing an unverified authorization code and state.  
/// Must be validated using a CSRF token before use.
/// # Example
/// ```rust,no_run
/// let response = RawCodeResponse::new(req).unwrap();
/// let csrf_token = store.get("csrf_token_key")?;
///
/// let code = response.exchange_with_code(csrf_token).expect("CSRF token mismatch!");
/// ```
#[derive(Debug, Clone)]
pub struct RawCodeResponse {
    state: RawCSRFToken,
    code: Code,
}

impl RawCodeResponse {
    pub fn new<Q>(query_src: Q) -> Result<Self, Error>
    where
        Q: QueryExtractor,
    {
        let query_str = query_src.extract_query().ok_or(Error::ParamsNotFound)?;
        let params: HashMap<_, _> = url::form_urlencoded::parse(query_str.as_bytes()).collect();
        Ok(Self {
            state: RawCSRFToken(
                params
                    .get("state")
                    .ok_or(Error::ParamsNotFound)?
                    .to_string(),
            ),
            code: Code(params.get("code").ok_or(Error::ParamsNotFound)?.to_string()),
        })
    }

    /// Must be validated using a CSRF token before use.
    pub fn exchange_with_code(self, csrf_token_val: &str) -> Result<Code, Error> {
        if self.state.0 == csrf_token_val {
            Ok(self.code)
        } else {
            Err(Error::CSRFNotMatch)
        }
    }
}

/// Trait that extracts query parameters from URL.  
///
/// The ```QueryExtractor``` extracts only the query portion of given a URL.  
///
/// For example, given the flollowing URL:   
/// ```https://example.com/path/to/auth?state=mystate&code=mycode```,  
/// it would return:  
///  ```state=mystate&code=mycode```  
///
/// The ```query_str``` can remain **URL-encoded**
pub trait QueryExtractor {
    fn extract_query(&self) -> Option<&str>;
}

impl<T> QueryExtractor for http::Request<T> {
    fn extract_query(&self) -> Option<&str> {
        self.uri().query()
    }
}

impl<T: QueryExtractor + ?Sized> QueryExtractor for &T {
    fn extract_query(&self) -> Option<&str> {
        (*self).extract_query()
    }
}

/// Indicates a value of ```access_type``` query param.  
///
/// ```Offline``` allows include [`RefreshToken`](crate::refresh_token::RefreshToken) in [`IDTokenResponse`](crate::id_token::IDTokenResponse)  
/// ```Online``` **not** allow include [`RefreshToken`](crate::refresh_token::RefreshToken) in [`IDTokenResponse`](crate::id_token::IDTokenResponse)  
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessType {
    Online,
    Offline,
}

/// Optional Scope Parameters  
///
/// In an OpenID Connect authentication request, the `scope` parameter specifies the type of user information
/// that should be included in the ID token. By default, the `openid` scope is required for authentication.
/// This enum allows adding **optional** scopes, such as `email`, `profile`, or both, to the request.
///
/// # Purpose
/// `AdditionalScope` is used to extend the default `scope` parameter when creating a `CodeRequest`.
/// It enables applications to request additional user information from Google.
///
/// # Variants
///
/// ## `Email`
/// - Requests the user's **email address** and **email verification status**.
/// - This is useful if the application needs to identify the user by their email address.
///
/// ## `Profile`
/// - Requests the user's **name, profile picture URL, and other basic profile information**.
/// - This is useful for displaying user details in the application.
///
/// ## Both
/// This allows you to add both `Email` and `Profile` scopes  
///
/// ## None
/// No additional scopes are added  
///
/// # Example
/// ```rust,no_run
/// use crate::code::AdditionalScope;
///
/// let additional_scopes = AdditionalScope::Both;
/// let request = CodeRequest::new(true, &config, additional_scopes, &csrf_token, &nonce);
/// let url = request.into_url().unwrap();
/// println!("Authorization URL: {}", url);
/// ```
///
/// If **no additional scopes** are specified, the request will **only include `openid`**, which is required for authentication.
///
/// # Notes
/// - Adding `email` or `profile` scopes allows the application to access more detailed user information.
/// - Ensure that the requested scopes align with the application's privacy policy and user consent.
#[derive(Debug, Clone, PartialEq)]
pub enum AdditionalScope {
    Email,
    Profile,
    Both,
    None,
}

#[cfg(test)]
mod tests {
    use url::Url;

    use crate::{code::AccessType, config::ConfigBuilder, csrf_token::CSRFToken, nonce::Nonce};

    use super::{AdditionalScope, CodeRequest, RawCodeResponse};

    #[test]
    fn test_code_req_offline() {
        let access_type = AccessType::Offline;

        let auth_endpoint = "https://auth.example.com/auth";
        let client_id = "my_client_id";
        let client_secret = "my_secret";
        let token_endpoint = "https://token.example.com";
        let redirect_uri = "https://redirect.example.com";

        let config = ConfigBuilder::new()
            .auth_endpoint(auth_endpoint)
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(token_endpoint)
            .redirect_uri(redirect_uri)
            .build();

        let scope = AdditionalScope::Both;
        let state = CSRFToken::new().unwrap();
        let nonce = Nonce::new();

        let code_req =
            CodeRequest::new(access_type.clone(), &config, scope.clone(), &state, &nonce);

        assert_eq!(code_req.access_type, access_type);
        assert_eq!(code_req.auth_endpoint.0, auth_endpoint);
        assert_eq!(code_req.client_id.0, client_id);
        assert_eq!(code_req.redirect_uri.0, redirect_uri);
        assert_eq!(*code_req.state, state);
        assert_eq!(*code_req.nonce, nonce);
        assert_eq!(code_req.scope, scope);
    }

    #[test]
    fn test_code_req_new_some_scope() {
        let access_type = AccessType::Online;

        let auth_endpoint = "https://auth.example.com/auth";
        let client_id = "my_client_id";
        let client_secret = "my_secret";
        let token_endpoint = "https://token.example.com";
        let redirect_uri = "https://redirect.example.com";

        let config = ConfigBuilder::new()
            .auth_endpoint(auth_endpoint)
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(token_endpoint)
            .redirect_uri(redirect_uri)
            .build();

        let scope = AdditionalScope::Both;
        let state = CSRFToken::new().unwrap();
        let nonce = Nonce::new();

        let code_req =
            CodeRequest::new(access_type.clone(), &config, scope.clone(), &state, &nonce);

        assert_eq!(code_req.access_type, access_type);
        assert_eq!(code_req.auth_endpoint.0, auth_endpoint);
        assert_eq!(code_req.client_id.0, client_id);
        assert_eq!(code_req.redirect_uri.0, redirect_uri);
        assert_eq!(*code_req.state, state);
        assert_eq!(*code_req.nonce, nonce);
        assert_eq!(code_req.scope, scope);
    }

    #[test]
    fn test_code_req_new_none_scope() {
        let access_type = AccessType::Online;

        let auth_endpoint = "https://auth.example.com/auth";
        let client_id = "my_client_id";
        let client_secret = "my_secret";
        let token_endpoint = "https://token.example.com";
        let redirect_uri = "https://redirect.example.com";

        let config = ConfigBuilder::new()
            .auth_endpoint(auth_endpoint)
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(token_endpoint)
            .redirect_uri(redirect_uri)
            .build();

        let scope = AdditionalScope::None;
        let state = CSRFToken::new().unwrap();
        let nonce = Nonce::new();

        let code_req =
            CodeRequest::new(access_type.clone(), &config, scope.clone(), &state, &nonce);

        assert_eq!(code_req.access_type, access_type);
        assert_eq!(code_req.auth_endpoint.0, auth_endpoint);
        assert_eq!(code_req.client_id.0, client_id);
        assert_eq!(code_req.redirect_uri.0, redirect_uri);
        assert_eq!(*code_req.state, state);
        assert_eq!(*code_req.nonce, nonce);
        assert_eq!(code_req.scope, scope);
    }

    #[test]
    fn test_code_req_into_url() {
        let access_type = AccessType::Online;

        let auth_endpoint = "https://auth.example.com/auth";
        let client_id = "my_client_id";
        let client_secret = "my_secret";
        let token_endpoint = "https://token.example.com";
        let redirect_url = "https://redirect.example.com";

        let config = ConfigBuilder::new()
            .auth_endpoint(auth_endpoint)
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(token_endpoint)
            .redirect_uri(redirect_url)
            .build();

        let scope = AdditionalScope::Both;
        let state = CSRFToken::new().unwrap();
        let nonce = Nonce::new();

        let code_req = CodeRequest::new(access_type, &config, scope, &state, &nonce);

        let url = code_req.try_into_url().unwrap();
        let expected_url = format!(
            "{}?response_type={}&client_id={}&scope={}&access_type={}&redirect_uri={}&state={}&nonce={}",
            auth_endpoint,
            "code",
            client_id,
            "openid email profile",
            "online",
            redirect_url,
            state.0,
            nonce.0,
        );
        assert_eq!(url, Url::parse(&expected_url).unwrap());
    }

    #[test]
    fn test_code_req_into_url_scope_one() {
        let access_type = AccessType::Online;

        let auth_endpoint = "https://auth.example.com/auth";
        let client_id = "my_client_id";
        let client_secret = "my_secret";
        let token_endpoint = "https://token.example.com";
        let redirect_url = "https://redirect.example.com";

        let config = ConfigBuilder::new()
            .auth_endpoint(auth_endpoint)
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(token_endpoint)
            .redirect_uri(redirect_url)
            .build();

        let scope = AdditionalScope::Email;
        let state = CSRFToken::new().unwrap();
        let nonce = Nonce::new();

        let code_req = CodeRequest::new(access_type, &config, scope, &state, &nonce);

        let url = code_req.try_into_url().unwrap();
        let expected_url = format!(
            "{}?response_type={}&client_id={}&scope={}&access_type={}&redirect_uri={}&state={}&nonce={}",
            auth_endpoint,
            "code",
            client_id,
            "openid email",
            "online",
            redirect_url,
            state.0,
            nonce.0,
        );
        assert_eq!(url, Url::parse(&expected_url).unwrap());
    }

    #[test]
    fn test_code_req_into_url_scope_none() {
        let access_type = AccessType::Online;

        let auth_endpoint = "https://auth.example.com/auth";
        let client_id = "my_client_id";
        let client_secret = "my_secret";
        let token_endpoint = "https://token.example.com";
        let redirect_url = "https://redirect.example.com";

        let config = ConfigBuilder::new()
            .auth_endpoint(auth_endpoint)
            .client_id(client_id)
            .client_secret(client_secret)
            .token_endpoint(token_endpoint)
            .redirect_uri(redirect_url)
            .build();

        let scope = AdditionalScope::None;
        let state = CSRFToken::new().unwrap();
        let nonce = Nonce::new();

        let code_req = CodeRequest::new(access_type, &config, scope, &state, &nonce);

        let url = code_req.try_into_url().unwrap();
        let expected_url = format!(
            "{}?response_type={}&client_id={}&scope={}&access_type={}&redirect_uri={}&state={}&nonce={}",
            auth_endpoint, "code", client_id, "openid", "online", redirect_url, state.0, nonce.0,
        );
        assert_eq!(url, Url::parse(&expected_url).unwrap());
    }

    #[test]
    fn test_construct_uncheck_code_res() {
        let code = "mycode";
        let state = "mystate";
        let uri = format!("https://www.example.com/autu?code={}&state={}", code, state);
        let http_req = http::Request::builder().uri(uri).body(()).unwrap();

        let raw_code_res = RawCodeResponse::new(http_req);

        assert!(raw_code_res.is_ok());

        assert_eq!(raw_code_res.clone().unwrap().state.0, "mystate");
        assert_eq!(raw_code_res.unwrap().code.0, "mycode");
    }

    #[test]
    fn test_construct_uncheck_code_res_none_params() {
        let uri = format!("https://www.example.com/");
        let http_req = http::Request::builder().uri(uri).body(()).unwrap();

        let raw_code_res = RawCodeResponse::new(http_req);

        assert!(raw_code_res.is_err());
    }
}