1use crate::errors::{AuthError, Result};
2use jsonwebtoken::{Algorithm, DecodingKey};
3use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5use std::time::Duration;
6use zeroize::Zeroizing;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct SecureJwtClaims {
10 pub sub: String,
11 pub iss: String,
12 pub aud: String,
13 pub exp: i64,
14 pub nbf: i64,
15 pub iat: i64,
16 pub jti: String,
17 pub scope: String,
18 pub typ: String,
19 pub sid: Option<String>,
20 pub client_id: Option<String>,
21 pub auth_ctx_hash: Option<String>,
22}
23
24#[derive(Debug, Clone)]
25pub struct SecureJwtConfig {
26 pub allowed_algorithms: Vec<Algorithm>,
27 pub required_issuers: HashSet<String>,
28 pub required_audiences: HashSet<String>,
29 pub max_token_lifetime: Duration,
30 pub clock_skew: Duration,
31 pub require_jti: bool,
32 pub validate_nbf: bool,
33 pub allowed_token_types: HashSet<String>,
34 pub require_secure_transport: bool,
35 pub jwt_secret: Zeroizing<String>,
37 pub rsa_public_key_pem: Option<String>,
39 pub ec_public_key_pem: Option<String>,
41 pub ed_public_key_pem: Option<String>,
43}
44
45impl Default for SecureJwtConfig {
46 fn default() -> Self {
47 use ring::rand::{SecureRandom, SystemRandom};
54 let rng = SystemRandom::new();
57 let mut bytes = [0u8; 32];
58 rng.fill(&mut bytes)
59 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
60 let jwt_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
61 s.push_str(&format!("{b:02x}"));
62 s
63 });
64
65 let mut allowed_token_types = HashSet::new();
66 allowed_token_types.insert("access".to_string());
67 allowed_token_types.insert("refresh".to_string());
68 allowed_token_types.insert("JARM".to_string());
69
70 let mut required_issuers = HashSet::new();
71 required_issuers.insert("auth-framework".to_string());
72
73 Self {
74 allowed_algorithms: vec![Algorithm::HS256],
78 required_issuers,
79 required_audiences: HashSet::new(),
80 max_token_lifetime: Duration::from_secs(3600),
81 clock_skew: Duration::from_secs(30),
82 require_jti: true,
83 validate_nbf: true,
84 allowed_token_types,
85 require_secure_transport: true,
86 jwt_secret: jwt_secret.into(),
87 rsa_public_key_pem: None,
88 ec_public_key_pem: None,
89 ed_public_key_pem: None,
90 }
91 }
92}
93
94fn is_hmac_algorithm(alg: Algorithm) -> bool {
96 matches!(alg, Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512)
97}
98
99impl SecureJwtConfig {
122 pub fn builder() -> SecureJwtConfigBuilder {
124 SecureJwtConfigBuilder::default()
125 }
126}
127
128#[derive(Default)]
130pub struct SecureJwtConfigBuilder {
131 config: SecureJwtConfig,
132}
133
134impl SecureJwtConfigBuilder {
135 pub fn with_algorithm(mut self, algo: Algorithm) -> Self {
137 self.config.allowed_algorithms.push(algo);
138 self
139 }
140
141 pub fn with_algorithms(mut self, algos: Vec<Algorithm>) -> Self {
143 self.config.allowed_algorithms = algos;
144 self
145 }
146
147 pub fn require_issuer(mut self, issuer: impl Into<String>) -> Self {
149 self.config.required_issuers.insert(issuer.into());
150 self
151 }
152
153 pub fn require_audience(mut self, audience: impl Into<String>) -> Self {
155 self.config.required_audiences.insert(audience.into());
156 self
157 }
158
159 pub fn with_max_lifetime(mut self, lifetime: Duration) -> Self {
161 self.config.max_token_lifetime = lifetime;
162 self
163 }
164
165 pub fn with_clock_skew(mut self, skew: Duration) -> Self {
167 self.config.clock_skew = skew;
168 self
169 }
170
171 pub fn require_jti(mut self, require: bool) -> Self {
173 self.config.require_jti = require;
174 self
175 }
176
177 pub fn with_secret(mut self, secret: impl Into<String>) -> Self {
179 self.config.jwt_secret = Zeroizing::new(secret.into());
180 self
181 }
182
183 pub fn build(self) -> SecureJwtConfig {
185 self.config
186 }
187}
188
189pub struct SecureJwtValidator {
190 config: SecureJwtConfig,
191 revoked_tokens: std::sync::Mutex<std::collections::HashMap<String, std::time::SystemTime>>,
196 on_revoke: std::sync::Mutex<Option<RevokeCallback>>,
202}
203
204type RevokeCallback = Box<dyn Fn(&str) + Send + Sync>;
206
207impl std::fmt::Debug for SecureJwtValidator {
208 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209 f.debug_struct("SecureJwtValidator")
210 .field("config", &self.config)
211 .field("revoked_tokens", &self.revoked_tokens)
212 .field(
213 "on_revoke",
214 &self.on_revoke.lock().ok().map(|g| g.is_some()),
215 )
216 .finish()
217 }
218}
219
220impl SecureJwtValidator {
221 pub fn new(config: SecureJwtConfig) -> Result<Self> {
222 let has_hmac = config
224 .allowed_algorithms
225 .iter()
226 .any(|a| is_hmac_algorithm(*a));
227 let has_rsa = config.allowed_algorithms.iter().any(|a| {
228 matches!(
229 a,
230 Algorithm::RS256
231 | Algorithm::RS384
232 | Algorithm::RS512
233 | Algorithm::PS256
234 | Algorithm::PS384
235 | Algorithm::PS512
236 )
237 });
238 let has_ec = config
239 .allowed_algorithms
240 .iter()
241 .any(|a| matches!(a, Algorithm::ES256 | Algorithm::ES384));
242 let has_eddsa = config
243 .allowed_algorithms
244 .iter()
245 .any(|a| matches!(a, Algorithm::EdDSA));
246
247 if has_hmac {
248 #[cfg(not(test))]
249 if config.jwt_secret.len() < 32 {
250 return Err(AuthError::Configuration {
251 message: "SecureJwtConfig::jwt_secret must be at least 32 characters \
252 when HMAC algorithms are enabled"
253 .to_string(),
254 help: Some(
255 "Provide a cryptographically random secret unique to your deployment"
256 .to_string(),
257 ),
258 docs_url: None,
259 source: None,
260 suggested_fix: None,
261 });
262 }
263 }
264 if has_rsa && config.rsa_public_key_pem.is_none() {
265 return Err(AuthError::Configuration {
266 message: "SecureJwtConfig::rsa_public_key_pem must be set when RSA/PS algorithms are enabled".to_string(),
267 help: Some("Set rsa_public_key_pem in SecureJwtConfig".to_string()),
268 docs_url: None,
269 source: None,
270 suggested_fix: None,
271 });
272 }
273 if has_ec && config.ec_public_key_pem.is_none() {
274 return Err(AuthError::Configuration {
275 message:
276 "SecureJwtConfig::ec_public_key_pem must be set when EC algorithms are enabled"
277 .to_string(),
278 help: Some("Set ec_public_key_pem in SecureJwtConfig".to_string()),
279 docs_url: None,
280 source: None,
281 suggested_fix: None,
282 });
283 }
284 if has_eddsa && config.ed_public_key_pem.is_none() {
285 return Err(AuthError::Configuration {
286 message: "SecureJwtConfig::ed_public_key_pem must be set when EdDSA is enabled"
287 .to_string(),
288 help: Some("Set ed_public_key_pem in SecureJwtConfig".to_string()),
289 docs_url: None,
290 source: None,
291 suggested_fix: None,
292 });
293 }
294
295 Ok(Self {
296 config,
297 revoked_tokens: std::sync::Mutex::new(std::collections::HashMap::new()),
298 on_revoke: std::sync::Mutex::new(None),
299 })
300 }
301
302 pub fn set_on_revoke<F>(&self, callback: F)
317 where
318 F: Fn(&str) + Send + Sync + 'static,
319 {
320 let mut guard = match self.on_revoke.lock() {
321 Ok(g) => g,
322 Err(poisoned) => poisoned.into_inner(),
323 };
324 *guard = Some(Box::new(callback));
325 }
326
327 pub fn get_decoding_key(&self) -> jsonwebtoken::DecodingKey {
331 jsonwebtoken::DecodingKey::from_secret(self.config.jwt_secret.as_bytes())
332 }
333
334 pub fn get_encoding_key(&self) -> jsonwebtoken::EncodingKey {
336 jsonwebtoken::EncodingKey::from_secret(self.config.jwt_secret.as_bytes())
337 }
338
339 fn decoding_key_for_algorithm(&self, alg: Algorithm) -> Result<DecodingKey> {
341 match alg {
342 Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
343 Ok(DecodingKey::from_secret(self.config.jwt_secret.as_bytes()))
344 }
345 Algorithm::RS256
346 | Algorithm::RS384
347 | Algorithm::RS512
348 | Algorithm::PS256
349 | Algorithm::PS384
350 | Algorithm::PS512 => {
351 let pem = self.config.rsa_public_key_pem.as_deref().ok_or_else(|| {
352 AuthError::Configuration {
353 message: "RSA public key PEM not configured".to_string(),
354 help: Some(
355 "Set rsa_public_key_pem in SecureJwtConfig for RSA/PS algorithms"
356 .to_string(),
357 ),
358 docs_url: None,
359 source: None,
360 suggested_fix: None,
361 }
362 })?;
363 DecodingKey::from_rsa_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
364 message: format!("Invalid RSA public key PEM: {e}"),
365 help: None,
366 docs_url: None,
367 source: None,
368 suggested_fix: None,
369 })
370 }
371 Algorithm::ES256 | Algorithm::ES384 => {
372 let pem = self.config.ec_public_key_pem.as_deref().ok_or_else(|| {
373 AuthError::Configuration {
374 message: "EC public key PEM not configured".to_string(),
375 help: Some(
376 "Set ec_public_key_pem in SecureJwtConfig for EC algorithms"
377 .to_string(),
378 ),
379 docs_url: None,
380 source: None,
381 suggested_fix: None,
382 }
383 })?;
384 DecodingKey::from_ec_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
385 message: format!("Invalid EC public key PEM: {e}"),
386 help: None,
387 docs_url: None,
388 source: None,
389 suggested_fix: None,
390 })
391 }
392 Algorithm::EdDSA => {
393 let pem = self.config.ed_public_key_pem.as_deref().ok_or_else(|| {
394 AuthError::Configuration {
395 message: "Ed25519 public key PEM not configured".to_string(),
396 help: Some(
397 "Set ed_public_key_pem in SecureJwtConfig for EdDSA".to_string(),
398 ),
399 docs_url: None,
400 source: None,
401 suggested_fix: None,
402 }
403 })?;
404 DecodingKey::from_ed_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
405 message: format!("Invalid Ed25519 public key PEM: {e}"),
406 help: None,
407 docs_url: None,
408 source: None,
409 suggested_fix: None,
410 })
411 }
412 }
413 }
414
415 pub fn validate(&self, token: &str) -> Result<SecureJwtClaims> {
424 let header = jsonwebtoken::decode_header(token)
426 .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
427
428 if !self.config.allowed_algorithms.contains(&header.alg) {
430 return Err(AuthError::Unauthorized(format!(
431 "Token algorithm {:?} is not permitted; allowed: {:?}",
432 header.alg, self.config.allowed_algorithms
433 )));
434 }
435
436 let decoding_key = self.decoding_key_for_algorithm(header.alg)?;
438
439 let mut validation = jsonwebtoken::Validation::new(header.alg);
441 validation.algorithms = self.config.allowed_algorithms.clone();
442 validation.leeway = self.config.clock_skew.as_secs();
443
444 validation.validate_exp = true;
446
447 validation.validate_nbf = self.config.validate_nbf;
449
450 if !self.config.required_audiences.is_empty() {
452 validation.set_audience(
453 &self
454 .config
455 .required_audiences
456 .iter()
457 .collect::<Vec<&String>>(),
458 );
459 } else {
460 validation.validate_aud = false;
461 }
462
463 if !self.config.required_issuers.is_empty() {
465 validation.set_issuer(
466 &self
467 .config
468 .required_issuers
469 .iter()
470 .collect::<Vec<&String>>(),
471 );
472 }
473
474 let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, &decoding_key, &validation)
476 .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
477
478 let claims = token_data.claims;
479
480 if self.is_token_revoked(&claims.jti)? {
484 return Err(AuthError::Unauthorized("Token is revoked".to_string()));
485 }
486
487 let token_lifetime = claims.exp.saturating_sub(claims.iat);
489 if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
490 {
491 return Err(AuthError::Unauthorized(format!(
492 "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
493 self.config.max_token_lifetime.as_secs()
494 )));
495 }
496
497 if self.config.require_jti && claims.jti.is_empty() {
499 return Err(AuthError::Unauthorized(
500 "Token missing required JTI claim".to_string(),
501 ));
502 }
503
504 if !self.config.allowed_token_types.is_empty()
506 && !claims.typ.is_empty()
507 && !self.config.allowed_token_types.contains(&claims.typ)
508 {
509 return Err(AuthError::Unauthorized(format!(
510 "Token type '{}' is not permitted",
511 claims.typ
512 )));
513 }
514
515 Ok(claims)
516 }
517
518 pub fn validate_token(
523 &self,
524 token: &str,
525 decoding_key: &DecodingKey,
526 ) -> Result<SecureJwtClaims> {
527 let header = jsonwebtoken::decode_header(token)
528 .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
529
530 if !self.config.allowed_algorithms.contains(&header.alg) {
531 return Err(AuthError::Unauthorized(format!(
532 "Token algorithm {:?} is not permitted; allowed: {:?}",
533 header.alg, self.config.allowed_algorithms
534 )));
535 }
536
537 let mut validation = jsonwebtoken::Validation::new(header.alg);
538 validation.algorithms = self.config.allowed_algorithms.clone();
539 validation.leeway = self.config.clock_skew.as_secs();
540 validation.validate_exp = true;
541 validation.validate_nbf = self.config.validate_nbf;
542
543 if !self.config.required_audiences.is_empty() {
544 validation.set_audience(
545 &self
546 .config
547 .required_audiences
548 .iter()
549 .collect::<Vec<&String>>(),
550 );
551 } else {
552 validation.validate_aud = false;
553 }
554
555 if !self.config.required_issuers.is_empty() {
556 validation.set_issuer(
557 &self
558 .config
559 .required_issuers
560 .iter()
561 .collect::<Vec<&String>>(),
562 );
563 }
564
565 let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, decoding_key, &validation)
566 .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
567
568 let claims = token_data.claims;
569
570 if self.is_token_revoked(&claims.jti)? {
571 return Err(AuthError::Unauthorized("Token is revoked".to_string()));
572 }
573
574 let token_lifetime = claims.exp.saturating_sub(claims.iat);
575 if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
576 {
577 return Err(AuthError::Unauthorized(format!(
578 "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
579 self.config.max_token_lifetime.as_secs()
580 )));
581 }
582
583 if self.config.require_jti && claims.jti.is_empty() {
584 return Err(AuthError::Unauthorized(
585 "Token missing required JTI claim".to_string(),
586 ));
587 }
588
589 if !self.config.allowed_token_types.is_empty()
590 && !claims.typ.is_empty()
591 && !self.config.allowed_token_types.contains(&claims.typ)
592 {
593 return Err(AuthError::Unauthorized(format!(
594 "Token type '{}' is not permitted",
595 claims.typ
596 )));
597 }
598
599 Ok(claims)
600 }
601
602 pub fn is_token_revoked(&self, jti: &str) -> Result<bool> {
608 let revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
609 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
610 })?;
611 Ok(revoked_tokens.contains_key(jti))
612 }
613
614 pub fn revoke_token(&self, jti: &str) -> Result<()> {
624 {
625 let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
626 AuthError::internal(
627 "Lock poisoned — a prior thread panicked while holding this lock",
628 )
629 })?;
630 revoked_tokens.insert(jti.to_string(), std::time::SystemTime::now());
631 }
632 if let Some(ref cb) = *self.on_revoke.lock().map_err(|_| {
635 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
636 })? {
637 cb(jti);
638 }
639 Ok(())
640 }
641
642 pub fn cleanup_revoked_tokens(&self, expired_cutoff: std::time::SystemTime) -> Result<()> {
652 const MAX_REVOKED_TOKENS: usize = 10_000;
653 let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
654 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
655 })?;
656
657 revoked_tokens.retain(|_, inserted_at| *inserted_at >= expired_cutoff);
660
661 if revoked_tokens.len() > MAX_REVOKED_TOKENS {
664 let target_len = MAX_REVOKED_TOKENS * 3 / 4;
665 let mut by_age: Vec<(String, std::time::SystemTime)> = revoked_tokens.drain().collect();
666 by_age.sort_unstable_by_key(|(_, t)| *t);
667 for (jti, inserted_at) in by_age.into_iter().rev().take(target_len) {
669 revoked_tokens.insert(jti, inserted_at);
670 }
671 tracing::warn!(
672 "Revoked token list exceeded {} entries; oldest entries were evicted.",
673 MAX_REVOKED_TOKENS
674 );
675 }
676
677 Ok(())
678 }
679}
680
681#[cfg(test)]
682mod tests {
683 use super::*;
684 use jsonwebtoken::{Algorithm, EncodingKey, Header};
685
686 fn test_config() -> SecureJwtConfig {
687 SecureJwtConfig {
688 jwt_secret: "a]test_secret_that_is_longer_than_32_chars_for_security!"
689 .to_string()
690 .into(),
691 ..SecureJwtConfig::default()
692 }
693 }
694
695 fn issue_token(config: &SecureJwtConfig, claims: &SecureJwtClaims) -> String {
696 let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
697 jsonwebtoken::encode(&Header::new(Algorithm::HS256), claims, &key).unwrap()
698 }
699
700 fn valid_claims() -> SecureJwtClaims {
701 let now = chrono::Utc::now().timestamp();
702 SecureJwtClaims {
703 sub: "user123".to_string(),
704 iss: "auth-framework".to_string(),
705 aud: "test".to_string(),
706 exp: now + 600,
707 nbf: now - 10,
708 iat: now,
709 jti: uuid::Uuid::new_v4().to_string(),
710 scope: "read".to_string(),
711 typ: "access".to_string(),
712 sid: None,
713 client_id: None,
714 auth_ctx_hash: None,
715 }
716 }
717
718 #[test]
719 fn test_default_config_generates_random_secret() {
720 let c1 = SecureJwtConfig::default();
721 let c2 = SecureJwtConfig::default();
722 assert_ne!(c1.jwt_secret, c2.jwt_secret);
723 assert!(c1.jwt_secret.len() >= 32);
724 }
725
726 #[test]
727 fn test_builder_fluent_api() {
728 let config = SecureJwtConfig::builder()
729 .with_secret("a]test_secret_that_is_longer_than_32_chars_for_security!")
730 .require_issuer("my-issuer")
731 .require_audience("my-aud")
732 .with_max_lifetime(Duration::from_secs(7200))
733 .with_clock_skew(Duration::from_secs(60))
734 .require_jti(false)
735 .build();
736
737 assert!(config.required_issuers.contains("my-issuer"));
738 assert!(config.required_audiences.contains("my-aud"));
739 assert_eq!(config.max_token_lifetime, Duration::from_secs(7200));
740 assert_eq!(config.clock_skew, Duration::from_secs(60));
741 assert!(!config.require_jti);
742 }
743
744 #[test]
745 fn test_validate_valid_token() {
746 let config = test_config();
747 let claims = valid_claims();
748 let token = issue_token(&config, &claims);
749 let validator = SecureJwtValidator::new(config).unwrap();
750 let result = validator.validate(&token).unwrap();
751 assert_eq!(result.sub, "user123");
752 assert_eq!(result.iss, "auth-framework");
753 }
754
755 #[test]
756 fn test_validate_rejects_expired_token() {
757 let config = test_config();
758 let mut claims = valid_claims();
759 claims.exp = chrono::Utc::now().timestamp() - 3600;
760 claims.iat = claims.exp - 600;
761 let token = issue_token(&config, &claims);
762 let validator = SecureJwtValidator::new(config).unwrap();
763 assert!(validator.validate(&token).is_err());
764 }
765
766 #[test]
767 fn test_validate_rejects_wrong_issuer() {
768 let config = test_config();
769 let mut claims = valid_claims();
770 claims.iss = "evil-issuer".to_string();
771 let token = issue_token(&config, &claims);
772 let validator = SecureJwtValidator::new(config).unwrap();
773 assert!(validator.validate(&token).is_err());
774 }
775
776 #[test]
777 fn test_revoke_and_check() {
778 let config = test_config();
779 let validator = SecureJwtValidator::new(config).unwrap();
780 let jti = "test-jti-123";
781 assert!(!validator.is_token_revoked(jti).unwrap());
782 validator.revoke_token(jti).unwrap();
783 assert!(validator.is_token_revoked(jti).unwrap());
784 }
785
786 #[test]
787 fn test_revoked_token_rejected() {
788 let config = test_config();
789 let claims = valid_claims();
790 let jti = claims.jti.clone();
791 let token = issue_token(&config, &claims);
792 let validator = SecureJwtValidator::new(config).unwrap();
793 validator.revoke_token(&jti).unwrap();
794 assert!(validator.validate(&token).is_err());
795 }
796
797 #[test]
798 fn test_cleanup_removes_old_entries() {
799 let config = test_config();
800 let validator = SecureJwtValidator::new(config).unwrap();
801 validator.revoke_token("old-jti").unwrap();
802 let future = std::time::SystemTime::now() + Duration::from_secs(3600);
804 validator.cleanup_revoked_tokens(future).unwrap();
805 assert!(!validator.is_token_revoked("old-jti").unwrap());
806 }
807
808 #[test]
809 fn test_on_revoke_callback() {
810 let config = test_config();
811 let validator = SecureJwtValidator::new(config).unwrap();
812 let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
813 let captured_clone = captured.clone();
814 validator.set_on_revoke(move |jti| {
815 captured_clone.lock().unwrap().push(jti.to_string());
816 });
817 validator.revoke_token("cb-jti-1").unwrap();
818 validator.revoke_token("cb-jti-2").unwrap();
819 let jtis = captured.lock().unwrap();
820 assert_eq!(jtis.len(), 2);
821 assert!(jtis.contains(&"cb-jti-1".to_string()));
822 assert!(jtis.contains(&"cb-jti-2".to_string()));
823 }
824
825 #[test]
826 fn test_rejects_disallowed_algorithm() {
827 let config = test_config();
828 let claims = valid_claims();
829 let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
831 let token = jsonwebtoken::encode(&Header::new(Algorithm::HS384), &claims, &key).unwrap();
832 let validator = SecureJwtValidator::new(config).unwrap();
833 assert!(validator.validate(&token).is_err());
834 }
835
836 #[test]
837 fn test_rejects_excessive_lifetime() {
838 let mut config = test_config();
839 config.max_token_lifetime = Duration::from_secs(300);
840 let mut claims = valid_claims();
841 let now = chrono::Utc::now().timestamp();
842 claims.iat = now;
843 claims.exp = now + 600; let token = issue_token(&config, &claims);
845 let validator = SecureJwtValidator::new(config).unwrap();
846 assert!(validator.validate(&token).is_err());
847 }
848
849 #[test]
850 fn test_missing_rsa_key_rejected() {
851 let mut config = test_config();
852 config.allowed_algorithms = vec![Algorithm::RS256];
853 let result = SecureJwtValidator::new(config);
854 assert!(result.is_err());
855 }
856}