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(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
24impl std::fmt::Debug for SecureJwtClaims {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 let mut d = f.debug_struct("SecureJwtClaims");
27 d.field("sub", &self.sub);
28 d.field("iss", &self.iss);
29 d.field("aud", &self.aud);
30 d.field("exp", &self.exp);
31 d.field("nbf", &self.nbf);
32 d.field("iat", &self.iat);
33 d.field("jti", &self.jti);
34 d.field("scope", &self.scope);
35 d.field("typ", &self.typ);
36 d.field("sid", &crate::utils::redact::redacted(&self.sid));
37 d.field("client_id", &self.client_id);
38 d.field("auth_ctx_hash", &self.auth_ctx_hash);
39 d.finish()
40 }
41}
42
43pub const TYP_REFRESH: &str = "refresh";
45pub const TYP_REFRESH_TOKEN: &str = "refresh_token";
47
48pub fn is_refresh_typ(typ: &str) -> bool {
52 typ == TYP_REFRESH || typ == TYP_REFRESH_TOKEN
53}
54
55#[derive(Debug, Clone)]
56pub struct SecureJwtConfig {
57 pub allowed_algorithms: Vec<Algorithm>,
58 pub required_issuers: HashSet<String>,
59 pub required_audiences: HashSet<String>,
60 pub max_token_lifetime: Duration,
61 pub clock_skew: Duration,
62 pub require_jti: bool,
63 pub validate_nbf: bool,
64 pub allowed_token_types: HashSet<String>,
65 pub require_secure_transport: bool,
66 pub jwt_secret: Zeroizing<String>,
68 pub rsa_public_key_pem: Option<String>,
70 pub ec_public_key_pem: Option<String>,
72 pub ed_public_key_pem: Option<String>,
74}
75
76impl Default for SecureJwtConfig {
77 fn default() -> Self {
78 use ring::rand::{SecureRandom, SystemRandom};
85 let rng = SystemRandom::new();
88 let mut bytes = [0u8; 32];
89 rng.fill(&mut bytes)
90 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
91 let jwt_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
92 s.push_str(&format!("{b:02x}"));
93 s
94 });
95
96 let mut allowed_token_types = HashSet::new();
97 allowed_token_types.insert("access".to_string());
98 allowed_token_types.insert("refresh".to_string());
99 allowed_token_types.insert("JARM".to_string());
100
101 let mut required_issuers = HashSet::new();
102 required_issuers.insert("auth-framework".to_string());
103
104 Self {
105 allowed_algorithms: vec![Algorithm::HS256],
109 required_issuers,
110 required_audiences: HashSet::new(),
111 max_token_lifetime: Duration::from_secs(3600),
112 clock_skew: Duration::from_secs(30),
113 require_jti: true,
114 validate_nbf: true,
115 allowed_token_types,
116 require_secure_transport: true,
117 jwt_secret: jwt_secret.into(),
118 rsa_public_key_pem: None,
119 ec_public_key_pem: None,
120 ed_public_key_pem: None,
121 }
122 }
123}
124
125fn is_hmac_algorithm(alg: Algorithm) -> bool {
127 matches!(alg, Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512)
128}
129
130impl SecureJwtConfig {
153 pub fn builder() -> SecureJwtConfigBuilder {
155 SecureJwtConfigBuilder::default()
156 }
157}
158
159#[derive(Default)]
161pub struct SecureJwtConfigBuilder {
162 config: SecureJwtConfig,
163}
164
165impl SecureJwtConfigBuilder {
166 pub fn with_algorithm(mut self, algo: Algorithm) -> Self {
168 self.config.allowed_algorithms.push(algo);
169 self
170 }
171
172 pub fn with_algorithms(mut self, algos: Vec<Algorithm>) -> Self {
174 self.config.allowed_algorithms = algos;
175 self
176 }
177
178 pub fn require_issuer(mut self, issuer: impl Into<String>) -> Self {
180 self.config.required_issuers.insert(issuer.into());
181 self
182 }
183
184 pub fn require_audience(mut self, audience: impl Into<String>) -> Self {
186 self.config.required_audiences.insert(audience.into());
187 self
188 }
189
190 pub fn with_max_lifetime(mut self, lifetime: Duration) -> Self {
192 self.config.max_token_lifetime = lifetime;
193 self
194 }
195
196 pub fn with_clock_skew(mut self, skew: Duration) -> Self {
198 self.config.clock_skew = skew;
199 self
200 }
201
202 pub fn require_jti(mut self, require: bool) -> Self {
204 self.config.require_jti = require;
205 self
206 }
207
208 pub fn with_secret(mut self, secret: impl Into<String>) -> Self {
210 self.config.jwt_secret = Zeroizing::new(secret.into());
211 self
212 }
213
214 pub fn build(self) -> SecureJwtConfig {
216 self.config
217 }
218}
219
220pub struct SecureJwtValidator {
221 config: SecureJwtConfig,
222 revoked_tokens: std::sync::Mutex<std::collections::HashMap<String, std::time::SystemTime>>,
227 on_revoke: std::sync::Mutex<Option<RevokeCallback>>,
233}
234
235type RevokeCallback = Box<dyn Fn(&str) + Send + Sync>;
237
238impl std::fmt::Debug for SecureJwtValidator {
239 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240 f.debug_struct("SecureJwtValidator")
241 .field("config", &self.config)
242 .field(
243 "revoked_tokens",
244 &crate::utils::redact::redacted(&self.revoked_tokens),
245 )
246 .field(
247 "on_revoke",
248 &self.on_revoke.lock().ok().map(|g| g.is_some()),
249 )
250 .finish()
251 }
252}
253
254impl SecureJwtValidator {
255 pub fn new(config: SecureJwtConfig) -> Result<Self> {
256 let has_hmac = config
258 .allowed_algorithms
259 .iter()
260 .any(|a| is_hmac_algorithm(*a));
261 let has_rsa = config.allowed_algorithms.iter().any(|a| {
262 matches!(
263 a,
264 Algorithm::RS256
265 | Algorithm::RS384
266 | Algorithm::RS512
267 | Algorithm::PS256
268 | Algorithm::PS384
269 | Algorithm::PS512
270 )
271 });
272 let has_ec = config
273 .allowed_algorithms
274 .iter()
275 .any(|a| matches!(a, Algorithm::ES256 | Algorithm::ES384));
276 let has_eddsa = config
277 .allowed_algorithms
278 .iter()
279 .any(|a| matches!(a, Algorithm::EdDSA));
280
281 if has_hmac {
282 #[cfg(not(test))]
283 if config.jwt_secret.len() < 32 {
284 return Err(AuthError::Configuration {
285 message: "SecureJwtConfig::jwt_secret must be at least 32 characters \
286 when HMAC algorithms are enabled"
287 .to_string(),
288 help: Some(
289 "Provide a cryptographically random secret unique to your deployment"
290 .to_string(),
291 ),
292 docs_url: None,
293 source: None,
294 suggested_fix: None,
295 });
296 }
297 }
298 if has_rsa && config.rsa_public_key_pem.is_none() {
299 return Err(AuthError::Configuration {
300 message: "SecureJwtConfig::rsa_public_key_pem must be set when RSA/PS algorithms are enabled".to_string(),
301 help: Some("Set rsa_public_key_pem in SecureJwtConfig".to_string()),
302 docs_url: None,
303 source: None,
304 suggested_fix: None,
305 });
306 }
307 if has_ec && config.ec_public_key_pem.is_none() {
308 return Err(AuthError::Configuration {
309 message:
310 "SecureJwtConfig::ec_public_key_pem must be set when EC algorithms are enabled"
311 .to_string(),
312 help: Some("Set ec_public_key_pem in SecureJwtConfig".to_string()),
313 docs_url: None,
314 source: None,
315 suggested_fix: None,
316 });
317 }
318 if has_eddsa && config.ed_public_key_pem.is_none() {
319 return Err(AuthError::Configuration {
320 message: "SecureJwtConfig::ed_public_key_pem must be set when EdDSA is enabled"
321 .to_string(),
322 help: Some("Set ed_public_key_pem in SecureJwtConfig".to_string()),
323 docs_url: None,
324 source: None,
325 suggested_fix: None,
326 });
327 }
328
329 Ok(Self {
330 config,
331 revoked_tokens: std::sync::Mutex::new(std::collections::HashMap::new()),
332 on_revoke: std::sync::Mutex::new(None),
333 })
334 }
335
336 pub fn set_on_revoke<F>(&self, callback: F)
351 where
352 F: Fn(&str) + Send + Sync + 'static,
353 {
354 let mut guard = match self.on_revoke.lock() {
355 Ok(g) => g,
356 Err(poisoned) => poisoned.into_inner(),
357 };
358 *guard = Some(Box::new(callback));
359 }
360
361 pub fn get_decoding_key(&self) -> jsonwebtoken::DecodingKey {
365 jsonwebtoken::DecodingKey::from_secret(self.config.jwt_secret.as_bytes())
366 }
367
368 pub fn get_encoding_key(&self) -> jsonwebtoken::EncodingKey {
370 jsonwebtoken::EncodingKey::from_secret(self.config.jwt_secret.as_bytes())
371 }
372
373 fn decoding_key_for_algorithm(&self, alg: Algorithm) -> Result<DecodingKey> {
375 match alg {
376 Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
377 Ok(DecodingKey::from_secret(self.config.jwt_secret.as_bytes()))
378 }
379 Algorithm::RS256
380 | Algorithm::RS384
381 | Algorithm::RS512
382 | Algorithm::PS256
383 | Algorithm::PS384
384 | Algorithm::PS512 => {
385 let pem = self.config.rsa_public_key_pem.as_deref().ok_or_else(|| {
386 AuthError::Configuration {
387 message: "RSA public key PEM not configured".to_string(),
388 help: Some(
389 "Set rsa_public_key_pem in SecureJwtConfig for RSA/PS algorithms"
390 .to_string(),
391 ),
392 docs_url: None,
393 source: None,
394 suggested_fix: None,
395 }
396 })?;
397 DecodingKey::from_rsa_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
398 message: format!("Invalid RSA public key PEM: {e}"),
399 help: None,
400 docs_url: None,
401 source: None,
402 suggested_fix: None,
403 })
404 }
405 Algorithm::ES256 | Algorithm::ES384 => {
406 let pem = self.config.ec_public_key_pem.as_deref().ok_or_else(|| {
407 AuthError::Configuration {
408 message: "EC public key PEM not configured".to_string(),
409 help: Some(
410 "Set ec_public_key_pem in SecureJwtConfig for EC algorithms"
411 .to_string(),
412 ),
413 docs_url: None,
414 source: None,
415 suggested_fix: None,
416 }
417 })?;
418 DecodingKey::from_ec_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
419 message: format!("Invalid EC public key PEM: {e}"),
420 help: None,
421 docs_url: None,
422 source: None,
423 suggested_fix: None,
424 })
425 }
426 Algorithm::EdDSA => {
427 let pem = self.config.ed_public_key_pem.as_deref().ok_or_else(|| {
428 AuthError::Configuration {
429 message: "Ed25519 public key PEM not configured".to_string(),
430 help: Some(
431 "Set ed_public_key_pem in SecureJwtConfig for EdDSA".to_string(),
432 ),
433 docs_url: None,
434 source: None,
435 suggested_fix: None,
436 }
437 })?;
438 DecodingKey::from_ed_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
439 message: format!("Invalid Ed25519 public key PEM: {e}"),
440 help: None,
441 docs_url: None,
442 source: None,
443 suggested_fix: None,
444 })
445 }
446 other => Err(AuthError::Configuration {
448 message: format!("Unsupported JWT algorithm {other:?}"),
449 help: None,
450 docs_url: None,
451 source: None,
452 suggested_fix: None,
453 }),
454 }
455 }
456
457 pub fn validate(&self, token: &str) -> Result<SecureJwtClaims> {
466 let header = jsonwebtoken::decode_header(token)
468 .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
469
470 if !self.config.allowed_algorithms.contains(&header.alg) {
472 return Err(AuthError::Unauthorized(format!(
473 "Token algorithm {:?} is not permitted; allowed: {:?}",
474 header.alg, self.config.allowed_algorithms
475 )));
476 }
477
478 let decoding_key = self.decoding_key_for_algorithm(header.alg)?;
480
481 let mut validation = jsonwebtoken::Validation::new(header.alg);
483 validation.algorithms = self.config.allowed_algorithms.clone();
484 validation.leeway = self.config.clock_skew.as_secs();
485
486 validation.validate_exp = true;
488
489 validation.validate_nbf = self.config.validate_nbf;
491
492 if !self.config.required_audiences.is_empty() {
494 validation.set_audience(
495 &self
496 .config
497 .required_audiences
498 .iter()
499 .collect::<Vec<&String>>(),
500 );
501 } else {
502 validation.validate_aud = false;
503 }
504
505 if !self.config.required_issuers.is_empty() {
507 validation.set_issuer(
508 &self
509 .config
510 .required_issuers
511 .iter()
512 .collect::<Vec<&String>>(),
513 );
514 }
515
516 let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, &decoding_key, &validation)
518 .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
519
520 let claims = token_data.claims;
521
522 if self.is_token_revoked(&claims.jti)? {
526 return Err(AuthError::Unauthorized("Token is revoked".to_string()));
527 }
528
529 let token_lifetime = claims.exp.saturating_sub(claims.iat);
531 if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
532 {
533 return Err(AuthError::Unauthorized(format!(
534 "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
535 self.config.max_token_lifetime.as_secs()
536 )));
537 }
538
539 if self.config.require_jti && claims.jti.is_empty() {
541 return Err(AuthError::Unauthorized(
542 "Token missing required JTI claim".to_string(),
543 ));
544 }
545
546 if !self.config.allowed_token_types.is_empty()
548 && !claims.typ.is_empty()
549 && !self.config.allowed_token_types.contains(&claims.typ)
550 {
551 return Err(AuthError::Unauthorized(format!(
552 "Token type '{}' is not permitted",
553 claims.typ
554 )));
555 }
556
557 Ok(claims)
558 }
559
560 pub fn validate_token(
565 &self,
566 token: &str,
567 decoding_key: &DecodingKey,
568 ) -> Result<SecureJwtClaims> {
569 let header = jsonwebtoken::decode_header(token)
570 .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
571
572 if !self.config.allowed_algorithms.contains(&header.alg) {
573 return Err(AuthError::Unauthorized(format!(
574 "Token algorithm {:?} is not permitted; allowed: {:?}",
575 header.alg, self.config.allowed_algorithms
576 )));
577 }
578
579 let mut validation = jsonwebtoken::Validation::new(header.alg);
580 validation.algorithms = self.config.allowed_algorithms.clone();
581 validation.leeway = self.config.clock_skew.as_secs();
582 validation.validate_exp = true;
583 validation.validate_nbf = self.config.validate_nbf;
584
585 if !self.config.required_audiences.is_empty() {
586 validation.set_audience(
587 &self
588 .config
589 .required_audiences
590 .iter()
591 .collect::<Vec<&String>>(),
592 );
593 } else {
594 validation.validate_aud = false;
595 }
596
597 if !self.config.required_issuers.is_empty() {
598 validation.set_issuer(
599 &self
600 .config
601 .required_issuers
602 .iter()
603 .collect::<Vec<&String>>(),
604 );
605 }
606
607 let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, decoding_key, &validation)
608 .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
609
610 let claims = token_data.claims;
611
612 if self.is_token_revoked(&claims.jti)? {
613 return Err(AuthError::Unauthorized("Token is revoked".to_string()));
614 }
615
616 let token_lifetime = claims.exp.saturating_sub(claims.iat);
617 if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
618 {
619 return Err(AuthError::Unauthorized(format!(
620 "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
621 self.config.max_token_lifetime.as_secs()
622 )));
623 }
624
625 if self.config.require_jti && claims.jti.is_empty() {
626 return Err(AuthError::Unauthorized(
627 "Token missing required JTI claim".to_string(),
628 ));
629 }
630
631 if !self.config.allowed_token_types.is_empty()
632 && !claims.typ.is_empty()
633 && !self.config.allowed_token_types.contains(&claims.typ)
634 {
635 return Err(AuthError::Unauthorized(format!(
636 "Token type '{}' is not permitted",
637 claims.typ
638 )));
639 }
640
641 Ok(claims)
642 }
643
644 pub fn is_token_revoked(&self, jti: &str) -> Result<bool> {
650 let revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
651 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
652 })?;
653 Ok(revoked_tokens.contains_key(jti))
654 }
655
656 pub fn revoke_token(&self, jti: &str) -> Result<()> {
666 {
667 let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
668 AuthError::internal(
669 "Lock poisoned — a prior thread panicked while holding this lock",
670 )
671 })?;
672 revoked_tokens.insert(jti.to_string(), std::time::SystemTime::now());
673 }
674 if let Some(ref cb) = *self.on_revoke.lock().map_err(|_| {
677 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
678 })? {
679 cb(jti);
680 }
681 Ok(())
682 }
683
684 pub fn cleanup_revoked_tokens(&self, expired_cutoff: std::time::SystemTime) -> Result<()> {
694 const MAX_REVOKED_TOKENS: usize = 10_000;
695 let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
696 AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
697 })?;
698
699 revoked_tokens.retain(|_, inserted_at| *inserted_at >= expired_cutoff);
702
703 if revoked_tokens.len() > MAX_REVOKED_TOKENS {
706 let target_len = MAX_REVOKED_TOKENS * 3 / 4;
707 let mut by_age: Vec<(String, std::time::SystemTime)> = revoked_tokens.drain().collect();
708 by_age.sort_unstable_by_key(|(_, t)| *t);
709 for (jti, inserted_at) in by_age.into_iter().rev().take(target_len) {
711 revoked_tokens.insert(jti, inserted_at);
712 }
713 tracing::warn!(
714 "Revoked token list exceeded {} entries; oldest entries were evicted.",
715 MAX_REVOKED_TOKENS
716 );
717 }
718
719 Ok(())
720 }
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726 use jsonwebtoken::{Algorithm, EncodingKey, Header};
727
728 fn test_config() -> SecureJwtConfig {
729 SecureJwtConfig {
730 jwt_secret: "a]test_secret_that_is_longer_than_32_chars_for_security!"
731 .to_string()
732 .into(),
733 ..SecureJwtConfig::default()
734 }
735 }
736
737 fn issue_token(config: &SecureJwtConfig, claims: &SecureJwtClaims) -> String {
738 let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
739 jsonwebtoken::encode(&Header::new(Algorithm::HS256), claims, &key).unwrap()
740 }
741
742 fn valid_claims() -> SecureJwtClaims {
743 let now = chrono::Utc::now().timestamp();
744 SecureJwtClaims {
745 sub: "user123".to_string(),
746 iss: "auth-framework".to_string(),
747 aud: "test".to_string(),
748 exp: now + 600,
749 nbf: now - 10,
750 iat: now,
751 jti: uuid::Uuid::new_v4().to_string(),
752 scope: "read".to_string(),
753 typ: "access".to_string(),
754 sid: None,
755 client_id: None,
756 auth_ctx_hash: None,
757 }
758 }
759
760 #[test]
765 fn a_token_signed_by_hand_verifies_and_a_tampered_one_does_not() {
766 #[derive(serde::Deserialize)]
767 struct C {
768 sub: String,
769 }
770 const TOKEN: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIiwiZXhwIjo0MTAyNDQ0ODAwfQ.ZZuykscIyOZdHswIzwjQd0kMJUt86iOkkW7Y-uoQPz4";
771 let key = DecodingKey::from_secret(b"known-answer-secret-for-compat-test-32b!");
772 let mut v = jsonwebtoken::Validation::new(Algorithm::HS256);
773 v.validate_exp = true;
774 v.required_spec_claims.clear();
775 let ok = jsonwebtoken::decode::<C>(TOKEN, &key, &v).expect("hand-signed token verifies");
776 assert_eq!(ok.claims.sub, "user123");
777
778 let (head, sig) = TOKEN.rsplit_once('.').unwrap();
779 let flipped = if sig.starts_with('A') { "B" } else { "A" };
780 let tampered = format!("{head}.{flipped}{}", &sig[1..]);
781 assert!(jsonwebtoken::decode::<C>(&tampered, &key, &v).is_err());
782 }
783
784 #[test]
787 fn decoding_key_selection_covers_every_known_algorithm() {
788 let v = SecureJwtValidator::new(test_config()).unwrap();
789 for alg in [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512] {
790 assert!(v.decoding_key_for_algorithm(alg).is_ok(), "{alg:?}");
791 }
792 for alg in [
793 Algorithm::RS256,
794 Algorithm::RS384,
795 Algorithm::RS512,
796 Algorithm::PS256,
797 Algorithm::PS384,
798 Algorithm::PS512,
799 Algorithm::ES256,
800 Algorithm::ES384,
801 Algorithm::EdDSA,
802 ] {
803 assert!(
804 matches!(
805 v.decoding_key_for_algorithm(alg),
806 Err(AuthError::Configuration { .. })
807 ),
808 "{alg:?} without a configured public key must be refused"
809 );
810 }
811 }
812
813 #[test]
814 fn test_default_config_generates_random_secret() {
815 let c1 = SecureJwtConfig::default();
816 let c2 = SecureJwtConfig::default();
817 assert_ne!(c1.jwt_secret, c2.jwt_secret);
818 assert!(c1.jwt_secret.len() >= 32);
819 }
820
821 #[test]
822 fn test_builder_fluent_api() {
823 let config = SecureJwtConfig::builder()
824 .with_secret("a]test_secret_that_is_longer_than_32_chars_for_security!")
825 .require_issuer("my-issuer")
826 .require_audience("my-aud")
827 .with_max_lifetime(Duration::from_secs(7200))
828 .with_clock_skew(Duration::from_secs(60))
829 .require_jti(false)
830 .build();
831
832 assert!(config.required_issuers.contains("my-issuer"));
833 assert!(config.required_audiences.contains("my-aud"));
834 assert_eq!(config.max_token_lifetime, Duration::from_secs(7200));
835 assert_eq!(config.clock_skew, Duration::from_secs(60));
836 assert!(!config.require_jti);
837 }
838
839 #[test]
840 fn test_validate_valid_token() {
841 let config = test_config();
842 let claims = valid_claims();
843 let token = issue_token(&config, &claims);
844 let validator = SecureJwtValidator::new(config).unwrap();
845 let result = validator.validate(&token).unwrap();
846 assert_eq!(result.sub, "user123");
847 assert_eq!(result.iss, "auth-framework");
848 }
849
850 #[test]
851 fn test_validate_rejects_expired_token() {
852 let config = test_config();
853 let mut claims = valid_claims();
854 claims.exp = chrono::Utc::now().timestamp() - 3600;
855 claims.iat = claims.exp - 600;
856 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_validate_rejects_wrong_issuer() {
863 let config = test_config();
864 let mut claims = valid_claims();
865 claims.iss = "evil-issuer".to_string();
866 let token = issue_token(&config, &claims);
867 let validator = SecureJwtValidator::new(config).unwrap();
868 assert!(validator.validate(&token).is_err());
869 }
870
871 #[test]
872 fn test_revoke_and_check() {
873 let config = test_config();
874 let validator = SecureJwtValidator::new(config).unwrap();
875 let jti = "test-jti-123";
876 assert!(!validator.is_token_revoked(jti).unwrap());
877 validator.revoke_token(jti).unwrap();
878 assert!(validator.is_token_revoked(jti).unwrap());
879 }
880
881 #[test]
882 fn test_revoked_token_rejected() {
883 let config = test_config();
884 let claims = valid_claims();
885 let jti = claims.jti.clone();
886 let token = issue_token(&config, &claims);
887 let validator = SecureJwtValidator::new(config).unwrap();
888 validator.revoke_token(&jti).unwrap();
889 assert!(validator.validate(&token).is_err());
890 }
891
892 #[test]
893 fn test_cleanup_removes_old_entries() {
894 let config = test_config();
895 let validator = SecureJwtValidator::new(config).unwrap();
896 validator.revoke_token("old-jti").unwrap();
897 let future = std::time::SystemTime::now() + Duration::from_secs(3600);
899 validator.cleanup_revoked_tokens(future).unwrap();
900 assert!(!validator.is_token_revoked("old-jti").unwrap());
901 }
902
903 #[test]
904 fn test_on_revoke_callback() {
905 let config = test_config();
906 let validator = SecureJwtValidator::new(config).unwrap();
907 let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
908 let captured_clone = captured.clone();
909 validator.set_on_revoke(move |jti| {
910 captured_clone.lock().unwrap().push(jti.to_string());
911 });
912 validator.revoke_token("cb-jti-1").unwrap();
913 validator.revoke_token("cb-jti-2").unwrap();
914 let jtis = captured.lock().unwrap();
915 assert_eq!(jtis.len(), 2);
916 assert!(jtis.contains(&"cb-jti-1".to_string()));
917 assert!(jtis.contains(&"cb-jti-2".to_string()));
918 }
919
920 #[test]
921 fn test_rejects_disallowed_algorithm() {
922 let config = test_config();
923 let claims = valid_claims();
924 let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
926 let token = jsonwebtoken::encode(&Header::new(Algorithm::HS384), &claims, &key).unwrap();
927 let validator = SecureJwtValidator::new(config).unwrap();
928 assert!(validator.validate(&token).is_err());
929 }
930
931 #[test]
932 fn test_rejects_excessive_lifetime() {
933 let mut config = test_config();
934 config.max_token_lifetime = Duration::from_secs(300);
935 let mut claims = valid_claims();
936 let now = chrono::Utc::now().timestamp();
937 claims.iat = now;
938 claims.exp = now + 600; let token = issue_token(&config, &claims);
940 let validator = SecureJwtValidator::new(config).unwrap();
941 assert!(validator.validate(&token).is_err());
942 }
943
944 #[test]
945 fn test_missing_rsa_key_rejected() {
946 let mut config = test_config();
947 config.allowed_algorithms = vec![Algorithm::RS256];
948 let result = SecureJwtValidator::new(config);
949 assert!(result.is_err());
950 }
951}