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