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