pdk-jwt-lib 1.10.0

PDK JWT 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

//! JWT claims and data structures
//!
//! This module provides data structures for representing JWT claims and headers.
//! It includes support for standard JWT claims, custom claims and claim validation.

use crate::error::jwt_error::JWTError;
use crate::parser::jwt_claims_parser::JWTClaimsParser;
use chrono::{DateTime, TimeZone, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

#[cfg(not(any(feature = "fips", fips)))]
use jwt_compact::Token;
#[cfg(not(any(feature = "fips", fips)))]
use jwt_simple::prelude::{Audiences, UnixTimeStamp};

/// JWT available claims.
pub mod claim_names {
    /// Audience claim.
    pub const AUD_CLAIM: &str = "aud";
    /// Subject claim.
    pub const SUBJECT_CLAIM: &str = "sub";
    /// Issuer claim.
    pub const ISSUER_CLAIM: &str = "iss";
    /// JWT ID claim.
    pub const JTI_CLAIM: &str = "jti";
    /// Nonce claim.
    pub const NONCE_CLAIM: &str = "nonce";
    /// Expiration claim.
    pub const EXPIRATION_CLAIM: &str = "exp";
    /// Not before claim.
    pub const NOT_BEFORE_CLAIM: &str = "nbf";
    /// Issued at claim.
    pub const ISSUED_AT_CLAIM: &str = "iat";
}

use claim_names::*;
use pdk_script::IntoValue;

/// Claim Structures to hold custom claims.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomClaims {
    /// Inner custom claims.
    #[serde(flatten)]
    pub inner: HashMap<String, serde_json::Value>,
}

/// The JWT decoded content. It consists of 2 key-value maps: one for
/// the JWT header and another one for the JWT body.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct JWTClaims {
    #[serde(flatten)]
    pub(crate) claims: HashMap<String, serde_json::Value>,
    #[serde(flatten)]
    pub(crate) headers: HashMap<String, serde_json::Value>,
}

impl JWTClaims {
    /// Create a new [`JWTClaims`] with the given expiration,
    /// not before, issued at, claims and headers.
    pub fn new(
        expiration: Option<DateTime<Utc>>,
        not_before: Option<DateTime<Utc>>,
        issued_at: Option<DateTime<Utc>>,
        claims: HashMap<String, Value>,
        headers: HashMap<String, Value>,
    ) -> Result<Self, JWTError> {
        let mut claims = claims;

        extract_datetime_value(EXPIRATION_CLAIM, &expiration, &mut claims);
        extract_datetime_value(NOT_BEFORE_CLAIM, &not_before, &mut claims);
        extract_datetime_value(ISSUED_AT_CLAIM, &issued_at, &mut claims);

        Ok(JWTClaims { claims, headers })
    }

    /// Get the audience claim.
    pub fn audience(&self) -> Option<Result<Vec<String>, JWTError>> {
        self.claims.get(AUD_CLAIM).map(parse_audiences_to_list)
    }

    /// Get the not before claim.
    pub fn not_before(&self) -> Option<DateTime<Utc>> {
        self.get_claim(NOT_BEFORE_CLAIM)
    }

    /// Get the expiration claim.
    pub fn expiration(&self) -> Option<DateTime<Utc>> {
        self.get_claim(EXPIRATION_CLAIM)
    }

    /// Get the issued at claim.
    pub fn issued_at(&self) -> Option<DateTime<Utc>> {
        self.get_claim(ISSUED_AT_CLAIM)
    }

    /// Get the issuer claim.
    pub fn issuer(&self) -> Option<String> {
        self.get_claim(ISSUER_CLAIM)
    }

    /// Get the JWT ID claim.
    pub fn jti(&self) -> Option<String> {
        self.get_claim(JTI_CLAIM)
    }

    /// Get the nonce claim.
    pub fn nonce(&self) -> Option<String> {
        self.get_claim(NONCE_CLAIM)
    }

    /// Get the subject claim.
    pub fn subject(&self) -> Option<String> {
        self.get_claim(SUBJECT_CLAIM)
    }

    /// Check if a specific claim exists.
    pub fn has_claim(&self, name: &str) -> bool {
        self.claims.contains_key(name)
    }

    /// Get a specific claim by name with type conversion.
    pub fn get_claim<T>(&self, name: &str) -> Option<T>
    where
        T: ValueRetrieval,
    {
        let value = self.claims.get(name);

        match value {
            Some(val) => T::retrieve(val.clone()),
            None => None,
        }
    }

    /// Check if a specific header exists.
    pub fn has_header(&self, name: &str) -> bool {
        self.headers.contains_key(name)
    }

    /// Get a specific header by name as string.
    pub fn get_header(&self, name: &str) -> Option<String> {
        let value = self.headers.get(name);

        match value {
            Some(val) => val.as_str().map(|str| str.into()),
            None => None,
        }
    }

    /// Serialize the claims to a [`Value`].
    pub fn to_serde(&self) -> Result<Value, JWTError> {
        serde_json::to_value(self)
            .map_err(|e| JWTError::TokenParseFailed(format!("Error serializing claims: {e}")))
    }

    /// Get all JWT claims as PDK script value.
    pub fn get_claims(&self) -> pdk_script::Value {
        self.claims.clone().into_value()
    }

    /// Get all JWT headers as PDK script value.
    pub fn get_headers(&self) -> pdk_script::Value {
        self.headers.clone().into_value()
    }
}

fn parse_audiences_to_list(aud: &Value) -> Result<Vec<String>, JWTError> {
    let correct_type = if aud.is_string() || aud.is_array() {
        Ok(aud)
    } else {
        Err(JWTError::ClaimAudValidationFailed)
    }?;

    if correct_type.is_string() {
        let aud_str = correct_type
            .as_str()
            .ok_or(JWTError::ClaimAudValidationFailed)?;
        Ok(vec![String::from(aud_str)])
    } else {
        let aud_array = correct_type
            .as_array()
            .ok_or(JWTError::ClaimAudValidationFailed)?;

        Ok(aud_array
            .iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect::<Vec<String>>())
    }
}

/// FIPS-safe representation of the standard + custom claims decoded from a JWT
/// payload. Replaces jwt-compact's `Claims<CustomClaims>` on the shared parsing
/// path so it carries no RustCrypto dependency.
pub struct RawClaims {
    /// Expiration (`exp`) claim.
    pub expiration: Option<DateTime<Utc>>,
    /// Not-before (`nbf`) claim.
    pub not_before: Option<DateTime<Utc>>,
    /// Issued-at (`iat`) claim.
    pub issued_at: Option<DateTime<Utc>>,
    /// Remaining (custom) claims.
    pub custom: CustomClaims,
}

impl RawClaims {
    /// Decode claims from a raw (base64-decoded) JSON payload. Standard numeric
    /// date claims (`exp`, `nbf`, `iat`) are parsed as seconds since the epoch
    /// (fractional seconds truncated) and removed from the custom map, matching
    /// jwt-compact's `Claims` split of standard vs custom fields.
    pub fn from_json_slice(payload: &[u8]) -> Result<Self, JWTError> {
        let mut inner: HashMap<String, Value> = serde_json::from_slice(payload)?;
        let expiration = take_timestamp(&mut inner, EXPIRATION_CLAIM)?;
        let not_before = take_timestamp(&mut inner, NOT_BEFORE_CLAIM)?;
        let issued_at = take_timestamp(&mut inner, ISSUED_AT_CLAIM)?;
        Ok(RawClaims {
            expiration,
            not_before,
            issued_at,
            custom: CustomClaims { inner },
        })
    }
}

/// Remove a standard date claim and parse it as a NumericDate (seconds since the
/// epoch, fractional part truncated). Returns `Ok(None)` when the claim is
/// absent, but `Err` when it is present with a non-numeric type — a present but
/// malformed date must reject the token (matching jwt-compact's behavior),
/// never be silently dropped (which would disable expiry / not-before checks).
fn take_timestamp(
    inner: &mut HashMap<String, Value>,
    key: &str,
) -> Result<Option<DateTime<Utc>>, JWTError> {
    let value = match inner.remove(key) {
        Some(value) => value,
        None => return Ok(None),
    };
    // `as_f64` (not `as_i64`) because JSON NumericDate values are commonly
    // encoded with a fractional part (e.g. `1693988656.597`); `as_i64` would
    // reject those valid tokens. We then truncate to whole seconds for the
    // `DateTime` (matching jwt-compact, which also drops sub-second precision).
    let secs = value.as_f64().ok_or_else(|| {
        JWTError::TokenParseFailed(format!("Claim '{key}' is not a numeric date"))
    })?;
    // RFC 7519 NumericDate is a non-negative number of seconds since the epoch.
    // Reject negatives (and non-finite values): a negative `nbf` is always "in
    // the past" and would silently pass the not-before check.
    if !secs.is_finite() || secs < 0.0 {
        return Err(JWTError::TokenParseFailed(format!(
            "Claim '{key}' is not a valid NumericDate"
        )));
    }
    Utc.timestamp_opt(secs as i64, 0)
        .single()
        .map(Some)
        .ok_or_else(|| JWTError::TokenParseFailed(format!("Claim '{key}' is out of range")))
}

/// Trait to convert raw (unverified) JWT claims to [`JWTClaims`].
pub trait TryFromRawClaims {
    fn try_from_raw_claims(claims: RawClaims, token: String) -> Result<JWTClaims, JWTError>;
}

impl TryFromRawClaims for JWTClaims {
    fn try_from_raw_claims(claims: RawClaims, token: String) -> Result<JWTClaims, JWTError> {
        let headers: HashMap<String, Value> = JWTClaimsParser::parse_headers(token)?;

        JWTClaims::new(
            claims.expiration,
            claims.not_before,
            claims.issued_at,
            claims.custom.inner,
            headers,
        )
    }
}

/// Trait to convert trusted JWT compact claims to [`JWTClaims`].
#[cfg(not(any(feature = "fips", fips)))]
pub trait TryFromTrustedJWTCompactClaims {
    fn try_from_trusted_jwt_compact_claims(
        claims: Token<CustomClaims>,
        token: String,
    ) -> Result<JWTClaims, JWTError>;
}

#[cfg(not(any(feature = "fips", fips)))]
impl TryFromTrustedJWTCompactClaims for JWTClaims {
    fn try_from_trusted_jwt_compact_claims(
        trusted_token: Token<CustomClaims>,
        token_str: String,
    ) -> Result<Self, JWTError> {
        let claims = trusted_token.claims().to_owned();

        let raw = RawClaims {
            expiration: claims.expiration,
            not_before: claims.not_before,
            issued_at: claims.issued_at,
            custom: claims.custom,
        };

        JWTClaims::try_from_raw_claims(raw, token_str)
    }
}

/// Trait to convert trusted JWT simple claims to [`JWTClaims`].
#[cfg(not(any(feature = "fips", fips)))]
pub trait TryFromTrustedJWTSimpleClaims {
    fn try_from_trusted_jwt_simple_claims(
        claims: jwt_simple::claims::JWTClaims<CustomClaims>,
        token: String,
    ) -> Result<JWTClaims, JWTError>;
}

#[cfg(not(any(feature = "fips", fips)))]
impl TryFromTrustedJWTSimpleClaims for JWTClaims {
    fn try_from_trusted_jwt_simple_claims(
        claims: jwt_simple::claims::JWTClaims<CustomClaims>,
        token: String,
    ) -> Result<Self, JWTError> {
        let mut custom_claims = claims.custom.inner;

        extract_value(ISSUER_CLAIM, &claims.issuer, &mut custom_claims);
        extract_value(SUBJECT_CLAIM, &claims.subject, &mut custom_claims);
        extract_value(JTI_CLAIM, &claims.jwt_id, &mut custom_claims);
        extract_value(NONCE_CLAIM, &claims.nonce, &mut custom_claims);
        parse_custom_claim_audiences_to_list(claims.audiences, &mut custom_claims);

        extract_numeric_date(EXPIRATION_CLAIM, &claims.expires_at, &mut custom_claims);
        extract_numeric_date(NOT_BEFORE_CLAIM, &claims.invalid_before, &mut custom_claims);
        extract_numeric_date(ISSUED_AT_CLAIM, &claims.issued_at, &mut custom_claims);

        let headers: HashMap<String, Value> = JWTClaimsParser::parse_headers(token)?;

        JWTClaims::new(None, None, None, custom_claims, headers)
    }
}

#[cfg(not(any(feature = "fips", fips)))]
fn parse_custom_claim_audiences_to_list(
    aud: Option<Audiences>,
    custom_claims: &mut HashMap<String, Value>,
) {
    if let Some(audiences) = aud {
        match audiences {
            Audiences::AsSet(set) => {
                if let Ok(value_set) = serde_json::to_value(set) {
                    custom_claims.insert(AUD_CLAIM.to_string(), value_set);
                }
            }
            Audiences::AsString(str) => {
                custom_claims.insert(AUD_CLAIM.to_string(), Value::String(str));
            }
        }
    }
}

/// Trait to be implemented for any sized data type for which a JWT claim wants to casted when
/// retrieved by the [`JWTClaims::get_claim`] method.
pub trait ValueRetrieval {
    fn retrieve(claim_value: serde_json::Value) -> Option<Self>
    where
        Self: Sized;
}

impl ValueRetrieval for Value {
    fn retrieve(claim_value: serde_json::Value) -> Option<Self> {
        Some(claim_value)
    }
}

impl ValueRetrieval for String {
    fn retrieve(claim_value: serde_json::Value) -> Option<Self> {
        Some(claim_value.as_str().unwrap().into())
    }
}

impl ValueRetrieval for f64 {
    fn retrieve(claim_value: serde_json::Value) -> Option<Self> {
        claim_value.as_f64()
    }
}

impl ValueRetrieval for Vec<String> {
    fn retrieve(claim_value: serde_json::Value) -> Option<Self> {
        claim_value.as_array().map(|val| {
            val.iter()
                .map(|item| item.as_str().unwrap().into())
                .collect()
        })
    }
}

impl ValueRetrieval for DateTime<Utc> {
    fn retrieve(claim_value: serde_json::Value) -> Option<Self> {
        claim_value
            .as_i64()
            .and_then(|val| Utc.timestamp_opt(val, 0).earliest())
    }
}

/* Helper functions */

fn extract_datetime_value(
    key: &str,
    datetime: &Option<DateTime<Utc>>,
    custom_claims: &mut HashMap<String, Value>,
) {
    if let Some(datetime) = datetime {
        custom_claims.insert(key.to_string(), Value::from(datetime.timestamp()));
    }
}

#[cfg(not(any(feature = "fips", fips)))]
fn extract_value(
    key: &str,
    claim_value: &Option<String>,
    custom_claims: &mut HashMap<String, Value>,
) {
    if let Some(claim) = claim_value {
        let value = Value::String(claim.to_string());
        custom_claims.insert(key.to_string(), value);
    }
}

#[cfg(not(any(feature = "fips", fips)))]
fn extract_numeric_date(
    key: &str,
    claim_value: &Option<UnixTimeStamp>,
    custom_claims: &mut HashMap<String, Value>,
) {
    if let Some(claim) = claim_value {
        let value = Value::from(claim.as_secs());
        custom_claims.insert(key.to_string(), value);
    }
}

#[cfg(test)]
mod tests {
    use crate::api::JWTClaimsParser;
    use pdk_script::IntoValue;
    use serde_json::json;

    #[cfg(not(any(feature = "fips", fips)))]
    fn valid_token() -> String {
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3JlZGFjdGVkLmFuei5jb20iLCJhdWQiOiJyZWRhY3RlZC5hbnouY29tL2VtYWlsQWRkcmVzcy1yZWRhY3RlZEBhbnouY29tIiwic3ViIjoicmVkYWN0ZWQuYW56LmNvbS9lbWFpbEFkZHJlc3MtcmVkYWN0ZWRAYW56LmNvbSIsImV4cCI6MTY5Mzk4ODY1Ni41OTcsInNjb3BlcyI6WyJyZWRhY3RlZDEiLCJyZWRhY3RlZCJdLCJhbXIiOlsicmVkYWN0ZWQiXSwiYWNyIjoicmVkYWN0ZWQifQ.EswBSyD9976PVC6o4tWwsT5rGTf2RJcvL7hdpcTwXUo"
            .to_string()
    }

    fn no_exp_token() -> String {
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3JlZGFjdGVkLmFuei5jb20iLCJhdWQiOiJyZWRhY3RlZC5hbnouY29tL2VtYWlsQWRkcmVzcy1yZWRhY3RlZEBhbnouY29tIiwic3ViIjoicmVkYWN0ZWQuYW56LmNvbS9lbWFpbEFkZHJlc3MtcmVkYWN0ZWRAYW56LmNvbSIsInNjb3BlcyI6WyJyZWRhY3RlZDEiLCJyZWRhY3RlZCJdLCJhbXIiOlsicmVkYWN0ZWQiXSwiYWNyIjoicmVkYWN0ZWQifQ.vxNPrXPIG8VuGb9Bf2MjLFXPRX9EmN97WZtM-jzQniE"
            .to_string()
    }

    mod tests_accessors {
        use crate::{error::jwt_error::JWTError, model::claims::JWTClaims};
        use chrono::{DateTime, Utc};
        use serde_json::Value;
        use std::collections::HashMap;

        impl JWTClaims {
            /// Create a new empty [`JWTClaims`].
            pub fn empty() -> Result<Self, JWTError> {
                JWTClaims::new(None, None, None, HashMap::default(), HashMap::default())
            }

            /// Create a new [`JWTClaims`] with only expiration claim.
            pub fn just_expiration(expiration: DateTime<Utc>) -> Result<Self, JWTError> {
                JWTClaims::new(
                    Some(expiration),
                    None,
                    None,
                    HashMap::default(),
                    HashMap::default(),
                )
            }

            /// Create a new [`JWTClaims`] with only not before claim.
            pub fn just_not_before(not_before: DateTime<Utc>) -> Result<Self, JWTError> {
                JWTClaims::new(
                    None,
                    Some(not_before),
                    None,
                    HashMap::default(),
                    HashMap::default(),
                )
            }

            /// Create a new [`JWTClaims`] with only custom claims.
            pub fn from_custom_claims(
                custom_claims: HashMap<String, Value>,
            ) -> Result<Self, JWTError> {
                JWTClaims::new(None, None, None, custom_claims, HashMap::default())
            }

            /// Get the number of custom claims.
            pub fn custom_claims_count(&self) -> usize {
                self.claims.len()
            }
        }
    }

    #[test]
    fn basic_methods() {
        let claims = JWTClaimsParser::parse(no_exp_token()).unwrap();

        assert!(claims.has_header("alg"));
        assert!(!claims.has_claim("alg"));
        assert!(claims.has_claim("iss"));
        assert!(!claims.has_header("iss"));

        assert_eq!(
            claims.get_headers(),
            json!({
              "alg": "HS256",
              "typ": "JWT"
            })
            .into_value()
        );

        assert_eq!(
            claims.get_claims(),
            json!(
                {
                  "iss": "https://redacted.anz.com",
                  "aud": "redacted.anz.com/emailAddress-redacted@anz.com",
                  "sub": "redacted.anz.com/emailAddress-redacted@anz.com",
                  "scopes": [
                    "redacted1",
                    "redacted"
                  ],
                  "amr": [
                    "redacted"
                  ],
                  "acr": "redacted"
                }
            )
            .into_value()
        );
    }

    mod audience_claim_extraction {
        use crate::model::claims::{claim_names::AUD_CLAIM, JWTClaims};
        use serde_json::Value::*;
        use serde_json::{Map, Number, Value};
        use std::collections::HashMap;
        use std::string::String;

        #[test]
        fn succeeds_on_string_type() {
            let token_claims = JWTClaims::from_custom_claims(HashMap::from([(
                AUD_CLAIM.to_string(),
                String(String::from("an_audience")),
            )]))
            .unwrap();

            assert!(token_claims.audience().is_some());
            assert!(token_claims.audience().unwrap().is_ok());
            assert_eq!(
                token_claims.audience().unwrap().unwrap(),
                vec![String::from("an_audience")]
            );
        }

        #[test]
        fn succeeds_on_list_type() {
            let token_claims = JWTClaims::from_custom_claims(HashMap::from([(
                AUD_CLAIM.to_string(),
                Array(vec![
                    String(String::from("an_audience1")),
                    String(String::from("an_audience2")),
                ]),
            )]))
            .unwrap();

            assert!(token_claims.audience().is_some());
            assert!(token_claims.audience().unwrap().is_ok());
            assert_eq!(
                token_claims.audience().unwrap().unwrap(),
                vec![String::from("an_audience1"), String::from("an_audience2")]
            );
        }

        #[test]
        fn fails_on_bool_type() {
            let token_claims =
                JWTClaims::from_custom_claims(HashMap::from([(AUD_CLAIM.to_string(), Bool(true))]))
                    .unwrap();

            assert!(token_claims.audience().is_some());
            assert!(token_claims.audience().unwrap().is_err());
        }

        #[test]
        fn fails_on_number_type() {
            let token_claims = JWTClaims::from_custom_claims(HashMap::from([(
                AUD_CLAIM.to_string(),
                Number(Number::from(1u64)),
            )]))
            .unwrap();

            assert!(token_claims.audience().is_some());
            assert!(token_claims.audience().unwrap().is_err());
        }

        #[test]
        fn fails_on_null_type() {
            let token_claims =
                JWTClaims::from_custom_claims(HashMap::from([(AUD_CLAIM.to_string(), Null)]))
                    .unwrap();

            assert!(token_claims.audience().is_some());
            assert!(token_claims.audience().unwrap().is_err());
        }

        #[test]
        fn fails_on_object_type() {
            let token_claims = JWTClaims::from_custom_claims(HashMap::from([(
                AUD_CLAIM.to_string(),
                Object(Map::<String, Value>::new()),
            )]))
            .unwrap();

            assert!(token_claims.audience().is_some());
            assert!(token_claims.audience().unwrap().is_err());
        }
    }

    #[cfg(not(any(feature = "fips", fips)))]
    mod jwt_simple_custom_claims_parsing {
        use super::super::*;
        use chrono::Duration;

        #[test]
        fn huge_exp_defaults_to_max_timestamp() {
            let claims: jwt_simple::claims::JWTClaims<CustomClaims> =
                serde_json::from_str(r#"{"exp":99999999999999999999999999999999}"#).unwrap();

            // 2106-02-07T06:28:15Z -> to increase this limit we need to replace jwt_simple
            let time = UnixTimeStamp::new(u64::MAX, 0);

            assert_eq!(claims.expires_at, Some(time));

            let jwt_claims: JWTClaims =
                JWTClaims::try_from_trusted_jwt_simple_claims(claims, super::valid_token())
                    .unwrap();

            assert_eq!(
                jwt_claims.expiration().unwrap().timestamp(),
                time.as_secs() as i64
            );
            assert_eq!(
                jwt_claims.expiration().unwrap().timestamp(),
                u32::MAX as i64
            );
        }

        #[test]
        fn parse_claims_and_exp() {
            let claims: jwt_simple::claims::JWTClaims<CustomClaims> = serde_json::from_str(r#"{"exp":1617757825, "jti": "key1", "sub": "anSubject", "iss": "anIss", "nonce": "anNonce"}"#).unwrap();

            let expiration = Duration::try_seconds(1617757825).unwrap();

            let jwt_claims: JWTClaims =
                JWTClaims::try_from_trusted_jwt_simple_claims(claims, super::valid_token())
                    .unwrap();

            // Retrieve them as custom claims
            assert_eq!(
                jwt_claims
                    .get_claim::<DateTime<Utc>>("exp")
                    .unwrap()
                    .timestamp_millis(),
                expiration.num_milliseconds()
            );
            assert_eq!(jwt_claims.get_claim::<String>("jti").unwrap(), "key1");
            assert_eq!(jwt_claims.get_claim::<String>("sub").unwrap(), "anSubject");
            assert_eq!(jwt_claims.get_claim::<String>("iss").unwrap(), "anIss");
            assert_eq!(jwt_claims.get_claim::<String>("nonce").unwrap(), "anNonce");
            assert!(jwt_claims.audience().is_none());

            // Retrieve them as standard claims
            assert_eq!(
                jwt_claims.expiration().unwrap().timestamp_millis(),
                expiration.num_milliseconds()
            );
            assert_eq!(jwt_claims.jti().unwrap(), "key1");
            assert_eq!(jwt_claims.subject().unwrap(), "anSubject");
            assert_eq!(jwt_claims.issuer().unwrap(), "anIss");
            assert_eq!(jwt_claims.nonce().unwrap(), "anNonce");
        }

        #[test]
        fn parse_custom_and_audiences_with_vec_claims() {
            let claims: jwt_simple::claims::JWTClaims<CustomClaims> = serde_json::from_str(r#"{"exp":1617757827, "otherClaim": "anCustomclaim", "aud": ["audience1", "audience2"]}"#).unwrap();

            let jwt_claims =
                JWTClaims::try_from_trusted_jwt_simple_claims(claims, super::valid_token())
                    .unwrap();

            assert_eq!(
                jwt_claims.get_claim::<String>("otherClaim").unwrap(),
                "anCustomclaim"
            );

            assert!(jwt_claims.audience().is_some());

            let audiences = jwt_claims.audience().unwrap();
            assert!(audiences.is_ok());

            let audiences_vec = audiences.unwrap();

            assert_eq!(audiences_vec.len(), 2);
            assert!(audiences_vec.contains(&String::from("audience1")));
            assert!(audiences_vec.contains(&String::from("audience2")));
        }

        #[test]
        fn parse_audiences_with_string_claims() {
            let claims: jwt_simple::claims::JWTClaims<CustomClaims> =
                serde_json::from_str(r#"{"exp":1617757827, "aud": "audience1"}"#).unwrap();

            let jwt_claims =
                JWTClaims::try_from_trusted_jwt_simple_claims(claims, super::valid_token())
                    .unwrap();

            assert!(jwt_claims.audience().is_some());

            let audiences = jwt_claims.audience().unwrap();
            assert!(audiences.is_ok());

            let audiences_vec = audiences.unwrap();

            assert_eq!(audiences_vec.len(), 1);
            assert!(audiences_vec.contains(&String::from("audience1")));
        }

        #[test]
        fn parse_other_claims() {
            let claims: jwt_simple::claims::JWTClaims<CustomClaims> =
                serde_json::from_str(r#"{"exp":1617757827, "iat":1617757827, "nbf": 1617757827}"#)
                    .unwrap();

            let duration = Duration::try_seconds(1617757827).unwrap();

            let jwt_claims =
                JWTClaims::try_from_trusted_jwt_simple_claims(claims, super::valid_token())
                    .unwrap();

            // Retrieve them as custom claims
            assert_eq!(
                jwt_claims
                    .get_claim::<DateTime<Utc>>("nbf")
                    .unwrap()
                    .timestamp_millis(),
                duration.num_milliseconds()
            );
            assert_eq!(
                jwt_claims
                    .get_claim::<DateTime<Utc>>("iat")
                    .unwrap()
                    .timestamp_millis(),
                duration.num_milliseconds()
            );
            assert_eq!(
                jwt_claims
                    .get_claim::<DateTime<Utc>>("exp")
                    .unwrap()
                    .timestamp_millis(),
                duration.num_milliseconds()
            );

            // Retrieve them as standard claims
            assert_eq!(
                jwt_claims.not_before().unwrap().timestamp_millis(),
                duration.num_milliseconds()
            );
            assert_eq!(
                jwt_claims.issued_at().unwrap().timestamp_millis(),
                duration.num_milliseconds()
            );
            assert_eq!(
                jwt_claims.expiration().unwrap().timestamp_millis(),
                duration.num_milliseconds()
            );

            // Retrieve headers extracted from token string

            assert_eq!(jwt_claims.get_header("alg").unwrap(), "HS256",);

            assert_eq!(jwt_claims.get_header("typ").unwrap(), "JWT",);
        }
    }
}