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
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};

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

use uuid::Uuid;

use graph_core::cache::{CacheStore, InMemoryCacheStore, TokenCache};
use graph_core::http::{AsyncResponseConverterExt, ResponseConverterExt};
use graph_core::identity::ForceTokenRefresh;
use graph_error::{AuthExecutionError, AuthExecutionResult, IdentityResult, AF};

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

use crate::identity::{
    AppConfig, AuthCodeAuthorizationUrlParameterBuilder, Authority, AzureCloudInstance,
    ConfidentialClientApplication, Token, TokenCredentialExecutor, CLIENT_ASSERTION_TYPE,
};
use crate::oauth_serializer::{AuthParameter, AuthSerializer};

credential_builder!(
    AuthorizationCodeCertificateCredentialBuilder,
    ConfidentialClientApplication<AuthorizationCodeCertificateCredential>
);

/// 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.
/// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow'
///
/// [X509Certificate] requires features = \["openssl"\]
/// ```rust,ignore
/// use graph_rs_sdk::oauth::{
///     ClientCertificateCredential, ConfidentialClientApplication, PKey, X509Certificate, X509,
/// };
/// use std::fs::File;
/// use std::io::Read;
/// use std::path::Path;
///
/// pub fn x509_certificate(
///     client_id: &str,
///     tenant: &str,
///     public_key_path: impl AsRef<Path>,
///     private_key_path: impl AsRef<Path>,
/// ) -> anyhow::Result<X509Certificate> {
///     // Use include_bytes!(file_path) if the files are local
///     let mut cert_file = File::open(public_key_path)?;
///     let mut certificate: Vec<u8> = Vec::new();
///     cert_file.read_to_end(&mut certificate)?;
///
///     let mut private_key_file = File::open(private_key_path)?;
///     let mut private_key: Vec<u8> = Vec::new();
///     private_key_file.read_to_end(&mut private_key)?;
///
///     let cert = X509::from_pem(certificate.as_slice())?;
///     let pkey = PKey::private_key_from_pem(private_key.as_slice())?;
///     Ok(X509Certificate::new_with_tenant(
///         client_id, tenant, cert, pkey,
///     ))
/// }
///
/// fn build_confidential_client(
///     client_id: &str,
///     tenant: &str,
///     scope: Vec<&str>,
///     x509certificate: X509Certificate,
/// ) -> anyhow::Result<ConfidentialClientApplication<ClientCertificateCredential>> {
///     Ok(ConfidentialClientApplication::builder(client_id)
///         .with_client_x509_certificate(&x509certificate)?
///         .with_tenant(tenant)
///         .with_scope(scope)
///         .build())
/// }
///
/// ```
#[derive(Clone)]
pub struct AuthorizationCodeCertificateCredential {
    pub(crate) app_config: AppConfig,
    /// The authorization code obtained from a call to authorize. The code should be obtained with all required scopes.
    pub(crate) authorization_code: Option<String>,
    /// The refresh token needed to make an access token request using a refresh token.
    /// Do not include an authorization code when using a refresh token.
    pub(crate) refresh_token: Option<String>,
    /// The same code_verifier that was used to obtain the authorization_code.
    /// Required if PKCE was used in the authorization code grant request. For more information,
    /// see the PKCE RFC https://datatracker.ietf.org/doc/html/rfc7636.
    pub(crate) code_verifier: Option<String>,
    /// The value must be set to urn:ietf:params:oauth:client-assertion-type:jwt-bearer.
    pub(crate) client_assertion_type: String,
    /// An assertion (a JSON web token) that you need to create and sign with the certificate
    /// you registered as credentials for your application. Read about certificate credentials
    /// to learn how to register your certificate and the format of the assertion.
    pub(crate) client_assertion: String,
    token_cache: InMemoryCacheStore<Token>,
}

impl Debug for AuthorizationCodeCertificateCredential {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthorizationCodeCertificateCredential")
            .field("app_config", &self.app_config)
            .finish()
    }
}
impl AuthorizationCodeCertificateCredential {
    pub fn new<T: AsRef<str>, U: IntoUrl>(
        client_id: T,
        authorization_code: T,
        client_assertion: T,
        redirect_uri: Option<U>,
    ) -> IdentityResult<AuthorizationCodeCertificateCredential> {
        let redirect_uri = {
            if let Some(redirect_uri) = redirect_uri {
                redirect_uri.into_url().ok()
            } else {
                None
            }
        };

        Ok(AuthorizationCodeCertificateCredential {
            app_config: AppConfig::builder(client_id.as_ref())
                .redirect_uri_option(redirect_uri)
                .build(),
            authorization_code: Some(authorization_code.as_ref().to_owned()),
            refresh_token: None,
            code_verifier: None,
            client_assertion_type: CLIENT_ASSERTION_TYPE.to_owned(),
            client_assertion: client_assertion.as_ref().to_owned(),
            token_cache: Default::default(),
        })
    }

    #[cfg(feature = "openssl")]
    pub fn builder(
        client_id: impl AsRef<str>,
        authorization_code: impl AsRef<str>,
        x509: &X509Certificate,
    ) -> IdentityResult<AuthorizationCodeCertificateCredentialBuilder> {
        AuthorizationCodeCertificateCredentialBuilder::new_with_auth_code_and_x509(
            authorization_code,
            x509,
            AppConfig::new(client_id.as_ref()),
        )
    }

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

    fn execute_cached_token_refresh(&mut self, cache_id: String) -> AuthExecutionResult<Token> {
        let response = self.execute()?;

        if !response.status().is_success() {
            return Err(AuthExecutionError::silent_token_auth(
                response.into_http_response()?,
            ));
        }

        let new_token: Token = response.json()?;
        self.token_cache.store(cache_id, new_token.clone());

        if new_token.refresh_token.is_some() {
            self.refresh_token = new_token.refresh_token.clone();
        }

        Ok(new_token)
    }

    async fn execute_cached_token_refresh_async(
        &mut self,
        cache_id: String,
    ) -> AuthExecutionResult<Token> {
        let response = self.execute_async().await?;

        if !response.status().is_success() {
            return Err(AuthExecutionError::silent_token_auth(
                response.into_http_response_async().await?,
            ));
        }

        let new_token: Token = response.json().await?;

        if new_token.refresh_token.is_some() {
            self.refresh_token = new_token.refresh_token.clone();
        }

        self.token_cache.store(cache_id, new_token.clone());
        Ok(new_token)
    }
}

#[async_trait]
impl TokenCache for AuthorizationCodeCertificateCredential {
    type Token = Token;

    fn get_token_silent(&mut self) -> Result<Self::Token, AuthExecutionError> {
        let cache_id = self.app_config.cache_id.to_string();

        match self.app_config.force_token_refresh {
            ForceTokenRefresh::Never => {
                // Attempt to bypass a read on the token store by using previous
                // refresh token stored outside of RwLock
                if self.refresh_token.is_some() {
                    if let Ok(token) = self.execute_cached_token_refresh(cache_id.clone()) {
                        return Ok(token);
                    }
                }

                if let Some(token) = self.token_cache.get(cache_id.as_str()) {
                    if token.is_expired_sub(time::Duration::minutes(5)) {
                        if let Some(refresh_token) = token.refresh_token.as_ref() {
                            self.refresh_token = Some(refresh_token.to_owned());
                        }

                        self.execute_cached_token_refresh(cache_id)
                    } else {
                        Ok(token)
                    }
                } else {
                    self.execute_cached_token_refresh(cache_id)
                }
            }
            ForceTokenRefresh::Once | ForceTokenRefresh::Always => {
                let token_result = self.execute_cached_token_refresh(cache_id);
                if self.app_config.force_token_refresh == ForceTokenRefresh::Once {
                    self.app_config.force_token_refresh = ForceTokenRefresh::Never;
                }
                token_result
            }
        }
    }

    async fn get_token_silent_async(&mut self) -> Result<Self::Token, AuthExecutionError> {
        let cache_id = self.app_config.cache_id.to_string();

        match self.app_config.force_token_refresh {
            ForceTokenRefresh::Never => {
                // Attempt to bypass a read on the token store by using previous
                // refresh token stored outside of RwLock
                if self.refresh_token.is_some() {
                    if let Ok(token) = self
                        .execute_cached_token_refresh_async(cache_id.clone())
                        .await
                    {
                        return Ok(token);
                    }
                }

                if let Some(old_token) = self.token_cache.get(cache_id.as_str()) {
                    if old_token.is_expired_sub(time::Duration::minutes(5)) {
                        if let Some(refresh_token) = old_token.refresh_token.as_ref() {
                            self.refresh_token = Some(refresh_token.to_owned());
                        }

                        self.execute_cached_token_refresh_async(cache_id).await
                    } else {
                        Ok(old_token.clone())
                    }
                } else {
                    self.execute_cached_token_refresh_async(cache_id).await
                }
            }
            ForceTokenRefresh::Once | ForceTokenRefresh::Always => {
                let token_result = self.execute_cached_token_refresh_async(cache_id).await;
                if self.app_config.force_token_refresh == ForceTokenRefresh::Once {
                    self.app_config.force_token_refresh = ForceTokenRefresh::Never;
                }
                token_result
            }
        }
    }

    fn with_force_token_refresh(&mut self, force_token_refresh: ForceTokenRefresh) {
        self.app_config.force_token_refresh = force_token_refresh;
    }
}

#[async_trait]
impl TokenCredentialExecutor for AuthorizationCodeCertificateCredential {
    fn form_urlencode(&mut self) -> IdentityResult<HashMap<String, String>> {
        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 AF::result(AuthParameter::ClientId);
        }

        if self.client_assertion.trim().is_empty() {
            return AF::result(AuthParameter::ClientAssertion);
        }

        if self.client_assertion_type.trim().is_empty() {
            self.client_assertion_type = CLIENT_ASSERTION_TYPE.to_owned();
        }

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

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

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

        if let Some(refresh_token) = self.refresh_token.as_ref() {
            if refresh_token.trim().is_empty() {
                return AF::msg_result(
                    AuthParameter::RefreshToken.alias(),
                    "refresh_token is empty - cannot be an empty string",
                );
            }

            serializer
                .refresh_token(refresh_token.as_ref())
                .grant_type("refresh_token");

            return serializer.as_credential_map(
                vec![AuthParameter::Scope],
                vec![
                    AuthParameter::RefreshToken,
                    AuthParameter::ClientId,
                    AuthParameter::GrantType,
                    AuthParameter::ClientAssertion,
                    AuthParameter::ClientAssertionType,
                ],
            );
        } else if let Some(authorization_code) = self.authorization_code.as_ref() {
            if authorization_code.trim().is_empty() {
                return AF::msg_result(
                    AuthParameter::AuthorizationCode.alias(),
                    "authorization_code is empty - cannot be an empty string",
                );
            }

            serializer
                .authorization_code(authorization_code.as_str())
                .grant_type("authorization_code");

            return serializer.as_credential_map(
                vec![AuthParameter::Scope, AuthParameter::CodeVerifier],
                vec![
                    AuthParameter::AuthorizationCode,
                    AuthParameter::ClientId,
                    AuthParameter::GrantType,
                    AuthParameter::RedirectUri,
                    AuthParameter::ClientAssertion,
                    AuthParameter::ClientAssertionType,
                ],
            );
        }

        AF::msg_result(
            format!(
                "{} or {}",
                AuthParameter::AuthorizationCode.alias(),
                AuthParameter::RefreshToken.alias()
            ),
            "Either authorization code or refresh token is required",
        )
    }

    fn client_id(&self) -> &Uuid {
        &self.app_config.client_id
    }

    fn authority(&self) -> Authority {
        self.app_config.authority.clone()
    }

    fn azure_cloud_instance(&self) -> AzureCloudInstance {
        self.app_config.azure_cloud_instance
    }

    fn app_config(&self) -> &AppConfig {
        &self.app_config
    }
}

#[derive(Clone)]
pub struct AuthorizationCodeCertificateCredentialBuilder {
    credential: AuthorizationCodeCertificateCredential,
}

impl AuthorizationCodeCertificateCredentialBuilder {
    #[cfg(feature = "openssl")]
    pub(crate) fn new_with_auth_code_and_x509(
        authorization_code: impl AsRef<str>,
        x509: &X509Certificate,
        app_config: AppConfig,
    ) -> IdentityResult<AuthorizationCodeCertificateCredentialBuilder> {
        let mut builder = Self {
            credential: AuthorizationCodeCertificateCredential {
                app_config,
                authorization_code: Some(authorization_code.as_ref().to_owned()),
                refresh_token: None,
                code_verifier: None,
                client_assertion_type: CLIENT_ASSERTION_TYPE.to_owned(),
                client_assertion: String::new(),
                token_cache: Default::default(),
            },
        };

        builder.with_x509(x509)?;
        Ok(builder)
    }

    #[cfg(feature = "interactive-auth")]
    #[cfg(feature = "openssl")]
    pub(crate) fn new_with_token(
        token: Token,
        x509: &X509Certificate,
        app_config: AppConfig,
    ) -> IdentityResult<AuthorizationCodeCertificateCredentialBuilder> {
        let cache_id = app_config.cache_id.clone();
        let mut token_cache = InMemoryCacheStore::new();
        token_cache.store(cache_id, token);

        let mut builder = Self {
            credential: AuthorizationCodeCertificateCredential {
                app_config,
                authorization_code: None,
                refresh_token: None,
                code_verifier: None,
                client_assertion_type: CLIENT_ASSERTION_TYPE.to_owned(),
                client_assertion: String::new(),
                token_cache,
            },
        };

        builder.with_x509(x509)?;
        Ok(builder)
    }

    #[allow(unused)]
    #[cfg(feature = "openssl")]
    pub(crate) fn new_authorization_response(
        value: (AppConfig, AuthorizationResponse, &X509Certificate),
    ) -> IdentityResult<AuthorizationCodeCertificateCredentialBuilder> {
        let (app_config, authorization_response, x509) = value;
        if let Some(authorization_code) = authorization_response.code.as_ref() {
            AuthorizationCodeCertificateCredentialBuilder::new_with_auth_code_and_x509(
                authorization_code,
                x509,
                app_config,
            )
        } else {
            AuthorizationCodeCertificateCredentialBuilder::new_with_token(
                Token::try_from(authorization_response.clone())?,
                x509,
                app_config,
            )
        }
    }

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

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

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

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

    #[cfg(feature = "openssl")]
    pub fn with_x509(
        &mut self,
        certificate_assertion: &X509Certificate,
    ) -> IdentityResult<&mut Self> {
        if let Some(tenant_id) = self.credential.authority().tenant_id() {
            self.with_client_assertion(
                certificate_assertion.sign_with_tenant(Some(tenant_id.clone()))?,
            );
        } else {
            self.with_client_assertion(certificate_assertion.sign_with_tenant(None)?);
        }
        Ok(self)
    }

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

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

    pub fn credential(self) -> AuthorizationCodeCertificateCredential {
        self.credential
    }
}

impl From<AuthorizationCodeCertificateCredential>
    for AuthorizationCodeCertificateCredentialBuilder
{
    fn from(credential: AuthorizationCodeCertificateCredential) -> Self {
        AuthorizationCodeCertificateCredentialBuilder { credential }
    }
}

impl From<AuthorizationCodeCertificateCredentialBuilder>
    for AuthorizationCodeCertificateCredential
{
    fn from(builder: AuthorizationCodeCertificateCredentialBuilder) -> Self {
        builder.credential
    }
}

impl Debug for AuthorizationCodeCertificateCredentialBuilder {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.credential.fmt(f)
    }
}