Skip to main content

auth_framework/security/
secure_jwt.rs

1use crate::errors::{AuthError, Result};
2use jsonwebtoken::{Algorithm, DecodingKey};
3use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5use std::time::Duration;
6
7#[derive(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
23impl std::fmt::Debug for SecureJwtClaims {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        let mut d = f.debug_struct("SecureJwtClaims");
26        d.field("sub", &self.sub);
27        d.field("iss", &self.iss);
28        d.field("aud", &self.aud);
29        d.field("exp", &self.exp);
30        d.field("nbf", &self.nbf);
31        d.field("iat", &self.iat);
32        d.field("jti", &self.jti);
33        d.field("scope", &self.scope);
34        d.field("typ", &self.typ);
35        d.field("sid", &crate::utils::redact::redacted(&self.sid));
36        d.field("client_id", &self.client_id);
37        d.field("auth_ctx_hash", &self.auth_ctx_hash);
38        d.finish()
39    }
40}
41
42#[derive(Clone)]
43pub struct SecureJwtConfig {
44    pub allowed_algorithms: Vec<Algorithm>,
45    pub required_issuers: HashSet<String>,
46    pub required_audiences: HashSet<String>,
47    pub max_token_lifetime: Duration,
48    pub clock_skew: Duration,
49    pub require_jti: bool,
50    pub validate_nbf: bool,
51    pub allowed_token_types: HashSet<String>,
52    pub require_secure_transport: bool,
53    /// HMAC secret for HS256/HS384/HS512
54    pub jwt_secret: String,
55    /// PEM-encoded RSA public key for RS256/RS384/RS512/PS256/PS384/PS512
56    pub rsa_public_key_pem: Option<String>,
57    /// PEM-encoded EC public key for ES256/ES384
58    pub ec_public_key_pem: Option<String>,
59    /// PEM-encoded Ed25519 public key for EdDSA
60    pub ed_public_key_pem: Option<String>,
61}
62
63impl std::fmt::Debug for SecureJwtConfig {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        let mut d = f.debug_struct("SecureJwtConfig");
66        d.field("allowed_algorithms", &self.allowed_algorithms);
67        d.field("required_issuers", &self.required_issuers);
68        d.field("required_audiences", &self.required_audiences);
69        d.field("max_token_lifetime", &self.max_token_lifetime);
70        d.field("clock_skew", &self.clock_skew);
71        d.field("require_jti", &self.require_jti);
72        d.field("validate_nbf", &self.validate_nbf);
73        d.field("allowed_token_types", &self.allowed_token_types);
74        d.field("require_secure_transport", &self.require_secure_transport);
75        d.field(
76            "jwt_secret",
77            &crate::utils::redact::redacted(&self.jwt_secret),
78        );
79        d.field("rsa_public_key_pem", &self.rsa_public_key_pem);
80        d.field("ec_public_key_pem", &self.ec_public_key_pem);
81        d.field("ed_public_key_pem", &self.ed_public_key_pem);
82        d.finish()
83    }
84}
85
86impl Default for SecureJwtConfig {
87    fn default() -> Self {
88        // Generate a fresh cryptographically random secret for each instance so that
89        // no default-constructed config ever carries a publicly-known key.
90        //
91        // Callers that need a stable, shared secret (e.g. multi-node clusters that
92        // must validate each other's tokens) must set `jwt_secret` explicitly after
93        // construction.
94        use ring::rand::{SecureRandom, SystemRandom};
95        // SAFETY: CSPRNG failure at initialization is terminal; the framework
96        // cannot operate without entropy.
97        let rng = SystemRandom::new();
98        let mut bytes = [0u8; 32];
99        rng.fill(&mut bytes)
100            .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
101        let jwt_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
102            s.push_str(&format!("{b:02x}"));
103            s
104        });
105
106        let mut allowed_token_types = HashSet::new();
107        allowed_token_types.insert("access".to_string());
108        allowed_token_types.insert("refresh".to_string());
109        allowed_token_types.insert("JARM".to_string());
110
111        let mut required_issuers = HashSet::new();
112        required_issuers.insert("auth-framework".to_string());
113
114        Self {
115            // Only advertise algorithms for which key material is actually present.
116            // Asymmetric algorithms require their corresponding PEM fields to be set;
117            // they are excluded from the default to prevent misconfiguration.
118            allowed_algorithms: vec![Algorithm::HS256],
119            required_issuers,
120            required_audiences: HashSet::new(),
121            max_token_lifetime: Duration::from_secs(3600),
122            clock_skew: Duration::from_secs(30),
123            require_jti: true,
124            validate_nbf: true,
125            allowed_token_types,
126            require_secure_transport: true,
127            jwt_secret,
128            rsa_public_key_pem: None,
129            ec_public_key_pem: None,
130            ed_public_key_pem: None,
131        }
132    }
133}
134
135/// Returns `true` if the algorithm belongs to the HMAC (symmetric) family.
136fn is_hmac_algorithm(alg: Algorithm) -> bool {
137    matches!(alg, Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512)
138}
139
140/// Validates JWT tokens with configurable algorithm support and in-memory revocation.
141///
142/// # Revocation Architecture
143///
144/// `SecureJwtValidator` maintains an **in-memory** revocation list (`HashMap<JTI, SystemTime>`)
145/// protected by a `Mutex`. This list is **lost on process restart** and is intended as a
146/// supplementary fast-path cache — not as a durable revocation store.
147///
148/// For production deployments, durable revocation should be handled by the storage-backed
149/// layer in the API module (see `src/api/auth.rs`), which persists revoked JTIs in the
150/// configured KV / database backend.
151///
152/// To bridge both layers, callers can register an optional `on_revoke` callback via
153/// [`SecureJwtValidator::set_on_revoke`]. When set, every call to [`revoke_token`] will
154/// first insert into the in-memory map and then invoke the callback with the JTI string,
155/// allowing the caller to persist the revocation to external storage without changing the
156/// existing API surface.
157///
158/// # Size Limits
159///
160/// [`cleanup_revoked_tokens`] enforces a hard cap of 10 000 entries and time-based eviction
161/// to prevent unbounded memory growth.
162impl SecureJwtConfig {
163    /// Create a new builder with secure default configurations.
164    pub fn builder() -> SecureJwtConfigBuilder {
165        SecureJwtConfigBuilder::default()
166    }
167}
168
169/// A builder for SecureJwtConfig
170#[derive(Default)]
171pub struct SecureJwtConfigBuilder {
172    config: SecureJwtConfig,
173}
174
175impl SecureJwtConfigBuilder {
176    /// Allow a specific JSON Web Signature algorithm
177    pub fn with_algorithm(mut self, algo: Algorithm) -> Self {
178        self.config.allowed_algorithms.push(algo);
179        self
180    }
181
182    /// Set the allowed algorithms, replacing any existing
183    pub fn with_algorithms(mut self, algos: Vec<Algorithm>) -> Self {
184        self.config.allowed_algorithms = algos;
185        self
186    }
187
188    /// Require a specific issuer string
189    pub fn require_issuer(mut self, issuer: impl Into<String>) -> Self {
190        self.config.required_issuers.insert(issuer.into());
191        self
192    }
193
194    /// Require a specific audience string
195    pub fn require_audience(mut self, audience: impl Into<String>) -> Self {
196        self.config.required_audiences.insert(audience.into());
197        self
198    }
199
200    /// Set the maximum allowed lifetime of a token before it is rejected
201    pub fn with_max_lifetime(mut self, lifetime: Duration) -> Self {
202        self.config.max_token_lifetime = lifetime;
203        self
204    }
205
206    /// Set the allowed clock skew when evaluating timestamps
207    pub fn with_clock_skew(mut self, skew: Duration) -> Self {
208        self.config.clock_skew = skew;
209        self
210    }
211
212    /// Set whether a JWT ID (jti) claim is required
213    pub fn require_jti(mut self, require: bool) -> Self {
214        self.config.require_jti = require;
215        self
216    }
217
218    /// Set the HMAC signing secret (required for symmetric signing operations)
219    pub fn with_secret(mut self, secret: impl Into<String>) -> Self {
220        self.config.jwt_secret = secret.into();
221        self
222    }
223
224    /// Build the SecureJwtConfig
225    pub fn build(self) -> SecureJwtConfig {
226        self.config
227    }
228}
229
230pub struct SecureJwtValidator {
231    config: SecureJwtConfig,
232    /// Maps JTI → insertion timestamp so we can evict by age in `cleanup_revoked_tokens`.
233    ///
234    /// **In-memory only** — entries do not survive process restarts. See the struct-level
235    /// documentation for the recommended dual-layer revocation approach.
236    revoked_tokens: std::sync::Mutex<std::collections::HashMap<String, std::time::SystemTime>>,
237    /// Optional callback invoked with the JTI string each time a token is revoked.
238    ///
239    /// Use [`set_on_revoke`] to register a closure that persists the revocation to durable
240    /// storage (database, KV store, etc.). The callback is invoked **after** the in-memory
241    /// insertion succeeds.
242    #[allow(clippy::type_complexity)] // private field; an alias would only be used once
243    on_revoke: std::sync::Mutex<Option<Box<dyn Fn(&str) + Send + Sync>>>,
244}
245
246impl std::fmt::Debug for SecureJwtValidator {
247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248        f.debug_struct("SecureJwtValidator")
249            .field("config", &self.config)
250            .field(
251                "revoked_tokens",
252                &crate::utils::redact::redacted(&self.revoked_tokens),
253            )
254            .field(
255                "on_revoke",
256                &self.on_revoke.lock().ok().map(|g| g.is_some()),
257            )
258            .finish()
259    }
260}
261
262impl SecureJwtValidator {
263    pub fn new(config: SecureJwtConfig) -> Result<Self> {
264        // Validate that every allowed algorithm has the required key material.
265        let has_hmac = config
266            .allowed_algorithms
267            .iter()
268            .any(|a| is_hmac_algorithm(*a));
269        let has_rsa = config.allowed_algorithms.iter().any(|a| {
270            matches!(
271                a,
272                Algorithm::RS256
273                    | Algorithm::RS384
274                    | Algorithm::RS512
275                    | Algorithm::PS256
276                    | Algorithm::PS384
277                    | Algorithm::PS512
278            )
279        });
280        let has_ec = config
281            .allowed_algorithms
282            .iter()
283            .any(|a| matches!(a, Algorithm::ES256 | Algorithm::ES384));
284        let has_eddsa = config
285            .allowed_algorithms
286            .iter()
287            .any(|a| matches!(a, Algorithm::EdDSA));
288
289        if has_hmac {
290            #[cfg(not(test))]
291            if config.jwt_secret.len() < 32 {
292                return Err(AuthError::Configuration {
293                    message: "SecureJwtConfig::jwt_secret must be at least 32 characters \
294                              when HMAC algorithms are enabled"
295                        .to_string(),
296                    help: Some(
297                        "Provide a cryptographically random secret unique to your deployment"
298                            .to_string(),
299                    ),
300                    docs_url: None,
301                    source: None,
302                    suggested_fix: None,
303                });
304            }
305        }
306        if has_rsa && config.rsa_public_key_pem.is_none() {
307            return Err(AuthError::Configuration {
308                message: "SecureJwtConfig::rsa_public_key_pem must be set when RSA/PS algorithms are enabled".to_string(),
309                help: Some("Set rsa_public_key_pem in SecureJwtConfig".to_string()),
310                docs_url: None,
311                source: None,
312                suggested_fix: None,
313            });
314        }
315        if has_ec && config.ec_public_key_pem.is_none() {
316            return Err(AuthError::Configuration {
317                message:
318                    "SecureJwtConfig::ec_public_key_pem must be set when EC algorithms are enabled"
319                        .to_string(),
320                help: Some("Set ec_public_key_pem in SecureJwtConfig".to_string()),
321                docs_url: None,
322                source: None,
323                suggested_fix: None,
324            });
325        }
326        if has_eddsa && config.ed_public_key_pem.is_none() {
327            return Err(AuthError::Configuration {
328                message: "SecureJwtConfig::ed_public_key_pem must be set when EdDSA is enabled"
329                    .to_string(),
330                help: Some("Set ed_public_key_pem in SecureJwtConfig".to_string()),
331                docs_url: None,
332                source: None,
333                suggested_fix: None,
334            });
335        }
336
337        Ok(Self {
338            config,
339            revoked_tokens: std::sync::Mutex::new(std::collections::HashMap::new()),
340            on_revoke: std::sync::Mutex::new(None),
341        })
342    }
343
344    /// Register an optional callback that is invoked with the JTI every time
345    /// [`revoke_token`] is called.
346    ///
347    /// This allows callers to persist revocations to durable storage (database,
348    /// KV store, etc.) without changing the existing validation or revocation API.
349    ///
350    /// # Example
351    ///
352    /// ```rust,ignore
353    /// validator.set_on_revoke(|jti| {
354    ///     // Persist to your storage backend
355    ///     storage.insert_revoked_jti(jti);
356    /// });
357    /// ```
358    pub fn set_on_revoke<F>(&self, callback: F)
359    where
360        F: Fn(&str) + Send + Sync + 'static,
361    {
362        let mut guard = match self.on_revoke.lock() {
363            Ok(g) => g,
364            Err(poisoned) => poisoned.into_inner(),
365        };
366        *guard = Some(Box::new(callback));
367    }
368
369    /// Get HMAC decoding key for backward-compatible call sites.
370    ///
371    /// Prefer `validate` which handles key selection automatically.
372    pub fn get_decoding_key(&self) -> jsonwebtoken::DecodingKey {
373        jsonwebtoken::DecodingKey::from_secret(self.config.jwt_secret.as_bytes())
374    }
375
376    /// Get HMAC encoding key for signing JWTs.
377    pub fn get_encoding_key(&self) -> jsonwebtoken::EncodingKey {
378        jsonwebtoken::EncodingKey::from_secret(self.config.jwt_secret.as_bytes())
379    }
380
381    /// Select the appropriate [`DecodingKey`] for the given algorithm.
382    fn decoding_key_for_algorithm(&self, alg: Algorithm) -> Result<DecodingKey> {
383        match alg {
384            Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
385                Ok(DecodingKey::from_secret(self.config.jwt_secret.as_bytes()))
386            }
387            Algorithm::RS256
388            | Algorithm::RS384
389            | Algorithm::RS512
390            | Algorithm::PS256
391            | Algorithm::PS384
392            | Algorithm::PS512 => {
393                let pem = self.config.rsa_public_key_pem.as_deref().ok_or_else(|| {
394                    AuthError::Configuration {
395                        message: "RSA public key PEM not configured".to_string(),
396                        help: Some(
397                            "Set rsa_public_key_pem in SecureJwtConfig for RSA/PS algorithms"
398                                .to_string(),
399                        ),
400                        docs_url: None,
401                        source: None,
402                        suggested_fix: None,
403                    }
404                })?;
405                DecodingKey::from_rsa_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
406                    message: format!("Invalid RSA public key PEM: {e}"),
407                    help: None,
408                    docs_url: None,
409                    source: None,
410                    suggested_fix: None,
411                })
412            }
413            Algorithm::ES256 | Algorithm::ES384 => {
414                let pem = self.config.ec_public_key_pem.as_deref().ok_or_else(|| {
415                    AuthError::Configuration {
416                        message: "EC public key PEM not configured".to_string(),
417                        help: Some(
418                            "Set ec_public_key_pem in SecureJwtConfig for EC algorithms"
419                                .to_string(),
420                        ),
421                        docs_url: None,
422                        source: None,
423                        suggested_fix: None,
424                    }
425                })?;
426                DecodingKey::from_ec_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
427                    message: format!("Invalid EC public key PEM: {e}"),
428                    help: None,
429                    docs_url: None,
430                    source: None,
431                    suggested_fix: None,
432                })
433            }
434            Algorithm::EdDSA => {
435                let pem = self.config.ed_public_key_pem.as_deref().ok_or_else(|| {
436                    AuthError::Configuration {
437                        message: "Ed25519 public key PEM not configured".to_string(),
438                        help: Some(
439                            "Set ed_public_key_pem in SecureJwtConfig for EdDSA".to_string(),
440                        ),
441                        docs_url: None,
442                        source: None,
443                        suggested_fix: None,
444                    }
445                })?;
446                DecodingKey::from_ed_pem(pem.as_bytes()).map_err(|e| AuthError::Configuration {
447                    message: format!("Invalid Ed25519 public key PEM: {e}"),
448                    help: None,
449                    docs_url: None,
450                    source: None,
451                    suggested_fix: None,
452                })
453            }
454        }
455    }
456
457    /// Validate a JWT, automatically selecting the key based on the token header algorithm.
458    ///
459    /// This is the preferred entry point. It:
460    /// 1. Decodes the JWT header to determine the claimed algorithm.
461    /// 2. Rejects the token immediately if the algorithm is not in `allowed_algorithms`.
462    /// 3. Selects the correct decoding key for the algorithm family.
463    /// 4. Validates the signature **and** all standard claims (exp, nbf, iss, aud).
464    /// 5. Performs additional checks: revocation, max lifetime, JTI presence, token type.
465    pub fn validate(&self, token: &str) -> Result<SecureJwtClaims> {
466        // 1. Decode header (no signature verification yet).
467        let header = jsonwebtoken::decode_header(token)
468            .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
469
470        // 2. Reject algorithms not in the configured allow-list.
471        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        // 3. Select the decoding key for this algorithm family.
479        let decoding_key = self.decoding_key_for_algorithm(header.alg)?;
480
481        // 4. Build validation rules — delegate standard claim checks to jsonwebtoken.
482        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        // Expiration: always enforced.
487        validation.validate_exp = true;
488
489        // Not-before: honour config.
490        validation.validate_nbf = self.config.validate_nbf;
491
492        // Audience: enforce if the config specifies required audiences.
493        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        // Issuer: enforce if the config specifies required issuers.
506        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        // 5. Decode & verify signature + standard claims.
517        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        // 6. Additional custom validations.
523
524        // Revocation check.
525        if self.is_token_revoked(&claims.jti)? {
526            return Err(AuthError::Unauthorized("Token is revoked".to_string()));
527        }
528
529        // Max token lifetime.
530        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        // JTI presence.
540        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        // Token type restriction.
547        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    /// Legacy validation entry point that accepts a caller-supplied decoding key.
561    ///
562    /// Prefer [`validate`] which handles algorithm checking and key selection internally.
563    /// This method still enforces the full allow-list and all claim checks.
564    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    /// Check whether `jti` appears in the **in-memory** revocation list.
645    ///
646    /// This only consults the local cache. For a complete revocation check that
647    /// also queries durable storage, combine this with the storage-backed lookup
648    /// in the API layer (`src/api/auth.rs`).
649    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    /// Revoke a token by its JTI.
657    ///
658    /// The JTI is inserted into the **in-memory** revocation map. If an
659    /// [`on_revoke`](Self::set_on_revoke) callback has been registered, it is
660    /// invoked with the JTI after the in-memory insertion, allowing durable
661    /// persistence without changing this method's signature.
662    ///
663    /// **Note:** Without a registered `on_revoke` callback, revocations are
664    /// volatile and will be lost on process restart.
665    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        // Invoke the persistence callback outside the revoked_tokens lock to
675        // avoid holding two locks simultaneously.
676        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    /// Remove revoked token entries that are older than `expired_cutoff`.
685    ///
686    /// This prevents unbounded memory growth in long-running deployments.  Callers should
687    /// pass a cutoff equal to `now − max_token_lifetime` so that every entry that could
688    /// still be used by a live token is preserved, while entries that can only correspond
689    /// to already-expired tokens are discarded.
690    ///
691    /// An additional size cap (10,000 entries) is enforced after time-based eviction:
692    /// if the map still exceeds the cap the oldest 25 % of entries are removed.
693    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        // Phase 1: remove entries whose insertion time predates the cutoff — these
700        // correspond to JWTs that would have expired naturally already.
701        revoked_tokens.retain(|_, inserted_at| *inserted_at >= expired_cutoff);
702
703        // Phase 2: hard size cap — if phase 1 was not enough (e.g. very short cleanup
704        // interval or very long token lifetime), evict the oldest 25 % of remaining entries.
705        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            // Re-insert only the newest entries.
710            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!".to_string(),
731            ..SecureJwtConfig::default()
732        }
733    }
734
735    fn issue_token(config: &SecureJwtConfig, claims: &SecureJwtClaims) -> String {
736        let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
737        jsonwebtoken::encode(&Header::new(Algorithm::HS256), claims, &key).unwrap()
738    }
739
740    fn valid_claims() -> SecureJwtClaims {
741        let now = chrono::Utc::now().timestamp();
742        SecureJwtClaims {
743            sub: "user123".to_string(),
744            iss: "auth-framework".to_string(),
745            aud: "test".to_string(),
746            exp: now + 600,
747            nbf: now - 10,
748            iat: now,
749            jti: uuid::Uuid::new_v4().to_string(),
750            scope: "read".to_string(),
751            typ: "access".to_string(),
752            sid: None,
753            client_id: None,
754            auth_ctx_hash: None,
755        }
756    }
757
758    #[test]
759    fn test_default_config_generates_random_secret() {
760        let c1 = SecureJwtConfig::default();
761        let c2 = SecureJwtConfig::default();
762        assert_ne!(c1.jwt_secret, c2.jwt_secret);
763        assert!(c1.jwt_secret.len() >= 32);
764    }
765
766    #[test]
767    fn test_builder_fluent_api() {
768        let config = SecureJwtConfig::builder()
769            .with_secret("a]test_secret_that_is_longer_than_32_chars_for_security!")
770            .require_issuer("my-issuer")
771            .require_audience("my-aud")
772            .with_max_lifetime(Duration::from_secs(7200))
773            .with_clock_skew(Duration::from_secs(60))
774            .require_jti(false)
775            .build();
776
777        assert!(config.required_issuers.contains("my-issuer"));
778        assert!(config.required_audiences.contains("my-aud"));
779        assert_eq!(config.max_token_lifetime, Duration::from_secs(7200));
780        assert_eq!(config.clock_skew, Duration::from_secs(60));
781        assert!(!config.require_jti);
782    }
783
784    #[test]
785    fn test_validate_valid_token() {
786        let config = test_config();
787        let claims = valid_claims();
788        let token = issue_token(&config, &claims);
789        let validator = SecureJwtValidator::new(config).unwrap();
790        let result = validator.validate(&token).unwrap();
791        assert_eq!(result.sub, "user123");
792        assert_eq!(result.iss, "auth-framework");
793    }
794
795    #[test]
796    fn test_validate_rejects_expired_token() {
797        let config = test_config();
798        let mut claims = valid_claims();
799        claims.exp = chrono::Utc::now().timestamp() - 3600;
800        claims.iat = claims.exp - 600;
801        let token = issue_token(&config, &claims);
802        let validator = SecureJwtValidator::new(config).unwrap();
803        assert!(validator.validate(&token).is_err());
804    }
805
806    #[test]
807    fn test_validate_rejects_wrong_issuer() {
808        let config = test_config();
809        let mut claims = valid_claims();
810        claims.iss = "evil-issuer".to_string();
811        let token = issue_token(&config, &claims);
812        let validator = SecureJwtValidator::new(config).unwrap();
813        assert!(validator.validate(&token).is_err());
814    }
815
816    #[test]
817    fn test_revoke_and_check() {
818        let config = test_config();
819        let validator = SecureJwtValidator::new(config).unwrap();
820        let jti = "test-jti-123";
821        assert!(!validator.is_token_revoked(jti).unwrap());
822        validator.revoke_token(jti).unwrap();
823        assert!(validator.is_token_revoked(jti).unwrap());
824    }
825
826    #[test]
827    fn test_revoked_token_rejected() {
828        let config = test_config();
829        let claims = valid_claims();
830        let jti = claims.jti.clone();
831        let token = issue_token(&config, &claims);
832        let validator = SecureJwtValidator::new(config).unwrap();
833        validator.revoke_token(&jti).unwrap();
834        assert!(validator.validate(&token).is_err());
835    }
836
837    #[test]
838    fn test_cleanup_removes_old_entries() {
839        let config = test_config();
840        let validator = SecureJwtValidator::new(config).unwrap();
841        validator.revoke_token("old-jti").unwrap();
842        // Cleanup with a cutoff in the future removes everything
843        let future = std::time::SystemTime::now() + Duration::from_secs(3600);
844        validator.cleanup_revoked_tokens(future).unwrap();
845        assert!(!validator.is_token_revoked("old-jti").unwrap());
846    }
847
848    #[test]
849    fn test_on_revoke_callback() {
850        let config = test_config();
851        let validator = SecureJwtValidator::new(config).unwrap();
852        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
853        let captured_clone = captured.clone();
854        validator.set_on_revoke(move |jti| {
855            captured_clone.lock().unwrap().push(jti.to_string());
856        });
857        validator.revoke_token("cb-jti-1").unwrap();
858        validator.revoke_token("cb-jti-2").unwrap();
859        let jtis = captured.lock().unwrap();
860        assert_eq!(jtis.len(), 2);
861        assert!(jtis.contains(&"cb-jti-1".to_string()));
862        assert!(jtis.contains(&"cb-jti-2".to_string()));
863    }
864
865    #[test]
866    fn test_rejects_disallowed_algorithm() {
867        let config = test_config();
868        let claims = valid_claims();
869        // Sign with HS384 but config only allows HS256
870        let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
871        let token = jsonwebtoken::encode(&Header::new(Algorithm::HS384), &claims, &key).unwrap();
872        let validator = SecureJwtValidator::new(config).unwrap();
873        assert!(validator.validate(&token).is_err());
874    }
875
876    #[test]
877    fn test_rejects_excessive_lifetime() {
878        let mut config = test_config();
879        config.max_token_lifetime = Duration::from_secs(300);
880        let mut claims = valid_claims();
881        let now = chrono::Utc::now().timestamp();
882        claims.iat = now;
883        claims.exp = now + 600; // 10 min > 5 min max
884        let token = issue_token(&config, &claims);
885        let validator = SecureJwtValidator::new(config).unwrap();
886        assert!(validator.validate(&token).is_err());
887    }
888
889    #[test]
890    fn test_missing_rsa_key_rejected() {
891        let mut config = test_config();
892        config.allowed_algorithms = vec![Algorithm::RS256];
893        let result = SecureJwtValidator::new(config);
894        assert!(result.is_err());
895    }
896}