Skip to main content

fastauth_core/
storage.rs

1//! Secondary storage: a key-value store every instance of an app shares, such as Redis or
2//! Valkey, for state that must agree across instances. Better Auth's `secondaryStorage`.
3//!
4//! fastauth keeps sessions, verification tokens and code attempts in the database, which
5//! instances already share, and the cookie cache in the client's cookie. The one piece of
6//! state each process keeps on its own is the rate limiter: with `.secondary_storage(..)` its
7//! counters live here, so a limit holds across every instance instead of once per instance.
8//! Without it, the limiter stays in memory.
9
10use std::future::Future;
11use std::pin::Pin;
12use std::sync::{Arc, Mutex};
13use std::time::{Duration, Instant};
14
15/// A key-value store with expiring keys, shared by every instance of the app. `fastauth-redis`
16/// implements it for Redis and Valkey.
17///
18/// Keys fastauth writes start with `fastauth:`. A TTL of zero counts as the shortest TTL the
19/// store has (one millisecond in Redis), never as "no expiry".
20pub trait SecondaryStorage: Send + Sync + 'static {
21    /// The value at `key`, or `None` when it doesn't exist or has expired.
22    fn get(&self, key: &str) -> impl Future<Output = Result<Option<String>, StorageError>> + Send;
23
24    /// Stores `value` at `key`, replacing any value and TTL it had. Without a `ttl` it never
25    /// expires.
26    fn set(
27        &self,
28        key: &str,
29        value: &str,
30        ttl: Option<Duration>,
31    ) -> impl Future<Output = Result<(), StorageError>> + Send;
32
33    /// Deletes `key`. Deleting a key that doesn't exist succeeds.
34    fn delete(&self, key: &str) -> impl Future<Output = Result<(), StorageError>> + Send;
35
36    /// Adds one to the counter at `key` and returns the new value, in one atomic step: two
37    /// instances incrementing at once get different values. A key that doesn't exist starts at
38    /// 1 and expires `ttl` later. Later increments don't extend the TTL, so the counter covers
39    /// a fixed window from its first increment. Rate limits rely on both properties.
40    fn increment(
41        &self,
42        key: &str,
43        ttl: Duration,
44    ) -> impl Future<Output = Result<u64, StorageError>> + Send;
45}
46
47/// A secondary storage call that failed, such as a lost connection.
48#[derive(Debug, thiserror::Error)]
49#[error("secondary storage: {0}")]
50pub struct StorageError(#[source] Box<dyn std::error::Error + Send + Sync>);
51
52impl StorageError {
53    pub fn new(err: impl std::error::Error + Send + Sync + 'static) -> Self {
54        Self(Box::new(err))
55    }
56}
57
58type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
59
60/// The object-safe face of [`SecondaryStorage`], for the parts of core that hold one.
61pub(crate) trait DynStorage: Send + Sync {
62    fn increment<'a>(
63        &'a self,
64        key: &'a str,
65        ttl: Duration,
66    ) -> BoxFuture<'a, Result<u64, StorageError>>;
67}
68
69impl<S: SecondaryStorage> DynStorage for S {
70    fn increment<'a>(
71        &'a self,
72        key: &'a str,
73        ttl: Duration,
74    ) -> BoxFuture<'a, Result<u64, StorageError>> {
75        Box::pin(SecondaryStorage::increment(self, key, ttl))
76    }
77}
78
79/// How long core waits for one secondary storage call unless
80/// [`Builder::secondary_storage_timeout`](crate::Builder::secondary_storage_timeout) says
81/// otherwise: about a hundred Redis round trips on one network, and well under the time a
82/// sign-in spends hashing the password.
83pub const DEFAULT_STORAGE_TIMEOUT: Duration = Duration::from_millis(100);
84
85/// After this many failed or timed-out calls in a row, core stops calling the storage.
86const BREAKER_THRESHOLD: u32 = 5;
87
88/// How long core leaves a failing storage alone before one call probes it again.
89const BREAKER_COOL_DOWN: Duration = Duration::from_secs(5);
90
91/// The secondary storage as core calls it: every call bounded by a timeout, and a circuit
92/// breaker that skips the storage for a cool-down after [`BREAKER_THRESHOLD`] failures in a
93/// row, so a dead store doesn't add the timeout to every request. Once the cool-down is over,
94/// one call probes the store; it closes the breaker when it succeeds and reopens it otherwise.
95pub(crate) struct GuardedStorage {
96    inner: Arc<dyn DynStorage>,
97    timeout: Duration,
98    threshold: u32,
99    cool_down: Duration,
100    breaker: Mutex<Breaker>,
101}
102
103#[derive(Default)]
104struct Breaker {
105    failures: u32,
106    open_until: Option<Instant>,
107}
108
109impl GuardedStorage {
110    pub(crate) fn new(inner: Arc<dyn DynStorage>, timeout: Duration) -> Self {
111        Self {
112            inner,
113            timeout,
114            threshold: BREAKER_THRESHOLD,
115            cool_down: BREAKER_COOL_DOWN,
116            breaker: Mutex::default(),
117        }
118    }
119
120    #[cfg(test)]
121    pub(crate) fn with_breaker(mut self, threshold: u32, cool_down: Duration) -> Self {
122        self.threshold = threshold;
123        self.cool_down = cool_down;
124        self
125    }
126
127    pub(crate) async fn increment(&self, key: &str, ttl: Duration) -> Result<u64, StorageError> {
128        if !self.admit() {
129            return Err(StorageError::new(std::io::Error::other(format!(
130                "skipped after {} failures in a row; probing again every {:?}",
131                self.threshold, self.cool_down
132            ))));
133        }
134        let result = tokio::time::timeout(self.timeout, self.inner.increment(key, ttl))
135            .await
136            .unwrap_or_else(|_| {
137                Err(StorageError::new(std::io::Error::new(
138                    std::io::ErrorKind::TimedOut,
139                    format!("no answer within {:?}", self.timeout),
140                )))
141            });
142        self.record(result.is_ok());
143        result
144    }
145
146    /// Whether a call may go to the storage. Once an open breaker's cool-down is over, the
147    /// first call to ask is the probe, and the others wait out a new cool-down.
148    fn admit(&self) -> bool {
149        let mut breaker = self.breaker.lock().unwrap();
150        let now = Instant::now();
151        match breaker.open_until {
152            Some(until) if now < until => false,
153            Some(_) => {
154                breaker.open_until = Some(now + self.cool_down);
155                true
156            }
157            None => true,
158        }
159    }
160
161    fn record(&self, ok: bool) {
162        let mut breaker = self.breaker.lock().unwrap();
163        if ok {
164            *breaker = Breaker::default();
165            return;
166        }
167        breaker.failures = breaker.failures.saturating_add(1);
168        if breaker.failures >= self.threshold {
169            breaker.open_until = Some(Instant::now() + self.cool_down);
170        }
171    }
172}
173
174/// An in-memory [`SecondaryStorage`] for core's own tests, which can be made to fail.
175#[cfg(test)]
176pub(crate) mod fake {
177    use std::collections::HashMap;
178    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
179    use std::sync::{Arc, Mutex, MutexGuard};
180    use std::time::{Duration, Instant};
181
182    use super::{SecondaryStorage, StorageError};
183
184    type Entries = HashMap<String, (String, Option<Instant>)>;
185
186    #[derive(Clone, Default)]
187    pub(crate) struct FakeStorage {
188        entries: Arc<Mutex<Entries>>,
189        down: Arc<AtomicBool>,
190        hanging: Arc<AtomicBool>,
191        increments: Arc<AtomicUsize>,
192    }
193
194    impl FakeStorage {
195        /// Every call fails while `down` is true, like a store that lost its connection.
196        pub(crate) fn set_down(&self, down: bool) {
197            self.down.store(down, Ordering::SeqCst);
198        }
199
200        /// Every increment waits forever while `hanging` is true, like a partitioned store.
201        pub(crate) fn set_hanging(&self, hanging: bool) {
202            self.hanging.store(hanging, Ordering::SeqCst);
203        }
204
205        /// How many increments reached the store.
206        pub(crate) fn increments(&self) -> usize {
207            self.increments.load(Ordering::SeqCst)
208        }
209
210        pub(crate) fn keys(&self) -> Vec<String> {
211            self.entries.lock().unwrap().keys().cloned().collect()
212        }
213
214        fn live(&self) -> Result<MutexGuard<'_, Entries>, StorageError> {
215            if self.down.load(Ordering::SeqCst) {
216                return Err(StorageError::new(std::io::Error::other(
217                    "connection refused",
218                )));
219            }
220            let mut entries = self.entries.lock().unwrap();
221            let now = Instant::now();
222            entries.retain(|_, (_, expires)| expires.is_none_or(|at| at > now));
223            Ok(entries)
224        }
225    }
226
227    fn expiry(ttl: Duration) -> Instant {
228        Instant::now() + ttl.max(Duration::from_millis(1))
229    }
230
231    impl SecondaryStorage for FakeStorage {
232        async fn get(&self, key: &str) -> Result<Option<String>, StorageError> {
233            Ok(self.live()?.get(key).map(|(value, _)| value.clone()))
234        }
235
236        async fn set(
237            &self,
238            key: &str,
239            value: &str,
240            ttl: Option<Duration>,
241        ) -> Result<(), StorageError> {
242            self.live()?
243                .insert(key.to_owned(), (value.to_owned(), ttl.map(expiry)));
244            Ok(())
245        }
246
247        async fn delete(&self, key: &str) -> Result<(), StorageError> {
248            self.live()?.remove(key);
249            Ok(())
250        }
251
252        async fn increment(&self, key: &str, ttl: Duration) -> Result<u64, StorageError> {
253            self.increments.fetch_add(1, Ordering::SeqCst);
254            if self.hanging.load(Ordering::SeqCst) {
255                std::future::pending::<()>().await;
256            }
257            let mut entries = self.live()?;
258            let (value, _) = entries
259                .entry(key.to_owned())
260                .or_insert_with(|| ("0".into(), Some(expiry(ttl))));
261            let next = value
262                .parse::<u64>()
263                .map_err(|_| StorageError::new(std::io::Error::other("not a counter")))?
264                + 1;
265            *value = next.to_string();
266            Ok(next)
267        }
268    }
269
270    #[tokio::test]
271    async fn fake_storage_passes_the_conformance_suite() {
272        crate::testing::run_storage_conformance(FakeStorage::default()).await;
273    }
274}