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