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
use std::borrow::Cow;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::jwk::PublicJwk;

/// The `cnf` (confirmation) claim, used to bind a JWT to a key (RFC 7800).
///
/// Only `jkt` (`DPoP` key thumbprint, RFC 9449) and `x5t#S256` (mTLS certificate
/// thumbprint, RFC 8705 §4) are the well-known members. `jwe` and `jku` are
/// captured to allow callers to detect and reject them.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfirmationClaim {
    /// The JWK thumbprint of the `DPoP` key bound to this token (RFC 9449 §4.2).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jkt: Option<String>,
    /// The SHA-256 thumbprint of the client certificate bound to this token (RFC 8705 §4).
    #[serde(rename = "x5t#S256", skip_serializing_if = "Option::is_none")]
    pub x5t_s256: Option<String>,
    /// Encrypted key confirmation (RFC 7800 §3.3).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jwe: Option<serde_json::Value>,
    /// JWK Set URL confirmation (RFC 7800 §3.5).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jku: Option<serde_json::Value>,
}

fn serialize_string_or_vec<S>(values: &'_ Vec<String>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    use serde::ser::SerializeSeq as _;

    match values.len() {
        0 => serializer.serialize_none(),
        1 => serializer.serialize_str(values[0].as_ref()),
        n => {
            let mut seq = serializer.serialize_seq(Some(n))?;
            for element in values {
                seq.serialize_element(element)?;
            }
            seq.end()
        }
    }
}

fn deserialize_string_or_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de;

    struct StringOrVec;

    impl<'de> de::Visitor<'de> for StringOrVec {
        type Value = Vec<String>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a string or array of strings")
        }

        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(vec![v])
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(vec![v.to_owned()])
        }

        fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(vec![v.to_owned()])
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: serde::de::SeqAccess<'de>,
        {
            let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(1));
            while let Some(value) = seq.next_element()? {
                vec.push(value);
            }
            Ok(vec)
        }

        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_any(self)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Vec::new())
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Vec::new())
        }
    }

    deserializer.deserialize_any(StringOrVec)
}

fn deserialize_whole_or_fractional<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de;

    struct WholeOrFractionalOrNull;

    impl<'de> de::Visitor<'de> for WholeOrFractionalOrNull {
        type Value = Option<u64>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a positive numeric value, or null")
        }

        fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Some(v))
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            if v < 0 {
                return Err(E::custom("cannot have a negative value"));
            }

            Ok(Some(v.cast_unsigned()))
        }

        #[allow(clippy::cast_possible_truncation)]
        #[allow(clippy::cast_precision_loss)]
        #[allow(clippy::cast_sign_loss)]
        fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            if v.is_nan() {
                return Err(E::custom("cannot be NaN"));
            }

            if v < 0.0 || v > u64::MAX as f64 {
                return Err(E::custom("outside u64 range"));
            }

            Ok(Some(v as u64))
        }

        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_any(self)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(None)
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(None)
        }
    }

    deserializer.deserialize_any(WholeOrFractionalOrNull)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound(deserialize = "ExtraHeaders: serde::de::Deserialize<'de>"))]
pub struct JwtHeader<'a, ExtraHeaders: Clone> {
    pub alg: Cow<'a, str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub typ: Option<Cow<'a, str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kid: Option<Cow<'a, str>>,
    /// RFC 7515 §4.1.11: critical header parameters. Any non-empty value means the
    /// verifier MUST understand all listed parameters or reject the JWS entirely.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub crit: Vec<String>,
    /// Embedded public key — present only in `DPoP` proofs (RFC 9449 §4.2).
    /// Must not appear in ordinary JWTs; validators should reject tokens that include
    /// it unless they are specifically processing a `DPoP` proof.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jwk: Option<PublicJwk>,
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub extra_headers: Option<Cow<'a, ExtraHeaders>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound(deserialize = "Claims: serde::de::Deserialize<'de>"))]
pub struct JwtClaims<'a, Claims: Clone> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iss: Option<Cow<'a, str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub: Option<Cow<'a, str>>,
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "deserialize_string_or_vec",
        serialize_with = "serialize_string_or_vec"
    )]
    pub aud: Vec<String>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_whole_or_fractional"
    )]
    pub iat: Option<u64>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_whole_or_fractional"
    )]
    pub exp: Option<u64>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_whole_or_fractional"
    )]
    pub nbf: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<Cow<'a, str>>,
    /// Key confirmation claim (RFC 7800). Binds the token to a `DPoP` key or mTLS certificate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cnf: Option<ConfirmationClaim>,
    /// Additional claims beyond the registered JWT claim set.
    #[serde(flatten)]
    pub claims: Cow<'a, Claims>,
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    // --- aud serialization ---

    #[test]
    fn aud_serialize_empty() {
        let claims = JwtClaims::<'static, ()> {
            iss: None,
            sub: None,
            aud: vec![],
            iat: None,
            exp: None,
            nbf: None,
            jti: None,
            cnf: None,
            claims: Cow::Owned(()),
        };
        let v = serde_json::to_value(&claims).unwrap();
        assert!(v.get("aud").is_none());
    }

    #[test]
    fn aud_serialize_single() {
        let claims = JwtClaims::<'static, ()> {
            iss: None,
            sub: None,
            aud: vec!["https://example.com".into()],
            iat: None,
            exp: None,
            nbf: None,
            jti: None,
            cnf: None,
            claims: Cow::Owned(()),
        };
        let v = serde_json::to_value(&claims).unwrap();
        assert_eq!(v["aud"], json!("https://example.com"));
    }

    #[test]
    fn aud_serialize_multiple() {
        let claims = JwtClaims::<'static, ()> {
            iss: None,
            sub: None,
            aud: vec!["a".into(), "b".into()],
            iat: None,
            exp: None,
            nbf: None,
            jti: None,
            cnf: None,
            claims: Cow::Owned(()),
        };
        let v = serde_json::to_value(&claims).unwrap();
        assert_eq!(v["aud"], json!(["a", "b"]));
    }

    // --- aud deserialization ---

    #[test]
    fn aud_deserialize_string() {
        let j = r#"{"aud":"x"}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.aud, vec!["x"]);
    }

    #[test]
    fn aud_deserialize_array() {
        let j = r#"{"aud":["a","b"]}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.aud, vec!["a", "b"]);
    }

    #[test]
    fn aud_deserialize_null() {
        let j = r#"{"aud":null}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert!(c.aud.is_empty());
    }

    #[test]
    fn aud_deserialize_absent() {
        let j = r"{}";
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert!(c.aud.is_empty());
    }

    // --- Timestamp deserialization ---

    #[test]
    fn timestamp_integer() {
        let j = r#"{"iat":1234}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.iat, Some(1234));
    }

    #[test]
    fn timestamp_float_truncates() {
        let j = r#"{"iat":1234.5}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.iat, Some(1234));
    }

    #[test]
    fn timestamp_negative_errors() {
        let j = r#"{"iat":-1}"#;
        let result = serde_json::from_str::<JwtClaims<'_, ()>>(j);
        assert!(result.is_err());
    }

    #[test]
    fn timestamp_null() {
        let j = r#"{"iat":null}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.iat, None);
    }

    #[test]
    fn timestamp_absent() {
        let j = r"{}";
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.iat, None);
        assert_eq!(c.exp, None);
        assert_eq!(c.nbf, None);
    }

    #[test]
    fn all_timestamps() {
        let j = r#"{"iat":100,"exp":200,"nbf":50}"#;
        let c: JwtClaims<'_, ()> = serde_json::from_str(j).unwrap();
        assert_eq!(c.iat, Some(100));
        assert_eq!(c.exp, Some(200));
        assert_eq!(c.nbf, Some(50));
    }

    // --- ConfirmationClaim roundtrip ---

    #[test]
    fn confirmation_claim_roundtrip() {
        let cnf = ConfirmationClaim {
            jkt: Some("thumbprint-value".into()),
            x5t_s256: Some("cert-thumbprint".into()),
            jwe: None,
            jku: None,
        };
        let json = serde_json::to_string(&cnf).unwrap();
        assert!(json.contains("\"jkt\""));
        assert!(json.contains("\"x5t#S256\""));

        let roundtripped: ConfirmationClaim = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtripped.jkt.as_deref(), Some("thumbprint-value"));
        assert_eq!(roundtripped.x5t_s256.as_deref(), Some("cert-thumbprint"));
    }

    #[test]
    fn confirmation_claim_skips_none() {
        let cnf = ConfirmationClaim {
            jkt: None,
            x5t_s256: None,
            jwe: None,
            jku: None,
        };
        let json = serde_json::to_string(&cnf).unwrap();
        assert_eq!(json, "{}");
    }
}