Per-IP fixed-window limiter
Browse files at this commit3cdfa6addb23e6887eee90d15bab6f83a51e11b8Parent: 90effd1- feat
- per-IP fixed-window limiter
1 changed file +325 -0
- src/rate_limit.rs +325 -0
src/rate_limit.rsadded+325 -0
| @@ -0,0 +1,325 @@ | |||
| 1 | +//! Per-client-IP rate limiting, hand-rolled on a fixed 60-second window — no | ||
| 2 | +//! extra crates, no background tasks. | ||
| 3 | +//! | ||
| 4 | +//! Two tiers are wired in: a strict one on the credential endpoints | ||
| 5 | +//! (`/auth/login`, `/auth/register`) in [`crate::web::auth::routes`] to blunt | ||
| 6 | +//! brute-force and enumeration attempts, and a generous catch-all over the | ||
| 7 | +//! whole API in [`crate::build_router`]. Both | ||
| 8 | +//! are configured per-minute via environment variables (see | ||
| 9 | +//! [`crate::config::Config`]); a limit of `0` switches that tier off entirely, | ||
| 10 | +//! which is also what the test suites use to stay unaffected. | ||
| 11 | +//! | ||
| 12 | +//! Requests are keyed by client IP. By default that is the peer address of the | ||
| 13 | +//! TCP connection ([`ConnectInfo`]). Behind a reverse proxy every connection | ||
| 14 | +//! shows the proxy's address, so set `TRUST_PROXY=true` to key on the | ||
| 15 | +//! **rightmost** `X-Forwarded-For` entry instead — that hop is appended by the | ||
| 16 | +//! nearest proxy and is the only one the client cannot forge. Never enable it | ||
| 17 | +//! when clients can reach the server directly: the header is then entirely | ||
| 18 | +//! attacker-controlled and the limiter is trivially bypassed. | ||
| 19 | +//! | ||
| 20 | +//! Fixed windows admit up to a 2× burst straddling a window boundary. That is | ||
| 21 | +//! an accepted trade-off for an implementation simple enough to read in one | ||
| 22 | +//! sitting; argon2 keeps each allowed login attempt expensive anyway. | ||
| 23 | + | ||
| 24 | +use std::collections::HashMap; | ||
| 25 | +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; | ||
| 26 | +use std::sync::{Arc, Mutex}; | ||
| 27 | +use std::time::Duration; | ||
| 28 | + | ||
| 29 | +use axum::extract::{ConnectInfo, Request}; | ||
| 30 | +use axum::middleware::Next; | ||
| 31 | +use axum::response::Response; | ||
| 32 | +// tokio's `Instant` wraps `std::time::Instant` in production but obeys | ||
| 33 | +// `tokio::time::pause`/`advance` under `start_paused` tests, which makes the | ||
| 34 | +// window arithmetic below testable without sleeping. | ||
| 35 | +use tokio::time::Instant; | ||
| 36 | + | ||
| 37 | +use crate::error::AppError; | ||
| 38 | + | ||
| 39 | +/// Once the bucket map holds this many distinct client IPs, expired entries are | ||
| 40 | +/// swept out on the next check. Keeps memory bounded without a reaper task. | ||
| 41 | +const PURGE_AT: usize = 10_000; | ||
| 42 | + | ||
| 43 | +/// Rate-limit knobs, sourced from the environment (see `.env.example`) and | ||
| 44 | +/// carried in [`crate::state::AppState`]. A `0` limit disables that tier. | ||
| 45 | +#[derive(Clone, Debug)] | ||
| 46 | +pub struct RateLimitConfig { | ||
| 47 | + /// Requests per minute per IP for `/auth/login` + `/auth/register`. | ||
| 48 | + pub auth_per_minute: u32, | ||
| 49 | + /// Requests per minute per IP for the whole API. | ||
| 50 | + pub api_per_minute: u32, | ||
| 51 | + /// Key clients by the rightmost `X-Forwarded-For` entry instead of the | ||
| 52 | + /// socket peer address. Only safe behind a proxy that appends it. | ||
| 53 | + pub trust_proxy: bool, | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +impl RateLimitConfig { | ||
| 57 | + /// Both tiers off. What the test helpers use so unrelated suites never | ||
| 58 | + /// trip a limit; dedicated rate-limit tests opt into tight configs. | ||
| 59 | + pub const fn unlimited() -> Self { | ||
| 60 | + Self { | ||
| 61 | + auth_per_minute: 0, | ||
| 62 | + api_per_minute: 0, | ||
| 63 | + trust_proxy: false, | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// A fixed-window counter per client IP: `max` requests per `window`, shared | ||
| 69 | +/// across clones (clones see the same buckets, so one limiter can be captured | ||
| 70 | +/// by a middleware closure and cloned per request for free). | ||
| 71 | +#[derive(Clone)] | ||
| 72 | +pub struct RateLimiter { | ||
| 73 | + max: u32, | ||
| 74 | + window: Duration, | ||
| 75 | + trust_proxy: bool, | ||
| 76 | + buckets: Arc<Mutex<HashMap<IpAddr, Bucket>>>, | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +struct Bucket { | ||
| 80 | + window_start: Instant, | ||
| 81 | + count: u32, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +impl RateLimiter { | ||
| 85 | + /// A limiter allowing `max` requests per fixed one-minute window. `max == 0` | ||
| 86 | + /// means disabled: every check passes and nothing is recorded. | ||
| 87 | + pub fn per_minute(max: u32, trust_proxy: bool) -> Self { | ||
| 88 | + Self { | ||
| 89 | + max, | ||
| 90 | + window: Duration::from_secs(60), | ||
| 91 | + trust_proxy, | ||
| 92 | + buckets: Arc::new(Mutex::new(HashMap::new())), | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + /// Axum middleware entry point: identify the caller, count the request, | ||
| 97 | + /// and either pass it along or answer `429` with a `Retry-After`. | ||
| 98 | + pub async fn enforce(&self, req: Request, next: Next) -> Result<Response, AppError> { | ||
| 99 | + let ip = client_ip(&req, self.trust_proxy); | ||
| 100 | + match self.check(ip) { | ||
| 101 | + Ok(()) => Ok(next.run(req).await), | ||
| 102 | + Err(retry_after_secs) => { | ||
| 103 | + tracing::warn!(%ip, retry_after_secs, "rate limit exceeded"); | ||
| 104 | + Err(AppError::TooManyRequests { retry_after_secs }) | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + /// Count one request from `ip`. `Err` carries the whole seconds (rounded | ||
| 110 | + /// up, at least 1) until the window resets — the `Retry-After` value. | ||
| 111 | + fn check(&self, ip: IpAddr) -> Result<(), u64> { | ||
| 112 | + if self.max == 0 { | ||
| 113 | + return Ok(()); | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + let now = Instant::now(); | ||
| 117 | + let mut buckets = self.buckets.lock().expect("rate limiter mutex poisoned"); | ||
| 118 | + | ||
| 119 | + if buckets.len() >= PURGE_AT { | ||
| 120 | + buckets.retain(|_, b| now.duration_since(b.window_start) < self.window); | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + let bucket = buckets.entry(ip).or_insert(Bucket { | ||
| 124 | + window_start: now, | ||
| 125 | + count: 0, | ||
| 126 | + }); | ||
| 127 | + if now.duration_since(bucket.window_start) >= self.window { | ||
| 128 | + bucket.window_start = now; | ||
| 129 | + bucket.count = 0; | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + if bucket.count < self.max { | ||
| 133 | + bucket.count += 1; | ||
| 134 | + Ok(()) | ||
| 135 | + } else { | ||
| 136 | + let remaining = self.window - now.duration_since(bucket.window_start); | ||
| 137 | + Err((remaining.as_secs_f64().ceil() as u64).max(1)) | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// Resolve the client IP a request is billed against. | ||
| 143 | +/// | ||
| 144 | +/// With `trust_proxy`, prefer the rightmost `X-Forwarded-For` entry — appended | ||
| 145 | +/// by the nearest (trusted) proxy, unlike the left entries which arrive | ||
| 146 | +/// attacker-controlled. Otherwise (or when the header is missing/unparseable) | ||
| 147 | +/// fall back to the connection's peer address. `oneshot`-driven routers carry | ||
| 148 | +/// no [`ConnectInfo`]; those requests share the unspecified-address bucket. | ||
| 149 | +fn client_ip(req: &Request, trust_proxy: bool) -> IpAddr { | ||
| 150 | + if trust_proxy | ||
| 151 | + && let Some(ip) = req | ||
| 152 | + .headers() | ||
| 153 | + .get("x-forwarded-for") | ||
| 154 | + .and_then(|v| v.to_str().ok()) | ||
| 155 | + .and_then(|v| v.rsplit(',').next()) | ||
| 156 | + .and_then(|entry| entry.trim().parse().ok()) | ||
| 157 | + { | ||
| 158 | + return ip; | ||
| 159 | + } | ||
| 160 | + | ||
| 161 | + req.extensions() | ||
| 162 | + .get::<ConnectInfo<SocketAddr>>() | ||
| 163 | + .map(|ci| ci.0.ip()) | ||
| 164 | + .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED)) | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +#[cfg(test)] | ||
| 168 | +mod tests { | ||
| 169 | + use super::*; | ||
| 170 | + use axum::body::Body; | ||
| 171 | + | ||
| 172 | + fn ip(last: u8) -> IpAddr { | ||
| 173 | + IpAddr::V4(Ipv4Addr::new(10, 0, 0, last)) | ||
| 174 | + } | ||
| 175 | + | ||
| 176 | + /// A request with an optional `X-Forwarded-For` header and an optional | ||
| 177 | + /// peer address, mirroring what a real connection / a proxy would produce. | ||
| 178 | + fn req(xff: Option<&str>, peer: Option<&str>) -> Request { | ||
| 179 | + let mut builder = axum::http::Request::builder().uri("/"); | ||
| 180 | + if let Some(v) = xff { | ||
| 181 | + builder = builder.header("x-forwarded-for", v); | ||
| 182 | + } | ||
| 183 | + let mut req = builder.body(Body::empty()).unwrap(); | ||
| 184 | + if let Some(addr) = peer { | ||
| 185 | + let addr: SocketAddr = addr.parse().unwrap(); | ||
| 186 | + req.extensions_mut().insert(ConnectInfo(addr)); | ||
| 187 | + } | ||
| 188 | + req | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + #[tokio::test] | ||
| 192 | + async fn client_ip_takes_rightmost_forwarded_hop_when_proxy_is_trusted() { | ||
| 193 | + let request = req(Some("1.1.1.1, 2.2.2.2"), Some("10.9.8.7:443")); | ||
| 194 | + assert_eq!( | ||
| 195 | + client_ip(&request, true), | ||
| 196 | + "2.2.2.2".parse::<IpAddr>().unwrap() | ||
| 197 | + ); | ||
| 198 | + | ||
| 199 | + let single = req(Some("2001:db8::7"), Some("10.9.8.7:443")); | ||
| 200 | + assert_eq!( | ||
| 201 | + client_ip(&single, true), | ||
| 202 | + "2001:db8::7".parse::<IpAddr>().unwrap() | ||
| 203 | + ); | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + #[tokio::test] | ||
| 207 | + async fn client_ip_ignores_forwarded_header_when_proxy_is_untrusted() { | ||
| 208 | + let request = req(Some("1.1.1.1"), Some("10.9.8.7:443")); | ||
| 209 | + assert_eq!( | ||
| 210 | + client_ip(&request, false), | ||
| 211 | + "10.9.8.7".parse::<IpAddr>().unwrap() | ||
| 212 | + ); | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + #[tokio::test] | ||
| 216 | + async fn client_ip_falls_back_to_peer_on_unparseable_forwarded_entries() { | ||
| 217 | + // Not an address at all, and the `ip:port` form some proxies emit — | ||
| 218 | + // neither may be billed as a distinct client. | ||
| 219 | + for garbage in ["not-an-ip", "1.2.3.4:5678", ""] { | ||
| 220 | + let request = req(Some(garbage), Some("10.9.8.7:443")); | ||
| 221 | + assert_eq!( | ||
| 222 | + client_ip(&request, true), | ||
| 223 | + "10.9.8.7".parse::<IpAddr>().unwrap(), | ||
| 224 | + "{garbage:?} must fall back to the peer address" | ||
| 225 | + ); | ||
| 226 | + } | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + #[tokio::test] | ||
| 230 | + async fn client_ip_is_unspecified_without_any_connection_info() { | ||
| 231 | + // `oneshot`-driven requests: no header, no peer. Everyone shares 0.0.0.0. | ||
| 232 | + let request = req(None, None); | ||
| 233 | + assert_eq!(client_ip(&request, true), IpAddr::V4(Ipv4Addr::UNSPECIFIED)); | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + #[tokio::test(start_paused = true)] | ||
| 237 | + async fn allows_up_to_max_then_rejects() { | ||
| 238 | + let limiter = RateLimiter::per_minute(3, false); | ||
| 239 | + for _ in 0..3 { | ||
| 240 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 241 | + } | ||
| 242 | + assert!(limiter.check(ip(1)).is_err()); | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + /// The boundary is exact at realistic limits too, the shipped defaults | ||
| 246 | + /// included: request `max` passes, request `max + 1` is rejected — never | ||
| 247 | + /// an off-by-one in either direction. | ||
| 248 | + #[tokio::test(start_paused = true)] | ||
| 249 | + async fn boundary_is_exact_at_production_scale_limits() { | ||
| 250 | + use crate::config::{DEFAULT_API_RATE_LIMIT, DEFAULT_AUTH_RATE_LIMIT}; | ||
| 251 | + | ||
| 252 | + for max in [1, DEFAULT_AUTH_RATE_LIMIT, 50, DEFAULT_API_RATE_LIMIT] { | ||
| 253 | + let limiter = RateLimiter::per_minute(max, false); | ||
| 254 | + for n in 1..=max { | ||
| 255 | + assert_eq!( | ||
| 256 | + limiter.check(ip(1)), | ||
| 257 | + Ok(()), | ||
| 258 | + "request {n}/{max} must be admitted" | ||
| 259 | + ); | ||
| 260 | + } | ||
| 261 | + assert_eq!( | ||
| 262 | + limiter.check(ip(1)), | ||
| 263 | + Err(60), | ||
| 264 | + "request {}/{max} must be rejected", | ||
| 265 | + max + 1 | ||
| 266 | + ); | ||
| 267 | + } | ||
| 268 | + } | ||
| 269 | + | ||
| 270 | + #[tokio::test(start_paused = true)] | ||
| 271 | + async fn window_resets_after_a_minute() { | ||
| 272 | + let limiter = RateLimiter::per_minute(1, false); | ||
| 273 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 274 | + assert!(limiter.check(ip(1)).is_err()); | ||
| 275 | + | ||
| 276 | + tokio::time::advance(Duration::from_secs(60)).await; | ||
| 277 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 278 | + } | ||
| 279 | + | ||
| 280 | + #[tokio::test(start_paused = true)] | ||
| 281 | + async fn retry_after_counts_down_and_never_hits_zero() { | ||
| 282 | + let limiter = RateLimiter::per_minute(1, false); | ||
| 283 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 284 | + assert_eq!(limiter.check(ip(1)), Err(60)); | ||
| 285 | + | ||
| 286 | + tokio::time::advance(Duration::from_secs(45)).await; | ||
| 287 | + assert_eq!(limiter.check(ip(1)), Err(15)); | ||
| 288 | + | ||
| 289 | + // 59.5s in: 0.5s remain, which must round up to 1, not down to 0. | ||
| 290 | + tokio::time::advance(Duration::from_millis(14_500)).await; | ||
| 291 | + assert_eq!(limiter.check(ip(1)), Err(1)); | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + #[tokio::test(start_paused = true)] | ||
| 295 | + async fn ips_get_independent_buckets() { | ||
| 296 | + let limiter = RateLimiter::per_minute(1, false); | ||
| 297 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 298 | + assert!(limiter.check(ip(1)).is_err()); | ||
| 299 | + assert!(limiter.check(ip(2)).is_ok()); | ||
| 300 | + } | ||
| 301 | + | ||
| 302 | + #[tokio::test(start_paused = true)] | ||
| 303 | + async fn zero_means_disabled() { | ||
| 304 | + let limiter = RateLimiter::per_minute(0, false); | ||
| 305 | + for _ in 0..1_000 { | ||
| 306 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 307 | + } | ||
| 308 | + assert!(limiter.buckets.lock().unwrap().is_empty()); | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + #[tokio::test(start_paused = true)] | ||
| 312 | + async fn stale_buckets_are_purged_once_map_is_large() { | ||
| 313 | + let limiter = RateLimiter::per_minute(5, false); | ||
| 314 | + for i in 0..PURGE_AT as u32 { | ||
| 315 | + let addr = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i)); | ||
| 316 | + assert!(limiter.check(addr).is_ok()); | ||
| 317 | + } | ||
| 318 | + assert_eq!(limiter.buckets.lock().unwrap().len(), PURGE_AT); | ||
| 319 | + | ||
| 320 | + // All those windows lapse; the next check sweeps them out. | ||
| 321 | + tokio::time::advance(Duration::from_secs(61)).await; | ||
| 322 | + assert!(limiter.check(ip(1)).is_ok()); | ||
| 323 | + assert_eq!(limiter.buckets.lock().unwrap().len(), 1); | ||
| 324 | + } | ||
| 325 | +} | ||