huskarl 0.8.0

A modern OAuth2 client library.
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
577
578
579
580
581
582
583
584
585
586
587
588
//! JWT bearer grant (RFC 7523 §2.1).
//!
//! Used to request an access token by presenting a JWT *assertion* that an
//! authority the authorization server trusts has signed. The assertion identifies
//! the principal the token is for; the client does not act on its own behalf (for
//! that, see [`client_credentials`](crate::grant::client_credentials)).
//!
//! This grant carries a **caller-supplied, already-signed** assertion. The
//! library does not mint the assertion — see [Creating the assertion
//! JWT](#creating-the-assertion-jwt) below for how to build and sign one.
//!
//! Note that the assertion (the *grant*) is independent of client authentication.
//! A client may still authenticate to the token endpoint separately — for example
//! with [`JwtBearer`](crate::core::client_auth::JwtBearer) (`private_key_jwt`) — in
//! addition to presenting a user assertion as the grant.
//!
//! # Usage
//!
//! ## 1. Set up your HTTP client
//!
//! A HTTP client needs to be configured. Using the `huskarl_reqwest` crate:
//!
//! ```rust
//! use huskarl_reqwest::ReqwestClient;
//!
//! # async fn setup_client() -> Result<(), Box<dyn std::error::Error>> {
//! let client: ReqwestClient = ReqwestClient::builder().build().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## 2. Set up client authentication (if necessary).
//!
//! This example shows the use of a client secret as credentials, but any
//! `ClientAuthentication` implementation can be used. Public clients may use
//! [`NoAuth`](crate::core::client_auth::NoAuth).
//!
//! ```rust
//! use huskarl::core::{
//!     client_auth::ClientSecret,
//!     secrets::{EnvVarSecret, encodings::StringEncoding},
//! };
//!
//! # async fn setup_client_auth() -> Result<(), Box<dyn std::error::Error>> {
//! let env_secret = EnvVarSecret::new("CLIENT_SECRET", &StringEncoding)?;
//! let client_auth: ClientSecret = ClientSecret::new(env_secret);
//! # Ok(())
//! # }
//! ```
//!
//! ## 3a. Set up the grant with authorization server metadata
//!
//! ```rust
//! use huskarl::{
//!     core::{client_auth::ClientSecret, server_metadata::AuthorizationServerMetadata},
//!     grant::jwt_bearer::JwtBearerGrant,
//! };
//! # use huskarl::core::http::HttpClient;
//! # use huskarl::core::secrets::EnvVarSecret;
//! # use huskarl::core::secrets::encodings::StringEncoding;
//! # async fn setup_grant() -> Result<(), Box<dyn std::error::Error>> {
//! # let client = huskarl_reqwest::ReqwestClient::builder()
//! #     .build()
//! #     .await?;
//! #
//! # let env_secret = EnvVarSecret::new("CLIENT_SECRET", &StringEncoding)?;
//! # let client_auth: ClientSecret = ClientSecret::new(env_secret);
//!
//! let metadata = AuthorizationServerMetadata::fetch()
//!     .http_client(&client)
//!     .issuer("https://my-issuer")
//!     .call()
//!     .await?;
//!
//! let grant: JwtBearerGrant = JwtBearerGrant::builder_from_metadata(&metadata)
//!     .client_id("client_id")
//!     .http_client(client)
//!     .client_auth(client_auth)
//!     .build();
//! # Ok(())
//! # }
//! ```
//!
//! ## 3b. Alternative: Set up the grant without metadata
//!
//! ```rust
//! use huskarl::{core::client_auth::ClientSecret, grant::jwt_bearer::JwtBearerGrant};
//! # use huskarl::core::http::HttpClient;
//! # use huskarl::core::secrets::EnvVarSecret;
//! # use huskarl::core::secrets::encodings::StringEncoding;
//! # async fn setup_grant() -> Result<(), Box<dyn std::error::Error>> {
//! # let client = huskarl_reqwest::ReqwestClient::builder()
//! #     .build()
//! #     .await?;
//! #
//! # let env_secret = EnvVarSecret::new("CLIENT_SECRET", &StringEncoding)?;
//! # let client_auth: ClientSecret = ClientSecret::new(env_secret);
//!
//! let grant: JwtBearerGrant = JwtBearerGrant::builder()
//!     .token_endpoint("https://my-server/token".parse()?)
//!     .client_id("client_id")
//!     .http_client(client)
//!     .client_auth(client_auth)
//!     .build();
//! # Ok(())
//! # }
//! ```
//!
//! ## 4. Get an access token.
//!
//! The `assertion` is the signed JWT from [Creating the assertion
//! JWT](#creating-the-assertion-jwt).
//!
//! ```rust
//! use huskarl::prelude::*; // Imports OAuth2ExchangeGrant which defines the exchange call.
//! use huskarl::grant::jwt_bearer::JwtBearerGrantParameters;
//! use huskarl::token::AccessToken;
//! # use huskarl::grant::jwt_bearer::JwtBearerGrant;
//! use huskarl::core::client_auth::ClientSecret;
//! # use huskarl::core::http::HttpClient;
//! # use huskarl::core::secrets::EnvVarSecret;
//! # use huskarl::core::secrets::encodings::StringEncoding;
//! # async fn run(assertion: String) -> Result<(), Box<dyn std::error::Error>> {
//! # let client = huskarl_reqwest::ReqwestClient::builder()
//! #     .build()
//! #     .await?;
//! #
//! # let client_auth: ClientSecret = ClientSecret::new(EnvVarSecret::new("CLIENT_SECRET", &StringEncoding)?);
//! #
//! # let grant: JwtBearerGrant = JwtBearerGrant::builder()
//! #     .token_endpoint("https://my-server/token".parse()?)
//! #     .client_id("client_id")
//! #     .http_client(client)
//! #     .client_auth(client_auth)
//! #     .build();
//!
//! let params = JwtBearerGrantParameters::builder()
//!     .assertion(assertion)
//!     .scopes(vec!["read", "write"])
//!     .build();
//! let response = grant.exchange(params).await?;
//! let token: &AccessToken = response.access_token();
//!
//! # Ok(())
//! # }
//! ```
//!
//! # Creating the assertion JWT
//!
//! RFC 7523 §3 requires the assertion to be a JWT signed by an issuer the
//! authorization server trusts. The claims identify the trusted issuer of the
//! assertion (`iss`), the principal the token is for (`sub`), and the
//! authorization server as the audience (`aud`); `exp` and `iat` bound its
//! lifetime. Build and sign one with [`Jwt`](crate::core::jwt::Jwt) and any
//! [`JwsSigner`](crate::core::crypto::signer::JwsSigner) (here, a freshly
//! generated key — in practice load a long-lived key the server trusts):
//!
//! The [`SecretString`] returned by `to_jws_compact` can be passed straight to
//! [`JwtBearerGrantParameters::builder().assertion(..)`](JwtBearerGrantParameters)
//! — the setter accepts any `Into<SecretString>` (`&str`, `String`, or
//! `SecretString`).
//!
//! ```rust
//! use std::time::Duration;
//!
//! use huskarl::core::{jwt::Jwt, secrets::SecretString};
//! use huskarl_crypto_native::asymmetric::signer::{GenerateAlgorithm, PrivateKey};
//!
//! # async fn make_assertion() -> Result<SecretString, Box<dyn std::error::Error>> {
//! let key = PrivateKey::generate(GenerateAlgorithm::Es256, None)?;
//!
//! let jwt = Jwt::builder()
//!     .issuer("https://issuer.example.com") // who vouches for the assertion (iss)
//!     .subject("user@example.com") // the principal the token is for (sub)
//!     .audience("https://my-issuer") // the authorization server (aud)
//!     .issued_now_expires_after(Duration::from_secs(300))
//!     .claims(())
//!     .build();
//!
//! let assertion = jwt.to_jws_compact(&key).await?;
//! Ok(assertion)
//! # }
//! ```

use std::sync::Arc;

use bon::Builder;
use serde::Serialize;

use crate::{
    core::{
        EndpointUrl,
        client_auth::ClientAuthentication,
        dpop::{AuthorizationServerDPoP, NoDPoP},
        http::HttpClient,
        secrets::SecretString,
    },
    grant::{
        core::{OAuth2ExchangeGrant, mk_scopes},
        refresh::RefreshGrant,
    },
};

/// An `OAuth2` JWT bearer grant (RFC 7523).
///
/// This grant requests an access token by presenting a signed JWT assertion that
/// vouches for the principal the token is for. The assertion is supplied by the
/// caller (see the [module documentation][crate::grant::jwt_bearer] for how to
/// create one); this grant does not mint it.
///
/// See the [module documentation][crate::grant::jwt_bearer] for a usage guide.
#[huskarl_macros::from_metadata(metadata = crate::core::server_metadata::AuthorizationServerMetadata)]
#[derive(Builder)]
#[builder(on(String, into))]
pub struct JwtBearerGrant {
    /// The client ID. Optional: omit it for an unidentified client (the
    /// assertion's `iss`/`sub` identify the principal; RFC 7523 §3.1 allows a
    /// grant with no client identification).
    client_id: Option<String>,

    /// The HTTP client used for token requests.
    #[builder(with = |client: impl HttpClient + 'static| Arc::new(client) as Arc<dyn HttpClient>)]
    http_client: Arc<dyn HttpClient>,

    /// The client authentication method. Optional: the assertion is the grant,
    /// independent of client authentication. Omit it to authenticate the client
    /// in no way; supply [`NoAuth`](crate::core::client_auth::NoAuth) to send the
    /// `client_id` without credentials, or any other
    /// [`ClientAuthentication`] to authenticate.
    #[builder(with = |auth: impl ClientAuthentication + 'static| Arc::new(auth) as Arc<dyn ClientAuthentication>)]
    client_auth: Option<Arc<dyn ClientAuthentication>>,

    /// The `DPoP` signer. Defaults to [`NoDPoP`] (no token sender-constraining).
    #[builder(
        with = |dpop: impl AuthorizationServerDPoP + 'static| Arc::new(dpop) as Arc<dyn AuthorizationServerDPoP>,
        default = Arc::new(NoDPoP),
    )]
    dpop: Arc<dyn AuthorizationServerDPoP>,

    /// The issuer for tokens created by the authorization server.
    #[from_metadata(path = "issuer")]
    issuer: Option<String>,

    /// The URL of the token endpoint.
    #[from_metadata(path = "token_endpoint")]
    token_endpoint: EndpointUrl,

    /// The mTLS alias for the token endpoint (RFC 8705 §5).
    #[from_metadata(path = "mtls_endpoint_aliases?.token_endpoint?")]
    mtls_token_endpoint: Option<EndpointUrl>,

    /// The endpoint used for token requests: the mTLS alias when the HTTP
    /// client uses mTLS, the primary token endpoint otherwise.
    #[builder(skip = crate::grant::core::resolve_mtls_alias(http_client.as_ref(), &token_endpoint, mtls_token_endpoint.as_ref()))]
    effective_token_endpoint: EndpointUrl,

    /// Supported endpoint auth methods; used to auto-select basic or
    /// form auth for client secrets.
    #[from_metadata(path = "token_endpoint_auth_methods_supported")]
    token_endpoint_auth_methods_supported: Option<Vec<String>>,
}

impl core::fmt::Debug for JwtBearerGrant {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("JwtBearerGrant")
            .field("client_id", &self.client_id)
            .field("issuer", &self.issuer)
            .field("token_endpoint", &self.token_endpoint)
            .field("mtls_token_endpoint", &self.mtls_token_endpoint)
            .finish_non_exhaustive()
    }
}

impl OAuth2ExchangeGrant for JwtBearerGrant {
    type Parameters = JwtBearerGrantParameters;
    type Form<'a> = JwtBearerGrantForm;

    /// A valid assertion may be presented repeatedly until it expires.
    fn reusable_parameters(&self) -> bool {
        true
    }

    fn client_id(&self) -> Option<&str> {
        self.client_id.as_deref()
    }

    fn issuer(&self) -> Option<&str> {
        self.issuer.as_deref()
    }

    fn client_auth(&self) -> Option<&dyn ClientAuthentication> {
        self.client_auth.as_deref()
    }

    fn token_endpoint(&self) -> &EndpointUrl {
        &self.token_endpoint
    }

    fn effective_token_endpoint(&self) -> &EndpointUrl {
        &self.effective_token_endpoint
    }

    fn dpop(&self) -> &dyn AuthorizationServerDPoP {
        self.dpop.as_ref()
    }

    fn http_client(&self) -> &dyn HttpClient {
        self.http_client.as_ref()
    }

    fn allowed_auth_methods(&self) -> Option<&[String]> {
        self.token_endpoint_auth_methods_supported.as_deref()
    }

    fn to_refresh_grant(&self) -> RefreshGrant {
        RefreshGrant::builder()
            .maybe_client_id(self.client_id.clone())
            .maybe_issuer(self.issuer.clone())
            .http_client(self.http_client.clone())
            .maybe_client_auth(self.client_auth.clone())
            .dpop(self.dpop.clone())
            .token_endpoint(self.effective_token_endpoint.clone())
            .maybe_token_endpoint_auth_methods_supported(
                self.token_endpoint_auth_methods_supported.clone(),
            )
            .build()
    }

    fn build_form(&self, params: Self::Parameters) -> Self::Form<'_> {
        JwtBearerGrantForm {
            grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
            assertion: params.assertion,
            scope: params.scope,
            resource: params.resource,
        }
    }
}

/// Parameters when requesting a token using the JWT bearer grant.
#[derive(Debug, Clone, Builder)]
pub struct JwtBearerGrantParameters {
    /// The signed JWT assertion (RFC 7523 §2.1).
    ///
    /// Accepts anything that converts into a
    /// [`SecretString`](crate::core::secrets::SecretString) — an already-signed
    /// compact JWS as a `&str` or `String`, or the `SecretString` returned by
    /// [`Jwt::to_jws_compact`](crate::core::jwt::Jwt::to_jws_compact). Held
    /// redacted; serialized only when the request is sent. See the [module
    /// documentation][crate::grant::jwt_bearer#creating-the-assertion-jwt] for how
    /// to build and sign one.
    #[builder(into)]
    assertion: SecretString,
    /// The requested scope(s) for the access token.
    #[builder(required, default, name = "scopes", with = |scopes: impl IntoIterator<Item = impl Into<String>>| mk_scopes(scopes))]
    scope: Option<String>,
    /// The target resource(s) for the access token (RFC 8707).
    resource: Option<Vec<String>>,
}

/// JWT bearer grant body.
#[derive(Debug, Serialize)]
pub struct JwtBearerGrantForm {
    grant_type: &'static str,
    assertion: SecretString,
    #[serde(skip_serializing_if = "Option::is_none")]
    scope: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    resource: Option<Vec<String>>,
}

#[cfg(all(test, not(target_family = "wasm")))]
mod tests {
    use std::sync::LazyLock;

    use httpmock::MockServer;
    use huskarl_crypto_native::asymmetric::signer::{GenerateAlgorithm, PrivateKey};
    use huskarl_reqwest::ReqwestClient;
    use serde_json::json;

    use crate::{
        core::{client_auth::NoAuth, dpop::DPoP, secrets::SecretString},
        grant::jwt_bearer::{JwtBearerGrant, JwtBearerGrantParameters},
        token::AccessToken,
    };

    static MOCK_SERVER: LazyLock<MockServer> = LazyLock::new(MockServer::start);

    fn http_client() -> ReqwestClient {
        reqwest::Client::new().into()
    }

    #[test]
    fn test_assertion_setter_accepts_str_string_and_secret() {
        // &str, String, and the SecretString from `to_jws_compact` all convert in.
        for assertion in [
            JwtBearerGrantParameters::builder()
                .assertion("a.b.c")
                .build(),
            JwtBearerGrantParameters::builder()
                .assertion(String::from("a.b.c"))
                .build(),
            JwtBearerGrantParameters::builder()
                .assertion(SecretString::new("a.b.c"))
                .build(),
        ] {
            assert_eq!(assertion.assertion.expose_secret(), "a.b.c");
        }
    }

    #[test]
    fn test_form_serializes_grant_type_and_assertion() {
        let form = super::JwtBearerGrantForm {
            grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
            assertion: SecretString::new("header.payload.signature"),
            scope: None,
            resource: None,
        };
        let encoded = serde_html_form::to_string(&form).unwrap();
        assert!(
            encoded.contains("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer"),
            "grant_type not found in: {encoded}"
        );
        assert!(
            encoded.contains("assertion=header.payload.signature"),
            "assertion not found in: {encoded}"
        );
        // Optional fields are omitted when absent.
        assert!(
            !encoded.contains("scope="),
            "scope should be omitted: {encoded}"
        );
    }

    #[tokio::test]
    async fn test_exchange() {
        use httpmock::prelude::*;

        use crate::prelude::*;

        let grant = JwtBearerGrant::builder()
            .token_endpoint(MOCK_SERVER.url("/no_dpop/token").parse().unwrap())
            .client_id("client")
            .http_client(http_client())
            .client_auth(NoAuth)
            .build();

        let mock = MOCK_SERVER
            .mock_async(|when, then| {
                when.method(POST)
                    .path("/no_dpop/token")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header_missing("DPoP")
                    .form_urlencoded_tuple(
                        "grant_type",
                        "urn:ietf:params:oauth:grant-type:jwt-bearer",
                    )
                    .form_urlencoded_tuple("assertion", "the.signed.assertion")
                    .form_urlencoded_tuple("client_id", "client");
                then.status(200)
                    .header("Content-Type", "application/json")
                    .json_body(json!({
                        "access_token": "access_token",
                        "token_type": "Bearer",
                    }));
            })
            .await;

        let response = grant
            .exchange(
                JwtBearerGrantParameters::builder()
                    .assertion("the.signed.assertion")
                    .build(),
            )
            .await;

        mock.assert();
        let response = response.unwrap();

        assert!(matches!(response.access_token(), AccessToken::Bearer(_)));
        assert_eq!(
            response.access_token().token().expose_secret(),
            "access_token"
        );
    }

    #[tokio::test]
    async fn test_exchange_anonymous_sends_no_client_id_or_auth() {
        use httpmock::prelude::*;

        use crate::prelude::*;

        // Neither `client_auth` nor `client_id` supplied: the assertion is the
        // grant, so an unidentified, unauthenticated request is valid
        // (RFC 7523 §3.1).
        let grant = JwtBearerGrant::builder()
            .token_endpoint(MOCK_SERVER.url("/anon/token").parse().unwrap())
            .http_client(http_client())
            .build();

        let mock = MOCK_SERVER
            .mock_async(|when, then| {
                when.method(POST)
                    .path("/anon/token")
                    .form_urlencoded_tuple(
                        "grant_type",
                        "urn:ietf:params:oauth:grant-type:jwt-bearer",
                    )
                    .form_urlencoded_tuple("assertion", "the.signed.assertion")
                    .form_urlencoded_tuple_missing("client_id")
                    .form_urlencoded_tuple_missing("client_secret")
                    .header_missing("Authorization");
                then.status(200)
                    .header("Content-Type", "application/json")
                    .json_body(json!({
                        "access_token": "access_token",
                        "token_type": "Bearer",
                    }));
            })
            .await;

        let response = grant
            .exchange(
                JwtBearerGrantParameters::builder()
                    .assertion("the.signed.assertion")
                    .build(),
            )
            .await;

        mock.assert();
        assert!(response.is_ok());
    }

    #[tokio::test]
    async fn test_exchange_with_dpop() {
        use httpmock::prelude::*;

        use crate::prelude::*;

        let grant = JwtBearerGrant::builder()
            .token_endpoint(MOCK_SERVER.url("/with_dpop/token").parse().unwrap())
            .client_id("client")
            .http_client(http_client())
            .client_auth(NoAuth)
            .dpop(
                DPoP::builder()
                    .signer(PrivateKey::generate(GenerateAlgorithm::Es256, None).unwrap())
                    .build(),
            )
            .build();

        let mock = MOCK_SERVER
            .mock_async(|when, then| {
                when.method(POST)
                    .path("/with_dpop/token")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header_exists("DPoP")
                    .form_urlencoded_tuple(
                        "grant_type",
                        "urn:ietf:params:oauth:grant-type:jwt-bearer",
                    )
                    .form_urlencoded_tuple("assertion", "the.signed.assertion");
                then.status(200)
                    .header("Content-Type", "application/json")
                    .json_body(json!({
                        "access_token": "access_token",
                        "token_type": "DPoP",
                    }));
            })
            .await;

        let response = grant
            .exchange(
                JwtBearerGrantParameters::builder()
                    .assertion("the.signed.assertion")
                    .build(),
            )
            .await;

        mock.assert();
        let response = response.unwrap();

        assert!(matches!(response.access_token(), AccessToken::Dpop(_)));
        assert_eq!(
            response.access_token().token().expose_secret(),
            "access_token"
        );
    }
}