entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! JWT signature verification (HMAC-based in v0.1.0).
//!
//! Implements the JWS Compact Serialization verification workflow per
//! RFC 7515 ยง5.2: split the token, decode the header, verify the
//! signature over the signing input (`header.payload`), then decode
//! and return the claims.

use core::fmt;

use crate::crypto::constant_time::constant_time_eq;
use crate::crypto::{HmacSha256, HmacSha512};
use crate::encoding::base64url_decode;

use super::claims::{JwtClaims, JwtClaimsError};
use super::decode::MAX_SIGNATURE_SEGMENT_LEN;
use super::header::{JwtAlgorithm, JwtHeader, JwtHeaderError};

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// The category of JWT signature verification failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum JwtSignatureErrorKind {
    /// The token does not have exactly three dot-separated segments.
    MalformedToken,
    /// The header segment could not be parsed.
    HeaderError(JwtHeaderError),
    /// The claims segment could not be parsed.
    ClaimsError(JwtClaimsError),
    /// The `"none"` algorithm is not permitted.
    NoneAlgorithm,
    /// The token's algorithm is asymmetric (`EdDSA`, `ES256`, `RS256`, or
    /// `RS512`) but an HMAC key
    /// was supplied to [`verify_jwt`]; use [`verify_jwt_asymmetric`] (or a
    /// [`KeyRing`](crate::jwt::KeyRing)) instead. This guards against an
    /// algorithm-confusion downgrade where an asymmetric token is fed to the
    /// symmetric verifier.
    #[cfg(feature = "asym-jwt")]
    AlgorithmMismatch,
    /// No key in the supplied JWKS / key ring matched the token's `kid`.
    #[cfg(feature = "asym-jwt")]
    NoMatchingKey,
    /// The signature does not match the computed HMAC.
    InvalidSignature,
    /// The signature segment is not valid Base64url.
    InvalidSignatureEncoding,
}

/// Error returned when JWT signature verification fails.
///
/// Error messages are deliberately vague to avoid leaking information
/// about which verification step failed to a potential attacker.
/// The specific [`kind`](Self) is available programmatically for
/// trusted server-side logging.
#[doc(alias = "signature_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JwtSignatureError {
    kind: JwtSignatureErrorKind,
}

impl fmt::Display for JwtSignatureError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            JwtSignatureErrorKind::MalformedToken => {
                write!(f, "jwt: malformed token structure")
            }
            JwtSignatureErrorKind::HeaderError(_) => {
                write!(f, "jwt: invalid header")
            }
            JwtSignatureErrorKind::ClaimsError(_) => {
                write!(f, "jwt: invalid claims")
            }
            JwtSignatureErrorKind::NoneAlgorithm => {
                write!(f, "jwt: 'none' algorithm is not permitted")
            }
            #[cfg(feature = "asym-jwt")]
            JwtSignatureErrorKind::AlgorithmMismatch => {
                write!(f, "jwt: algorithm does not match the supplied key")
            }
            #[cfg(feature = "asym-jwt")]
            JwtSignatureErrorKind::NoMatchingKey => {
                write!(f, "jwt: no key matched the token's key id")
            }
            JwtSignatureErrorKind::InvalidSignature => {
                write!(f, "jwt: signature verification failed")
            }
            JwtSignatureErrorKind::InvalidSignatureEncoding => {
                write!(f, "jwt: invalid signature encoding")
            }
        }
    }
}

impl JwtSignatureError {
    /// Returns `true` if the error is due to a signature mismatch.
    #[must_use]
    #[inline]
    pub fn is_invalid_signature(&self) -> bool {
        self.kind == JwtSignatureErrorKind::InvalidSignature
    }

    /// Returns `true` if the token structure is malformed.
    #[must_use]
    #[inline]
    pub fn is_malformed_token(&self) -> bool {
        self.kind == JwtSignatureErrorKind::MalformedToken
    }

    /// Returns `true` if the `"none"` algorithm was rejected.
    #[must_use]
    #[inline]
    pub fn is_none_algorithm(&self) -> bool {
        self.kind == JwtSignatureErrorKind::NoneAlgorithm
    }

    /// Returns `true` if the token's algorithm did not match the supplied
    /// key (an asymmetric token presented to the HMAC verifier, or vice
    /// versa).
    #[cfg(feature = "asym-jwt")]
    #[must_use]
    #[inline]
    pub fn is_algorithm_mismatch(&self) -> bool {
        self.kind == JwtSignatureErrorKind::AlgorithmMismatch
    }

    /// Returns `true` if no key matched the token's `kid` (JWKS / key-ring
    /// verification).
    #[cfg(feature = "asym-jwt")]
    #[must_use]
    #[inline]
    pub fn is_no_matching_key(&self) -> bool {
        self.kind == JwtSignatureErrorKind::NoMatchingKey
    }

    /// Constructs a "no matching key" error.
    #[cfg(feature = "asym-jwt")]
    #[must_use]
    #[inline]
    pub(crate) fn no_matching_key() -> Self {
        Self {
            kind: JwtSignatureErrorKind::NoMatchingKey,
        }
    }

    /// Returns `true` if the header could not be parsed.
    #[must_use]
    #[inline]
    pub fn is_header_error(&self) -> bool {
        matches!(self.kind, JwtSignatureErrorKind::HeaderError(_))
    }

    /// Returns `true` if the claims could not be parsed.
    #[must_use]
    #[inline]
    pub fn is_claims_error(&self) -> bool {
        matches!(self.kind, JwtSignatureErrorKind::ClaimsError(_))
    }

    /// Returns `true` if the signature encoding is invalid.
    #[must_use]
    #[inline]
    pub fn is_invalid_signature_encoding(&self) -> bool {
        self.kind == JwtSignatureErrorKind::InvalidSignatureEncoding
    }
}

impl std::error::Error for JwtSignatureError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.kind {
            JwtSignatureErrorKind::HeaderError(err) => Some(err),
            JwtSignatureErrorKind::ClaimsError(err) => Some(err),
            JwtSignatureErrorKind::MalformedToken
            | JwtSignatureErrorKind::NoneAlgorithm
            | JwtSignatureErrorKind::InvalidSignature
            | JwtSignatureErrorKind::InvalidSignatureEncoding => None,
            #[cfg(feature = "asym-jwt")]
            JwtSignatureErrorKind::AlgorithmMismatch | JwtSignatureErrorKind::NoMatchingKey => None,
        }
    }
}

impl From<JwtHeaderError> for JwtSignatureError {
    fn from(err: JwtHeaderError) -> Self {
        Self {
            kind: JwtSignatureErrorKind::HeaderError(err),
        }
    }
}

impl From<JwtClaimsError> for JwtSignatureError {
    fn from(err: JwtClaimsError) -> Self {
        Self {
            kind: JwtSignatureErrorKind::ClaimsError(err),
        }
    }
}

// ---------------------------------------------------------------------------
// Compact-token primitives
// ---------------------------------------------------------------------------

/// Splits a JWS Compact Serialization token into its three dot-separated
/// segments `(header, payload, signature)`.
///
/// Returns [`JwtSignatureErrorKind::MalformedToken`] unless the token has
/// exactly three segments. Segments may individually be empty (e.g. the
/// signature of an `alg=none` token); only the segment *count* is checked
/// here, matching RFC 7515 ยง5.2 structural validation.
pub(super) fn split_compact(token: &str) -> Result<(&str, &str, &str), JwtSignatureError> {
    let parts: Vec<&str> = token.splitn(4, '.').collect();
    if parts.len() != 3 {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::MalformedToken,
        });
    }
    Ok((parts[0], parts[1], parts[2]))
}

/// Base64url-decode the signature segment under a length bound.
///
/// The signature is raw bytes, so it never passes through `decode_segment`'s
/// `MAX_SEGMENT_LEN` gate โ€” without this it is the one unbounded allocation on
/// the verification path for an untrusted token.
fn decode_signature(signature_b64: &str) -> Result<Vec<u8>, JwtSignatureError> {
    // JWS uses UNPADDED base64url (RFC 7515 ยง2). Tolerating `=` gives every
    // token two encodings that both verify, defeating any replay/dedup cache
    // that keys on the token bytes.
    if signature_b64.as_bytes().contains(&b'=') {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::InvalidSignatureEncoding,
        });
    }
    if signature_b64.len() > MAX_SIGNATURE_SEGMENT_LEN {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::InvalidSignatureEncoding,
        });
    }
    base64url_decode(signature_b64).map_err(|_| JwtSignatureError {
        kind: JwtSignatureErrorKind::InvalidSignatureEncoding,
    })
}

/// Builds the JWS signing input `header_b64.payload_b64` (RFC 7515 ยง5.2
/// step 8 / ยง5.1): the raw ASCII bytes over which the signature is computed.
pub(super) fn signing_input(header_b64: &str, payload_b64: &str) -> String {
    let mut input = String::with_capacity(header_b64.len() + 1 + payload_b64.len());
    input.push_str(header_b64);
    input.push('.');
    input.push_str(payload_b64);
    input
}

// ---------------------------------------------------------------------------
// Verification
// ---------------------------------------------------------------------------

/// Verifies a complete JWT string and returns the parsed header and claims.
///
/// The token must be in JWS Compact Serialization format:
/// `base64url(header).base64url(payload).base64url(signature)`.
///
/// # Security
///
/// - The `"none"` algorithm is **always rejected**, even if the token
///   carries no signature. This prevents signature bypass attacks where
///   an attacker modifies the header to claim `"alg":"none"`.
/// - Signature comparison uses [`constant_time_eq`] to prevent timing
///   side-channel attacks.
/// - The function does **not** validate time-based claims (`exp`, `nbf`).
///   Callers must perform their own temporal validation using
///   [`JwtClaims::validate_exp`] and related methods.
///
/// # Errors
///
/// Returns [`JwtSignatureError`] if the token is malformed, the header
/// or claims cannot be parsed, the algorithm is `"none"`, or the
/// signature does not match.
#[must_use = "verification may fail; handle the Result"]
pub fn verify_jwt(token: &str, key: &[u8]) -> Result<(JwtHeader, JwtClaims), JwtSignatureError> {
    // Split into exactly 3 dot-separated segments.
    let (header_b64, payload_b64, signature_b64) = split_compact(token)?;

    // Parse the header to determine the algorithm.
    let header = JwtHeader::parse(header_b64)?;

    // SECURITY: Reject the "none" algorithm unconditionally. Allowing it
    // would let an attacker forge tokens by stripping the signature and
    // changing the algorithm to "none".
    if header.alg() == JwtAlgorithm::None {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::NoneAlgorithm,
        });
    }

    // Decode the provided signature.
    let provided_sig = decode_signature(signature_b64)?;

    // The signing input is the raw ASCII bytes of "header_b64.payload_b64"
    // (RFC 7515 ยง5.2 step 8).
    let signing_input = signing_input(header_b64, payload_b64);

    // SECURITY: Compute the expected signature and compare using
    // constant-time comparison to prevent timing side-channel attacks.
    let signature_valid = match header.alg() {
        JwtAlgorithm::HS256 => {
            let computed = HmacSha256::mac(key, signing_input.as_bytes());
            constant_time_eq(&computed, &provided_sig)
        }
        JwtAlgorithm::HS512 => {
            let computed = HmacSha512::mac(key, signing_input.as_bytes());
            constant_time_eq(&computed, &provided_sig)
        }
        // SECURITY: an asymmetric token must not be verifiable with an HMAC
        // key. Rejecting here (rather than silently treating the public key
        // as an HMAC secret) closes the classic RS256/HS256-style
        // algorithm-confusion attack. Asymmetric tokens go through
        // `verify_jwt_asymmetric` / `KeyRing::verify`.
        #[cfg(feature = "asym-jwt")]
        JwtAlgorithm::EdDSA | JwtAlgorithm::ES256 | JwtAlgorithm::RS256 | JwtAlgorithm::RS512 => {
            return Err(JwtSignatureError {
                kind: JwtSignatureErrorKind::AlgorithmMismatch,
            });
        }
        JwtAlgorithm::None => {
            // Already rejected above; this arm is unreachable.
            return Err(JwtSignatureError {
                kind: JwtSignatureErrorKind::NoneAlgorithm,
            });
        }
    };

    if !signature_valid {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::InvalidSignature,
        });
    }

    // Parse the claims only after signature verification succeeds.
    let claims = JwtClaims::parse(payload_b64)?;

    Ok((header, claims))
}

/// Verifies a JWT signed with an asymmetric algorithm (`EdDSA`, `ES256`, or
/// the verify-only `RS256`/`RS512`) against a single public key.
///
/// The token must use the algorithm `key.algorithm()` corresponds to; a
/// token whose `alg` does not match โ€” including a symmetric `HS*` token or
/// `alg=none` โ€” is rejected without attempting verification. This is the
/// asymmetric counterpart to [`verify_jwt`]; for key selection by `kid`
/// across a published key set, use [`KeyRing::verify`](crate::jwt::KeyRing::verify).
///
/// # Security
///
/// - `alg=none` is **always rejected** (as in [`verify_jwt`]).
/// - The header `alg` is checked against the supplied key's algorithm
///   *before* verification, closing algorithm-confusion downgrades.
/// - Signature verification is delegated to the audited curve
///   implementation; a malformed signature is reported as an invalid
///   signature, never a panic.
///
/// This function does **not** validate `exp`/`nbf`; the caller validates
/// temporal claims via [`JwtClaims`].
///
/// # Errors
///
/// Returns [`JwtSignatureError`] if the token is malformed, the algorithm
/// is `none` or does not match the key, or the signature is invalid.
#[cfg(feature = "asym-jwt")]
#[must_use = "verification may fail; handle the Result"]
pub fn verify_jwt_asymmetric(
    token: &str,
    key: &super::AsymmetricVerifyingKey,
) -> Result<(JwtHeader, JwtClaims), JwtSignatureError> {
    let (header_b64, payload_b64, signature_b64) = split_compact(token)?;

    let header = JwtHeader::parse(header_b64)?;

    // SECURITY: reject `none` and any algorithm that is not the key's.
    if header.alg() == JwtAlgorithm::None {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::NoneAlgorithm,
        });
    }
    if header.alg() != key.algorithm().to_jwt_algorithm() {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::AlgorithmMismatch,
        });
    }

    let provided_sig = decode_signature(signature_b64)?;

    let signing_input = signing_input(header_b64, payload_b64);

    if !key.verify(signing_input.as_bytes(), &provided_sig) {
        return Err(JwtSignatureError {
            kind: JwtSignatureErrorKind::InvalidSignature,
        });
    }

    let claims = JwtClaims::parse(payload_b64)?;
    Ok((header, claims))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::error::Error as _;

    use super::*;
    use crate::encoding::base64url_encode;

    /// Helper: creates a signed JWT token string for testing.
    fn make_jwt(header_json: &str, claims_json: &str, key: &[u8], alg: &str) -> String {
        let header_b64 = base64url_encode(header_json.as_bytes());
        let payload_b64 = base64url_encode(claims_json.as_bytes());
        let signing_input = format!("{header_b64}.{payload_b64}");

        let sig = match alg {
            "HS256" => {
                let mac = HmacSha256::mac(key, signing_input.as_bytes());
                base64url_encode(&mac)
            }
            "HS512" => {
                let mac = HmacSha512::mac(key, signing_input.as_bytes());
                base64url_encode(&mac)
            }
            _ => String::new(),
        };

        format!("{header_b64}.{payload_b64}.{sig}")
    }

    const TEST_KEY: &[u8] = b"super-secret-key-for-testing-only";

    // --- Valid HS256 JWT verification ---

    #[test]
    fn verify_valid_hs256() {
        let header = r#"{"alg":"HS256","typ":"JWT"}"#;
        let claims = r#"{"iss":"test","sub":"user-1","aud":"my-app","exp":9999999999}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let (hdr, clm) = verify_jwt(&token, TEST_KEY).unwrap();
        assert_eq!(hdr.alg(), JwtAlgorithm::HS256);
        assert_eq!(clm.iss(), Some("test"));
        assert_eq!(clm.sub(), Some("user-1"));
        assert!(clm.validate_aud("my-app"));
    }

    // --- Valid HS512 JWT verification ---

    #[test]
    fn verify_valid_hs512() {
        let header = r#"{"alg":"HS512","typ":"JWT"}"#;
        let claims = r#"{"iss":"test","sub":"user-2"}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS512");

        let (hdr, clm) = verify_jwt(&token, TEST_KEY).unwrap();
        assert_eq!(hdr.alg(), JwtAlgorithm::HS512);
        assert_eq!(clm.sub(), Some("user-2"));
    }

    // --- Invalid signature rejected ---

    #[test]
    fn reject_invalid_signature() {
        let header = r#"{"alg":"HS256","typ":"JWT"}"#;
        let claims = r#"{"sub":"user-1"}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        // Verify with a different key should fail.
        let err = verify_jwt(&token, b"wrong-key").unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::InvalidSignature,
            },
        );
        assert!(err.to_string().contains("signature verification failed"));
    }

    #[test]
    fn reject_tampered_payload() {
        let header = r#"{"alg":"HS256","typ":"JWT"}"#;
        let claims = r#"{"sub":"user-1"}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        // Replace the payload with a different one (keeping original signature).
        let parts: Vec<&str> = token.splitn(3, '.').collect();
        let tampered_payload = base64url_encode(br#"{"sub":"admin"}"#);
        let tampered = format!("{}.{}.{}", parts[0], tampered_payload, parts[2]);

        assert!(verify_jwt(&tampered, TEST_KEY).is_err());
    }

    // --- "none" algorithm rejected ---

    #[test]
    fn reject_none_algorithm() {
        let header = r#"{"alg":"none"}"#;
        let claims = r#"{"sub":"attacker"}"#;
        let header_b64 = base64url_encode(header.as_bytes());
        let payload_b64 = base64url_encode(claims.as_bytes());
        // "none" algorithm tokens typically have an empty signature segment.
        let token = format!("{header_b64}.{payload_b64}.");

        let err = verify_jwt(&token, TEST_KEY).unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::NoneAlgorithm,
            },
        );
        assert!(err.to_string().contains("none"));
    }

    // --- Algorithm-confusion (RS256/EdDSA presented to the HMAC verifier) ---

    #[cfg(feature = "asym-jwt")]
    #[test]
    fn reject_asymmetric_alg_on_hmac_verifier() {
        // The classic RS256โ†’HS256 confusion attack: present an asymmetric
        // token to the HMAC `verify_jwt`, passing the public key bytes as the
        // "HMAC secret". The asym arm must reject with `AlgorithmMismatch`
        // *before* treating the key as an HMAC secret โ€” never compute an HMAC
        // over the public key. We don't need a real signature: the algorithm
        // check fires first.
        for alg in ["RS256", "RS512", "ES256", "EdDSA"] {
            let header = format!(r#"{{"alg":"{alg}"}}"#);
            let header_b64 = base64url_encode(header.as_bytes());
            let payload_b64 = base64url_encode(br#"{"sub":"attacker"}"#);
            let token = format!("{header_b64}.{payload_b64}.AAAA");

            let err = verify_jwt(&token, b"public-key-bytes-as-hmac-secret").unwrap_err();
            assert!(
                err.is_algorithm_mismatch(),
                "{alg} token must be rejected as algorithm mismatch on the HMAC verifier"
            );
        }
    }

    #[cfg(feature = "asym-jwt")]
    #[test]
    fn reject_hmac_alg_on_asymmetric_verifier() {
        // The inverse confusion: an `HS256` token presented to the asymmetric
        // verifier must be rejected as an algorithm mismatch, not verified.
        use crate::jwt::{AsymmetricAlgorithm, AsymmetricSigningKey};

        let signing = AsymmetricSigningKey::generate(AsymmetricAlgorithm::EdDsa).unwrap();
        let verifying = signing.to_verifying_key();

        let header = r#"{"alg":"HS256"}"#;
        let claims = r#"{"sub":"attacker"}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let err = verify_jwt_asymmetric(&token, &verifying).unwrap_err();
        assert!(err.is_algorithm_mismatch());
    }

    // --- Expired claims ---

    #[test]
    fn expired_claims_validation() {
        let header = r#"{"alg":"HS256"}"#;
        let claims = r#"{"exp": 1000}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let (_, clm) = verify_jwt(&token, TEST_KEY).unwrap();
        // Token expired at t=1000, current time is t=2000.
        assert!(!clm.validate_exp(2000, 0));
    }

    #[test]
    fn not_expired_claims_validation() {
        let header = r#"{"alg":"HS256"}"#;
        let claims = r#"{"exp": 9999999999}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let (_, clm) = verify_jwt(&token, TEST_KEY).unwrap();
        assert!(clm.validate_exp(1000, 0));
    }

    // --- Wrong audience ---

    #[test]
    fn wrong_audience() {
        let header = r#"{"alg":"HS256"}"#;
        let claims = r#"{"aud":"expected-client"}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let (_, clm) = verify_jwt(&token, TEST_KEY).unwrap();
        assert!(!clm.validate_aud("wrong-client"));
        assert!(clm.validate_aud("expected-client"));
    }

    // --- Wrong issuer ---

    #[test]
    fn wrong_issuer() {
        let header = r#"{"alg":"HS256"}"#;
        let claims = r#"{"iss":"https://auth.example.com"}"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let (_, clm) = verify_jwt(&token, TEST_KEY).unwrap();
        assert!(!clm.validate_iss("https://evil.example.com"));
        assert!(clm.validate_iss("https://auth.example.com"));
    }

    // --- Malformed JWT ---

    #[test]
    fn reject_missing_parts() {
        // Only one segment.
        let err = verify_jwt("onlyonepart", TEST_KEY).unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::MalformedToken,
            },
        );
    }

    #[test]
    fn reject_two_parts() {
        let err = verify_jwt("part1.part2", TEST_KEY).unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::MalformedToken,
            },
        );
    }

    #[test]
    fn reject_four_parts() {
        let err = verify_jwt("a.b.c.d", TEST_KEY).unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::MalformedToken,
            },
        );
    }

    #[test]
    fn reject_empty_token() {
        let err = verify_jwt("", TEST_KEY).unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::MalformedToken,
            },
        );
    }

    #[test]
    fn reject_invalid_header_encoding() {
        let err = verify_jwt("!!!.payload.sig", TEST_KEY).unwrap_err();
        assert!(
            err.to_string().contains("invalid header"),
            "expected 'invalid header' in '{err}'",
        );
        // SECURITY: Verify the source error is preserved for diagnostics.
        assert!(
            err.source().is_some(),
            "expected source error for HeaderError"
        );
    }

    #[test]
    fn reject_invalid_signature_encoding() {
        let header = r#"{"alg":"HS256"}"#;
        let claims = r#"{"sub":"user"}"#;
        let header_b64 = base64url_encode(header.as_bytes());
        let payload_b64 = base64url_encode(claims.as_bytes());
        let token = format!("{header_b64}.{payload_b64}.!!!invalid!!!");

        let err = verify_jwt(&token, TEST_KEY).unwrap_err();
        assert_eq!(
            err,
            JwtSignatureError {
                kind: JwtSignatureErrorKind::InvalidSignatureEncoding,
            },
        );
    }

    // --- Display ---

    #[test]
    fn error_display_messages() {
        // NOTE: HeaderError and ClaimsError now wrap their source errors,
        // so we test them separately with dummy inner values.
        let simple_cases = [
            (
                JwtSignatureErrorKind::MalformedToken,
                "malformed token structure",
            ),
            (JwtSignatureErrorKind::NoneAlgorithm, "none"),
            (
                JwtSignatureErrorKind::InvalidSignature,
                "signature verification failed",
            ),
            (
                JwtSignatureErrorKind::InvalidSignatureEncoding,
                "invalid signature encoding",
            ),
        ];

        for (kind, expected_substr) in simple_cases {
            let err = JwtSignatureError { kind };
            assert!(
                err.to_string().contains(expected_substr),
                "expected '{expected_substr}' in '{err}'",
            );
        }

        // Verify display for variants wrapping source errors.
        let header_err = JwtSignatureError::from(JwtHeader::parse("!!!invalid!!!").unwrap_err());
        assert!(
            header_err.to_string().contains("invalid header"),
            "expected 'invalid header' in '{header_err}'",
        );

        let claims_err = JwtSignatureError::from(JwtClaims::parse("!!!invalid!!!").unwrap_err());
        assert!(
            claims_err.to_string().contains("invalid claims"),
            "expected 'invalid claims' in '{claims_err}'",
        );
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> = Box::new(JwtSignatureError {
            kind: JwtSignatureErrorKind::InvalidSignature,
        });
        let _ = err.to_string();
    }

    // --- End-to-end with full claim set ---

    #[test]
    fn end_to_end_full_claim_set() {
        let header = r#"{"alg":"HS256","typ":"JWT","kid":"test-key-1"}"#;
        let claims = r#"{
            "iss": "https://auth.example.com",
            "sub": "user-42",
            "aud": ["app-1", "app-2"],
            "exp": 9999999999,
            "nbf": 1000,
            "iat": 1000,
            "jti": "token-id-xyz",
            "custom": "value"
        }"#;
        let token = make_jwt(header, claims, TEST_KEY, "HS256");

        let (hdr, clm) = verify_jwt(&token, TEST_KEY).unwrap();

        assert_eq!(hdr.alg(), JwtAlgorithm::HS256);
        assert_eq!(hdr.typ(), Some("JWT"));
        assert_eq!(hdr.kid(), Some("test-key-1"));

        assert_eq!(clm.iss(), Some("https://auth.example.com"));
        assert_eq!(clm.sub(), Some("user-42"));
        assert_eq!(clm.aud(), &["app-1", "app-2"]);
        assert_eq!(clm.exp(), Some(9_999_999_999));
        assert_eq!(clm.nbf(), Some(1000));
        assert_eq!(clm.iat(), Some(1000));
        assert_eq!(clm.jti(), Some("token-id-xyz"));
        assert_eq!(
            clm.get_claim("custom").and_then(|v| v.as_str()),
            Some("value"),
        );

        assert!(clm.validate_iss("https://auth.example.com"));
        assert!(clm.validate_aud("app-1"));
        assert!(clm.validate_aud("app-2"));
        assert!(clm.validate_exp(5000, 0));
    }
}