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