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 other => Err(AuthError::Configuration {
426 message: format!("Unsupported JWT algorithm {other:?}"),
427 help: None,
428 docs_url: None,
429 source: None,
430 suggested_fix: None,
431 }),
432 }
433 }
434
435 pub fn validate(&self, token: &str) -> Result<SecureJwtClaims> {
444 let header = jsonwebtoken::decode_header(token)
446 .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
447
448 if !self.config.allowed_algorithms.contains(&header.alg) {
450 return Err(AuthError::Unauthorized(format!(
451 "Token algorithm {:?} is not permitted; allowed: {:?}",
452 header.alg, self.config.allowed_algorithms
453 )));
454 }
455
456 let decoding_key = self.decoding_key_for_algorithm(header.alg)?;
458
459 let mut validation = jsonwebtoken::Validation::new(header.alg);
461 validation.algorithms = self.config.allowed_algorithms.clone();
462 validation.leeway = self.config.clock_skew.as_secs();
463
464 validation.validate_exp = true;
466
467 validation.validate_nbf = self.config.validate_nbf;
469
470 if !self.config.required_audiences.is_empty() {
472 validation.set_audience(
473 &self
474 .config
475 .required_audiences
476 .iter()
477 .collect::<Vec<&String>>(),
478 );
479 } else {
480 validation.validate_aud = false;
481 }
482
483 if !self.config.required_issuers.is_empty() {
485 validation.set_issuer(
486 &self
487 .config
488 .required_issuers
489 .iter()
490 .collect::<Vec<&String>>(),
491 );
492 }
493
494 let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, &decoding_key, &validation)
496 .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
497
498 let claims = token_data.claims;
499
500 if self.is_token_revoked(&claims.jti)? {
504 return Err(AuthError::Unauthorized("Token is revoked".to_string()));
505 }
506
507 let token_lifetime = claims.exp.saturating_sub(claims.iat);
509 if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
510 {
511 return Err(AuthError::Unauthorized(format!(
512 "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
513 self.config.max_token_lifetime.as_secs()
514 )));
515 }
516
517 if self.config.require_jti && claims.jti.is_empty() {
519 return Err(AuthError::Unauthorized(
520 "Token missing required JTI claim".to_string(),
521 ));
522 }
523
524 if !self.config.allowed_token_types.is_empty()
526 && !claims.typ.is_empty()
527 && !self.config.allowed_token_types.contains(&claims.typ)
528 {
529 return Err(AuthError::Unauthorized(format!(
530 "Token type '{}' is not permitted",
531 claims.typ
532 )));
533 }
534
535 Ok(claims)
536 }
537
538 pub fn validate_token(
543 &self,
544 token: &str,
545 decoding_key: &DecodingKey,
546 ) -> Result<SecureJwtClaims> {
547 let header = jsonwebtoken::decode_header(token)
548 .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
549
550 if !self.config.allowed_algorithms.contains(&header.alg) {
551 return Err(AuthError::Unauthorized(format!(
552 "Token algorithm {:?} is not permitted; allowed: {:?}",
553 header.alg, self.config.allowed_algorithms
554 )));
555 }
556
557 let mut validation = jsonwebtoken::Validation::new(header.alg);
558 validation.algorithms = self.config.allowed_algorithms.clone();
559 validation.leeway = self.config.clock_skew.as_secs();
560 validation.validate_exp = true;
561 validation.validate_nbf = self.config.validate_nbf;
562
563 if !self.config.required_audiences.is_empty() {
564 validation.set_audience(
565 &self
566 .config
567 .required_audiences
568 .iter()
569 .collect::<Vec<&String>>(),
570 );
571 } else {
572 validation.validate_aud = false;
573 }
574
575 if !self.config.required_issuers.is_empty() {
576 validation.set_issuer(
577 &self
578 .config
579 .required_issuers
580 .iter()
581 .collect::<Vec<&String>>(),
582 );
583 }
584
585 let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, decoding_key, &validation)
586 .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
587
588 let claims = token_data.claims;
589
590 if self.is_token_revoked(&claims.jti)? {
591 return Err(AuthError::Unauthorized("Token is revoked".to_string()));
592 }
593
594 let token_lifetime = claims.exp.saturating_sub(claims.iat);
595 if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
596 {
597 return Err(AuthError::Unauthorized(format!(
598 "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
599 self.config.max_token_lifetime.as_secs()
600 )));
601 }
602
603 if self.config.require_jti && claims.jti.is_empty() {
604 return Err(AuthError::Unauthorized(
605 "Token missing required JTI claim".to_string(),
606 ));
607 }
608
609 if !self.config.allowed_token_types.is_empty()
610 && !claims.typ.is_empty()
611 && !self.config.allowed_token_types.contains(&claims.typ)
612 {
613 return Err(AuthError::Unauthorized(format!(
614 "Token type '{}' is not permitted",
615 claims.typ
616 )));
617 }
618
619 Ok(claims)
620 }
621
622 pub fn is_token_revoked(&self, jti: &str) -> Result<bool> {
628 let revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
629 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
630 })?;
631 Ok(revoked_tokens.contains_key(jti))
632 }
633
634 pub fn revoke_token(&self, jti: &str) -> Result<()> {
644 {
645 let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
646 AuthError::internal(
647 "Lock poisoned — a prior thread panicked while holding this lock",
648 )
649 })?;
650 revoked_tokens.insert(jti.to_string(), std::time::SystemTime::now());
651 }
652 if let Some(ref cb) = *self.on_revoke.lock().map_err(|_| {
655 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
656 })? {
657 cb(jti);
658 }
659 Ok(())
660 }
661
662 pub fn cleanup_revoked_tokens(&self, expired_cutoff: std::time::SystemTime) -> Result<()> {
672 const MAX_REVOKED_TOKENS: usize = 10_000;
673 let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
674 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
675 })?;
676
677 revoked_tokens.retain(|_, inserted_at| *inserted_at >= expired_cutoff);
680
681 if revoked_tokens.len() > MAX_REVOKED_TOKENS {
684 let target_len = MAX_REVOKED_TOKENS * 3 / 4;
685 let mut by_age: Vec<(String, std::time::SystemTime)> = revoked_tokens.drain().collect();
686 by_age.sort_unstable_by_key(|(_, t)| *t);
687 for (jti, inserted_at) in by_age.into_iter().rev().take(target_len) {
689 revoked_tokens.insert(jti, inserted_at);
690 }
691 tracing::warn!(
692 "Revoked token list exceeded {} entries; oldest entries were evicted.",
693 MAX_REVOKED_TOKENS
694 );
695 }
696
697 Ok(())
698 }
699}
700
701#[cfg(test)]
702mod tests {
703 use super::*;
704 use jsonwebtoken::{Algorithm, EncodingKey, Header};
705
706 fn test_config() -> SecureJwtConfig {
707 SecureJwtConfig {
708 jwt_secret: "a]test_secret_that_is_longer_than_32_chars_for_security!"
709 .to_string()
710 .into(),
711 ..SecureJwtConfig::default()
712 }
713 }
714
715 fn issue_token(config: &SecureJwtConfig, claims: &SecureJwtClaims) -> String {
716 let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
717 jsonwebtoken::encode(&Header::new(Algorithm::HS256), claims, &key).unwrap()
718 }
719
720 fn valid_claims() -> SecureJwtClaims {
721 let now = chrono::Utc::now().timestamp();
722 SecureJwtClaims {
723 sub: "user123".to_string(),
724 iss: "auth-framework".to_string(),
725 aud: "test".to_string(),
726 exp: now + 600,
727 nbf: now - 10,
728 iat: now,
729 jti: uuid::Uuid::new_v4().to_string(),
730 scope: "read".to_string(),
731 typ: "access".to_string(),
732 sid: None,
733 client_id: None,
734 auth_ctx_hash: None,
735 }
736 }
737
738 #[test]
743 fn a_token_signed_by_hand_verifies_and_a_tampered_one_does_not() {
744 #[derive(serde::Deserialize)]
745 struct C {
746 sub: String,
747 }
748 const TOKEN: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIiwiZXhwIjo0MTAyNDQ0ODAwfQ.ZZuykscIyOZdHswIzwjQd0kMJUt86iOkkW7Y-uoQPz4";
749 let key = DecodingKey::from_secret(b"known-answer-secret-for-compat-test-32b!");
750 let mut v = jsonwebtoken::Validation::new(Algorithm::HS256);
751 v.validate_exp = true;
752 v.required_spec_claims.clear();
753 let ok = jsonwebtoken::decode::<C>(TOKEN, &key, &v).expect("hand-signed token verifies");
754 assert_eq!(ok.claims.sub, "user123");
755
756 let (head, sig) = TOKEN.rsplit_once('.').unwrap();
757 let flipped = if sig.starts_with('A') { "B" } else { "A" };
758 let tampered = format!("{head}.{flipped}{}", &sig[1..]);
759 assert!(jsonwebtoken::decode::<C>(&tampered, &key, &v).is_err());
760 }
761
762 #[test]
765 fn decoding_key_selection_covers_every_known_algorithm() {
766 let v = SecureJwtValidator::new(test_config()).unwrap();
767 for alg in [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512] {
768 assert!(v.decoding_key_for_algorithm(alg).is_ok(), "{alg:?}");
769 }
770 for alg in [
771 Algorithm::RS256,
772 Algorithm::RS384,
773 Algorithm::RS512,
774 Algorithm::PS256,
775 Algorithm::PS384,
776 Algorithm::PS512,
777 Algorithm::ES256,
778 Algorithm::ES384,
779 Algorithm::EdDSA,
780 ] {
781 assert!(
782 matches!(
783 v.decoding_key_for_algorithm(alg),
784 Err(AuthError::Configuration { .. })
785 ),
786 "{alg:?} without a configured public key must be refused"
787 );
788 }
789 }
790
791 #[test]
792 fn test_default_config_generates_random_secret() {
793 let c1 = SecureJwtConfig::default();
794 let c2 = SecureJwtConfig::default();
795 assert_ne!(c1.jwt_secret, c2.jwt_secret);
796 assert!(c1.jwt_secret.len() >= 32);
797 }
798
799 #[test]
800 fn test_builder_fluent_api() {
801 let config = SecureJwtConfig::builder()
802 .with_secret("a]test_secret_that_is_longer_than_32_chars_for_security!")
803 .require_issuer("my-issuer")
804 .require_audience("my-aud")
805 .with_max_lifetime(Duration::from_secs(7200))
806 .with_clock_skew(Duration::from_secs(60))
807 .require_jti(false)
808 .build();
809
810 assert!(config.required_issuers.contains("my-issuer"));
811 assert!(config.required_audiences.contains("my-aud"));
812 assert_eq!(config.max_token_lifetime, Duration::from_secs(7200));
813 assert_eq!(config.clock_skew, Duration::from_secs(60));
814 assert!(!config.require_jti);
815 }
816
817 #[test]
818 fn test_validate_valid_token() {
819 let config = test_config();
820 let claims = valid_claims();
821 let token = issue_token(&config, &claims);
822 let validator = SecureJwtValidator::new(config).unwrap();
823 let result = validator.validate(&token).unwrap();
824 assert_eq!(result.sub, "user123");
825 assert_eq!(result.iss, "auth-framework");
826 }
827
828 #[test]
829 fn test_validate_rejects_expired_token() {
830 let config = test_config();
831 let mut claims = valid_claims();
832 claims.exp = chrono::Utc::now().timestamp() - 3600;
833 claims.iat = claims.exp - 600;
834 let token = issue_token(&config, &claims);
835 let validator = SecureJwtValidator::new(config).unwrap();
836 assert!(validator.validate(&token).is_err());
837 }
838
839 #[test]
840 fn test_validate_rejects_wrong_issuer() {
841 let config = test_config();
842 let mut claims = valid_claims();
843 claims.iss = "evil-issuer".to_string();
844 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_revoke_and_check() {
851 let config = test_config();
852 let validator = SecureJwtValidator::new(config).unwrap();
853 let jti = "test-jti-123";
854 assert!(!validator.is_token_revoked(jti).unwrap());
855 validator.revoke_token(jti).unwrap();
856 assert!(validator.is_token_revoked(jti).unwrap());
857 }
858
859 #[test]
860 fn test_revoked_token_rejected() {
861 let config = test_config();
862 let claims = valid_claims();
863 let jti = claims.jti.clone();
864 let token = issue_token(&config, &claims);
865 let validator = SecureJwtValidator::new(config).unwrap();
866 validator.revoke_token(&jti).unwrap();
867 assert!(validator.validate(&token).is_err());
868 }
869
870 #[test]
871 fn test_cleanup_removes_old_entries() {
872 let config = test_config();
873 let validator = SecureJwtValidator::new(config).unwrap();
874 validator.revoke_token("old-jti").unwrap();
875 let future = std::time::SystemTime::now() + Duration::from_secs(3600);
877 validator.cleanup_revoked_tokens(future).unwrap();
878 assert!(!validator.is_token_revoked("old-jti").unwrap());
879 }
880
881 #[test]
882 fn test_on_revoke_callback() {
883 let config = test_config();
884 let validator = SecureJwtValidator::new(config).unwrap();
885 let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
886 let captured_clone = captured.clone();
887 validator.set_on_revoke(move |jti| {
888 captured_clone.lock().unwrap().push(jti.to_string());
889 });
890 validator.revoke_token("cb-jti-1").unwrap();
891 validator.revoke_token("cb-jti-2").unwrap();
892 let jtis = captured.lock().unwrap();
893 assert_eq!(jtis.len(), 2);
894 assert!(jtis.contains(&"cb-jti-1".to_string()));
895 assert!(jtis.contains(&"cb-jti-2".to_string()));
896 }
897
898 #[test]
899 fn test_rejects_disallowed_algorithm() {
900 let config = test_config();
901 let claims = valid_claims();
902 let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
904 let token = jsonwebtoken::encode(&Header::new(Algorithm::HS384), &claims, &key).unwrap();
905 let validator = SecureJwtValidator::new(config).unwrap();
906 assert!(validator.validate(&token).is_err());
907 }
908
909 #[test]
910 fn test_rejects_excessive_lifetime() {
911 let mut config = test_config();
912 config.max_token_lifetime = Duration::from_secs(300);
913 let mut claims = valid_claims();
914 let now = chrono::Utc::now().timestamp();
915 claims.iat = now;
916 claims.exp = now + 600; let token = issue_token(&config, &claims);
918 let validator = SecureJwtValidator::new(config).unwrap();
919 assert!(validator.validate(&token).is_err());
920 }
921
922 #[test]
923 fn test_missing_rsa_key_rejected() {
924 let mut config = test_config();
925 config.allowed_algorithms = vec![Algorithm::RS256];
926 let result = SecureJwtValidator::new(config);
927 assert!(result.is_err());
928 }
929}