tablo_core/auth/throttle.rs
1//! [`LoginThrottle`]: counts sign-in attempts per login and client address, and refuses one past
2//! its limit.
3
4mod shared;
5
6use std::{
7 collections::HashMap,
8 hash::{BuildHasher, RandomState},
9 net::IpAddr,
10 sync::{
11 Mutex,
12 atomic::{AtomicBool, Ordering},
13 },
14 time::{Duration, Instant},
15};
16
17use topcoat::context::Cx;
18
19pub use self::shared::AuthThrottle;
20
21/// The most counts a throttle keeps at once; past it, an expired count is dropped first, else the
22/// oldest under its limit, and the oldest refusing one only when every count refuses: a flood of
23/// fresh logins cannot release a refused one.
24const MAX_TRACKED: usize = 10_000;
25
26/// How many sign-in attempts one login may make from one client address in a window, as
27/// [`Auth::throttle`](crate::Auth::throttle) sets it.
28///
29/// Each attempt that reaches the authenticator counts against the login it names, trimmed and
30/// lowercased, and the address [`client_ip`](topcoat::router::request::client_ip) answers, from
31/// the first attempt of the window; a successful sign-in clears that count. Past the limit, the
32/// login page refuses the attempt without asking the authenticator, with the same 403 and message
33/// as a wrong password, until the window ends, and logs a warning.
34///
35/// Keying on the address keeps a guesser from locking the account's owner out from elsewhere.
36/// Behind a reverse proxy every request carries the proxy's address unless the router trusts it
37/// through [`TrustedProxies`](topcoat::router::TrustedProxies); until then the count is per login
38/// alone, and a guesser can lock the owner out.
39///
40/// [`Auth::account_throttle`](crate::Auth::account_throttle) adds an opt-in, looser count per login
41/// across addresses. The first sign-in that carries `X-Forwarded-For` or `Forwarded` and whose
42/// client address is still the connection's logs a warning: either the router trusts no proxy, or
43/// the request bypassed the trusted ones.
44///
45/// It does not limit one client across logins, nor a login
46/// spelled several ways that the authenticator's lookup treats as one, as MySQL's default
47/// collation does with accents: a per-IP limit at the proxy covers those. Counts live in the
48/// process and per panel, so each replica and each panel counts its own attempts, and a restart
49/// clears them; [`in_database`](Self::in_database) keeps them where every replica reads them, and
50/// [`Auth::throttles_in_database`](crate::Auth::throttles_in_database) does so for every throttle a
51/// panel declares.
52///
53/// ```rust
54/// use std::time::Duration;
55///
56/// use tablo_core::{Auth, LoginThrottle};
57///
58/// let auth = Auth::password().throttle(LoginThrottle::new(10, Duration::from_secs(300)));
59/// # let _ = auth;
60/// ```
61pub struct LoginThrottle {
62 limit: Option<Limit>,
63 hasher: RandomState,
64 counts: Mutex<HashMap<u64, Count>>,
65 in_database: bool,
66}
67
68#[derive(Debug, Clone, Copy)]
69struct Limit {
70 attempts: u32,
71 window: Duration,
72}
73
74#[derive(Debug, Clone, Copy)]
75struct Count {
76 attempts: u32,
77 since: Instant,
78}
79
80impl LoginThrottle {
81 /// Allows `attempts` sign-in attempts per login in each `window`.
82 ///
83 /// The panel refuses to mount when `attempts` is `0` or `window` is zero: neither allows a
84 /// sign-in.
85 #[must_use]
86 pub fn new(attempts: u32, window: Duration) -> Self {
87 Self::with(Some(Limit { attempts, window }))
88 }
89
90 /// Counts nothing, for a deployment whose proxy limits sign-ins.
91 #[must_use]
92 pub fn off() -> Self {
93 Self::with(None)
94 }
95
96 /// Keeps the counts in the database, as [`AuthThrottle`] rows, rather than in the process:
97 /// every replica then counts against the same limit, and a restart forgets nothing. Each
98 /// attempt costs a serializable transaction, and mounting requires the model, which
99 /// [`models!`](crate::models!) registers.
100 ///
101 /// ```rust
102 /// use std::time::Duration;
103 ///
104 /// use tablo_core::{Auth, LoginThrottle};
105 ///
106 /// let auth =
107 /// Auth::password().throttle(LoginThrottle::new(10, Duration::from_secs(300)).in_database());
108 /// # let _ = auth;
109 /// ```
110 #[must_use]
111 pub fn in_database(mut self) -> Self {
112 self.count_in_database();
113 self
114 }
115
116 /// [`in_database`](Self::in_database) in place, for
117 /// [`Auth::throttles_in_database`](crate::Auth::throttles_in_database).
118 pub(super) fn count_in_database(&mut self) {
119 self.in_database = true;
120 }
121
122 fn with(limit: Option<Limit>) -> Self {
123 Self {
124 limit,
125 hasher: RandomState::new(),
126 counts: Mutex::new(HashMap::new()),
127 in_database: false,
128 }
129 }
130
131 /// Whether the throttle counts in the database, which then needs [`AuthThrottle`].
132 pub(crate) fn counts_in_database(&self) -> bool {
133 self.limit.is_some() && self.in_database
134 }
135
136 /// Whether the limit allows no sign-in at all: no attempt, or a window of no time.
137 pub(crate) fn allows_none(&self) -> bool {
138 self.limit
139 .is_some_and(|limit| limit.attempts == 0 || limit.window.is_zero())
140 }
141
142 /// Counts an attempt for `login` from `client`, or answers `false` when the pair is past its
143 /// limit. `scope` names what the throttle counts, so two throttles keep apart in the database.
144 pub(crate) async fn attempt(
145 &self,
146 cx: &Cx,
147 scope: &str,
148 login: &str,
149 client: Option<IpAddr>,
150 ) -> topcoat::Result<bool> {
151 match self.limit {
152 Some(limit) if self.in_database => {
153 shared::attempt(cx, limit, &shared::Slot::of(cx, scope, login, client)).await
154 }
155 _ => Ok(self.attempt_at(login, client, Instant::now())),
156 }
157 }
158
159 /// The window's length in whole seconds, rounded up: how long a refused client waits at
160 /// most. Zero for a throttle that counts nothing.
161 pub(crate) fn window_secs(&self) -> u64 {
162 self.limit.map_or(0, |limit| {
163 limit.window.as_secs() + u64::from(limit.window.subsec_nanos() > 0)
164 })
165 }
166
167 fn attempt_at(&self, login: &str, client: Option<IpAddr>, now: Instant) -> bool {
168 let Some(limit) = self.limit else {
169 return true;
170 };
171 let key = self.key(login, client);
172 let mut counts = self
173 .counts
174 .lock()
175 .unwrap_or_else(|poison| poison.into_inner());
176 if !counts.contains_key(&key) && counts.len() >= MAX_TRACKED {
177 counts.retain(|_, count| now.duration_since(count.since) < limit.window);
178 if counts.len() >= MAX_TRACKED
179 && let Some(oldest) = counts
180 .iter()
181 .min_by_key(|(_, count)| (count.attempts >= limit.attempts, count.since))
182 .map(|(key, _)| *key)
183 {
184 counts.remove(&oldest);
185 }
186 }
187 let count = counts.entry(key).or_insert(Count {
188 attempts: 0,
189 since: now,
190 });
191 if now.duration_since(count.since) >= limit.window {
192 *count = Count {
193 attempts: 0,
194 since: now,
195 };
196 }
197 if count.attempts >= limit.attempts {
198 return false;
199 }
200 count.attempts += 1;
201 true
202 }
203
204 /// Clears the count of `login` from `client` after it signs in there.
205 pub(crate) async fn clear(
206 &self,
207 cx: &Cx,
208 scope: &str,
209 login: &str,
210 client: Option<IpAddr>,
211 ) -> topcoat::Result<()> {
212 if self.counts_in_database() {
213 return shared::clear(cx, &shared::Slot::of(cx, scope, login, client)).await;
214 }
215 self.clear_here(login, client);
216 Ok(())
217 }
218
219 /// Clears the count of `login` from `client` in the process.
220 fn clear_here(&self, login: &str, client: Option<IpAddr>) {
221 if self.limit.is_some() {
222 let key = self.key(login, client);
223 self.counts
224 .lock()
225 .unwrap_or_else(|poison| poison.into_inner())
226 .remove(&key);
227 }
228 }
229
230 /// The count's key: a hash of the login and the address, so the map holds no login in the
231 /// clear.
232 fn key(&self, login: &str, client: Option<IpAddr>) -> u64 {
233 self.hasher.hash_one((login.trim().to_lowercase(), client))
234 }
235}
236
237/// Logs one warning per process when a sign-in carries a forwarding header the router did not
238/// read: the throttle then keys on the proxy's address, which every client shares.
239pub(crate) fn warn_unforwarded(cx: &topcoat::context::Cx) {
240 static WARNED: AtomicBool = AtomicBool::new(false);
241 if WARNED.load(Ordering::Relaxed) {
242 return;
243 }
244 let headers = topcoat::router::request::headers(cx);
245 let forwarded = headers.contains_key("x-forwarded-for") || headers.contains_key("forwarded");
246 let peer = topcoat::router::request::remote_addr(cx).map(|addr| addr.ip());
247 if forwarded
248 && peer.is_some()
249 && topcoat::router::request::client_ip(cx) == peer
250 && !WARNED.swap(true, Ordering::Relaxed)
251 {
252 tracing::warn!(
253 peer = ?peer,
254 "a sign-in carries a forwarding header the router ignores; register \
255 `TrustedProxies` so sign-in throttles count per client, not per proxy"
256 );
257 }
258}
259
260/// Five attempts per login and address a minute.
261impl Default for LoginThrottle {
262 fn default() -> Self {
263 Self::new(5, Duration::from_secs(60))
264 }
265}
266
267impl std::fmt::Debug for LoginThrottle {
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 match self.limit {
270 Some(Limit { attempts, window }) => f
271 .debug_struct("LoginThrottle")
272 .field("attempts", &attempts)
273 .field("window", &window)
274 .field("in_database", &self.in_database)
275 .finish(),
276 None => f.write_str("LoginThrottle::off"),
277 }
278 }
279}
280
281#[cfg(test)]
282mod tests;