huskarl 0.9.1

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
//! 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)). The
//! assertion is caller-supplied and already signed — the library does not mint it.
//!
//! See the [JWT bearer how-to guide](crate::_docs::guide::jwt_bearer) for
//! step-by-step setup, including how to build and sign the assertion JWT.

use std::sync::Arc;

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

use crate::{
    cache::GrantParametersSource,
    core::{
        EndpointUrl, Error,
        client_auth::ClientAuthentication,
        dpop::{AuthorizationServerDPoP, NoDPoP},
        http::HttpClient,
        platform::MaybeSendBoxFuture,
        secrets::SecretString,
    },
    grant::{
        core::{OAuth2ExchangeGrant, join_space},
        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
    /// (see the [module docs](self#usage)). Omit it to send no client
    /// credentials, 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;

    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: join_space(params.scope.as_deref()),
            resource: params.resource,
            authorization_details: params.authorization_details,
        }
    }
}

/// 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`] — 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.
    scope: Option<Vec<String>>,
    /// The target resource(s) for the access token (RFC 8707).
    resource: Option<Vec<String>>,
    /// RFC 9396 `authorization_details` requested for the issued access token.
    authorization_details: Option<Vec<crate::core::AuthorizationDetail>>,
}

/// A JWT bearer assertion may be presented repeatedly until it expires, so this
/// fixed source clones the same assertion for each exchange — fine while it is
/// valid, but once its `exp` passes the cache cannot obtain a new token. For an
/// assertion the client mints itself, use a [`from_fn`](crate::cache::from_fn)
/// source that re-signs a fresh assertion per exchange.
impl GrantParametersSource<Self> for JwtBearerGrantParameters {
    fn acquire(&self) -> MaybeSendBoxFuture<'_, Result<Option<Self>, Error>> {
        let params = self.clone();
        Box::pin(async move { Ok(Some(params)) })
    }

    // A rejected (e.g. expired) assertion will only be rejected again; stop
    // replaying it.
    fn discard_after_rejection(&self) -> bool {
        true
    }
}

/// JWT bearer grant body.
#[derive(Debug, Serialize, Builder)]
pub struct JwtBearerGrantForm {
    grant_type: &'static str,
    assertion: SecretString,
    scope: Option<String>,
    resource: Option<Vec<String>>,
    /// RFC 9396 `authorization_details` requested for the issued access token.
    authorization_details: Option<Vec<crate::core::AuthorizationDetail>>,
}

#[cfg(test)]
#[cfg(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::builder()
            .grant_type("urn:ietf:params:oauth:grant-type:jwt-bearer")
            .assertion(SecretString::new("header.payload.signature"))
            .build();
        let encoded = crate::core::oauth_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"
        );
    }
}