uselesskey-jsonwebtoken 0.7.0

jsonwebtoken adapter traits for uselesskey fixtures (EncodingKey/DecodingKey).
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
//! Comprehensive tests for uselesskey-jsonwebtoken integration
//!
//! Tests cover:
//! - JWT encoding/decoding with all key types
//! - Error handling for mismatched algorithms
//! - Key conversion edge cases
//! - Cross-key type validation failures
//! - Deterministic key behavior
//! - Negative test cases

mod testutil;

use jsonwebtoken::{Algorithm, DecodingKey, Header, Validation, decode, encode, errors::ErrorKind};
use serde::{Deserialize, Serialize};
use testutil::fx;
use uselesskey_core::{Factory, Seed};
use uselesskey_jsonwebtoken::JwtKeyExt;

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TestClaims {
    sub: String,
    exp: usize,
    iat: usize,
    iss: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    custom: Option<String>,
}

impl TestClaims {
    fn new(sub: &str, exp: usize, iat: usize, iss: &str) -> Self {
        Self {
            sub: sub.to_string(),
            exp,
            iat,
            iss: iss.to_string(),
            custom: None,
        }
    }

    fn with_custom(mut self, custom: &str) -> Self {
        self.custom = Some(custom.to_string());
        self
    }
}

#[cfg(feature = "rsa")]
mod rsa_tests {
    use super::*;
    use uselesskey_rsa::{RsaFactoryExt, RsaSpec};

    #[test]
    fn test_rsa_rs256_algorithm() {
        let fx = fx();
        let keypair = fx.rsa("test-rs256", RsaSpec::rs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::RS256);

        let token = encode(&header, &claims, &keypair.encoding_key())
            .unwrap_or_else(|e| panic!("Failed to encode with RS256: {:?}", e));

        let validation = Validation::new(Algorithm::RS256);
        let decoded = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation)
            .unwrap_or_else(|e| panic!("Failed to decode with RS256: {:?}", e));

        assert_eq!(decoded.claims, claims, "Claims mismatch for RS256");
    }

    #[test]
    fn test_rsa_custom_key_sizes() {
        let test_cases = [(2048, "rsa-2048"), (3072, "rsa-3072"), (4096, "rsa-4096")];

        for (bits, label) in test_cases {
            let fx = fx();
            let keypair = fx.rsa(label, RsaSpec::new(bits));

            let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, label);
            let header = Header::new(Algorithm::RS256);

            let token = encode(&header, &claims, &keypair.encoding_key())
                .unwrap_or_else(|e| panic!("Failed to encode with {}-bit key: {:?}", bits, e));

            let validation = Validation::new(Algorithm::RS256);
            let decoded = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation)
                .unwrap_or_else(|e| panic!("Failed to decode with {}-bit key: {:?}", bits, e));

            assert_eq!(
                decoded.claims, claims,
                "Claims mismatch for {}-bit key",
                bits
            );
        }
    }

    #[test]
    fn test_rsa_algorithm_mismatch_fails() {
        let fx = fx();
        let keypair = fx.rsa("test-mismatch", RsaSpec::rs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with RS256
        let header = Header::new(Algorithm::RS256);
        let token = encode(&header, &claims, &keypair.encoding_key()).unwrap();

        // Try to decode with RS384 validation (even though we don't support RS384, this tests validation)
        let validation = Validation::new(Algorithm::RS384);
        let result = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong algorithm should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidAlgorithm => {} // Expected
            other => panic!("Expected InvalidAlgorithm error, got: {:?}", other),
        }
    }

    #[test]
    fn test_rsa_cross_key_validation_fails() {
        let fx = fx();
        let key_a = fx.rsa("issuer-a", RsaSpec::rs256());
        let key_b = fx.rsa("issuer-b", RsaSpec::rs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "issuer-a");

        // Sign with key_a
        let header = Header::new(Algorithm::RS256);
        let token = encode(&header, &claims, &key_a.encoding_key()).unwrap();

        // Try to decode with key_b
        let validation = Validation::new(Algorithm::RS256);
        let result = decode::<TestClaims>(&token, &key_b.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong key should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidSignature => {} // Expected
            other => panic!("Expected InvalidSignature error, got: {:?}", other),
        }
    }

    #[test]
    fn test_rsa_mismatched_key_rejects_signature() {
        let fx = fx();
        let rsa = fx.rsa("mismatch-test", RsaSpec::rs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::RS256);

        // Sign a token with the real private key
        let token = encode(&header, &claims, &rsa.encoding_key()).unwrap();

        // Build a DecodingKey from the mismatched public key DER
        let mismatched_der = rsa.mismatched_public_key_spki_der();
        let mismatched_decoding_key = DecodingKey::from_rsa_der(&mismatched_der);

        // Attempting to verify with the mismatched key should fail
        let validation = Validation::new(Algorithm::RS256);
        let result = decode::<TestClaims>(&token, &mismatched_decoding_key, &validation);

        assert!(
            result.is_err(),
            "Decoding with mismatched public key should fail"
        );
        match result.unwrap_err().kind() {
            ErrorKind::InvalidSignature => {} // Expected
            other => panic!("Expected InvalidSignature error, got: {:?}", other),
        }
    }

    #[test]
    fn test_rsa_deterministic_keys() {
        let seed = Seed::from_env_value("deterministic-test-seed").unwrap();
        let fx1 = Factory::deterministic(seed);
        let fx2 = Factory::deterministic(seed);

        let key1 = fx1.rsa("deterministic-test", RsaSpec::rs256());
        let key2 = fx2.rsa("deterministic-test", RsaSpec::rs256());

        // Keys should be identical
        assert_eq!(
            key1.private_key_pkcs8_pem(),
            key2.private_key_pkcs8_pem(),
            "Deterministic keys should be identical"
        );

        // Test JWT creation with deterministic keys
        let claims = TestClaims::new("det-user", 2_000_000_000, 1234567890, "det-issuer");
        let header = Header::new(Algorithm::RS256);

        let token1 = encode(&header, &claims, &key1.encoding_key()).unwrap();
        let token2 = encode(&header, &claims, &key2.encoding_key()).unwrap();

        // Tokens should be identical when using identical keys and claims
        assert_eq!(
            token1, token2,
            "Tokens should be identical with deterministic keys"
        );

        // Both tokens should decode correctly
        let validation = Validation::new(Algorithm::RS256);
        let decoded1 = decode::<TestClaims>(&token1, &key1.decoding_key(), &validation).unwrap();
        let decoded2 = decode::<TestClaims>(&token2, &key2.decoding_key(), &validation).unwrap();

        assert_eq!(decoded1.claims, claims);
        assert_eq!(decoded2.claims, claims);
    }

    #[test]
    fn test_rsa_key_conversion_edge_cases() {
        let fx = fx();
        let keypair = fx.rsa("edge-case-test", RsaSpec::rs256());

        // Test that encoding and decoding keys can be created multiple times
        let enc_key1 = keypair.encoding_key();
        let enc_key2 = keypair.encoding_key();
        let dec_key1 = keypair.decoding_key();
        let dec_key2 = keypair.decoding_key();

        // Keys should be functionally identical
        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::RS256);

        let token1 = encode(&header, &claims, &enc_key1).unwrap();
        let token2 = encode(&header, &claims, &enc_key2).unwrap();

        // Tokens should be identical
        assert_eq!(token1, token2);

        // Both decoding keys should work
        let validation = Validation::new(Algorithm::RS256);
        let decoded1 = decode::<TestClaims>(&token1, &dec_key1, &validation).unwrap();
        let decoded2 = decode::<TestClaims>(&token2, &dec_key2, &validation).unwrap();

        assert_eq!(decoded1.claims, claims);
        assert_eq!(decoded2.claims, claims);
    }
}

#[cfg(feature = "ecdsa")]
mod ecdsa_tests {
    use super::*;
    use uselesskey_ecdsa::{EcdsaFactoryExt, EcdsaSpec};

    #[test]
    fn test_ecdsa_es256_algorithm() {
        let fx = fx();
        let keypair = fx.ecdsa("test-es256", EcdsaSpec::es256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::ES256);

        let token = encode(&header, &claims, &keypair.encoding_key())
            .unwrap_or_else(|e| panic!("Failed to encode with ES256: {:?}", e));

        let validation = Validation::new(Algorithm::ES256);
        let decoded = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation)
            .unwrap_or_else(|e| panic!("Failed to decode with ES256: {:?}", e));

        assert_eq!(decoded.claims, claims, "Claims mismatch for ES256");
    }

    #[test]
    fn test_ecdsa_es384_algorithm() {
        let fx = fx();
        let keypair = fx.ecdsa("test-es384", EcdsaSpec::es384());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::ES384);

        let token = encode(&header, &claims, &keypair.encoding_key())
            .unwrap_or_else(|e| panic!("Failed to encode with ES384: {:?}", e));

        let validation = Validation::new(Algorithm::ES384);
        let decoded = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation)
            .unwrap_or_else(|e| panic!("Failed to decode with ES384: {:?}", e));

        assert_eq!(decoded.claims, claims, "Claims mismatch for ES384");
    }

    #[test]
    fn test_ecdsa_algorithm_mismatch_fails() {
        let fx = fx();
        let keypair = fx.ecdsa("test-mismatch", EcdsaSpec::es256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with ES256
        let header = Header::new(Algorithm::ES256);
        let token = encode(&header, &claims, &keypair.encoding_key()).unwrap();

        // Try to decode with ES384 validation
        let validation = Validation::new(Algorithm::ES384);
        let result = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong algorithm should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidAlgorithm => {} // Expected
            other => panic!("Expected InvalidAlgorithm error, got: {:?}", other),
        }
    }

    #[test]
    fn test_ecdsa_cross_key_validation_fails() {
        let fx = fx();
        let key_a = fx.ecdsa("issuer-a", EcdsaSpec::es256());
        let key_b = fx.ecdsa("issuer-b", EcdsaSpec::es256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "issuer-a");

        // Sign with key_a
        let header = Header::new(Algorithm::ES256);
        let token = encode(&header, &claims, &key_a.encoding_key()).unwrap();

        // Try to decode with key_b
        let validation = Validation::new(Algorithm::ES256);
        let result = decode::<TestClaims>(&token, &key_b.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong key should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidSignature => {} // Expected
            other => panic!("Expected InvalidSignature error, got: {:?}", other),
        }
    }
}

#[cfg(feature = "ed25519")]
mod ed25519_tests {
    use super::*;
    use uselesskey_ed25519::{Ed25519FactoryExt, Ed25519Spec};

    #[test]
    fn test_ed25519_sign_and_verify() {
        let fx = fx();
        let keypair = fx.ed25519("test-ed25519", Ed25519Spec::new());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer")
            .with_custom("ed25519-test");

        let header = Header::new(Algorithm::EdDSA);
        let token = encode(&header, &claims, &keypair.encoding_key()).unwrap();

        let validation = Validation::new(Algorithm::EdDSA);
        let decoded = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation).unwrap();

        assert_eq!(decoded.claims, claims);
    }

    #[test]
    fn test_ed25519_cross_key_validation_fails() {
        let fx = fx();
        let key_a = fx.ed25519("issuer-a", Ed25519Spec::new());
        let key_b = fx.ed25519("issuer-b", Ed25519Spec::new());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "issuer-a");

        // Sign with key_a
        let header = Header::new(Algorithm::EdDSA);
        let token = encode(&header, &claims, &key_a.encoding_key()).unwrap();

        // Try to decode with key_b
        let validation = Validation::new(Algorithm::EdDSA);
        let result = decode::<TestClaims>(&token, &key_b.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong key should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidSignature => {} // Expected
            other => panic!("Expected InvalidSignature error, got: {:?}", other),
        }
    }

    #[test]
    fn test_ed25519_algorithm_mismatch_fails() {
        let fx = fx();
        let keypair = fx.ed25519("test-mismatch", Ed25519Spec::new());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with EdDSA
        let header = Header::new(Algorithm::EdDSA);
        let token = encode(&header, &claims, &keypair.encoding_key()).unwrap();

        // Try to decode with RS256 validation (completely different algorithm family)
        let validation = Validation::new(Algorithm::RS256);
        let result = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong algorithm should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidAlgorithm => {} // Expected
            other => panic!("Expected InvalidAlgorithm error, got: {:?}", other),
        }
    }
}

#[cfg(feature = "hmac")]
mod hmac_tests {
    use super::*;
    use uselesskey_hmac::{HmacFactoryExt, HmacSpec};

    #[test]
    fn test_hmac_hs256_algorithm() {
        let fx = fx();
        let secret = fx.hmac("test-hs256", HmacSpec::hs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::HS256);

        let token = encode(&header, &claims, &secret.encoding_key())
            .unwrap_or_else(|e| panic!("Failed to encode with HS256: {:?}", e));

        let validation = Validation::new(Algorithm::HS256);
        let decoded = decode::<TestClaims>(&token, &secret.decoding_key(), &validation)
            .unwrap_or_else(|e| panic!("Failed to decode with HS256: {:?}", e));

        assert_eq!(decoded.claims, claims, "Claims mismatch for HS256");
    }

    #[test]
    fn test_hmac_hs384_algorithm() {
        let fx = fx();
        let secret = fx.hmac("test-hs384", HmacSpec::hs384());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::HS384);

        let token = encode(&header, &claims, &secret.encoding_key())
            .unwrap_or_else(|e| panic!("Failed to encode with HS384: {:?}", e));

        let validation = Validation::new(Algorithm::HS384);
        let decoded = decode::<TestClaims>(&token, &secret.decoding_key(), &validation)
            .unwrap_or_else(|e| panic!("Failed to decode with HS384: {:?}", e));

        assert_eq!(decoded.claims, claims, "Claims mismatch for HS384");
    }

    #[test]
    fn test_hmac_hs512_algorithm() {
        let fx = fx();
        let secret = fx.hmac("test-hs512", HmacSpec::hs512());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");
        let header = Header::new(Algorithm::HS512);

        let token = encode(&header, &claims, &secret.encoding_key())
            .unwrap_or_else(|e| panic!("Failed to encode with HS512: {:?}", e));

        let validation = Validation::new(Algorithm::HS512);
        let decoded = decode::<TestClaims>(&token, &secret.decoding_key(), &validation)
            .unwrap_or_else(|e| panic!("Failed to decode with HS512: {:?}", e));

        assert_eq!(decoded.claims, claims, "Claims mismatch for HS512");
    }

    #[test]
    fn test_hmac_algorithm_mismatch_fails() {
        let fx = fx();
        let secret = fx.hmac("test-mismatch", HmacSpec::hs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with HS256
        let header = Header::new(Algorithm::HS256);
        let token = encode(&header, &claims, &secret.encoding_key()).unwrap();

        // Try to decode with HS384 validation
        let validation = Validation::new(Algorithm::HS384);
        let result = decode::<TestClaims>(&token, &secret.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong algorithm should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidAlgorithm => {} // Expected
            other => panic!("Expected InvalidAlgorithm error, got: {:?}", other),
        }
    }

    #[test]
    fn test_hmac_cross_secret_validation_fails() {
        let fx = fx();
        let secret_a = fx.hmac("secret-a", HmacSpec::hs256());
        let secret_b = fx.hmac("secret-b", HmacSpec::hs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with secret_a
        let header = Header::new(Algorithm::HS256);
        let token = encode(&header, &claims, &secret_a.encoding_key()).unwrap();

        // Try to decode with secret_b
        let validation = Validation::new(Algorithm::HS256);
        let result = decode::<TestClaims>(&token, &secret_b.decoding_key(), &validation);

        assert!(result.is_err(), "Decoding with wrong secret should fail");
        match result.unwrap_err().kind() {
            ErrorKind::InvalidSignature => {} // Expected
            other => panic!("Expected InvalidSignature error, got: {:?}", other),
        }
    }

    #[test]
    fn test_hmac_deterministic_secrets() {
        let seed = Seed::from_env_value("hmac-deterministic-test-seed").unwrap();
        let fx1 = Factory::deterministic(seed);
        let fx2 = Factory::deterministic(seed);

        let secret1 = fx1.hmac("deterministic-test", HmacSpec::hs256());
        let secret2 = fx2.hmac("deterministic-test", HmacSpec::hs256());

        // Secrets should be identical
        assert_eq!(
            secret1.secret_bytes(),
            secret2.secret_bytes(),
            "Deterministic secrets should be identical"
        );

        // Test JWT creation with deterministic secrets
        let claims = TestClaims::new("det-user", 2_000_000_000, 1234567890, "det-issuer");
        let header = Header::new(Algorithm::HS256);

        let token1 = encode(&header, &claims, &secret1.encoding_key()).unwrap();
        let token2 = encode(&header, &claims, &secret2.encoding_key()).unwrap();

        // Tokens should be identical when using identical secrets and claims
        assert_eq!(
            token1, token2,
            "Tokens should be identical with deterministic secrets"
        );

        // Both tokens should decode correctly
        let validation = Validation::new(Algorithm::HS256);
        let decoded1 = decode::<TestClaims>(&token1, &secret1.decoding_key(), &validation).unwrap();
        let decoded2 = decode::<TestClaims>(&token2, &secret2.decoding_key(), &validation).unwrap();

        assert_eq!(decoded1.claims, claims);
        assert_eq!(decoded2.claims, claims);
    }
}

#[cfg(all(feature = "rsa", feature = "ecdsa"))]
mod cross_algorithm_tests {
    use super::*;
    use uselesskey_ecdsa::{EcdsaFactoryExt, EcdsaSpec};
    use uselesskey_rsa::{RsaFactoryExt, RsaSpec};

    #[test]
    fn test_cross_algorithm_family_fails() {
        let fx = fx();
        let rsa_key = fx.rsa("rsa-test", RsaSpec::rs256());
        let ecdsa_key = fx.ecdsa("ecdsa-test", EcdsaSpec::es256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with RSA
        let header = Header::new(Algorithm::RS256);
        let token = encode(&header, &claims, &rsa_key.encoding_key()).unwrap();

        // Try to decode with ECDSA key
        let validation = Validation::new(Algorithm::RS256);
        let result = decode::<TestClaims>(&token, &ecdsa_key.decoding_key(), &validation);

        assert!(
            result.is_err(),
            "Decoding RSA token with ECDSA key should fail"
        );
    }

    #[test]
    fn test_cross_algorithm_validation_fails() {
        let fx = fx();
        let rsa_key = fx.rsa("rsa-test", RsaSpec::rs256());

        let claims = TestClaims::new("user123", 2_000_000_000, 1234567890, "test-issuer");

        // Sign with RSA
        let header = Header::new(Algorithm::RS256);
        let token = encode(&header, &claims, &rsa_key.encoding_key()).unwrap();

        // Try to decode with ES256 validation
        let validation = Validation::new(Algorithm::ES256);
        let result = decode::<TestClaims>(&token, &rsa_key.decoding_key(), &validation);

        assert!(
            result.is_err(),
            "Decoding with wrong algorithm validation should fail"
        );
        match result.unwrap_err().kind() {
            ErrorKind::InvalidAlgorithm => {} // Expected
            other => panic!("Expected InvalidAlgorithm error, got: {:?}", other),
        }
    }
}

#[test]
fn test_expired_token_fails() {
    #[cfg(feature = "rsa")]
    {
        use uselesskey_rsa::{RsaFactoryExt, RsaSpec};

        let fx = fx();
        let keypair = fx.rsa("expired-test", RsaSpec::rs256());

        // Create a token that's already expired
        let past_time = 1000000000; // 2001-09-09
        let claims = TestClaims::new("user123", past_time, past_time - 1000, "test-issuer");
        let header = Header::new(Algorithm::RS256);
        let token = encode(&header, &claims, &keypair.encoding_key()).unwrap();

        let mut validation = Validation::new(Algorithm::RS256);
        validation.validate_exp = true; // Ensure expiration is validated

        let result = decode::<TestClaims>(&token, &keypair.decoding_key(), &validation);
        assert!(result.is_err(), "Expired token should fail validation");
        match result.unwrap_err().kind() {
            ErrorKind::ExpiredSignature => {} // Expected
            other => panic!("Expected ExpiredSignature error, got: {:?}", other),
        }
    }
}

#[test]
fn test_malformed_token_fails() {
    #[cfg(feature = "hmac")]
    {
        use uselesskey_hmac::{HmacFactoryExt, HmacSpec};

        let fx = fx();
        let secret = fx.hmac("malformed-test", HmacSpec::hs256());

        let malformed_tokens = [
            "not.a.jwt",
            "invalid.header.payload",
            "header.invalidsignature",
            "too.many.parts.in.this.token.signature",
            "",
            "justonelongstring",
        ];

        let validation = Validation::new(Algorithm::HS256);

        for malformed_token in malformed_tokens {
            let result = decode::<TestClaims>(malformed_token, &secret.decoding_key(), &validation);
            assert!(
                result.is_err(),
                "Malformed token '{}' should fail",
                malformed_token
            );
        }
    }
}