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            // `Algorithm` is `#[non_exhaustive]`: an algorithm added later is refused, never defaulted.
425            other => Err(AuthError::Configuration {
426                message: format!("Unsupported JWT algorithm {other:?}"),
427                help: None,
428                docs_url: None,
429                source: None,
430                suggested_fix: None,
431            }),
432        }
433    }
434
435    /// Validate a JWT, automatically selecting the key based on the token header algorithm.
436    ///
437    /// This is the preferred entry point. It:
438    /// 1. Decodes the JWT header to determine the claimed algorithm.
439    /// 2. Rejects the token immediately if the algorithm is not in `allowed_algorithms`.
440    /// 3. Selects the correct decoding key for the algorithm family.
441    /// 4. Validates the signature **and** all standard claims (exp, nbf, iss, aud).
442    /// 5. Performs additional checks: revocation, max lifetime, JTI presence, token type.
443    pub fn validate(&self, token: &str) -> Result<SecureJwtClaims> {
444        // 1. Decode header (no signature verification yet).
445        let header = jsonwebtoken::decode_header(token)
446            .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
447
448        // 2. Reject algorithms not in the configured allow-list.
449        if !self.config.allowed_algorithms.contains(&header.alg) {
450            return Err(AuthError::Unauthorized(format!(
451                "Token algorithm {:?} is not permitted; allowed: {:?}",
452                header.alg, self.config.allowed_algorithms
453            )));
454        }
455
456        // 3. Select the decoding key for this algorithm family.
457        let decoding_key = self.decoding_key_for_algorithm(header.alg)?;
458
459        // 4. Build validation rules — delegate standard claim checks to jsonwebtoken.
460        let mut validation = jsonwebtoken::Validation::new(header.alg);
461        validation.algorithms = self.config.allowed_algorithms.clone();
462        validation.leeway = self.config.clock_skew.as_secs();
463
464        // Expiration: always enforced.
465        validation.validate_exp = true;
466
467        // Not-before: honour config.
468        validation.validate_nbf = self.config.validate_nbf;
469
470        // Audience: enforce if the config specifies required audiences.
471        if !self.config.required_audiences.is_empty() {
472            validation.set_audience(
473                &self
474                    .config
475                    .required_audiences
476                    .iter()
477                    .collect::<Vec<&String>>(),
478            );
479        } else {
480            validation.validate_aud = false;
481        }
482
483        // Issuer: enforce if the config specifies required issuers.
484        if !self.config.required_issuers.is_empty() {
485            validation.set_issuer(
486                &self
487                    .config
488                    .required_issuers
489                    .iter()
490                    .collect::<Vec<&String>>(),
491            );
492        }
493
494        // 5. Decode & verify signature + standard claims.
495        let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, &decoding_key, &validation)
496            .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
497
498        let claims = token_data.claims;
499
500        // 6. Additional custom validations.
501
502        // Revocation check.
503        if self.is_token_revoked(&claims.jti)? {
504            return Err(AuthError::Unauthorized("Token is revoked".to_string()));
505        }
506
507        // Max token lifetime.
508        let token_lifetime = claims.exp.saturating_sub(claims.iat);
509        if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
510        {
511            return Err(AuthError::Unauthorized(format!(
512                "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
513                self.config.max_token_lifetime.as_secs()
514            )));
515        }
516
517        // JTI presence.
518        if self.config.require_jti && claims.jti.is_empty() {
519            return Err(AuthError::Unauthorized(
520                "Token missing required JTI claim".to_string(),
521            ));
522        }
523
524        // Token type restriction.
525        if !self.config.allowed_token_types.is_empty()
526            && !claims.typ.is_empty()
527            && !self.config.allowed_token_types.contains(&claims.typ)
528        {
529            return Err(AuthError::Unauthorized(format!(
530                "Token type '{}' is not permitted",
531                claims.typ
532            )));
533        }
534
535        Ok(claims)
536    }
537
538    /// Legacy validation entry point that accepts a caller-supplied decoding key.
539    ///
540    /// Prefer [`validate`] which handles algorithm checking and key selection internally.
541    /// This method still enforces the full allow-list and all claim checks.
542    pub fn validate_token(
543        &self,
544        token: &str,
545        decoding_key: &DecodingKey,
546    ) -> Result<SecureJwtClaims> {
547        let header = jsonwebtoken::decode_header(token)
548            .map_err(|e| AuthError::Unauthorized(format!("Invalid JWT header: {e}")))?;
549
550        if !self.config.allowed_algorithms.contains(&header.alg) {
551            return Err(AuthError::Unauthorized(format!(
552                "Token algorithm {:?} is not permitted; allowed: {:?}",
553                header.alg, self.config.allowed_algorithms
554            )));
555        }
556
557        let mut validation = jsonwebtoken::Validation::new(header.alg);
558        validation.algorithms = self.config.allowed_algorithms.clone();
559        validation.leeway = self.config.clock_skew.as_secs();
560        validation.validate_exp = true;
561        validation.validate_nbf = self.config.validate_nbf;
562
563        if !self.config.required_audiences.is_empty() {
564            validation.set_audience(
565                &self
566                    .config
567                    .required_audiences
568                    .iter()
569                    .collect::<Vec<&String>>(),
570            );
571        } else {
572            validation.validate_aud = false;
573        }
574
575        if !self.config.required_issuers.is_empty() {
576            validation.set_issuer(
577                &self
578                    .config
579                    .required_issuers
580                    .iter()
581                    .collect::<Vec<&String>>(),
582            );
583        }
584
585        let token_data = jsonwebtoken::decode::<SecureJwtClaims>(token, decoding_key, &validation)
586            .map_err(|e| AuthError::Unauthorized(format!("JWT validation failed: {e}")))?;
587
588        let claims = token_data.claims;
589
590        if self.is_token_revoked(&claims.jti)? {
591            return Err(AuthError::Unauthorized("Token is revoked".to_string()));
592        }
593
594        let token_lifetime = claims.exp.saturating_sub(claims.iat);
595        if token_lifetime > 0 && (token_lifetime as u64) > self.config.max_token_lifetime.as_secs()
596        {
597            return Err(AuthError::Unauthorized(format!(
598                "Token lifetime ({token_lifetime}s) exceeds maximum allowed ({}s)",
599                self.config.max_token_lifetime.as_secs()
600            )));
601        }
602
603        if self.config.require_jti && claims.jti.is_empty() {
604            return Err(AuthError::Unauthorized(
605                "Token missing required JTI claim".to_string(),
606            ));
607        }
608
609        if !self.config.allowed_token_types.is_empty()
610            && !claims.typ.is_empty()
611            && !self.config.allowed_token_types.contains(&claims.typ)
612        {
613            return Err(AuthError::Unauthorized(format!(
614                "Token type '{}' is not permitted",
615                claims.typ
616            )));
617        }
618
619        Ok(claims)
620    }
621
622    /// Check whether `jti` appears in the **in-memory** revocation list.
623    ///
624    /// This only consults the local cache. For a complete revocation check that
625    /// also queries durable storage, combine this with the storage-backed lookup
626    /// in the API layer (`src/api/auth.rs`).
627    pub fn is_token_revoked(&self, jti: &str) -> Result<bool> {
628        let revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
629            AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
630        })?;
631        Ok(revoked_tokens.contains_key(jti))
632    }
633
634    /// Revoke a token by its JTI.
635    ///
636    /// The JTI is inserted into the **in-memory** revocation map. If an
637    /// [`on_revoke`](Self::set_on_revoke) callback has been registered, it is
638    /// invoked with the JTI after the in-memory insertion, allowing durable
639    /// persistence without changing this method's signature.
640    ///
641    /// **Note:** Without a registered `on_revoke` callback, revocations are
642    /// volatile and will be lost on process restart.
643    pub fn revoke_token(&self, jti: &str) -> Result<()> {
644        {
645            let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
646                AuthError::internal(
647                    "Lock poisoned — a prior thread panicked while holding this lock",
648                )
649            })?;
650            revoked_tokens.insert(jti.to_string(), std::time::SystemTime::now());
651        }
652        // Invoke the persistence callback outside the revoked_tokens lock to
653        // avoid holding two locks simultaneously.
654        if let Some(ref cb) = *self.on_revoke.lock().map_err(|_| {
655            AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
656        })? {
657            cb(jti);
658        }
659        Ok(())
660    }
661
662    /// Remove revoked token entries that are older than `expired_cutoff`.
663    ///
664    /// This prevents unbounded memory growth in long-running deployments.  Callers should
665    /// pass a cutoff equal to `now − max_token_lifetime` so that every entry that could
666    /// still be used by a live token is preserved, while entries that can only correspond
667    /// to already-expired tokens are discarded.
668    ///
669    /// An additional size cap (10,000 entries) is enforced after time-based eviction:
670    /// if the map still exceeds the cap the oldest 25 % of entries are removed.
671    pub fn cleanup_revoked_tokens(&self, expired_cutoff: std::time::SystemTime) -> Result<()> {
672        const MAX_REVOKED_TOKENS: usize = 10_000;
673        let mut revoked_tokens = self.revoked_tokens.lock().map_err(|_| {
674            AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock")
675        })?;
676
677        // Phase 1: remove entries whose insertion time predates the cutoff — these
678        // correspond to JWTs that would have expired naturally already.
679        revoked_tokens.retain(|_, inserted_at| *inserted_at >= expired_cutoff);
680
681        // Phase 2: hard size cap — if phase 1 was not enough (e.g. very short cleanup
682        // interval or very long token lifetime), evict the oldest 25 % of remaining entries.
683        if revoked_tokens.len() > MAX_REVOKED_TOKENS {
684            let target_len = MAX_REVOKED_TOKENS * 3 / 4;
685            let mut by_age: Vec<(String, std::time::SystemTime)> = revoked_tokens.drain().collect();
686            by_age.sort_unstable_by_key(|(_, t)| *t);
687            // Re-insert only the newest entries.
688            for (jti, inserted_at) in by_age.into_iter().rev().take(target_len) {
689                revoked_tokens.insert(jti, inserted_at);
690            }
691            tracing::warn!(
692                "Revoked token list exceeded {} entries; oldest entries were evicted.",
693                MAX_REVOKED_TOKENS
694            );
695        }
696
697        Ok(())
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704    use jsonwebtoken::{Algorithm, EncodingKey, Header};
705
706    fn test_config() -> SecureJwtConfig {
707        SecureJwtConfig {
708            jwt_secret: "a]test_secret_that_is_longer_than_32_chars_for_security!"
709                .to_string()
710                .into(),
711            ..SecureJwtConfig::default()
712        }
713    }
714
715    fn issue_token(config: &SecureJwtConfig, claims: &SecureJwtClaims) -> String {
716        let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
717        jsonwebtoken::encode(&Header::new(Algorithm::HS256), claims, &key).unwrap()
718    }
719
720    fn valid_claims() -> SecureJwtClaims {
721        let now = chrono::Utc::now().timestamp();
722        SecureJwtClaims {
723            sub: "user123".to_string(),
724            iss: "auth-framework".to_string(),
725            aud: "test".to_string(),
726            exp: now + 600,
727            nbf: now - 10,
728            iat: now,
729            jti: uuid::Uuid::new_v4().to_string(),
730            scope: "read".to_string(),
731            typ: "access".to_string(),
732            sid: None,
733            client_id: None,
734            auth_ctx_hash: None,
735        }
736    }
737
738    /// Known answer: an HS256 token produced outside this crate (HMAC-SHA256 by hand, so by no
739    /// version of jsonwebtoken) still verifies, and the same token with a flipped signature does not.
740    /// It must pass on every jsonwebtoken major this crate supports, so tokens issued before an
741    /// upgrade keep verifying after it.
742    #[test]
743    fn a_token_signed_by_hand_verifies_and_a_tampered_one_does_not() {
744        #[derive(serde::Deserialize)]
745        struct C {
746            sub: String,
747        }
748        const TOKEN: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIiwiZXhwIjo0MTAyNDQ0ODAwfQ.ZZuykscIyOZdHswIzwjQd0kMJUt86iOkkW7Y-uoQPz4";
749        let key = DecodingKey::from_secret(b"known-answer-secret-for-compat-test-32b!");
750        let mut v = jsonwebtoken::Validation::new(Algorithm::HS256);
751        v.validate_exp = true;
752        v.required_spec_claims.clear();
753        let ok = jsonwebtoken::decode::<C>(TOKEN, &key, &v).expect("hand-signed token verifies");
754        assert_eq!(ok.claims.sub, "user123");
755
756        let (head, sig) = TOKEN.rsplit_once('.').unwrap();
757        let flipped = if sig.starts_with('A') { "B" } else { "A" };
758        let tampered = format!("{head}.{flipped}{}", &sig[1..]);
759        assert!(jsonwebtoken::decode::<C>(&tampered, &key, &v).is_err());
760    }
761
762    /// Key selection per algorithm: HMAC uses the configured secret; every asymmetric algorithm needs
763    /// its public key configured and is refused (not defaulted) without one.
764    #[test]
765    fn decoding_key_selection_covers_every_known_algorithm() {
766        let v = SecureJwtValidator::new(test_config()).unwrap();
767        for alg in [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512] {
768            assert!(v.decoding_key_for_algorithm(alg).is_ok(), "{alg:?}");
769        }
770        for alg in [
771            Algorithm::RS256,
772            Algorithm::RS384,
773            Algorithm::RS512,
774            Algorithm::PS256,
775            Algorithm::PS384,
776            Algorithm::PS512,
777            Algorithm::ES256,
778            Algorithm::ES384,
779            Algorithm::EdDSA,
780        ] {
781            assert!(
782                matches!(
783                    v.decoding_key_for_algorithm(alg),
784                    Err(AuthError::Configuration { .. })
785                ),
786                "{alg:?} without a configured public key must be refused"
787            );
788        }
789    }
790
791    #[test]
792    fn test_default_config_generates_random_secret() {
793        let c1 = SecureJwtConfig::default();
794        let c2 = SecureJwtConfig::default();
795        assert_ne!(c1.jwt_secret, c2.jwt_secret);
796        assert!(c1.jwt_secret.len() >= 32);
797    }
798
799    #[test]
800    fn test_builder_fluent_api() {
801        let config = SecureJwtConfig::builder()
802            .with_secret("a]test_secret_that_is_longer_than_32_chars_for_security!")
803            .require_issuer("my-issuer")
804            .require_audience("my-aud")
805            .with_max_lifetime(Duration::from_secs(7200))
806            .with_clock_skew(Duration::from_secs(60))
807            .require_jti(false)
808            .build();
809
810        assert!(config.required_issuers.contains("my-issuer"));
811        assert!(config.required_audiences.contains("my-aud"));
812        assert_eq!(config.max_token_lifetime, Duration::from_secs(7200));
813        assert_eq!(config.clock_skew, Duration::from_secs(60));
814        assert!(!config.require_jti);
815    }
816
817    #[test]
818    fn test_validate_valid_token() {
819        let config = test_config();
820        let claims = valid_claims();
821        let token = issue_token(&config, &claims);
822        let validator = SecureJwtValidator::new(config).unwrap();
823        let result = validator.validate(&token).unwrap();
824        assert_eq!(result.sub, "user123");
825        assert_eq!(result.iss, "auth-framework");
826    }
827
828    #[test]
829    fn test_validate_rejects_expired_token() {
830        let config = test_config();
831        let mut claims = valid_claims();
832        claims.exp = chrono::Utc::now().timestamp() - 3600;
833        claims.iat = claims.exp - 600;
834        let token = issue_token(&config, &claims);
835        let validator = SecureJwtValidator::new(config).unwrap();
836        assert!(validator.validate(&token).is_err());
837    }
838
839    #[test]
840    fn test_validate_rejects_wrong_issuer() {
841        let config = test_config();
842        let mut claims = valid_claims();
843        claims.iss = "evil-issuer".to_string();
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_revoke_and_check() {
851        let config = test_config();
852        let validator = SecureJwtValidator::new(config).unwrap();
853        let jti = "test-jti-123";
854        assert!(!validator.is_token_revoked(jti).unwrap());
855        validator.revoke_token(jti).unwrap();
856        assert!(validator.is_token_revoked(jti).unwrap());
857    }
858
859    #[test]
860    fn test_revoked_token_rejected() {
861        let config = test_config();
862        let claims = valid_claims();
863        let jti = claims.jti.clone();
864        let token = issue_token(&config, &claims);
865        let validator = SecureJwtValidator::new(config).unwrap();
866        validator.revoke_token(&jti).unwrap();
867        assert!(validator.validate(&token).is_err());
868    }
869
870    #[test]
871    fn test_cleanup_removes_old_entries() {
872        let config = test_config();
873        let validator = SecureJwtValidator::new(config).unwrap();
874        validator.revoke_token("old-jti").unwrap();
875        // Cleanup with a cutoff in the future removes everything
876        let future = std::time::SystemTime::now() + Duration::from_secs(3600);
877        validator.cleanup_revoked_tokens(future).unwrap();
878        assert!(!validator.is_token_revoked("old-jti").unwrap());
879    }
880
881    #[test]
882    fn test_on_revoke_callback() {
883        let config = test_config();
884        let validator = SecureJwtValidator::new(config).unwrap();
885        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
886        let captured_clone = captured.clone();
887        validator.set_on_revoke(move |jti| {
888            captured_clone.lock().unwrap().push(jti.to_string());
889        });
890        validator.revoke_token("cb-jti-1").unwrap();
891        validator.revoke_token("cb-jti-2").unwrap();
892        let jtis = captured.lock().unwrap();
893        assert_eq!(jtis.len(), 2);
894        assert!(jtis.contains(&"cb-jti-1".to_string()));
895        assert!(jtis.contains(&"cb-jti-2".to_string()));
896    }
897
898    #[test]
899    fn test_rejects_disallowed_algorithm() {
900        let config = test_config();
901        let claims = valid_claims();
902        // Sign with HS384 but config only allows HS256
903        let key = EncodingKey::from_secret(config.jwt_secret.as_bytes());
904        let token = jsonwebtoken::encode(&Header::new(Algorithm::HS384), &claims, &key).unwrap();
905        let validator = SecureJwtValidator::new(config).unwrap();
906        assert!(validator.validate(&token).is_err());
907    }
908
909    #[test]
910    fn test_rejects_excessive_lifetime() {
911        let mut config = test_config();
912        config.max_token_lifetime = Duration::from_secs(300);
913        let mut claims = valid_claims();
914        let now = chrono::Utc::now().timestamp();
915        claims.iat = now;
916        claims.exp = now + 600; // 10 min > 5 min max
917        let token = issue_token(&config, &claims);
918        let validator = SecureJwtValidator::new(config).unwrap();
919        assert!(validator.validate(&token).is_err());
920    }
921
922    #[test]
923    fn test_missing_rsa_key_rejected() {
924        let mut config = test_config();
925        config.allowed_algorithms = vec![Algorithm::RS256];
926        let result = SecureJwtValidator::new(config);
927        assert!(result.is_err());
928    }
929}