cedarling 0.0.39

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

use std::borrow::Cow;
use std::collections::HashSet;

use crate::common::issuer_utils::IssClaim;
use crate::common::policy_store::{TokenEntityMetadata, TrustedIssuer};
use crate::jwt::decode::{DecodeJwtError, DecodedJwt};
use crate::jwt::key_service::DecodingKeyInfo;
use crate::jwt::validation::TrustedIssuerError;
use crate::jwt::{
    Arc, JwtStatus, JwtStatusError, OwnedValidatorInfo, StatusListCache, TokenKind, ValidatorInfo,
};
use jsonwebtoken::errors::{ErrorKind, new_error};
use jsonwebtoken::{self as jwt, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, PartialEq, Deserialize, Clone)]
pub(crate) struct ValidatedJwt {
    #[serde(flatten)]
    pub claims: Value,
    #[serde(skip)]
    pub trusted_iss: Option<Arc<TrustedIssuer>>,
}

impl ValidatedJwt {
    /// Gets the value of the status list claim in the [`referenced token`]
    ///
    /// [`referenced token`]: https://www.ietf.org/archive/id/draft-ietf-oauth-status-list-10.html#name-referenced-token
    pub(crate) fn get_ref_status(&self) -> Result<Option<RefJwtStatusList>, serde_json::Error> {
        let Some(status) = self.claims.get("status") else {
            return Ok(None);
        };

        let status_list = serde_json::from_value::<RefJwtStatusListClaim>(status.clone())?;

        Ok(Some(status_list.status_list))
    }
}

/// Struct for deserializing the status list of the [`referenced token`]
///
/// [`referenced token`]: https://www.ietf.org/archive/id/draft-ietf-oauth-status-list-10.html#name-referenced-token
#[derive(Debug, Deserialize, PartialEq)]
struct RefJwtStatusListClaim {
    status_list: RefJwtStatusList,
}

/// The value of the status list claim in the [`referenced token`]
///
/// [`referenced token`]: https://www.ietf.org/archive/id/draft-ietf-oauth-status-list-10.html#name-referenced-token
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub(crate) struct RefJwtStatusList {
    pub idx: usize,
    pub uri: String,
    /// Maximum amount of time, in seconds, that the Status List Token can be cached
    /// before a fresh copy SHOULD be retrieved.
    #[serde(default)]
    pub ttl: Option<u64>,
}

/// This struct is a wrapper over [`jsonwebtoken::Validation`] which implements an
/// additional check for requiring custom JWT claims.
#[derive(Debug, Clone)]
pub(crate) struct JwtValidator {
    pub(crate) validation: Validation,
    /// Expected issuer in canonical form.
    ///
    /// `jsonwebtoken::Validation::set_issuer` does byte-level equality against
    /// the raw `iss` claim, so it rejects equivalent issuers that differ only
    /// by trailing slash, case, default port, etc. We bypass it and run a
    /// URL-aware check via [`IssClaim`] instead.
    expected_iss: Option<IssClaim>,
    required_claims: HashSet<String>,
    validate_signature: bool,
    validate_status_list: bool,
    status_list_cache: StatusListCache,
}

impl JwtValidator {
    /// Creates a new validator for the tokens passed through [`crate::Cedarling::authorize`]
    pub(super) fn new_input_tkn_validator<'a>(
        iss: Option<&'a IssClaim>,
        tkn_name: &'a str,
        token_metadata: &TokenEntityMetadata,
        algorithm: Algorithm,
        status_lists: StatusListCache,
        validate_signature: bool,
        validate_status_list: bool,
    ) -> (Self, ValidatorInfo<'a>) {
        let token_kind = TokenKind::AuthzRequestInput(tkn_name);

        let mut validation = Validation::new(algorithm);
        validation.validate_exp = true;
        validation.validate_nbf = true;

        // we will validate the missing claims in another function since the
        // jsonwebtoken crate does not support required custom claims
        // ... but this defaults to true so we need to set it to false.
        validation.required_spec_claims.clear();
        validation.validate_aud = false;

        let required_claims = token_metadata.required_claims.iter().cloned().collect();

        let key = ValidatorInfo {
            iss,
            token_kind,
            algorithm,
        };

        let validator = JwtValidator {
            validation,
            expected_iss: iss.cloned(),
            required_claims,
            validate_signature,
            validate_status_list,
            status_list_cache: status_lists,
        };

        (validator, key)
    }

    /// Creates a new validator for multi-issuer tokens passed through [`crate::Cedarling::authorize_multi_issuer`]
    pub(super) fn new_multi_issuer_tkn_validator<'a>(
        iss: Option<&'a IssClaim>,
        tkn_name: &'a str,
        token_metadata: &TokenEntityMetadata,
        algorithm: Algorithm,
        status_lists: StatusListCache,
        validate_signature: bool,
        validate_status_list: bool,
    ) -> (Self, ValidatorInfo<'a>) {
        let token_kind = TokenKind::AuthorizeMultiIssuer(Cow::Borrowed(tkn_name));

        let mut validation = Validation::new(algorithm);
        validation.validate_exp = true;
        validation.validate_nbf = true;

        validation.required_spec_claims.clear();
        validation.validate_aud = false;

        let required_claims = token_metadata.required_claims.iter().cloned().collect();

        let key = ValidatorInfo {
            iss,
            token_kind,
            algorithm,
        };

        let validator = JwtValidator {
            validation,
            expected_iss: iss.cloned(),
            required_claims,
            validate_signature,
            validate_status_list,
            status_list_cache: status_lists,
        };

        (validator, key)
    }

    /// Creates a new validator for status list tokens
    pub(super) fn new_status_list_tkn_validator(
        iss: Option<&'_ IssClaim>,
        status_list_uri: Option<String>,
        algorithm: Algorithm,
        validate_signature: bool,
    ) -> (Self, ValidatorInfo<'_>) {
        let token_kind = TokenKind::StatusList;

        let mut validation = Validation::new(algorithm);
        validation.validate_exp = true;
        validation.validate_nbf = true;

        // we will validate the missing claims in another function since the
        // jsonwebtoken crate does not support required custom claims
        // ... but this defaults to true so we need to set it to false.
        validation.required_spec_claims.clear();
        validation.validate_aud = false;
        validation.sub = status_list_uri;

        let required_claims = ["sub", "iat", "status_list"]
            .into_iter()
            .map(std::convert::Into::into)
            .collect();

        let key = ValidatorInfo {
            iss,
            token_kind,
            algorithm,
        };

        let validator = JwtValidator {
            validation,
            expected_iss: iss.cloned(),
            required_claims,
            validate_signature,
            validate_status_list: false,
            status_list_cache: StatusListCache::default(),
        };

        (validator, key)
    }

    /// Validates JWT by checking:
    /// - The JWT's Signature
    /// - If the claims are valid (e.g. the JWT isn't expired)
    /// - If the status of the JWT isn't [`invalid`] or [`suspended`].
    ///
    /// [`invalid`]: JwtStatus::Invalid
    /// [`suspended`]: JwtStatus::Suspended
    pub(crate) fn validate_jwt(
        &self,
        jwt: &str,
        decoding_key: Option<Arc<DecodingKey>>,
    ) -> Result<ValidatedJwt, ValidateJwtError> {
        // TODO: Simplify this branching and decode/validation flow.
        // Tracking issue: https://github.com/JanssenProject/jans/issues/13287
        let validated_jwt = if self.validate_signature {
            let Some(decoding_key) = decoding_key else {
                return Err(ValidateJwtError::MissingValidationKey);
            };
            jwt::decode::<ValidatedJwt>(jwt, decoding_key.as_ref(), &self.validation)?.claims
        } else {
            let validated_jwt = jwt::dangerous::insecure_decode::<ValidatedJwt>(jwt)?.claims;
            self.validate_claims_without_signature(&validated_jwt)?;
            validated_jwt
        };

        // URL-aware `iss` check — runs for both the signed and insecure paths.
        // `jsonwebtoken` either skipped the iss check (signed path) because
        // we never set `validation.iss`, or it doesn't run at all (insecure
        // path). Either way we normalize through `IssClaim` here.
        self.validate_iss(&validated_jwt.claims)?;

        // Custom implementation of requiring custom claims
        let missing_claims = self
            .required_claims
            .iter()
            .filter(|claim| validated_jwt.claims.get(claim).is_none())
            .cloned()
            .collect::<Vec<String>>();
        if !missing_claims.is_empty() {
            Err(ValidateJwtError::MissingClaims(missing_claims))?;
        }

        if self.validate_status_list {
            // Check if the JWT has a status claim
            let Some(ref_status_list) = validated_jwt.get_ref_status()? else {
                // status validation is not required if the JWT does not
                // have a status claim
                return Ok(validated_jwt);
            };

            let jwt_status = {
                self.status_list_cache
                    .status_lists
                    .read()
                    .expect("obtain status list read lock")
                    .get(&ref_status_list.uri)
                    .ok_or(ValidateJwtError::MissingStatusList)?
                    .get_status(ref_status_list.idx)?
            };

            if !jwt_status.is_valid() {
                return Err(ValidateJwtError::RejectJwtStatus(jwt_status));
            }
        }

        Ok(validated_jwt)
    }

    fn validate_claims_without_signature(
        &self,
        validated_jwt: &ValidatedJwt,
    ) -> Result<(), ValidateJwtError> {
        let now = jwt::get_current_timestamp();
        let claims = &validated_jwt.claims;

        if self.validation.validate_exp
            && let Some(exp) = claims.get("exp")
        {
            let exp = exp.as_u64().ok_or_else(|| {
                ValidateJwtError::ValidateJwt(new_error(ErrorKind::InvalidClaimFormat(
                    "exp".to_string(),
                )))
            })?;

            if exp < self.validation.reject_tokens_expiring_in_less_than {
                return Err(ValidateJwtError::ValidateJwt(new_error(
                    ErrorKind::InvalidToken,
                )));
            }

            if exp - self.validation.reject_tokens_expiring_in_less_than
                < now.saturating_sub(self.validation.leeway)
            {
                return Err(ValidateJwtError::ValidateJwt(new_error(
                    ErrorKind::ExpiredSignature,
                )));
            }
        }

        if self.validation.validate_nbf
            && let Some(nbf) = claims.get("nbf")
        {
            let nbf = nbf.as_u64().ok_or_else(|| {
                ValidateJwtError::ValidateJwt(new_error(ErrorKind::InvalidClaimFormat(
                    "nbf".to_string(),
                )))
            })?;

            if nbf > now.saturating_add(self.validation.leeway) {
                return Err(ValidateJwtError::ValidateJwt(new_error(
                    ErrorKind::ImmatureSignature,
                )));
            }
        }

        if let (Some(sub), Some(expected_sub)) = (
            claims.get("sub").and_then(Value::as_str),
            self.validation.sub.as_deref(),
        ) && sub != expected_sub
        {
            return Err(ValidateJwtError::ValidateJwt(new_error(
                ErrorKind::InvalidSubject,
            )));
        }

        Ok(())
    }

    /// Validate the `iss` claim against [`Self::expected_iss`] using
    /// canonical [`IssClaim`] equality.
    ///
    /// When an expected issuer is configured, the claim MUST be present and
    /// MUST be a string (or array of strings) that normalizes to the
    /// expected value. Missing / non-string `iss` is rejected — defaults to
    /// safe rather than silently accepting tokens with no usable issuer.
    fn validate_iss(&self, claims: &Value) -> Result<(), ValidateJwtError> {
        let Some(expected) = self.expected_iss.as_ref() else {
            return Ok(());
        };
        let invalid = || ValidateJwtError::ValidateJwt(new_error(ErrorKind::InvalidIssuer));
        let matched = match claims.get("iss") {
            Some(Value::String(iss)) => IssClaim::new(iss) == *expected,
            Some(Value::Array(iss_values)) => iss_values
                .iter()
                .filter_map(Value::as_str)
                .any(|iss| IssClaim::new(iss) == *expected),
            _ => false,
        };
        if matched { Ok(()) } else { Err(invalid()) }
    }
}

impl DecodedJwt {
    pub(crate) fn iss(&self) -> Option<IssClaim> {
        self.claims
            .inner
            .get("iss")
            .and_then(|x| x.as_str())
            .map(IssClaim::new)
    }

    pub(crate) fn decoding_key_info(&self) -> DecodingKeyInfo {
        DecodingKeyInfo {
            issuer: self.iss(),
            kid: self.header.kid.clone(),
            algorithm: self.header.alg,
        }
    }
}

impl TryFrom<DecodedJwt> for ValidatedJwt {
    type Error = serde_json::Error;

    fn try_from(decoded_jwt: DecodedJwt) -> Result<Self, Self::Error> {
        Ok(Self {
            claims: decoded_jwt.claims.inner,
            trusted_iss: None,
        })
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ValidateJwtError {
    #[error("failed to decode the JWT: {0}")]
    DecodeJwt(#[from] DecodeJwtError),
    #[error("failed to validate the JWT since no key was available")]
    MissingValidationKey,
    #[error(
        "failed to validate JWT {0:?}: no validator was initialized. this may be due to an untrusted issuer or an unsupported algorithm"
    )]
    MissingValidator(OwnedValidatorInfo),
    #[error("failed to validate the JWT: {0}")]
    ValidateJwt(#[from] jwt::errors::Error),
    #[error("validation failed since the JWT is missing the following required claims: {0:#?}")]
    MissingClaims(Vec<String>),
    #[error("failed to get the status for the JWT: {0}")]
    GetJwtStatus(#[from] JwtStatusError),
    #[error("the token is rejected because it's status is: {0}")]
    RejectJwtStatus(JwtStatus),
    #[error("there isn't a status list available for the token")]
    MissingStatusList,
    #[error("failed to deserialize the JWT's status claim: {0}")]
    DeserializeStatusClaim(#[from] serde_json::Error),
    #[error("failed to validate the JWT's trusted issuer: {0}")]
    TrustedIssuerValidation(#[source] TrustedIssuerError),
}

#[cfg(test)]
mod test {
    use std::collections::{HashMap, HashSet};
    use std::sync::LazyLock;

    use crate::common::issuer_utils::IssClaim;
    use crate::common::policy_store::TokenEntityMetadata;
    use crate::jwt::status_list::{JwtStatus, StatusBitSize, StatusList};
    use crate::jwt::validation::{JwtValidator, ValidateJwtError, ValidatedJwt};
    use crate::jwt::{StatusListCache, test_utils::*};
    use jsonwebtoken::Algorithm;
    use serde_json::json;
    use test_utils::assert_eq;

    #[track_caller]
    fn generate_keys() -> KeyPair {
        generate_keypair_hs256(Some("some_hs256_key")).expect("Should generate keys")
    }

    static TEST_TKN_ENTITY_METADATA: LazyLock<TokenEntityMetadata> =
        LazyLock::new(|| TokenEntityMetadata {
            trusted: true,
            entity_type_name: "Jans::AccessToken".into(),
            token_id: "jti".into(),
            required_claims: HashSet::from(["exp".into(), "nbf".into()]),
        });

    #[test]
    fn can_decode_jwt_without_sig_validation() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        // Generate token
        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 1_516_239_022,
            "exp": u64::MAX,
            "nbf": u64::MIN,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            false,
            false,
        );

        let result = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect("should validate JWT");

        let expected = ValidatedJwt {
            claims,
            trusted_iss: None,
        };

        assert_eq!(result, expected);
    }

    #[test]
    fn decoding_errors_if_token_is_expired_when_without_sig_validation() {
        let iss = "127.0.0.1";
        let keys = generate_keys();

        // Generate token
        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 1_516_239_022,
            "exp": 0,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let mut tkn_entity_metadata = TEST_TKN_ENTITY_METADATA.clone();
        tkn_entity_metadata.required_claims = HashSet::from(["exp".into()]);
        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            false,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("should error due to expired JWT");

        assert!(matches!(err, ValidateJwtError::ValidateJwt(ref e)
            if *e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature
        ));
    }

    #[test]
    fn can_decode_and_validate_jwt() {
        let iss = "127.0.0.1";
        let keys = generate_keys();

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 0,
            "nbf": 10,
            "exp": u64::MAX,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let result = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect("Should successfully process JWT");

        let expected = ValidatedJwt {
            claims,
            trusted_iss: None,
        };

        assert_eq!(result, expected);
    }

    #[test]
    fn validates_jwt_when_token_iss_has_trailing_slash() {
        // Trusted-issuer config holds the canonical (no-slash) origin.
        // Token emits `iss` with a trailing slash (Auth0-style).
        // These are semantically the same issuer and must pass validation.
        let keys = generate_keys();
        let expected_iss = "https://dev-vci4e3lpvw2symco231.eu.auth0.com";
        let token_iss = "https://dev-vci4e3lpvw2symco231.eu.auth0.com/";

        let claims = json!({
            "iss": token_iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 0,
            "nbf": 10,
            "exp": u64::MAX,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(expected_iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let result = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect("trailing-slash iss must validate against canonical expected iss");

        let expected = ValidatedJwt {
            claims,
            trusted_iss: None,
        };
        assert_eq!(
            result, expected,
            "validate_jwt should accept trailing-slash iss and produce expected ValidatedJwt with claims and no trusted_iss"
        );
    }

    #[test]
    fn rejects_token_missing_iss_when_expected_iss_configured() {
        // Security: when the validator was configured with an expected
        // issuer, a token that omits the `iss` claim entirely (or sets it
        // to a non-string value) must NOT be accepted just because there is
        // nothing to compare against.
        let keys = generate_keys();
        let expected_iss = "https://issuer.example.com";

        let claims_missing = json!({
            "sub": "1234567890",
            "iat": 0,
            "nbf": 10,
            "exp": u64::MAX,
        });
        let token_missing = generate_token_using_claims(&claims_missing, &keys)
            .expect("Should generate token using keys");

        let claims_non_string = json!({
            "iss": 42,
            "sub": "1234567890",
            "iat": 0,
            "nbf": 10,
            "exp": u64::MAX,
        });
        let token_non_string = generate_token_using_claims(&claims_non_string, &keys)
            .expect("Should generate token using keys");

        let decoding_key = keys.decoding_key().unwrap();
        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(expected_iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        for token in [token_missing, token_non_string] {
            let err = validator
                .validate_jwt(&token, Some(decoding_key.clone()))
                .expect_err("token without valid iss must be rejected");
            assert!(
                matches!(
                    err,
                    ValidateJwtError::ValidateJwt(ref e)
                        if *e.kind() == jsonwebtoken::errors::ErrorKind::InvalidIssuer
                ),
                "expected InvalidIssuer, got {err:?}"
            );
        }
    }

    #[test]
    fn errors_on_expired_token() {
        let iss = "127.0.0.1";
        let keys = generate_keys();

        // Generate token
        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 1_516_239_022,
            "exp": 0,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let mut tkn_entity_metadata = TEST_TKN_ENTITY_METADATA.clone();
        tkn_entity_metadata.required_claims = HashSet::from(["exp".into(), "nbf".into()]);
        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("should error when validating JWT");

        assert!(
            matches!(
                err,
                ValidateJwtError::ValidateJwt(ref e)
                    if *e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature
            ),
            "expected validation to fail due to the token being expired."
        );
    }

    #[test]
    fn errors_on_immature_token() {
        let iss = "127.0.0.1";
        let keys = generate_keys();

        // Generate token
        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 1_516_239_022,
            "nbf": u64::MAX,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("should error when validating JWT");

        assert!(
            matches!(
                err,
                ValidateJwtError::ValidateJwt(ref e)
                    if *e.kind() == jsonwebtoken::errors::ErrorKind::ImmatureSignature
            ),
            "expected validation to fail due to the token being immature."
        );
    }

    #[test]
    fn can_check_missing_claims() {
        let iss = "127.0.0.1";
        let keys = generate_keys();

        // Generate token
        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 1_516_239_022,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        // Base case where all required claims are present
        let mut tkn_entity_metadata = TEST_TKN_ENTITY_METADATA.clone();
        tkn_entity_metadata.required_claims =
            HashSet::from(["sub", "name", "iat"].map(std::convert::Into::into));
        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_entity_metadata,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let result = validator
            .validate_jwt(&token, Some(decoding_key.clone()))
            .expect("Should process JWT successfully");

        let expected = ValidatedJwt {
            claims,
            trusted_iss: None,
        };

        assert_eq!(result, expected);

        // Error case where `nbf` is missing from the token.
        let mut tkn_entity_metadata = TEST_TKN_ENTITY_METADATA.clone();
        tkn_entity_metadata.required_claims =
            HashSet::from(["sub", "name", "iat", "nbf"].map(std::convert::Into::into));
        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_entity_metadata,
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("expected an error while validating the JWT");

        assert!(
            matches!(
            err,
            ValidateJwtError::MissingClaims(missing_claims)
                if missing_claims == vec!["nbf".to_string()]
            ),
            "expected an error due to missing `nbf` claim"
        );
    }

    #[tokio::test]
    async fn reject_invalid_token_from_status_list() {
        let bit_size = StatusBitSize::try_from(1u8).unwrap();
        let status_list = [0b1111_1111];

        let mut server = MockServer::new_with_defaults().await.unwrap();
        server.generate_status_list_endpoint(bit_size, &status_list, None);
        let iss = server.issuer();
        let decoding_key = server.jwt_decoding_key().unwrap();
        let mut claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 0,
            "nbf": 10,
            "exp": u64::MAX,
        });
        let token = server
            .generate_token_with_hs256sig(&mut claims, Some(0))
            .unwrap();

        let status_lists: StatusListCache = HashMap::from([(
            server.status_list_endpoint().unwrap().to_string(),
            StatusList {
                bit_size,
                list: status_list.to_vec(),
            },
        )])
        .into();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&iss),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            status_lists,
            true,
            true,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("should error because the status of the token is JwtStatus::Invalid");

        assert!(
            matches!(
                err,
                ValidateJwtError::RejectJwtStatus(ref status)
                    if *status == JwtStatus::Invalid
            ),
            "GOT {err:?}: {err}"
        );
    }

    /// Helper: `TokenEntityMetadata` with **empty** `required_claims`.
    /// Represents the default configuration most deployments use.
    fn tkn_meta_no_required_claims() -> TokenEntityMetadata {
        TokenEntityMetadata {
            trusted: true,
            entity_type_name: "Jans::AccessToken".into(),
            token_id: "jti".into(),
            required_claims: HashSet::new(),
        }
    }

    /// Expired token (exp=0) is rejected even when "exp" is not in `required_claims`.
    #[test]
    fn rejects_expired_token_without_exp_in_required_claims_no_sig() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "iat": 1_516_239_022,
            "exp": 0,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_meta_no_required_claims(),
            Algorithm::HS256,
            StatusListCache::default(),
            false,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("expired token should be rejected even when 'exp' is not in required_claims");

        assert!(
            matches!(err, ValidateJwtError::ValidateJwt(ref e)
                if *e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature),
            "expected ExpiredSignature, got {err:?}"
        );
    }

    /// Expired token (exp=0) is rejected with signature validation when "exp" is not in `required_claims`.
    #[test]
    fn rejects_expired_token_without_exp_in_required_claims_with_sig() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "iat": 1_516_239_022,
            "exp": 0,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_meta_no_required_claims(),
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("expired token should be rejected even when 'exp' is not in required_claims");

        assert!(
            matches!(err, ValidateJwtError::ValidateJwt(ref e)
                if *e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature),
            "expected ExpiredSignature, got {err:?}"
        );
    }

    /// Immature token (`nbf=u64::MAX`) is rejected even when "nbf" is not in `required_claims`.
    #[test]
    fn rejects_immature_token_without_nbf_in_required_claims_no_sig() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "iat": 1_516_239_022,
            "nbf": u64::MAX,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_meta_no_required_claims(),
            Algorithm::HS256,
            StatusListCache::default(),
            false,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("immature token should be rejected even when 'nbf' is not in required_claims");

        assert!(
            matches!(err, ValidateJwtError::ValidateJwt(ref e)
                if *e.kind() == jsonwebtoken::errors::ErrorKind::ImmatureSignature),
            "expected ImmatureSignature, got {err:?}"
        );
    }

    /// Immature token (`nbf=u64::MAX`) is rejected with signature validation when "nbf" is not in `required_claims`.
    #[test]
    fn rejects_immature_token_without_nbf_in_required_claims_with_sig() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "iat": 1_516_239_022,
            "nbf": u64::MAX,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_meta_no_required_claims(),
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("immature token should be rejected even when 'nbf' is not in required_claims");

        assert!(
            matches!(err, ValidateJwtError::ValidateJwt(ref e)
                if *e.kind() == jsonwebtoken::errors::ErrorKind::ImmatureSignature),
            "expected ImmatureSignature, got {err:?}"
        );
    }

    /// Expired token is rejected by the multi-issuer validator when "exp" is not in `required_claims`.
    #[test]
    fn rejects_expired_token_multi_issuer_without_exp_in_required_claims() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "iat": 1_516_239_022,
            "exp": 0,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_multi_issuer_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_meta_no_required_claims(),
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("expired token should be rejected by multi-issuer validator even when 'exp' is not in required_claims");

        assert!(
            matches!(err, ValidateJwtError::ValidateJwt(ref e)
                if *e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature),
            "expected ExpiredSignature, got {err:?}"
        );
    }

    /// Immature token is rejected by the multi-issuer validator when "nbf" is not in `required_claims`.
    #[test]
    fn rejects_immature_token_multi_issuer_without_nbf_in_required_claims() {
        let keys = generate_keys();
        let iss = "127.0.0.1";

        let claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "iat": 1_516_239_022,
            "nbf": u64::MAX,
        });
        let token =
            generate_token_using_claims(&claims, &keys).expect("Should generate token using keys");
        let decoding_key = keys.decoding_key().unwrap();

        let (validator, _) = JwtValidator::new_multi_issuer_tkn_validator(
            Some(&IssClaim::new(iss)),
            "access_token",
            &tkn_meta_no_required_claims(),
            Algorithm::HS256,
            StatusListCache::default(),
            true,
            false,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("immature token should be rejected by multi-issuer validator even when 'nbf' is not in required_claims");

        assert!(
            matches!(err, ValidateJwtError::ValidateJwt(ref e)
                if *e.kind() == jsonwebtoken::errors::ErrorKind::ImmatureSignature),
            "expected ImmatureSignature, got {err:?}"
        );
    }

    #[tokio::test]
    async fn reject_suspended_token_from_status_list() {
        let bit_size = StatusBitSize::try_from(1u8).unwrap();
        let status_list = [0b1111_1111];

        let mut server = MockServer::new_with_defaults().await.unwrap();
        server.generate_status_list_endpoint(bit_size, &status_list, None);
        let iss = server.issuer();
        let decoding_key = server.jwt_decoding_key().unwrap();
        let mut claims = json!({
            "iss": iss,
            "sub": "1234567890",
            "name": "John Doe",
            "iat": 0,
            "nbf": 10,
            "exp": u64::MAX,
        });
        let token = server
            .generate_token_with_hs256sig(&mut claims, Some(0))
            .unwrap();

        let status_lists: StatusListCache = HashMap::from([(
            server.status_list_endpoint().unwrap().to_string(),
            StatusList {
                bit_size: 2u8.try_into().unwrap(),
                list: vec![0b1010_1010],
            },
        )])
        .into();

        let (validator, _) = JwtValidator::new_input_tkn_validator(
            Some(&iss),
            "access_token",
            &TEST_TKN_ENTITY_METADATA,
            Algorithm::HS256,
            status_lists,
            true,
            true,
        );

        let err = validator
            .validate_jwt(&token, Some(decoding_key))
            .expect_err("should error because the status of the token is JwtStatus::Suspended");

        assert!(
            matches!(
                err,
                ValidateJwtError::RejectJwtStatus(ref status)
                    if *status == JwtStatus::Suspended
            ),
            "GOT {err:?}: {err}"
        );
    }
}