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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
use std::collections::{BTreeSet, HashMap};
use std::fmt::{Debug, Formatter};

use http::{HeaderMap, HeaderName, HeaderValue};
use reqwest::IntoUrl;

use url::Url;
use uuid::Uuid;

use graph_core::crypto::{secure_random_32, ProofKeyCodeExchange};
use graph_error::{IdentityResult, AF};

use crate::identity::{
    AppConfig, AsQuery, AuthorizationCodeAssertionCredentialBuilder,
    AuthorizationCodeCredentialBuilder, AuthorizationUrl, AzureCloudInstance, Prompt, ResponseMode,
    ResponseType,
};
use crate::oauth_serializer::{AuthParameter, AuthSerializer};

#[cfg(feature = "openssl")]
use crate::identity::X509Certificate;

#[cfg(feature = "interactive-auth")]
use {
    crate::identity::{
        tracing_targets::INTERACTIVE_AUTH, AuthorizationCodeCertificateCredentialBuilder,
        AuthorizationResponse, Token,
    },
    crate::interactive::{
        HostOptions, InteractiveAuthEvent, UserEvents, WebViewAuth, WebViewAuthorizationEvent,
        WebViewHostValidator, WebViewOptions, WithInteractiveAuth,
    },
    crate::{Assertion, Secret},
    graph_error::{AuthExecutionError, WebViewError, WebViewResult},
    tao::{event_loop::EventLoopProxy, window::Window},
    wry::{WebView, WebViewBuilder},
};

credential_builder_base!(AuthCodeAuthorizationUrlParameterBuilder);

/// Get the authorization url required to perform the initial authorization and redirect in the
/// authorization code flow.
///
/// The authorization code flow begins with the client directing the user to the /authorize
/// endpoint.
///
/// The OAuth 2.0 authorization code grant type, or auth code flow, enables a client application
/// to obtain authorized access to protected resources like web APIs. The auth code flow requires
/// a user-agent that supports redirection from the authorization server (the Microsoft identity platform)
/// back to your application. For example, a web browser, desktop, or mobile application operated
/// by a user to sign in to your app and access their data.
///
/// Reference: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code
///
/// # Build a confidential client for the authorization code grant.
/// Use [with_authorization_code](crate::identity::ConfidentialClientApplicationBuilder::with_auth_code) to set the authorization code received from
/// the authorization step, see [Request an authorization code](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code)
/// You can use the [AuthCodeAuthorizationUrlParameterBuilder](crate::identity::AuthCodeAuthorizationUrlParameterBuilder)
/// to build the url that the user will be directed to authorize at.
///
/// ```rust
/// use uuid::Uuid;
/// use graph_oauth::{AzureCloudInstance, ConfidentialClientApplication, Prompt};
/// use url::Url;
///
/// let auth_url_builder = ConfidentialClientApplication::builder(Uuid::new_v4())
///     .auth_code_url_builder()
///     .with_tenant("tenant-id")
///     .with_prompt(Prompt::Login)
///     .with_state("1234")
///     .with_scope(vec!["User.Read"])
///     .with_redirect_uri(Url::parse("http://localhost:8000").unwrap())
///     .build();
///
/// let url = auth_url_builder.url();
/// // or
/// let url = auth_url_builder.url_with_host(&AzureCloudInstance::AzurePublic);
/// ```
#[derive(Clone)]
pub struct AuthCodeAuthorizationUrlParameters {
    pub(crate) app_config: AppConfig,
    pub(crate) response_type: BTreeSet<ResponseType>,
    /// Optional (recommended)
    ///
    /// Specifies how the identity platform should return the requested token to your app.
    ///
    /// Supported values:
    ///
    /// - query: Default when requesting an access token. Provides the code as a query string
    /// parameter on your redirect URI. The query parameter isn't supported when requesting an
    /// ID token by using the implicit flow.
    /// - fragment: Default when requesting an ID token by using the implicit flow.
    /// Also supported if requesting only a code.
    /// - form_post: Executes a POST containing the code to your redirect URI.
    /// Supported when requesting a code.
    pub(crate) response_mode: Option<ResponseMode>,
    /// A value included in the request, generated by the app, that is included in the
    /// resulting id_token as a claim. The app can then verify this value to mitigate token
    /// replay attacks. The value is typically a randomized, unique string that can be used
    /// to identify the origin of the request.
    /// The nonce is automatically generated unless set by the caller.
    pub(crate) nonce: Option<String>,
    pub(crate) state: Option<String>,
    /// Optional
    /// Indicates the type of user interaction that is required. The only valid values at
    /// this time are login, none, consent, and select_account.
    ///
    /// The [Prompt::Login] claim forces the user to enter their credentials on that request,
    /// which negates single sign-on.
    ///
    /// The [Prompt::None] parameter is the opposite, and should be paired with a login_hint to
    /// indicate which user must be signed in. These parameters ensure that the user isn't
    /// presented with any interactive prompt at all. If the request can't be completed silently
    /// via single sign-on, the Microsoft identity platform returns an error. Causes include no
    /// signed-in user, the hinted user isn't signed in, or multiple users are signed in but no
    /// hint was provided.
    ///
    /// The [Prompt::Consent] claim triggers the OAuth consent dialog after the
    /// user signs in. The dialog asks the user to grant permissions to the app.
    ///
    /// Finally, [Prompt::SelectAccount] shows the user an account selector, negating silent SSO but
    /// allowing the user to pick which account they intend to sign in with, without requiring
    /// credential entry. You can't use both login_hint and select_account.
    pub(crate) prompt: BTreeSet<Prompt>,
    /// Optional
    /// The realm of the user in a federated directory. This skips the email-based discovery
    /// process that the user goes through on the sign-in page, for a slightly more streamlined
    /// user experience. For tenants that are federated through an on-premises directory
    /// like AD FS, this often results in a seamless sign-in because of the existing login session.
    pub(crate) domain_hint: Option<String>,
    /// Optional
    /// You can use this parameter to pre-fill the username and email address field of the
    /// sign-in page for the user, if you know the username ahead of time. Often, apps use
    /// this parameter during re-authentication, after already extracting the login_hint
    /// optional claim from an earlier sign-in.
    pub(crate) login_hint: Option<String>,
    pub(crate) code_challenge: Option<String>,
    pub(crate) code_challenge_method: Option<String>,
}

impl Debug for AuthCodeAuthorizationUrlParameters {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthCodeAuthorizationUrlParameters")
            .field("app_config", &self.app_config)
            .field("response_type", &self.response_type)
            .field("response_mode", &self.response_mode)
            .field("prompt", &self.prompt)
            .finish()
    }
}

impl AuthCodeAuthorizationUrlParameters {
    pub fn new(
        client_id: impl AsRef<str>,
        redirect_uri: impl IntoUrl,
    ) -> IdentityResult<AuthCodeAuthorizationUrlParameters> {
        let mut response_type = BTreeSet::new();
        response_type.insert(ResponseType::Code);
        let redirect_uri_result = Url::parse(redirect_uri.as_str());

        Ok(AuthCodeAuthorizationUrlParameters {
            app_config: AppConfig::builder(client_id.as_ref())
                .redirect_uri(redirect_uri.into_url().or(redirect_uri_result)?)
                .build(),
            response_type,
            response_mode: None,
            nonce: None,
            state: None,
            prompt: Default::default(),
            domain_hint: None,
            login_hint: None,
            code_challenge: None,
            code_challenge_method: None,
        })
    }

    pub fn builder(client_id: impl TryInto<Uuid>) -> AuthCodeAuthorizationUrlParameterBuilder {
        AuthCodeAuthorizationUrlParameterBuilder::new(client_id)
    }

    pub fn url(&self) -> IdentityResult<Url> {
        self.url_with_host(&AzureCloudInstance::default())
    }

    pub fn url_with_host(&self, azure_cloud_instance: &AzureCloudInstance) -> IdentityResult<Url> {
        self.authorization_url_with_host(azure_cloud_instance)
    }

    pub fn into_credential(
        self,
        authorization_code: impl AsRef<str>,
    ) -> AuthorizationCodeCredentialBuilder {
        AuthorizationCodeCredentialBuilder::new_with_auth_code(authorization_code, self.app_config)
    }

    pub fn into_assertion_credential(
        self,
        authorization_code: impl AsRef<str>,
    ) -> AuthorizationCodeAssertionCredentialBuilder {
        AuthorizationCodeAssertionCredentialBuilder::new_with_auth_code(
            self.app_config,
            authorization_code,
        )
    }

    #[cfg(feature = "openssl")]
    pub fn into_certificate_credential(
        self,
        authorization_code: impl AsRef<str>,
        x509: &X509Certificate,
    ) -> IdentityResult<AuthorizationCodeCertificateCredentialBuilder> {
        AuthorizationCodeCertificateCredentialBuilder::new_with_auth_code_and_x509(
            authorization_code,
            x509,
            self.app_config,
        )
    }

    /// Get the nonce.
    ///
    /// This value may be generated automatically by the client and may be useful for users
    /// who want to manually verify that the nonce stored in the client is the same as the
    /// nonce returned in the response from the authorization server.
    /// Verifying the nonce helps mitigate token replay attacks.
    pub fn nonce(&mut self) -> Option<&String> {
        self.nonce.as_ref()
    }

    #[cfg(feature = "interactive-auth")]
    pub(crate) fn interactive_webview_authentication(
        &self,
        options: WebViewOptions,
    ) -> WebViewResult<AuthorizationResponse> {
        let uri = self
            .url()
            .map_err(|err| Box::new(AuthExecutionError::from(err)))?;
        let redirect_uri = self.redirect_uri().cloned().unwrap();
        let (sender, receiver) = std::sync::mpsc::channel();

        std::thread::spawn(move || {
            AuthCodeAuthorizationUrlParameters::run(uri, vec![redirect_uri], options, sender)
                .unwrap();
        });
        let mut iter = receiver.try_iter();
        let mut next = iter.next();

        while next.is_none() {
            next = iter.next();
        }

        match next {
            None => unreachable!(),
            Some(auth_event) => match auth_event {
                InteractiveAuthEvent::InvalidRedirectUri(reason) => {
                    Err(WebViewError::InvalidUri(reason))
                }
                InteractiveAuthEvent::ReachedRedirectUri(uri) => {
                    let query = uri
                        .query()
                        .or(uri.fragment())
                        .ok_or(WebViewError::InvalidUri(format!(
                            "uri missing query or fragment: {}",
                            uri
                        )))?;

                    let response_query: AuthorizationResponse =
                        serde_urlencoded::from_str(query)
                            .map_err(|err| WebViewError::InvalidUri(err.to_string()))?;

                    if response_query.is_err() {
                        tracing::debug!(target: INTERACTIVE_AUTH, "error in authorization query or fragment from redirect uri");
                        return Err(WebViewError::Authorization {
                            error: response_query
                                .error
                                .map(|query_error| query_error.to_string())
                                .unwrap_or_default(),
                            error_description: response_query.error_description.unwrap_or_default(),
                            error_uri: response_query.error_uri.map(|uri| uri.to_string()),
                        });
                    }

                    tracing::debug!(target: INTERACTIVE_AUTH, "parsed authorization query or fragment from redirect uri");

                    Ok(response_query)
                }
                InteractiveAuthEvent::WindowClosed(window_close_reason) => {
                    Err(WebViewError::WindowClosed(window_close_reason.to_string()))
                }
            },
        }
    }

    #[allow(dead_code)]
    #[cfg(feature = "interactive-auth")]
    pub(crate) fn interactive_authentication_builder(
        &self,
        options: WebViewOptions,
    ) -> WebViewResult<AuthorizationResponse> {
        let uri = self
            .url()
            .map_err(|err| Box::new(AuthExecutionError::from(err)))?;
        let redirect_uri = self.redirect_uri().cloned().unwrap();
        let (sender, receiver) = std::sync::mpsc::channel();

        std::thread::spawn(move || {
            AuthCodeAuthorizationUrlParameters::run(uri, vec![redirect_uri], options, sender)
                .unwrap();
        });
        let mut iter = receiver.try_iter();
        let mut next = iter.next();

        while next.is_none() {
            next = iter.next();
        }

        match next {
            None => unreachable!(),
            Some(auth_event) => match auth_event {
                InteractiveAuthEvent::InvalidRedirectUri(reason) => {
                    Err(WebViewError::InvalidUri(reason))
                }
                InteractiveAuthEvent::ReachedRedirectUri(uri) => {
                    let query = uri
                        .query()
                        .or(uri.fragment())
                        .ok_or(WebViewError::InvalidUri(format!(
                            "uri missing query or fragment: {}",
                            uri
                        )))?;

                    let response_query: AuthorizationResponse =
                        serde_urlencoded::from_str(query)
                            .map_err(|err| WebViewError::InvalidUri(err.to_string()))?;

                    Ok(response_query)
                }
                InteractiveAuthEvent::WindowClosed(window_close_reason) => {
                    Err(WebViewError::WindowClosed(window_close_reason.to_string()))
                }
            },
        }
    }
}

#[cfg(feature = "interactive-auth")]
mod internal {
    use super::*;

    impl WebViewAuth for AuthCodeAuthorizationUrlParameters {
        fn webview(
            host_options: HostOptions,
            window: &Window,
            proxy: EventLoopProxy<UserEvents>,
        ) -> anyhow::Result<WebView> {
            let start_uri = host_options.start_uri.clone();
            let validator = WebViewHostValidator::try_from(host_options)?;
            Ok(WebViewBuilder::new(window)
                .with_url(start_uri.as_ref())
                // Disables file drop
                .with_file_drop_handler(|_| true)
                .with_navigation_handler(move |uri| {
                    if let Ok(url) = Url::parse(uri.as_str()) {
                        let is_valid_host = validator.is_valid_uri(&url);
                        let is_redirect = validator.is_redirect_host(&url);

                        if is_redirect {
                            proxy.send_event(UserEvents::ReachedRedirectUri(url))
                                .unwrap();
                            proxy.send_event(UserEvents::InternalCloseWindow)
                                .unwrap();
                            return true;
                        }

                        is_valid_host
                    } else {
                        tracing::debug!(target: INTERACTIVE_AUTH, "unable to navigate webview - url is none");
                        proxy.send_event(UserEvents::CloseWindow).unwrap();
                        false
                    }
                })
                .build()?)
        }
    }
}

impl AuthorizationUrl for AuthCodeAuthorizationUrlParameters {
    fn redirect_uri(&self) -> Option<&Url> {
        self.app_config.redirect_uri.as_ref()
    }

    fn authorization_url(&self) -> IdentityResult<Url> {
        self.authorization_url_with_host(&AzureCloudInstance::default())
    }

    fn authorization_url_with_host(
        &self,
        azure_cloud_instance: &AzureCloudInstance,
    ) -> IdentityResult<Url> {
        let mut serializer = AuthSerializer::new();

        if let Some(redirect_uri) = self.app_config.redirect_uri.as_ref() {
            if redirect_uri.as_str().trim().is_empty() {
                return AF::result("redirect_uri");
            } else {
                serializer.redirect_uri(redirect_uri.as_str());
            }
        }

        let client_id = self.app_config.client_id.to_string();
        if client_id.is_empty() || self.app_config.client_id.is_nil() {
            return AF::result("client_id");
        }

        if self.app_config.scope.is_empty() {
            return AF::result("scope");
        }

        serializer
            .client_id(client_id.as_str())
            .set_scope(self.app_config.scope.clone());

        let response_types: Vec<String> =
            self.response_type.iter().map(|s| s.to_string()).collect();

        if response_types.is_empty() {
            serializer.response_type("code");
            if let Some(response_mode) = self.response_mode.as_ref() {
                serializer.response_mode(response_mode.as_ref());
            }
        } else {
            let response_type = response_types.join(" ").trim().to_owned();
            if response_type.is_empty() {
                serializer.response_type("code");
            } else {
                serializer.response_type(response_type);
            }

            // Set response_mode
            if self.response_type.contains(&ResponseType::IdToken) {
                if self.response_mode.eq(&Some(ResponseMode::Query)) {
                    return Err(AF::msg_err(
                        "response_mode",
                        "ResponseType::IdToken requires ResponseMode::Fragment or ResponseMode::FormPost")
                    );
                } else if let Some(response_mode) = self.response_mode.as_ref() {
                    serializer.response_mode(response_mode.as_ref());
                }
            } else if let Some(response_mode) = self.response_mode.as_ref() {
                serializer.response_mode(response_mode.as_ref());
            }
        }

        if let Some(state) = self.state.as_ref() {
            serializer.state(state.as_str());
        }

        if !self.prompt.is_empty() {
            serializer.prompt(&self.prompt.as_query());
        }

        if let Some(domain_hint) = self.domain_hint.as_ref() {
            serializer.domain_hint(domain_hint.as_str());
        }

        if let Some(login_hint) = self.login_hint.as_ref() {
            serializer.login_hint(login_hint.as_str());
        }

        if let Some(nonce) = self.nonce.as_ref() {
            serializer.nonce(nonce);
        }

        if let Some(code_challenge) = self.code_challenge.as_ref() {
            serializer.code_challenge(code_challenge.as_str());
        }

        if let Some(code_challenge_method) = self.code_challenge_method.as_ref() {
            serializer.code_challenge_method(code_challenge_method.as_str());
        }

        let query = serializer.encode_query(
            vec![
                AuthParameter::ResponseMode,
                AuthParameter::State,
                AuthParameter::Prompt,
                AuthParameter::LoginHint,
                AuthParameter::DomainHint,
                AuthParameter::Nonce,
                AuthParameter::CodeChallenge,
                AuthParameter::CodeChallengeMethod,
            ],
            vec![
                AuthParameter::ClientId,
                AuthParameter::ResponseType,
                AuthParameter::RedirectUri,
                AuthParameter::Scope,
            ],
        )?;

        let mut uri = azure_cloud_instance.auth_uri(&self.app_config.authority)?;
        uri.set_query(Some(query.as_str()));
        Ok(uri)
    }
}

#[derive(Clone)]
pub struct AuthCodeAuthorizationUrlParameterBuilder {
    credential: AuthCodeAuthorizationUrlParameters,
}

impl AuthCodeAuthorizationUrlParameterBuilder {
    pub fn new(client_id: impl TryInto<Uuid>) -> AuthCodeAuthorizationUrlParameterBuilder {
        let mut response_type = BTreeSet::new();
        response_type.insert(ResponseType::Code);
        AuthCodeAuthorizationUrlParameterBuilder {
            credential: AuthCodeAuthorizationUrlParameters {
                app_config: AppConfig::new(client_id),
                response_mode: None,
                response_type,
                nonce: None,
                state: None,
                prompt: Default::default(),
                domain_hint: None,
                login_hint: None,
                code_challenge: None,
                code_challenge_method: None,
            },
        }
    }

    pub(crate) fn new_with_app_config(
        app_config: AppConfig,
    ) -> AuthCodeAuthorizationUrlParameterBuilder {
        let mut response_type = BTreeSet::new();
        response_type.insert(ResponseType::Code);
        AuthCodeAuthorizationUrlParameterBuilder {
            credential: AuthCodeAuthorizationUrlParameters {
                app_config,
                response_mode: None,
                response_type,
                nonce: None,
                state: None,
                prompt: Default::default(),
                domain_hint: None,
                login_hint: None,
                code_challenge: None,
                code_challenge_method: None,
            },
        }
    }

    pub fn with_redirect_uri(&mut self, redirect_uri: Url) -> &mut Self {
        self.credential.app_config.redirect_uri = Some(redirect_uri);
        self
    }

    /// Default is code. Must include code for the authorization code flow.
    /// Can also include id_token or token if using the hybrid flow.
    pub fn with_response_type<I: IntoIterator<Item = ResponseType>>(
        &mut self,
        response_type: I,
    ) -> &mut Self {
        self.credential.response_type = response_type.into_iter().collect();
        self
    }

    /// Specifies how the identity platform should return the requested token to your app.
    ///
    /// Supported values:
    ///
    /// - **query**: Default when requesting an access token. Provides the code as a query string
    ///     parameter on your redirect URI. The query parameter is not supported when requesting an
    ///     ID token by using the implicit flow.
    /// - **fragment**: Default when requesting an ID token by using the implicit flow.
    ///     Also supported if requesting only a code.
    /// - **form_post**: Executes a POST containing the code to your redirect URI.
    ///     Supported when requesting a code.
    pub fn with_response_mode(&mut self, response_mode: ResponseMode) -> &mut Self {
        self.credential.response_mode = Some(response_mode);
        self
    }

    /// A value included in the request, generated by the app, that is included in the
    /// resulting id_token as a claim. The app can then verify this value to mitigate token
    /// replay attacks. The value is typically a randomized, unique string that can be used
    /// to identify the origin of the request.
    pub fn with_nonce<T: AsRef<str>>(&mut self, nonce: T) -> &mut Self {
        self.credential.nonce = Some(nonce.as_ref().to_owned());
        self
    }

    /// Generates a secure random nonce.
    /// Nonce is a value included in the request, generated by the app, that is included in the
    /// resulting id_token as a claim. The app can then verify this value to mitigate token
    /// replay attacks. The value is typically a randomized, unique string that can be used
    /// to identify the origin of the request.
    pub fn with_generated_nonce(&mut self) -> &mut Self {
        self.credential.nonce = Some(secure_random_32());
        self
    }

    pub fn with_state<T: AsRef<str>>(&mut self, state: T) -> &mut Self {
        self.credential.state = Some(state.as_ref().to_owned());
        self
    }

    /// Indicates the type of user interaction that is required. Valid values are login, none,
    /// consent, and select_account.
    ///
    /// - **prompt=login** forces the user to enter their credentials on that request, negating single-sign on.
    /// - **prompt=none** is the opposite. It ensures that the user isn't presented with any interactive prompt.
    ///     If the request can't be completed silently by using single-sign on, the Microsoft identity platform returns an interaction_required error.
    /// - **prompt=consent** triggers the OAuth consent dialog after the user signs in, asking the user to
    ///     grant permissions to the app.
    /// - **prompt=select_account** interrupts single sign-on providing account selection experience
    ///     listing all the accounts either in session or any remembered account or an option to choose to use a different account altogether.
    pub fn with_prompt<I: IntoIterator<Item = Prompt>>(&mut self, prompt: I) -> &mut Self {
        self.credential.prompt.extend(prompt.into_iter());
        self
    }

    pub fn with_domain_hint<T: AsRef<str>>(&mut self, domain_hint: T) -> &mut Self {
        self.credential.domain_hint = Some(domain_hint.as_ref().to_owned());
        self
    }

    pub fn with_login_hint<T: AsRef<str>>(&mut self, login_hint: T) -> &mut Self {
        self.credential.login_hint = Some(login_hint.as_ref().to_owned());
        self
    }

    /// Used to secure authorization code grants by using Proof Key for Code Exchange (PKCE).
    /// Required if code_challenge_method is included.
    pub fn with_code_challenge<T: AsRef<str>>(&mut self, code_challenge: T) -> &mut Self {
        self.credential.code_challenge = Some(code_challenge.as_ref().to_owned());
        self
    }

    /// The method used to encode the code_verifier for the code_challenge parameter.
    /// This SHOULD be S256, but the spec allows the use of plain if the client can't support SHA256.
    ///
    /// If excluded, code_challenge is assumed to be plaintext if code_challenge is included.
    /// The Microsoft identity platform supports both plain and S256.
    pub fn with_code_challenge_method<T: AsRef<str>>(
        &mut self,
        code_challenge_method: T,
    ) -> &mut Self {
        self.credential.code_challenge_method = Some(code_challenge_method.as_ref().to_owned());
        self
    }

    /// Sets the code_challenge and code_challenge_method using the [ProofKeyCodeExchange]
    /// Callers should keep the [ProofKeyCodeExchange] and provide it to the credential
    /// builder in order to set the client verifier and request an access token.
    pub fn with_pkce(&mut self, proof_key_for_code_exchange: &ProofKeyCodeExchange) -> &mut Self {
        self.with_code_challenge(proof_key_for_code_exchange.code_challenge.as_str());
        self.with_code_challenge_method(proof_key_for_code_exchange.code_challenge_method.as_str());
        self
    }

    pub fn build(&self) -> AuthCodeAuthorizationUrlParameters {
        self.credential.clone()
    }

    pub fn url_with_host(&self, azure_cloud_instance: &AzureCloudInstance) -> IdentityResult<Url> {
        self.credential.url_with_host(azure_cloud_instance)
    }

    pub fn url(&self) -> IdentityResult<Url> {
        self.credential.url()
    }

    pub fn with_auth_code(
        self,
        authorization_code: impl AsRef<str>,
    ) -> AuthorizationCodeCredentialBuilder {
        AuthorizationCodeCredentialBuilder::new_with_auth_code(
            authorization_code,
            self.credential.app_config,
        )
    }

    pub fn with_auth_code_assertion(
        self,
        authorization_code: impl AsRef<str>,
    ) -> AuthorizationCodeAssertionCredentialBuilder {
        AuthorizationCodeAssertionCredentialBuilder::new_with_auth_code(
            self.credential.app_config,
            authorization_code,
        )
    }

    #[cfg(feature = "openssl")]
    pub fn with_auth_code_x509_certificate(
        self,
        authorization_code: impl AsRef<str>,
        x509: &X509Certificate,
    ) -> IdentityResult<AuthorizationCodeCertificateCredentialBuilder> {
        AuthorizationCodeCertificateCredentialBuilder::new_with_auth_code_and_x509(
            authorization_code,
            x509,
            self.credential.app_config,
        )
    }
}

#[cfg(feature = "interactive-auth")]
impl WithInteractiveAuth<Secret> for AuthCodeAuthorizationUrlParameterBuilder {
    type CredentialBuilder = AuthorizationCodeCredentialBuilder;

    fn with_interactive_auth(
        &self,
        auth_type: Secret,
        options: WebViewOptions,
    ) -> WebViewResult<WebViewAuthorizationEvent<Self::CredentialBuilder>> {
        let authorization_response = self
            .credential
            .interactive_webview_authentication(options)?;

        if authorization_response.is_err() {
            tracing::debug!(target: INTERACTIVE_AUTH, "error in authorization query or fragment from redirect uri");
            return Ok(WebViewAuthorizationEvent::Unauthorized(
                authorization_response,
            ));
        }

        tracing::debug!(target: INTERACTIVE_AUTH, "parsed authorization query or fragment from redirect uri");

        let mut credential_builder = {
            if let Some(authorization_code) = authorization_response.code.as_ref() {
                AuthorizationCodeCredentialBuilder::new_with_auth_code(
                    authorization_code,
                    self.credential.app_config.clone(),
                )
            } else {
                AuthorizationCodeCredentialBuilder::new_with_token(
                    self.credential.app_config.clone(),
                    Token::try_from(authorization_response.clone())?,
                )
            }
        };

        credential_builder.with_client_secret(auth_type.0);
        Ok(WebViewAuthorizationEvent::Authorized {
            authorization_response,
            credential_builder,
        })
    }
}

#[cfg(feature = "interactive-auth")]
impl WithInteractiveAuth<Assertion> for AuthCodeAuthorizationUrlParameterBuilder {
    type CredentialBuilder = AuthorizationCodeAssertionCredentialBuilder;

    fn with_interactive_auth(
        &self,
        auth_type: Assertion,
        options: WebViewOptions,
    ) -> WebViewResult<WebViewAuthorizationEvent<Self::CredentialBuilder>> {
        let authorization_response = self
            .credential
            .interactive_webview_authentication(options)?;

        if authorization_response.is_err() {
            tracing::debug!(target: INTERACTIVE_AUTH, "error in authorization query or fragment from redirect uri");
            return Ok(WebViewAuthorizationEvent::Unauthorized(
                authorization_response,
            ));
        }

        tracing::debug!(target: INTERACTIVE_AUTH, "parsed authorization query or fragment from redirect uri");
        let mut credential_builder = {
            if let Some(authorization_code) = authorization_response.code.as_ref() {
                AuthorizationCodeAssertionCredentialBuilder::new_with_auth_code(
                    self.credential.app_config.clone(),
                    authorization_code,
                )
            } else {
                AuthorizationCodeAssertionCredentialBuilder::new_with_token(
                    self.credential.app_config.clone(),
                    Token::try_from(authorization_response.clone())?,
                )
            }
        };

        credential_builder.with_client_assertion(auth_type.0);
        Ok(WebViewAuthorizationEvent::Authorized {
            authorization_response,
            credential_builder,
        })
    }
}

#[cfg(feature = "openssl")]
#[cfg(feature = "interactive-auth")]
impl WithInteractiveAuth<&X509Certificate> for AuthCodeAuthorizationUrlParameterBuilder {
    type CredentialBuilder = AuthorizationCodeCertificateCredentialBuilder;

    fn with_interactive_auth(
        &self,
        auth_type: &X509Certificate,
        options: WebViewOptions,
    ) -> WebViewResult<WebViewAuthorizationEvent<Self::CredentialBuilder>> {
        let authorization_response = self
            .credential
            .interactive_webview_authentication(options)?;

        if authorization_response.is_err() {
            tracing::debug!(target: INTERACTIVE_AUTH, "error in authorization query or fragment from redirect uri");
            return Ok(WebViewAuthorizationEvent::Unauthorized(
                authorization_response,
            ));
        }

        tracing::debug!(target: INTERACTIVE_AUTH, "parsed authorization query or fragment from redirect uri");
        let mut credential_builder = {
            if let Some(authorization_code) = authorization_response.code.as_ref() {
                AuthorizationCodeCertificateCredentialBuilder::new_with_auth_code_and_x509(
                    authorization_code,
                    auth_type,
                    self.credential.app_config.clone(),
                )?
            } else {
                AuthorizationCodeCertificateCredentialBuilder::new_with_token(
                    Token::try_from(authorization_response.clone())?,
                    auth_type,
                    self.credential.app_config.clone(),
                )?
            }
        };

        credential_builder.with_x509(auth_type)?;
        Ok(WebViewAuthorizationEvent::Authorized {
            authorization_response,
            credential_builder,
        })
    }
}

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

    #[test]
    fn serialize_uri() {
        let authorizer = AuthCodeAuthorizationUrlParameters::builder(Uuid::new_v4())
            .with_redirect_uri(Url::parse("https://localhost:8080").unwrap())
            .with_scope(["read", "write"])
            .build();

        let url_result = authorizer.url();
        assert!(url_result.is_ok());
    }

    #[test]
    fn url_with_host() {
        let url_result = AuthCodeAuthorizationUrlParameters::builder(Uuid::new_v4())
            .with_redirect_uri(Url::parse("https://localhost:8080").unwrap())
            .with_scope(["read", "write"])
            .url_with_host(&AzureCloudInstance::AzureGermany);

        assert!(url_result.is_ok());
    }

    #[test]
    #[should_panic]
    fn response_type_id_token_panics_when_response_mode_query() {
        let url = AuthCodeAuthorizationUrlParameters::builder(Uuid::new_v4())
            .with_redirect_uri(Url::parse("https://localhost:8080").unwrap())
            .with_scope(["read", "write"])
            .with_response_mode(ResponseMode::Query)
            .with_response_type(vec![ResponseType::IdToken])
            .url()
            .unwrap();

        let _query = url.query().unwrap();
    }

    #[test]
    fn response_mode_not_set() {
        let url = AuthCodeAuthorizationUrlParameters::builder(Uuid::new_v4())
            .with_redirect_uri(Url::parse("https://localhost:8080").unwrap())
            .with_scope(["read", "write"])
            .url()
            .unwrap();

        let query = url.query().unwrap();
        assert!(!query.contains("response_mode"));
        assert!(query.contains("response_type=code"));
    }

    #[test]
    fn multi_response_type_set() {
        let url = AuthCodeAuthorizationUrlParameters::builder(Uuid::new_v4())
            .with_redirect_uri(Url::parse("https://localhost:8080").unwrap())
            .with_scope(["read", "write"])
            .with_response_mode(ResponseMode::FormPost)
            .with_response_type(vec![ResponseType::IdToken, ResponseType::Code])
            .url()
            .unwrap();

        let query = url.query().unwrap();
        assert!(query.contains("response_mode=form_post"));
        assert!(query.contains("response_type=code+id_token"));
    }

    #[test]
    fn generate_nonce() {
        let url = AuthCodeAuthorizationUrlParameters::builder(Uuid::new_v4())
            .with_redirect_uri(Url::parse("https://localhost:8080").unwrap())
            .with_scope(["read", "write"])
            .with_generated_nonce()
            .url()
            .unwrap();

        let query = url.query().unwrap();
        assert!(query.contains("nonce"));
    }
}