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