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
use crate::identity::credentials::app_config::AppConfig;
use crate::identity::{AzureCloudInstance, Prompt, ResponseMode, ResponseType};
use crate::oauth_serializer::{AuthParameter, AuthSerializer};
use graph_core::crypto::secure_random_32;
use graph_error::{AuthorizationFailure, IdentityResult, AF};
use http::{HeaderMap, HeaderName, HeaderValue};
use reqwest::IntoUrl;
use std::collections::HashMap;
use url::Url;

credential_builder_base!(ImplicitCredentialBuilder);

/// The defining characteristic of the implicit grant is that tokens (ID tokens or access tokens)
/// are returned directly from the /authorize endpoint instead of the /token endpoint. This is
/// often used as part of the authorization code flow, in what is called the "hybrid flow" -
/// retrieving the ID token on the /authorize request along with an authorization code.
/// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
#[derive(Clone)]
pub struct ImplicitCredential {
    pub(crate) app_config: AppConfig,
    /// Required
    /// If not set, defaults to code
    /// Must include id_token for OpenID Connect sign-in. It may also include the response_type
    /// token. Using token here will allow your app to receive an access token immediately from
    /// the authorize endpoint without having to make a second request to the authorize endpoint.
    /// If you use the token response_type, the scope parameter must contain a scope indicating
    /// which resource to issue the token for (for example, user.read on Microsoft Graph). It can
    /// also contain code in place of token to provide an authorization code, for use in the
    /// authorization code flow. This id_token+code response is sometimes called the hybrid flow.
    pub(crate) response_type: Vec<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: ResponseMode,
    /// Optional
    /// A value included in the request that will also be returned in the token response.
    /// It can be a string of any content that you wish. A randomly generated unique value is
    /// typically used for preventing cross-site request forgery attacks. The state is also used
    /// to encode information about the user's state in the app before the authentication request
    /// occurred, such as the page or view they were on.
    pub(crate) state: Option<String>,
    /// Required
    ///  A value included in the request, generated by the app, that will be 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. Only required when an id_token is requested.
    pub(crate) nonce: String,
    /// Optional
    /// Indicates the type of user interaction that is required. The only valid values at this
    /// time are 'login', 'none', 'select_account', and 'consent'. prompt=login will force the
    /// user to enter their credentials on that request, negating single-sign on. prompt=none is
    /// the opposite - it will ensure that the user isn't presented with any interactive prompt
    /// whatsoever. If the request can't be completed silently via single-sign on, the Microsoft
    /// identity platform will return an error. prompt=select_account sends the user to an account
    /// picker where all of the accounts remembered in the session will appear. prompt=consent
    /// will trigger the OAuth consent dialog after the user signs in, asking the user to grant
    /// permissions to the app.
    pub(crate) prompt: Option<Prompt>,
    /// 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>,
    /// Optional
    /// If included, it will skip the email-based discovery process that user goes through on
    /// the sign-in page, leading to a slightly more streamlined user experience. This parameter
    /// is commonly used for Line of Business apps that operate in a single tenant, where they'll
    /// provide a domain name within a given tenant, forwarding the user to the federation provider
    /// for that tenant. This hint prevents guests from signing into this application, and limits
    /// the use of cloud credentials like FIDO.
    pub(crate) domain_hint: Option<String>,
}

impl ImplicitCredential {
    pub fn new<U: ToString, I: IntoIterator<Item = U>>(
        client_id: impl AsRef<str>,
        scope: I,
    ) -> ImplicitCredential {
        ImplicitCredential {
            app_config: AppConfig::builder(client_id.as_ref()).scope(scope).build(),
            response_type: vec![ResponseType::Code],
            response_mode: ResponseMode::Query,
            state: None,
            nonce: secure_random_32(),
            prompt: None,
            login_hint: None,
            domain_hint: None,
        }
    }

    pub fn builder(client_id: impl AsRef<str>) -> ImplicitCredentialBuilder {
        ImplicitCredentialBuilder::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> {
        let mut serializer = AuthSerializer::new();
        let client_id = self.app_config.client_id.to_string();
        if client_id.is_empty() || self.app_config.client_id.is_nil() {
            return AuthorizationFailure::result("client_id");
        }

        if self.nonce.trim().is_empty() {
            return AuthorizationFailure::result("nonce");
        }

        serializer
            .client_id(client_id.as_str())
            .nonce(self.nonce.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(ResponseType::Code);
            serializer.response_mode(self.response_mode.as_ref());
        } else {
            let response_type = response_types.join(" ").trim().to_owned();
            if response_type.is_empty() {
                serializer.response_type(ResponseType::Code);
            } else {
                serializer.response_type(response_type);
            }

            if self.response_type.contains(&ResponseType::IdToken) {
                // id_token requires fragment or form_post. The Microsoft identity
                // platform recommends form_post. Unless you explicitly set
                // fragment then form_post is used here when response type is id_token.
                // Please file an issue if you encounter related problems.
                if self.response_mode.eq(&ResponseMode::Query) {
                    return Err(AF::msg_err(
                        "response_mode",
                        "ResponseType::IdToken requires ResponseMode::Fragment or ResponseMode::FormPost")
                    );
                } else {
                    serializer.response_mode(self.response_mode.as_ref());
                }
            } else {
                serializer.response_mode(self.response_mode.as_ref());
            }
        }

        // https://learn.microsoft.com/en-us/azure/active-directory/develop/scopes-oidc
        if self.app_config.scope.is_empty() {
            return Err(AF::required("scope"));
        }

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

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

        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());
        }

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

        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 ImplicitCredentialBuilder {
    credential: ImplicitCredential,
}

impl ImplicitCredentialBuilder {
    pub fn new(client_id: impl AsRef<str>) -> ImplicitCredentialBuilder {
        ImplicitCredentialBuilder {
            credential: ImplicitCredential {
                app_config: AppConfig::new(client_id.as_ref()),
                response_type: vec![ResponseType::Code],
                response_mode: ResponseMode::Query,
                state: None,
                nonce: secure_random_32(),
                prompt: None,
                login_hint: None,
                domain_hint: None,
            },
        }
    }

    pub fn with_redirect_uri<U: IntoUrl>(&mut self, redirect_uri: U) -> anyhow::Result<&mut Self> {
        self.credential.app_config.redirect_uri = Some(redirect_uri.into_url()?);
        Ok(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 = response_mode;
        self
    }

    /// A value included in the request 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.
    ///
    /// To have the client generate a nonce for you use [with_nonce_generated](crate::identity::legacy::ImplicitCredentialBuilder::with_generated_nonce)
    pub fn with_nonce<T: AsRef<str>>(&mut self, nonce: T) -> &mut Self {
        self.credential.nonce = nonce.as_ref().to_owned();
        self
    }

    /// Generates a secure random nonce.
    /// 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 = 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(&mut self, prompt: Prompt) -> &mut Self {
        self.credential.prompt = Some(prompt);
        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
    }

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

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

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

    #[test]
    fn serialize_uri() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_type(vec![ResponseType::Token])
            .with_redirect_uri("https://localhost/myapp")
            .unwrap()
            .with_scope(["User.Read"])
            .with_response_mode(ResponseMode::Fragment)
            .with_state("12345")
            .with_nonce("678910")
            .with_prompt(Prompt::None)
            .with_login_hint("myuser@mycompany.com")
            .build();

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

    #[test]
    fn set_open_id_fragment() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_type(vec![ResponseType::IdToken])
            .with_response_mode(ResponseMode::Fragment)
            .with_redirect_uri("https://localhost:8080/myapp")
            .unwrap()
            .with_scope(["User.Read"])
            .with_nonce("678910")
            .build();

        let url_result = authorizer.url();
        assert!(url_result.is_ok());
        let url = url_result.unwrap();
        let url_str = url.as_str();
        assert!(url_str.contains("response_mode=fragment"))
    }

    #[test]
    fn set_response_mode_fragment() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_mode(ResponseMode::Fragment)
            .with_redirect_uri("https://localhost:8080/myapp")
            .unwrap()
            .with_scope(["User.Read"])
            .with_nonce("678910")
            .build();

        let url_result = authorizer.url();
        assert!(url_result.is_ok());
        let url = url_result.unwrap();
        let url_str = url.as_str();
        assert!(url_str.contains("response_mode=fragment"))
    }

    #[test]
    fn response_type_id_token_token_serializes() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_type(vec![ResponseType::IdToken, ResponseType::Token])
            .with_response_mode(ResponseMode::Fragment)
            .with_redirect_uri("http://localhost:8080/myapp")
            .unwrap()
            .with_scope(["User.Read"])
            .with_nonce("678910")
            .build();

        let url_result = authorizer.url();
        assert!(url_result.is_ok());
        let url = url_result.unwrap();
        let url_str = url.as_str();
        assert!(url_str.contains("response_mode=fragment"));
        assert!(url_str.contains("response_type=id_token+token"));
    }

    #[test]
    fn response_type_id_token_token_serializes_from_string() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_type(ResponseType::StringSet(
                vec!["id_token".to_owned(), "token".to_owned()]
                    .into_iter()
                    .collect(),
            ))
            .with_response_mode(ResponseMode::FormPost)
            .with_redirect_uri("http://localhost:8080/myapp")
            .unwrap()
            .with_scope(["User.Read"])
            .with_nonce("678910")
            .build();

        let url_result = authorizer.url();
        assert!(url_result.is_ok());
        let url = url_result.unwrap();
        let url_str = url.as_str();
        assert!(url_str.contains("response_mode=form_post"));
        assert!(url_str.contains("response_type=id_token+token"))
    }

    #[test]
    #[should_panic]
    fn response_type_id_token_panics_with_response_mode_query() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_type(ResponseType::IdToken)
            .with_redirect_uri("http://localhost:8080/myapp")
            .unwrap()
            .with_scope(["User.Read"])
            .with_nonce("678910")
            .build();

        let url = authorizer.url().unwrap();
        let url_str = url.as_str();
        assert!(url_str.contains("response_type=id_token"))
    }

    #[test]
    #[should_panic]
    fn missing_scope_panic() {
        let authorizer = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_response_type(vec![ResponseType::Token])
            .with_redirect_uri("https://example.com/myapp")
            .unwrap()
            .with_nonce("678910")
            .build();

        let _ = authorizer.url().unwrap();
    }

    #[test]
    fn generate_nonce() {
        let url = ImplicitCredential::builder("6731de76-14a6-49ae-97bc-6eba6914391e")
            .with_redirect_uri("http://localhost:8080")
            .unwrap()
            .with_client_id(Uuid::new_v4())
            .with_scope(["read", "write"])
            .with_response_type(vec![ResponseType::Code, ResponseType::IdToken])
            .with_response_mode(ResponseMode::Fragment)
            .url()
            .unwrap();

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