larust_http/throttle.rs
1//! Laravel's `throttle` middleware - a fixed-window request-rate limit,
2//! keyed by the caller's real TCP peer address (`ConnectInfo<SocketAddr>`,
3//! see `larust_core::Application::serve()`'s `into_make_service_with_connect_info`
4//! wiring), never a client-supplied header like `X-Forwarded-For` - this
5//! framework has no "trusted proxy" concept to validate such a header
6//! against, so trusting it would make the limiter trivially bypassable
7//! (a different value per request) while looking like it works.
8//!
9//! Rejects with `429 Too Many Requests` plus a `Retry-After` header once a
10//! key's bucket is exhausted, matching Laravel's own `ThrottleRequests`
11//! response shape. Hand-rolled rather than built on `tower::limit`
12//! (present in this workspace's dependency tree only via `tower`'s default
13//! features; its `RateLimit` service isn't `Clone`, failing `Router::
14//! middleware()`'s bound without extra wrapping, and it has no per-key
15//! bucketing at all) or a new dependency like `governor` - this mirrors
16//! `csrf.rs`'s own hand-written `axum::middleware::from_fn`-style shape
17//! instead, the established house style for this kind of thing.
18
19use axum::extract::{ConnectInfo, Request, State};
20use axum::http::{header, StatusCode};
21use axum::middleware::{from_fn_with_state, FromFnLayer, Next};
22use axum::response::{IntoResponse, Response};
23use std::collections::HashMap;
24use std::future::Future;
25use std::net::SocketAddr;
26use std::pin::Pin;
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29
30/// Caps how many distinct keys (source IPs, plus the one shared fallback
31/// below) this process tracks at once, mirroring `larust_live::lock`'s
32/// identical `MAX_SESSION_LOCKS` cap and reasoning: without a bound, a
33/// flood of requests from many distinct source addresses could grow this
34/// table without limit. Unlike that module, a new key arriving at the cap
35/// **fails open** here (allowed, just not tracked) rather than evicting
36/// the oldest entry - this cap protects this process's own memory, it
37/// isn't meant to be a rejection mechanism in its own right, and a
38/// genuinely abusive client keeps reusing the same key regardless, so its
39/// own bucket still catches it.
40const MAX_TRACKED_KEYS: usize = 10_000;
41
42/// The shared bucket key for any request with no `ConnectInfo` at all.
43/// Every request driven through `larust_testing::TestClient` falls into
44/// this case - it dispatches via `tower::ServiceExt::oneshot`, never a
45/// real accepted TCP connection, so `ConnectInfo` is never populated.
46/// Sharing one bucket keeps existing and future tests from needing to
47/// know anything about rate limiting to pass, at the cost of tests
48/// sharing a limit with each other if a single test fires more requests
49/// than the configured limit within one window - not the case for any
50/// test in this codebase today.
51const NO_CONNECT_INFO_KEY: &str = "__no_connect_info__";
52
53/// How often [`ThrottleState::allow`] pays for a full table scan to reclaim
54/// buckets whose key stopped being requested entirely (so nothing else
55/// would ever touch that bucket again to expire it naturally) - matches
56/// `larust_cache::sql_store`'s own `EXPIRY_SWEEP_INTERVAL_SECS` convention.
57/// An individual key's own window reset doesn't depend on this at all; see
58/// [`ThrottleState::allow`]'s doc comment.
59const SWEEP_INTERVAL: Duration = Duration::from_secs(300);
60
61struct Bucket {
62 count: u32,
63 window_start: Instant,
64}
65
66struct BucketState {
67 buckets: HashMap<String, Bucket>,
68 last_sweep: Instant,
69}
70
71/// `pub` only because it has to appear in [`per`]/[`per_minute`]'s public
72/// return type (see that doc comment) - every field stays private, so
73/// nothing outside this module can construct or inspect one.
74pub struct ThrottleState {
75 max_requests: u32,
76 window: Duration,
77 state: Mutex<BucketState>,
78}
79
80impl ThrottleState {
81 /// `true` if a request keyed `key` may proceed, recording it against
82 /// that key's bucket either way. A fixed-window counter (matches
83 /// Laravel's own `RateLimiter` algorithm, not token-bucket/sliding-
84 /// window) - a key's window simply resets, rather than aligning to a
85 /// global clock, once `window` has elapsed since it was first seen.
86 ///
87 /// A looked-up key's own expiry is checked here directly (an O(1)
88 /// touch of the one bucket this call already needs) rather than by
89 /// scanning every tracked key on every request - the full-table sweep
90 /// below exists only to reclaim memory from keys that stop being
91 /// requested (and so would never otherwise expire), and is gated to
92 /// run at most once per [`SWEEP_INTERVAL`] for that reason.
93 fn allow(&self, key: &str) -> bool {
94 let mut state = self
95 .state
96 .lock()
97 .unwrap_or_else(|poisoned| poisoned.into_inner());
98 let now = Instant::now();
99
100 if now.duration_since(state.last_sweep) >= SWEEP_INTERVAL {
101 state
102 .buckets
103 .retain(|_, bucket| now.duration_since(bucket.window_start) < self.window);
104 state.last_sweep = now;
105 }
106
107 if let Some(bucket) = state.buckets.get_mut(key) {
108 if now.duration_since(bucket.window_start) >= self.window {
109 bucket.count = 1;
110 bucket.window_start = now;
111 return true;
112 }
113 if bucket.count >= self.max_requests {
114 return false;
115 }
116 bucket.count += 1;
117 return true;
118 }
119
120 if state.buckets.len() < MAX_TRACKED_KEYS {
121 state.buckets.insert(
122 key.to_string(),
123 Bucket {
124 count: 1,
125 window_start: now,
126 },
127 );
128 }
129 true
130 }
131}
132
133/// `middleware`'s own extractor arguments (every one before `Next`), as a
134/// tuple - `axum::middleware::from_fn_with_state`'s hidden extractor-arity
135/// marker parameter, spelled out explicitly (see [`per`]'s own doc comment
136/// for why it has to be).
137type Extractors = (
138 State<Arc<ThrottleState>>,
139 Option<ConnectInfo<SocketAddr>>,
140 Request,
141);
142
143/// A plain `fn` pointer, not the anonymous type of an `async fn` item -
144/// see [`per`]'s own doc comment for why `middleware` has to be written to
145/// coerce to this rather than left as an `async fn`.
146type MiddlewareFn = fn(
147 State<Arc<ThrottleState>>,
148 Option<ConnectInfo<SocketAddr>>,
149 Request,
150 Next,
151) -> MiddlewareFuture;
152type MiddlewareFuture = Pin<Box<dyn Future<Output = Response> + Send>>;
153
154/// `max_requests` per rolling minute - Laravel's own common default
155/// (`throttle:60,1`) when a route doesn't specify its own limit.
156pub fn per_minute(max_requests: u32) -> FromFnLayer<MiddlewareFn, Arc<ThrottleState>, Extractors> {
157 per(max_requests, Duration::from_secs(60))
158}
159
160/// `max_requests` per `window` - the general form behind [`per_minute`].
161/// Usable via `Router::middleware(...)` the same way `csrf::verify`/
162/// `DefaultBodyLimit::max(...)` already are.
163///
164/// Returns the fully concrete `FromFnLayer<...>` type rather than `impl
165/// tower::Layer<axum::routing::Route> + Clone + Send + 'static` - tempting
166/// since that's exactly what `Router::middleware()` requires, but an
167/// opaque `impl Trait` return only carries the bounds spelled out on it,
168/// not the *other* facts a caller in a different crate needs (that
169/// `L::Service` is itself `Clone + Send + tower::Service<Request>`,
170/// `Router::middleware()`'s real bound on `L::Service`) - those get
171/// erased at the opaque-type boundary, so `demo`/`examples/blog`'s own
172/// `.middleware(throttle::per_minute(60))` call failed to type-check
173/// against `impl Trait` even though this exact value works fine passed
174/// directly. A concrete, nameable return type has no such boundary; every
175/// real trait impl on it stays visible everywhere. Same reason `Router::
176/// middleware()`'s own doc comment says to call `axum::middleware::
177/// from_fn(handler)` directly at the `.middleware(...)` call site instead
178/// of through a wrapping function - this file does the equivalent by
179/// keeping the concrete type nameable instead.
180pub fn per(
181 max_requests: u32,
182 window: Duration,
183) -> FromFnLayer<MiddlewareFn, Arc<ThrottleState>, Extractors> {
184 let state = Arc::new(ThrottleState {
185 max_requests,
186 window,
187 state: Mutex::new(BucketState {
188 buckets: HashMap::new(),
189 last_sweep: Instant::now(),
190 }),
191 });
192 from_fn_with_state(state, middleware as MiddlewareFn)
193}
194
195/// A plain `fn`, not `async fn` - `async fn`'s return type is anonymous
196/// and can't be named, which [`MiddlewareFn`] (and so [`per`]'s own
197/// concrete return type) needs it to be; boxing the future by hand is what
198/// makes that possible.
199fn middleware(
200 State(state): State<Arc<ThrottleState>>,
201 connect_info: Option<ConnectInfo<SocketAddr>>,
202 request: Request,
203 next: Next,
204) -> MiddlewareFuture {
205 Box::pin(async move {
206 let key = connect_info
207 .map(|ConnectInfo(addr)| addr.ip().to_string())
208 .unwrap_or_else(|| NO_CONNECT_INFO_KEY.to_string());
209
210 if !state.allow(&key) {
211 return reject(state.window);
212 }
213
214 next.run(request).await
215 })
216}
217
218fn reject(window: Duration) -> Response {
219 (
220 StatusCode::TOO_MANY_REQUESTS,
221 [(header::RETRY_AFTER, window.as_secs().to_string())],
222 "Too Many Requests",
223 )
224 .into_response()
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 fn state(max_requests: u32, window: Duration) -> ThrottleState {
232 ThrottleState {
233 max_requests,
234 window,
235 state: Mutex::new(BucketState {
236 buckets: HashMap::new(),
237 last_sweep: Instant::now(),
238 }),
239 }
240 }
241
242 #[test]
243 fn allows_up_to_the_limit_then_rejects_the_next_request_in_the_same_window() {
244 let state = state(3, Duration::from_secs(60));
245 assert!(state.allow("a"));
246 assert!(state.allow("a"));
247 assert!(state.allow("a"));
248 assert!(!state.allow("a"));
249 }
250
251 #[test]
252 fn a_fresh_window_resets_the_count() {
253 // A generous margin (150ms) between the window's own length and how
254 // long the test sleeps past it - found genuinely flaky under load,
255 // not hypothetically: the previous 50ms/80ms pairing (a 30ms
256 // margin) passed reliably in isolation but intermittently failed
257 // when run alongside this crate's other ~19 tests in the same
258 // binary, since `cargo test`'s default parallel scheduling can
259 // delay a real `thread::sleep`'s wakeup by tens of milliseconds
260 // under contention. Still fast in the common case (a quarter
261 // second), just no longer assuming near-zero scheduling jitter.
262 let state = state(1, Duration::from_millis(100));
263 assert!(state.allow("a"));
264 assert!(!state.allow("a"));
265 std::thread::sleep(Duration::from_millis(250));
266 assert!(state.allow("a"));
267 }
268
269 #[test]
270 fn different_keys_have_independent_buckets() {
271 let state = state(1, Duration::from_secs(60));
272 assert!(state.allow("a"));
273 assert!(!state.allow("a"));
274 assert!(state.allow("b"));
275 }
276
277 #[test]
278 fn a_new_key_at_capacity_fails_open_rather_than_panicking_or_rejecting() {
279 let state = state(1, Duration::from_secs(60));
280 for i in 0..MAX_TRACKED_KEYS {
281 assert!(state.allow(&i.to_string()));
282 }
283 assert!(state.allow("one-more-past-capacity"));
284 }
285}