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