Skip to main content

systemprompt_api/services/middleware/jwt/
revocation.rs

1//! JTI revocation gate for the JWT context extractor.
2//!
3//! Runs as the final stateful check after a token's claims, its backing user,
4//! and the session row have all validated. It answers the one question
5//! signature validation cannot: has this specific token been explicitly
6//! revoked (logout, admin revoke, refresh rotation)? A negative result is
7//! cached so the hot path costs one map lookup. Fails closed — a revocation
8//! store error rejects the request rather than admitting an unverifiable token.
9//!
10//! Copyright (c) systemprompt.io — Business Source License 1.1.
11//! See <https://systemprompt.io> for licensing details.
12
13use std::sync::Arc;
14use systemprompt_database::DbPool;
15use systemprompt_models::execution::context::ContextExtractionError;
16use systemprompt_oauth::OauthResult;
17use systemprompt_oauth::repository::{JtiRevocationCache, OAuthRepository};
18
19#[derive(Clone)]
20pub struct JtiRevocationChecker {
21    repo: Arc<OAuthRepository>,
22    cache: Arc<JtiRevocationCache>,
23}
24
25impl std::fmt::Debug for JtiRevocationChecker {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.debug_struct("JtiRevocationChecker")
28            .finish_non_exhaustive()
29    }
30}
31
32impl JtiRevocationChecker {
33    pub fn from_pool(db: &DbPool) -> OauthResult<Self> {
34        Ok(Self {
35            repo: Arc::new(OAuthRepository::new(db)?),
36            cache: Arc::new(JtiRevocationCache::new()),
37        })
38    }
39
40    pub async fn ensure_not_revoked(&self, jti: &str) -> Result<(), ContextExtractionError> {
41        if jti.is_empty() {
42            return Ok(());
43        }
44        match self.cache.peek(jti) {
45            Some(true) => return Err(ContextExtractionError::Revoked),
46            Some(false) => return Ok(()),
47            None => {},
48        }
49
50        let revoked = self.repo.is_jti_revoked(jti).await.map_err(|e| {
51            ContextExtractionError::DatabaseError {
52                message: format!("JTI revocation lookup failed: {e}"),
53            }
54        })?;
55        self.cache.record(jti, revoked);
56        if revoked {
57            Err(ContextExtractionError::Revoked)
58        } else {
59            Ok(())
60        }
61    }
62}