huskarl-core 0.6.3

Base library for huskarl (OAuth2 client) ecosystem.
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
use std::{borrow::Cow, convert::Infallible};

use base64::prelude::*;
use bon::Builder;
use serde::Serialize;
use snafu::prelude::*;

use crate::{
    crypto::signer::JwsSigner,
    jwk::PublicJwk,
    jwt::{
        builder::jwt_builder::{SetClaims, SetExtraHeaders},
        structure::{JwtClaims, JwtHeader},
    },
    platform::{Duration, SystemTime, SystemTimeError},
    secrets::SecretString,
};

/// A built JWT with all information except signing metadata.
///
/// This represents a full JWT that can be signed with information
/// from the signing layer. The signing layer can add the algorithm
/// and key ID information, creates a JWS signature, and builds the
/// final string.
#[non_exhaustive]
#[derive(Debug, Clone, Builder)]
#[builder(
    start_fn(vis = "", name = "builder_internal"),
    generics(setters(name = "with_{}"))
)]
pub struct Jwt<'a, ExtraHeaders = (), Claims = ()>
where
    ExtraHeaders: Serialize + Clone,
    Claims: Serialize + Clone,
{
    /// The type (`typ`) of the JWT.
    #[builder(default = "JWT", into)]
    pub typ: Cow<'a, str>,
    /// The issuer (`iss`) of the JWT.
    #[builder(into)]
    pub issuer: Option<Cow<'a, str>>,
    /// The subject (`sub`) of the JWT.
    #[builder(into)]
    pub subject: Option<Cow<'a, str>>,
    /// The audiences (`aud`) of the JWT.
    #[builder(default, into)]
    pub audiences: Vec<String>,
    /// The number of seconds since the epoch (`iat`) when the JWT was issued.
    pub issued_at: Option<SystemTime>,
    /// The number of seconds since the epoch (`exp`) when the JWT will expire (or has expired).
    pub expiration: Option<SystemTime>,
    /// The number of seconds since the epoch (`nbf`) when the JWT will (or did) become valid.
    pub not_before: Option<SystemTime>,
    /// The unique identifier (`jti`) for this JWT, can be used to avoid replay attacks.
    #[builder(required, into, default = crate::uuid::uuid_v7())]
    pub jti: Option<String>,
    /// Embedded public key (`jwk` header parameter). Present only in `DPoP` proofs (RFC 9449 ยง4.2).
    pub jwk: Option<PublicJwk>,
    /// Extra key/value pairs in the JWT protected header not included above.
    #[builder(setters(vis = "", name = "extra_headers_internal"))]
    pub extra_headers: Option<ExtraHeaders>,
    /// Additional claims beyond the registered JWT claim set.
    #[builder(setters(vis = "", name = "claims_internal"))]
    pub claims: Claims,
}

impl<'a> Jwt<'a, (), ()> {
    /// Creates a new [`JwtBuilder`] with no extra headers or claims.
    pub fn builder() -> JwtBuilder<'a, (), ()> {
        Jwt::<(), ()>::builder_internal()
    }
}

impl<'a, ExtraHeaders, Claims, S: jwt_builder::State> JwtBuilder<'a, ExtraHeaders, Claims, S>
where
    ExtraHeaders: Serialize + Clone,
    Claims: Serialize + Clone,
{
    /// Sets a single audience value for the JWT.
    pub fn audience(
        self,
        audience: impl Into<String>,
    ) -> JwtBuilder<'a, ExtraHeaders, Claims, jwt_builder::SetAudiences<S>>
    where
        S::Audiences: jwt_builder::IsUnset,
    {
        self.audiences(vec![audience.into()])
    }

    /// Sets the issued value for the JWT to the current time.
    ///
    /// # Panics
    ///
    /// This call panics if the reported time is before the epoch.
    pub fn issued_now(self) -> JwtBuilder<'a, ExtraHeaders, Claims, jwt_builder::SetIssuedAt<S>>
    where
        S::IssuedAt: jwt_builder::IsUnset,
    {
        self.issued_at(crate::platform::SystemTime::now())
    }

    /// Sets the issued value for the JWT to the current time, and the expiry time to the current time plus a specified duration.
    ///
    /// # Panics
    ///
    /// This call panics if the reported time is before the epoch.
    pub fn issued_now_expires_after(
        self,
        after: Duration,
    ) -> JwtBuilder<'a, ExtraHeaders, Claims, jwt_builder::SetExpiration<jwt_builder::SetIssuedAt<S>>>
    where
        S::IssuedAt: jwt_builder::IsUnset,
        S::Expiration: jwt_builder::IsUnset,
    {
        let now = crate::platform::SystemTime::now();
        self.issued_at(now).expiration(now + after)
    }

    /// Sets `iat`, `nbf`, and `exp` from a single captured timestamp.
    ///
    /// Equivalent to [`issued_now_expires_after`](Self::issued_now_expires_after) but also sets
    /// `nbf` to the same `now` value, ensuring `iat == nbf` without a race between calls.
    ///
    /// # Panics
    ///
    /// This call panics if the reported time is before the epoch.
    pub fn issued_now_not_before_now_expires_after(
        self,
        after: Duration,
    ) -> JwtBuilder<
        'a,
        ExtraHeaders,
        Claims,
        jwt_builder::SetNotBefore<jwt_builder::SetExpiration<jwt_builder::SetIssuedAt<S>>>,
    >
    where
        S::IssuedAt: jwt_builder::IsUnset,
        S::Expiration: jwt_builder::IsUnset,
        S::NotBefore: jwt_builder::IsUnset,
    {
        let now = crate::platform::SystemTime::now();
        self.issued_at(now).expiration(now + after).not_before(now)
    }

    /// Sets additional claims for the JWT, replacing the current claims type parameter.
    pub fn claims<E2>(self, claims: E2) -> JwtBuilder<'a, ExtraHeaders, E2, SetClaims<S>>
    where
        E2: Serialize + Clone,
        S::Claims: jwt_builder::IsUnset,
    {
        self.with_claims::<E2>().claims_internal(claims)
    }

    /// Sets extra headers for the JWT, replacing the current extra-headers type parameter.
    pub fn extra_headers<E2>(self, headers: E2) -> JwtBuilder<'a, E2, Claims, SetExtraHeaders<S>>
    where
        E2: Serialize + Clone,
        S::ExtraHeaders: jwt_builder::IsUnset,
    {
        self.with_extra_headers::<E2>()
            .extra_headers_internal(headers)
    }
}

#[derive(Debug, Snafu)]
pub enum JwsSigningInputError {
    /// Failed to encode claims as they could not be converted to JSON.
    EncodeClaims {
        /// The underlying error from `serde_json`.
        source: serde_json::Error,
    },
    /// Failed to encode headers as they could not be converted to JSON.
    EncodeHeader {
        /// The underlying error from `serde_json`.
        source: serde_json::Error,
    },
    /// Failed to convert the current time to a JWT-compatible format.
    Time {
        /// The underlying error.
        source: SystemTimeError,
    },
}

/// Errors that occur when attempting to serialize the JWT.
#[derive(Debug, Snafu)]
pub enum JwsSerializationError<SgnErr: crate::Error + 'static = Infallible> {
    /// Failed to generate the JWT signing input.
    GenerateSigningInput {
        /// The underlying error.
        source: JwsSigningInputError,
    },
    /// Failed to sign the JWT.
    Sign {
        /// The underlying signing error.
        source: SgnErr,
    },
    /// Failed to normalize the URI for use in a `DPoP` proof.
    NormalizeUri {
        /// The underlying HTTP error.
        source: http::Error,
    },
    /// No JWK thumbprint provided for proof.
    ///
    /// This indicates a logic error; the caller should provide a thumbprint
    /// when `DPoP` is configured.
    NoThumbprint,
    /// No matching key was found for the given thumbprint.
    NoMatchingKeyForThumbprint,
}

impl<SgnErr: crate::Error> crate::Error for JwsSerializationError<SgnErr> {
    fn is_retryable(&self) -> bool {
        match self {
            JwsSerializationError::GenerateSigningInput { .. }
            | JwsSerializationError::NormalizeUri { .. }
            | JwsSerializationError::NoMatchingKeyForThumbprint
            | JwsSerializationError::NoThumbprint => false,
            JwsSerializationError::Sign { source } => source.is_retryable(),
        }
    }
}

impl<ExtraHeaders, Claims> Jwt<'_, ExtraHeaders, Claims>
where
    ExtraHeaders: Serialize + Clone,
    Claims: Serialize + Clone,
{
    /// Creates a string using the JWS compact serialization.
    ///
    /// The key must already have been selected by the caller.
    ///
    /// # Errors
    ///
    /// Returns an error if the JWT could not be serialized to JSON, or signing failed.
    pub async fn to_jws_compact<Sgn: JwsSigner>(
        &self,
        signer: &Sgn,
    ) -> Result<SecretString, JwsSerializationError<Sgn::Error>> {
        let signing_input = self
            .generate_jwt_signing_input(&signer.jws_algorithm(), signer.key_id().as_deref())
            .context(GenerateSigningInputSnafu)?;

        let signature = signer
            .sign(signing_input.as_bytes())
            .await
            .context(SignSnafu)?;

        let signature_b64 = BASE64_URL_SAFE_NO_PAD.encode(&signature);
        let result = [signing_input, signature_b64].join(".");

        Ok(SecretString::new(result))
    }

    fn generate_jwt_signing_input(
        &self,
        alg: &str,
        kid: Option<&str>,
    ) -> Result<String, JwsSigningInputError> {
        let jwt_header = JwtHeader {
            alg: Cow::Borrowed(alg),
            typ: Some(Cow::Borrowed(&self.typ)),
            kid: kid.map(Cow::Borrowed),
            crit: Vec::new(),
            jwk: self.jwk.clone(),
            extra_headers: self.extra_headers.as_ref().map(Cow::Borrowed),
        };

        let iat = self
            .issued_at
            .map(|iat| {
                iat.duration_since(SystemTime::UNIX_EPOCH)
                    .map(|dur| dur.as_secs())
            })
            .transpose()
            .context(TimeSnafu)?;

        let exp = self
            .expiration
            .map(|exp| {
                exp.duration_since(SystemTime::UNIX_EPOCH)
                    .map(|dur| dur.as_secs())
            })
            .transpose()
            .context(TimeSnafu)?;

        let nbf = self
            .not_before
            .map(|nbf| {
                nbf.duration_since(SystemTime::UNIX_EPOCH)
                    .map(|dur| dur.as_secs())
            })
            .transpose()
            .context(TimeSnafu)?;

        let jwt_claims = JwtClaims {
            iss: self.issuer.as_deref().map(Cow::Borrowed),
            sub: self.subject.as_deref().map(Cow::Borrowed),
            aud: self.audiences.clone(),
            iat,
            exp,
            nbf,
            jti: self.jti.as_deref().map(Cow::Borrowed),
            cnf: None,
            claims: Cow::Borrowed(&self.claims),
        };
        let jwt_header_json = serde_json::to_vec(&jwt_header).context(EncodeHeaderSnafu)?;
        let jwt_header_b64 = BASE64_URL_SAFE_NO_PAD.encode(&jwt_header_json);
        let jwt_claims_json = serde_json::to_vec(&jwt_claims).context(EncodeClaimsSnafu)?;
        let jwt_claims_b64 = BASE64_URL_SAFE_NO_PAD.encode(&jwt_claims_json);

        Ok([jwt_header_b64, jwt_claims_b64].join("."))
    }
}

#[cfg(test)]
mod tests {
    use std::convert::Infallible;

    use base64::prelude::*;
    use serde::Serialize;

    use crate::{crypto::signer::JwsSigner, jwt::Jwt, platform::SystemTime};

    #[derive(Debug, Clone)]
    struct MockJwsSigner {
        alg: &'static str,
        kid: Option<&'static str>,
    }

    impl JwsSigner for MockJwsSigner {
        type Error = Infallible;
        fn jws_algorithm(&self) -> Cow<'_, str> {
            self.alg.into()
        }
        fn key_id(&self) -> Option<Cow<'_, str>> {
            self.kid.map(Into::into)
        }
        async fn sign(&self, _input: &[u8]) -> Result<Vec<u8>, Infallible> {
            Ok(vec![0xDE, 0xAD])
        }
    }

    use std::borrow::Cow;

    #[tokio::test]
    async fn to_jws_compact_basic() {
        let signer = MockJwsSigner {
            alg: "ES256",
            kid: None,
        };
        let jwt = Jwt::builder()
            .jti(Some("test-jti".to_string()))
            .claims(())
            .build();
        let compact = jwt.to_jws_compact(&signer).await.unwrap();
        let parts: Vec<&str> = compact.expose_secret().split('.').collect();
        assert_eq!(parts.len(), 3);

        // Verify header
        let header_json: serde_json::Value =
            serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(parts[0]).unwrap()).unwrap();
        assert_eq!(header_json["alg"], "ES256");
        assert_eq!(header_json["typ"], "JWT");

        // Verify signature is base64url of [0xDE, 0xAD]
        let sig_bytes = BASE64_URL_SAFE_NO_PAD.decode(parts[2]).unwrap();
        assert_eq!(sig_bytes, vec![0xDE, 0xAD]);
    }

    #[tokio::test]
    async fn to_jws_compact_with_all_fields() {
        let signer = MockJwsSigner {
            alg: "RS256",
            kid: Some("key-1"),
        };
        let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
        let exp = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(2_000_000);
        let nbf = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(999_999);

        let jwt = Jwt::builder()
            .issuer("my-issuer")
            .subject("my-subject")
            .audiences(vec!["aud1".into(), "aud2".into()])
            .issued_at(now)
            .expiration(exp)
            .not_before(nbf)
            .jti(Some("unique-id".to_string()))
            .claims(())
            .build();

        let compact = jwt.to_jws_compact(&signer).await.unwrap();
        let parts: Vec<&str> = compact.expose_secret().split('.').collect();

        let header: serde_json::Value =
            serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(parts[0]).unwrap()).unwrap();
        assert_eq!(header["alg"], "RS256");
        assert_eq!(header["kid"], "key-1");
        assert_eq!(header["typ"], "JWT");

        let claims: serde_json::Value =
            serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(parts[1]).unwrap()).unwrap();
        assert_eq!(claims["iss"], "my-issuer");
        assert_eq!(claims["sub"], "my-subject");
        assert_eq!(claims["aud"], serde_json::json!(["aud1", "aud2"]));
        assert_eq!(claims["iat"], 1_000_000);
        assert_eq!(claims["exp"], 2_000_000);
        assert_eq!(claims["nbf"], 999_999);
        assert_eq!(claims["jti"], "unique-id");
    }

    #[tokio::test]
    async fn to_jws_compact_with_extra_headers_and_claims() {
        #[derive(Debug, Clone, Serialize)]
        struct ExtraHeaders {
            nonce: String,
        }

        #[derive(Debug, Clone, Serialize)]
        struct ExtraClaims {
            scope: String,
        }

        let signer = MockJwsSigner {
            alg: "ES256",
            kid: None,
        };
        let jwt = Jwt::builder()
            .jti(Some("jti-val".to_string()))
            .extra_headers(ExtraHeaders {
                nonce: "abc123".into(),
            })
            .claims(ExtraClaims {
                scope: "openid".into(),
            })
            .build();

        let compact = jwt.to_jws_compact(&signer).await.unwrap();
        let parts: Vec<&str> = compact.expose_secret().split('.').collect();

        let header: serde_json::Value =
            serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(parts[0]).unwrap()).unwrap();
        assert_eq!(header["nonce"], "abc123");

        let claims: serde_json::Value =
            serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(parts[1]).unwrap()).unwrap();
        assert_eq!(claims["scope"], "openid");
    }

    #[tokio::test]
    async fn to_jws_compact_no_kid() {
        let signer = MockJwsSigner {
            alg: "EdDSA",
            kid: None,
        };
        let jwt = Jwt::builder().jti(Some("j".to_string())).claims(()).build();
        let compact = jwt.to_jws_compact(&signer).await.unwrap();
        let parts: Vec<&str> = compact.expose_secret().split('.').collect();

        let header: serde_json::Value =
            serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(parts[0]).unwrap()).unwrap();
        assert!(header.get("kid").is_none());
    }
}