1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Pluggable JTI (JWT ID) revocation / single-use store.
//!
//! A `JtiStore` records which JWT ids are spent: revoked at logout, or
//! consumed by a single-use impersonation handoff. A request carrying
//! a spent `jti` must be rejected, or the token can be replayed until
//! it expires.
//!
//! Anything the store forgets becomes valid again. A restart or an
//! eviction can drop an entry. A store that is not shared never sees
//! the other processes. In both cases a revoked `jti` still works
//! until its `exp`. Use a shared, durable store once you run more
//! than one instance.
//!
//! - [`InMemoryJtiStore`] — process-local map, the default for every
//! shipped consumer. Good for one instance, dev and tests.
//! `mark_used` prunes expired entries on each call, so memory stays
//! bounded with no background sweeper.
//! - Anything else — implement [`JtiStore`] over Redis, a database
//! table, or another shared store.
//! [`RedisCache`](crate::cache::redis_backend::RedisCache) is the
//! smallest bridge.
//!
//! [`InMemoryJtiStore`]: crate::jti_store::InMemoryJtiStore
//! [`JtiStore`]: crate::jti_store::JtiStore
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
/// Future returned by the [`JtiStore`] methods.
///
/// Boxed because consumers hold the store as `Arc<dyn JtiStore>`, and
/// `async fn` in a trait is not dyn-compatible. Written by hand rather
/// than with `#[async_trait]` so this ungated module still builds when
/// the optional `async-trait` dependency is off.
pub type JtiFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Storage backend for "this JTI is no longer valid" lookups.
///
/// Implementations MUST make `mark_used` atomic: for one `jti`, exactly
/// one concurrent caller may see `true` and every other must see
/// `false`. Otherwise two requests can spend the same single-use token.
///
/// The methods return futures so a durable store can `await` its write.
/// Revoking is the one operation you want to be immediate everywhere; a
/// store that buffers writes keeps accepting a revoked `jti` on other
/// instances until it catches up.
///
/// A synchronous implementation just wraps the body:
///
/// ```ignore
/// impl JtiStore for MyStore {
/// fn is_used<'a>(&'a self, jti: &'a str) -> JtiFuture<'a, bool> {
/// Box::pin(async move { self.map.lock().unwrap().contains_key(jti) })
/// }
/// fn mark_used<'a>(&'a self, jti: &'a str, exp_unix: i64) -> JtiFuture<'a, bool> {
/// Box::pin(async move { /* … */ true })
/// }
/// }
/// ```
///
/// …and a durable one is a single query:
///
/// ```ignore
/// fn mark_used<'a>(&'a self, jti: &'a str, exp_unix: i64) -> JtiFuture<'a, bool> {
/// Box::pin(async move {
/// // One atomic round trip. Not `rows_affected == 1`: a MySQL
/// // skip also reports 1 row, so a replay would pass.
/// rustango::sql::insert_or_ignore(&pool, &insert).await.unwrap_or(false)
/// })
/// }
/// ```
pub trait JtiStore: Send + Sync {
/// Returns `true` if `jti` has previously been marked used /
/// blacklisted. Read-only; never mutates the store.
fn is_used<'a>(&'a self, jti: &'a str) -> JtiFuture<'a, bool>;
/// Atomically check and record. Returns `true` when the caller is
/// the first to use this `jti`, `false` when it was already there
/// (a replay — reject the request).
///
/// `exp_unix` is the JWT's `exp` claim (unix seconds). Stores MAY
/// use it to prune entries.
///
/// Write it as one conditional write
/// ([`insert_or_ignore`](crate::sql::insert_or_ignore), Redis `SET NX`),
/// never a read then a write.
fn mark_used<'a>(&'a self, jti: &'a str, exp_unix: i64) -> JtiFuture<'a, bool>;
/// Rough count of tracked JTIs, for dashboards and tests. Not on
/// the hot path.
///
/// Returns `None` when the store cannot count cheaply, which is
/// also the default, so an implementation may ignore this method.
fn approx_size(&self) -> JtiFuture<'_, Option<usize>> {
Box::pin(async { None })
}
/// `true` when revocations live in this process only; other
/// replicas keep accepting a revoked token.
fn is_process_local(&self) -> bool {
false
}
}
/// In-process JTI store. The default for every shipped JWT / handoff
/// consumer. Its entries are lost on restart and not shared with other
/// processes, so a revoked `jti` can still be replayed there.
pub struct InMemoryJtiStore {
inner: Mutex<HashMap<String, i64>>,
}
impl InMemoryJtiStore {
#[must_use]
pub fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
}
}
/// Test-only entry count.
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.inner.lock().unwrap_or_else(|e| e.into_inner()).len()
}
}
impl Default for InMemoryJtiStore {
fn default() -> Self {
Self::new()
}
}
impl JtiStore for InMemoryJtiStore {
fn is_process_local(&self) -> bool {
true
}
// Bodies await nothing, so the `std::sync::Mutex` guard never
// crosses a suspend point.
fn is_used<'a>(&'a self, jti: &'a str) -> JtiFuture<'a, bool> {
Box::pin(async move {
let map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
map.contains_key(jti)
})
}
fn mark_used<'a>(&'a self, jti: &'a str, exp_unix: i64) -> JtiFuture<'a, bool> {
Box::pin(async move {
let mut map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
// Prune expired entries so memory stays bounded without a
// background sweeper.
let now = chrono::Utc::now().timestamp();
map.retain(|_, &mut e| e > now);
if map.contains_key(jti) {
return false;
}
map.insert(jti.to_owned(), exp_unix);
true
})
}
fn approx_size(&self) -> JtiFuture<'_, Option<usize>> {
Box::pin(async move { Some(self.inner.lock().unwrap_or_else(|e| e.into_inner()).len()) })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn fresh_jti_is_not_used() {
let store = InMemoryJtiStore::new();
assert!(!store.is_used("token-1").await);
}
#[tokio::test]
async fn first_mark_used_returns_true() {
let store = InMemoryJtiStore::new();
let exp = chrono::Utc::now().timestamp() + 60;
assert!(store.mark_used("token-1", exp).await);
assert!(store.is_used("token-1").await);
}
#[tokio::test]
async fn second_mark_used_returns_false_single_use_guarantee() {
let store = InMemoryJtiStore::new();
let exp = chrono::Utc::now().timestamp() + 60;
assert!(store.mark_used("token-1", exp).await);
assert!(
!store.mark_used("token-1", exp).await,
"second use must return false to preserve single-use guard"
);
}
#[tokio::test]
async fn distinct_jtis_dont_collide() {
let store = InMemoryJtiStore::new();
let exp = chrono::Utc::now().timestamp() + 60;
assert!(store.mark_used("token-a", exp).await);
assert!(store.mark_used("token-b", exp).await);
assert!(store.is_used("token-a").await);
assert!(store.is_used("token-b").await);
assert!(!store.is_used("token-c").await);
}
#[tokio::test]
async fn expired_entries_are_pruned_on_next_mark() {
let store = InMemoryJtiStore::new();
let already_expired = chrono::Utc::now().timestamp() - 60;
// Insert the expired entry through the lock: `mark_used`
// would prune it right away.
store
.inner
.lock()
.unwrap()
.insert("stale".to_owned(), already_expired);
assert_eq!(store.len(), 1);
let fresh_exp = chrono::Utc::now().timestamp() + 60;
assert!(store.mark_used("fresh", fresh_exp).await);
// `mark_used` pruned `stale`, so only `fresh` is left.
assert_eq!(store.len(), 1);
assert!(!store.is_used("stale").await);
assert!(store.is_used("fresh").await);
}
#[test]
fn only_the_in_memory_store_is_process_local() {
struct Shared;
impl JtiStore for Shared {
fn is_used<'a>(&'a self, _: &'a str) -> JtiFuture<'a, bool> {
Box::pin(async { false })
}
fn mark_used<'a>(&'a self, _: &'a str, _: i64) -> JtiFuture<'a, bool> {
Box::pin(async { true })
}
}
assert!(InMemoryJtiStore::new().is_process_local());
assert!(!Shared.is_process_local());
}
#[tokio::test]
async fn trait_object_is_usable() {
// `Arc<dyn JtiStore>` is the shape every consumer takes, and
// the reason the trait returns boxed futures.
let store: std::sync::Arc<dyn JtiStore> = std::sync::Arc::new(InMemoryJtiStore::new());
let exp = chrono::Utc::now().timestamp() + 60;
assert!(store.mark_used("via-dyn", exp).await);
assert!(store.is_used("via-dyn").await);
}
/// A store that awaits between the check and the record, like a
/// database-backed one. `mark_used` must stay single-use under
/// concurrency.
#[tokio::test]
async fn awaiting_store_keeps_the_single_use_guarantee() {
struct AwaitingStore(Mutex<HashMap<String, i64>>);
impl JtiStore for AwaitingStore {
fn is_used<'a>(&'a self, jti: &'a str) -> JtiFuture<'a, bool> {
Box::pin(async move {
tokio::task::yield_now().await;
self.0.lock().unwrap().contains_key(jti)
})
}
fn mark_used<'a>(&'a self, jti: &'a str, exp_unix: i64) -> JtiFuture<'a, bool> {
Box::pin(async move {
tokio::task::yield_now().await;
// Single conditional write, holding the lock across the
// check and the insert.
let mut map = self.0.lock().unwrap();
if map.contains_key(jti) {
return false;
}
map.insert(jti.to_owned(), exp_unix);
true
})
}
}
let store: std::sync::Arc<dyn JtiStore> =
std::sync::Arc::new(AwaitingStore(Mutex::new(HashMap::new())));
let exp = chrono::Utc::now().timestamp() + 60;
// Two concurrent claims on the same jti: exactly one must win.
let (a, b) = tokio::join!(store.mark_used("race", exp), store.mark_used("race", exp));
assert!(a ^ b, "exactly one concurrent mark_used must succeed");
assert!(store.is_used("race").await);
}
}